repo
string | commit
string | message
string | diff
string |
---|---|---|---|
schuyler1d/cbook
|
c1fe0eb76360053d6fc607e0a0652b0126d13bfc
|
got something actually working. but unicrap seems broken
|
diff --git a/client/index.html b/client/index.html
index 3800b64..6196ec2 100644
--- a/client/index.html
+++ b/client/index.html
@@ -1,205 +1,205 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html>
<head>
<title>CBook</title>
<style type="text/css">
body {background-color:#EDFEFF}
textarea {width:100%;}
.hide,.sec {display:none;}
.sec:target {display:block;}
.small{font-size:9px;}
a.bookmarklet {
text-decoration:none;
text-align:center;
padding:5px;
background-color:#BBBBBB;
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
}
</style>
</head>
<body>
<span id="decrypt_output"></span>
- <form id="encode" class="sec" onsubmit="return false;">
+ <form id="encrypt" class="sec" onsubmit="return false;">
<textarea name="txt"></textarea>
- <button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button>
+ <button onclick="p.innerHTML = encrypt_message(t.value, (c.checked?'unicrap':'base64'), f.value);return false;">encrypt</button>
for friends of
<select id="friendkey" name="friendkey">
</select>
<input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span>
<span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a>
<p id="output"></p>
<!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button-->
</form>
<div id="decode" class="sec"></div>
<div id="setup">
<form id="addfriends" class="sec" action="#addfriends">
<h4>Add Friends</h4>
Site passphrase:
<input type="text" size="30" name="passphrase" />
<textarea rows="8" name="friendlinks"></textarea>
<input type="submit" value="Add Friends"/>
</form>
<form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;">
<h4>Generate Your Key</h4>
Name or Alias:
<input type="text" size="30" name="alias" /><br />
<input type="submit" value="Generate your Friends-Key" /><br />
<span id="keylinksec" class="hide">
Share this link with all your friends.
<a id="keylink" class="hide" href="#foo">link for friends</a>
</span>
<br />
Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">♔ cbϴϴk</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text.
</form>
</div>
<a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a>
<script type="text/javascript" src="js/base64.js"></script>
<script type="text/javascript" src="js/ecmascrypt_v003.js"></script>
<script type="text/javascript" src="js/local_session.js"></script>
<script type="text/javascript" src="js/base.js"></script>
<script type="text/javascript" id="bookmarklet_source">
function bookmarklet(loc,friends) {
var active = document.activeElement,
tags = {},
nodes = [],
crown = String.fromCharCode(9812),
lt = String.fromCharCode(60),
amp = String.fromCharCode(38),
quot = String.fromCharCode(34),
laq = lt+amp+quot;
var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?',
html_regex_str = lt+'([:\\w]+)[^'+lt+']+';
var html_regex = new RegExp(html_regex_str+crypted_regex_str),
crypted_regex = new RegExp(crypted_regex_str, 'g');
var mkfrm = function(par,src,height) {
if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') {
return;
par.removeChild(par.firstChild);
}
var frm = par.ownerDocument.createElement('iframe');
frm.setAttribute('width', par.offsetWidth);
frm.setAttribute('height', Math.max(40,height||par.offsetHeight));
frm.setAttribute('class','cbook');
/*par.appendChild(frm);*/
par.insertBefore(frm,par.firstChild);
frm.src = src;
return frm;
};
/* begin process */
if (document.evaluate) {
var xPathResult = document
.evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]',
document.body,
null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) {
var textNode = xPathResult.snapshotItem(i);
var frm_loc = loc+'?decrypt;mode=postMessage#decrypt=';
var local_str = textNode.data;
var higher_str = textNode.parentNode.parentNode.textContent;
var m = crypted_regex.exec(local_str);
var n = crypted_regex.exec(higher_str);
if (m!=null) {
nodes.push(textNode);
do {
frm_loc += m[0];
} while ((m = crypted_regex.exec(local_str)) != null);
var frm = mkfrm(textNode.parentNode, frm_loc);
} else if (n!=null) { /*for facebook, which breaks up long words*/
nodes.push(textNode);
do {
frm_loc += n[0];
} while ((n = crypted_regex.exec(higher_str)) != null);
var frm = mkfrm(textNode.parentNode.parentNode, frm_loc);
}
}
} else {/*if we ever start caring about IE*/
var matches = document.body.innerHTML.split(html_regex);
while (matches.length > 1) {
matches.shift();
var tag = matches.shift();
/*coded = matches.shift();*/
tags[tag] = [];
}
for (t in tags) {
var elts = document.getElementsByTagName(t);
for (var i=0;elts.length>i;i++) {
/*while (i--) {*/
var m = elts[i].innerHTML.match(crypted_regex);
var dbl_parent = elts[i].innerHTML.match(html_regex);
if (m!=null) if(dbl_parent==null) {
tags[t].push(elts[i]);
var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]);
}
}
}
}
if (active.tagName.toLowerCase() in {textarea:1,input:1}
|| active.contenteditable
) {
var compress = (/twitter/.test(location) ? ';compress=true' : '');
- var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101);
+ var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encrypt',101);
var w = window;/*frm.contentWindow;*/
var listener = function(evt) {
if (evt.source == frm.contentWindow) {
var key = 'value';
if (active.contenteditable) {
key = 'innerHTML';
} else {
if (active.getAttribute('placeholder')==active.value) {
if (active.className) {/*facebook*/
active.className = active.className.replace('placeholder','')
}
}
}
/*add space, in to separate a possible first cmessage from the next*/
if (active[key]) active[key]+= ' ';
active[key] += evt.data;
}
};
if (w.addEventListener) {
w.addEventListener('message',listener,false);
} else if (w.attachEvent) {
w.attachEvent('message',listener);
}
}
}
</script>
<script type="text/javascript">
window.t = document.forms[0].elements["txt"];
window.c = document.forms[0].elements["compress"];
window.f = document.forms[0].elements["friendkey"];
window.p = document.getElementById('output');
var dec = document.location.hash.match(/decrypt=(.+)$/);
if (dec!=null) {
document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]);
var x = window.parent.location;
//window.parent.location = x+'#foooo';
}
- if (/encode/.test(document.location.hash)) {
- document.forms['encode'].elements['txt'].focus();
- document.forms['encode'].elements['compress'].checked = (
+ if (/encrypt/.test(document.location.hash)) {
+ document.forms['encrypt'].elements['txt'].focus();
+ document.forms['encrypt'].elements['compress'].checked = (
/compress=true/.test(document.location.search)
);
Stor.populateKeysOnSelect(document.getElementById('friendkey'));
}
update_bookmarklet();
</script>
</body>
</html>
diff --git a/client/js/base.js b/client/js/base.js
index 6440e28..6f7f1e3 100644
--- a/client/js/base.js
+++ b/client/js/base.js
@@ -1,243 +1,257 @@
var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?',
regex_args = ['codec','hash','iv','ciphtext'],
html_regex = '<([:\\w]+)[^<]+';
var crypted_regex = new RegExp(crypted_regex_str,'g');
/*
facebook: document.getElementsByClassName('uiStreamMessage')
twitter:
//document.activeElement to know which element has focus
15chars for IV
1char for addition
4chars for â.â¿ (could make it 3)
'http://skyb.us/' == 15 chars
140=15+1+4+15+105
*/
var global= {
- encrypt_key:"99add3674eea0f3a84201b8f65017114",
- encrypt_iv:"80a5c7ce51fbeb81a9bad0f44112c17408eb46b172fec9b118bfa6dd2a2772fe",
- mode:0,//0:OFB,1:CFB,2:CBC
- keysize:16//32 for 256, 24 for 192, 16 for 128
+ FAIL_ENCODING:'Failed to decrypt message, likely due to encoding problems.<br />',
+ FAIL_NOKEY:'None of your saved keys could decrypt this message.<br />'
}
-function cryptArgs(iv) {
+function cryptArgs(iv, encrypt_key_numbers) {
///see http://www.josh-davis.org/ecmascrypt
///NOTE:if CBC, then we need to save the msgsize
var mode = 0; //0:OFB,1:CFB,2:CBC
var keysize = 16; //32 for 256, 24 for 192, 16 for 128
- var hexkey = global.encrypt_key;
- var iv = iv||global.encrypt_iv;
- return [mode,ecmaScrypt.toNumbers(hexkey),keysize,iv];
+ encrypt_key_numbers = encrypt_key_numbers || ecmaScrypt.toNumbers(global.encrypt_key);
+ return [mode, encrypt_key_numbers, keysize, iv];
}
var U2N = new (function() {
/* we'll need to get a lot smarter.
we should be accepting/creating unicode characters within the
character range that HTML considers 'character' text.
http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets
parseInt('10FFFF',16) - parseInt('10000',16) == 1048575
1114111 - 65536 ==
String.fromCharCode(85267) seems to be 'real' first character
*/
this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars
this.compress = function(low_unicode) {
var arr = [];
var c = low_unicode.length;
while (c--) {
arr.unshift(low_unicode.charCodeAt(c));
}
return this.unicode(arr);
}
this.decompress = function(high_unicode) {
var nums = this.nums(high_unicode);
var str = '';
for (var i=0;i<nums.length;i++) {
str += String.fromCharCode(nums[i]);
}
return str;
}
this.lowcoding = function(cipher) {
var outhex = '';
for(var i = 0;i < cipher.length;i++) {
outhex += ecmaScrypt.toHex(cipher.charCodeAt(i));
}
return outhex;
}
this.unicode = function(nums) {
///take nums array of numbers from 0-255
var u_string='';
for (var i=0;i<nums.length;i++) {
var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) );
if (n>65535) {
///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes
throw Error('cannot deal with high chars yet');
}
if (n>2299099) {
throw Error('cannot deal with high unicode compression yet');
//but I think the answer is that we'll have some marker
//for NON-encoded text and then
//
}
///random suspects:
if (n==1759 || n==130) {
throw Error('random suspect--not sure it is culprit');
}
if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars
//console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes');
//throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n);
}
if (8192 < n && n < 8447) { //255 chars
///http://en.wikipedia.org/wiki/Unicode_control_characters
///seem to be grouped all in the 2000 -20FF range
throw Error('Wide fence for control chars. we can be more picky'+n);
}
///Any code D800âDFFF is invalid: UTF-16 conflict (2047 chars)
try {
var c = String.fromCharCode(n);
encodeURIComponent(c);
u_string += c;
} catch(e) {
throw Error('could not encode uri component for char:'+n);
}
}
if (u_string.match(/\s/)!=null) {
throw Error('FAILS BY WHITESPACE');
}
return u_string;
};
this.nums = function(u_string) {
var nums = [];
var m = u_string.length;
for (var i=0;i<m;i++) {
var n = u_string.charCodeAt(i)-this.min;
nums.push(n%256);
var x2 = parseInt(n/256,10);
if (x2 != 0) nums.push(x2);
}
return nums;
};
})();//end U2N
var CBook= {
+ chars:{'.':'unicrap',',':'base64'},
unicrap:{
chr:'.',
encrypt:function(iv,ciph) {
var compressed = U2N.compress(ciph.cipher);
var compressed_IV = U2N.unicode(iv);
//cheat on making exceptions and just try decrypt
decrypt.apply(null,CBook.unicrap.decrypt(compressed_IV,compressed));
return [compressed_IV, compressed];
},
decrypt:function(iv,ciphtext) {
return [U2N.nums(iv), U2N.decompress(ciphtext)];
}
},
base64:{
chr:',',
encrypt:function(iv,ciph) {
return [Base64.encodeBytes(iv),
Base64.encode(ciph.cipher)];
},
decrypt:function(iv64,ciphtext) {
return [Base64.decodeBytes(iv64),
Base64.decode(ciphtext)];
}
}
/*,hex:{
chr:'_',
encrypt:function(iv,ciph) {
return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)];
},
decrypt:function(iv,ciphtext) {
}
}*/
};//end CBook
function format_post(codec,hash,iv,ciphertext) {
var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':';
//console.log(rv.length);
return rv;
}
function test_unicode(txt,f) {
f = f||function(c) {
return c.match(/([\w\W])/);
};
for (var i=0;i<txt.length;i++) {
var r = f(String.fromCharCode(txt.charCodeAt(i)));
if (r) {
console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i));
}
}
}
function decrypt_message(crypted) {
var x;
var retval = '';
while ((x = crypted_regex.exec(crypted)) != null) {
- for (m in CBook) {
- if (CBook[m].chr == x[1]) {
- try {
- retval += decrypt.apply(null,CBook[m].decrypt(x[3],x[4])) + '<br />';
- }catch(e) {
- retval += 'Failed to decrypt message, likely due to encoding problems<br />';
- }
- }
+ var friend_keys = Stor.getKeysByIdentifier(x[2]),
+ cbook_method = CBook[CBook.chars[x[1]]],
+ success = false;
+ if (!friend_keys || !friend_keys.length ) {
+ retval += global.FAIL_NOKEY;
+ continue;
+ }
+ try {
+ var iv_ciph = cbook_method.decrypt(x[3],x[4]);
+ }catch(e) {
+ retval += global.FAIL_ENCODING;
+ continue;
}
+ var i = friend_keys.length;
+ while (i--) {
+ try {
+ var msg = decrypt(iv_ciph[0],iv_ciph[1],Base64.decodeBytes(friend_keys[i]));
+ retval += msg+ '<br />';
+ success = true;
+ continue;
+ } catch(e) {/*probably, just the wrong key, keep trying*/}
+ }
+ if (!success) retval += global.FAIL_NOKEY;
}
return retval;
}
-function encrypt_message(plaintext, mode, key) {
+function encrypt_message(plaintext, mode, key_and_ref) {
mode = mode || 'hex';
- var tries = 200;
- var comp = [];
- comp.push(CBook[mode].chr, key);
+ var key_ref = key_and_ref.substr(0,1),
+ key = Base64.decodeBytes(key_and_ref.substr(2)),
+ tries = 200,
+ comp = [];
while (--tries) {
try {
- comp.push.apply(comp,
- CBook[mode].encrypt.apply(null,
- encrypt(plaintext)));
+ comp = CBook[mode].encrypt.apply(null,encrypt(plaintext, key));
break;
} catch(e) {
//console.log(e);
}
}
+
+ comp.unshift(CBook[mode].chr, key_ref);
+
if (tries == 0) {
throw Error('tried too many times and failed');
}
var rv = format_post.apply(null,comp);
if (window.parent != window && window.postMessage) {
window.parent.postMessage(rv,"*");
}
return rv;
}
-function encrypt(plaintext) {
+function encrypt(plaintext, encrypt_key_numbers) {
var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128);
- var crypt_args = cryptArgs(iv);
+ var crypt_args = cryptArgs(iv, encrypt_key_numbers);
crypt_args.unshift(plaintext);
return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args)];
}
-function decrypt(iv,ciph_string) {
- var crypt_args = cryptArgs(iv);
+function decrypt(iv,ciph_string, encrypt_key_numbers) {
+ var crypt_args = cryptArgs(iv, encrypt_key_numbers);
if (crypt_args[0]==2)
throw Error('if CBC, then we need to save the msgsize');
crypt_args.unshift(ciph_string,0);
var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args);
return plaintext;
}
function update_bookmarklet() {
var bk = document.getElementById('bookmarklet_source').innerHTML;
var target = document.getElementById('bookmarklet');
target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")';
}
function tryGenuine() {
/*will try to show genuinity*/
}
\ No newline at end of file
diff --git a/client/js/local_session.js b/client/js/local_session.js
index 49de6ae..b3ee5fa 100644
--- a/client/js/local_session.js
+++ b/client/js/local_session.js
@@ -1,152 +1,157 @@
/*
{
CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']}
MY_KEYS: {"s":['{{key1}}']}
PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}}
}
*/
(function() {
var global = this;
function hasAttr(obj,key) {
try {
return (typeof(obj[key]) != 'undefined');
} catch(e) {return false;}
}
function NOT(bool) {
return !bool;
}
function StorageWrapper(stor) {
this.KEYS_KEY = 'KEYS';
this.hasKey = function(key) {
return (stor.getItem(key) != null);
}
this.get = function(key,default_val) {
return (this.hasKey(key) ? stor.getItem(key) : default_val);
}
var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}'));
this.set = function(key,value) {
stor.setItem(key,value);
key_dict[key]=1;
stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict));
}
///actually returns a dict in the form {key1:1,key2:1,...}
this.keyDict = function() {
return key_dict;
}
this.del = function(key) {
delete stor[key];
delete key_dict[key];
stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict));
}
this.deleteEveryFuckingThing = function() {
for (a in key_dict)
this.del(a);
}
}
function MyStorage() {
var self = this;
this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]);
//this.sessStor = new StorageWrapper(global.sessionStorage);
this.nsPERSON = 'PERSON_';
this.nsPEOPLE = 'CBOOK_PEOPLE';
this.nsME = 'MY_KEYS';
this.getKeyIdentifier = function(key_base64) {
///first two bytes of the sha256 hash of the key in base64;
var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16);
return Base64._keyStr[Math.floor(x/4)];
}
+ this.getKeysByIdentifier = function(ident) {
+ var friends = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}'));
+ return friends[ident];
+ }
+
this.keyList = function() {
var key_list = [/*me-friends divider:*/['','','---------']];
var me = JSON.parse(self.permStor.get(self.nsME,'{}'));
var friends = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}'));
for (k in friends) {
for (var i=0;i<friends[k].length;i++) {
var secret = friends[k][i];
var alias = self.getInfo(secret).alias.v;
var side = ((secret in me) ?'unshift':'push');
key_list[side]([k,secret,alias]);
}
}
return key_list;
}
this.populateKeysOnSelect = function(select) {
var key_list = self.keyList();
for (var i=0;i<key_list.length;i++) {
var k=key_list[i];
var o=document.createElement('option');
- o.value = k[0]+k[1];
+ o.value = k[0]+':'+k[1];
o.innerHTML = k[2];
select.appendChild(o);
}
}
this.generateKey = function(frm) {
var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128));
var prefix = self.getKeyIdentifier(newsecret);
var alias = frm.elements['alias'].value;
///v:value, p:privacy
var obj = {"alias":{"v":alias,"p":"friends"}};
self.addMyKey(newsecret, obj, prefix);
self.addFriend(newsecret, obj, prefix);
alert('New key generated.');
}
this.addMyKey = function(secret) {
var keys = JSON.parse(self.permStor.get(self.nsME,'{}'));
keys[secret]=1;
self.permStor.set(self.nsME, JSON.stringify(keys));
}
this.addFriend = function(newsecret, obj, prefix) {
prefix = prefix || self.getKeyIdentifier(newsecret);
var key = self.nsPERSON + newsecret;
if (self.permStor.hasKey(key)) {
var old_person = self.permStor.get(key);
if (NOT(obj.alias && obj.alias.v)
|| NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) {
return;
}
}
if (NOT(obj.alias && obj.alias.v)) {
return; //atm, don't support friends w/o aliases
}
self.permStor.set(key, JSON.stringify(obj));
self.addPrefix(prefix, newsecret, self.nsPEOPLE);
}
this.addPrefix = function(prefix, newsecret, namespace) {
var ppl = JSON.parse(self.permStor.get(namespace,'{}'));
ppl[prefix] = ppl[prefix] || [];
ppl[prefix].push(newsecret);
self.permStor.set(namespace, JSON.stringify(ppl));
}
this.getInfo = function(secret) {
return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}'));
}
this.backupFriends = function() {
}
this.restoreFriends = function(friend_str) {
}
}
if (window.localStorage) {
global.Stor = new MyStorage();
global.e = global.Stor;
} else {
throw "No localStorage support in browser (yet)!";
}
})();
\ No newline at end of file
|
schuyler1d/cbook
|
445d652253e1a2483ef7c8ec1474e9c61076bdf8
|
connecting key generation to menu
|
diff --git a/client/index.html b/client/index.html
index a99cc7b..3800b64 100644
--- a/client/index.html
+++ b/client/index.html
@@ -1,205 +1,205 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html>
<head>
<title>CBook</title>
<style type="text/css">
body {background-color:#EDFEFF}
textarea {width:100%;}
.hide,.sec {display:none;}
.sec:target {display:block;}
.small{font-size:9px;}
a.bookmarklet {
text-decoration:none;
text-align:center;
padding:5px;
background-color:#BBBBBB;
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
}
</style>
</head>
<body>
<span id="decrypt_output"></span>
<form id="encode" class="sec" onsubmit="return false;">
<textarea name="txt"></textarea>
<button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button>
for friends of
- <select name="friendkey">
- <option value="s">mine</option>
+ <select id="friendkey" name="friendkey">
</select>
<input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span>
<span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a>
<p id="output"></p>
<!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button-->
</form>
<div id="decode" class="sec"></div>
<div id="setup">
<form id="addfriends" class="sec" action="#addfriends">
<h4>Add Friends</h4>
Site passphrase:
<input type="text" size="30" name="passphrase" />
<textarea rows="8" name="friendlinks"></textarea>
<input type="submit" value="Add Friends"/>
</form>
- <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;">
+ <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;">
<h4>Generate Your Key</h4>
Name or Alias:
<input type="text" size="30" name="alias" /><br />
<input type="submit" value="Generate your Friends-Key" /><br />
<span id="keylinksec" class="hide">
Share this link with all your friends.
<a id="keylink" class="hide" href="#foo">link for friends</a>
</span>
<br />
Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">♔ cbϴϴk</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text.
</form>
</div>
<a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a>
<script type="text/javascript" src="js/base64.js"></script>
<script type="text/javascript" src="js/ecmascrypt_v003.js"></script>
<script type="text/javascript" src="js/local_session.js"></script>
<script type="text/javascript" src="js/base.js"></script>
<script type="text/javascript" id="bookmarklet_source">
function bookmarklet(loc,friends) {
var active = document.activeElement,
tags = {},
nodes = [],
crown = String.fromCharCode(9812),
lt = String.fromCharCode(60),
amp = String.fromCharCode(38),
quot = String.fromCharCode(34),
laq = lt+amp+quot;
var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?',
html_regex_str = lt+'([:\\w]+)[^'+lt+']+';
var html_regex = new RegExp(html_regex_str+crypted_regex_str),
crypted_regex = new RegExp(crypted_regex_str, 'g');
var mkfrm = function(par,src,height) {
if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') {
return;
par.removeChild(par.firstChild);
}
var frm = par.ownerDocument.createElement('iframe');
frm.setAttribute('width', par.offsetWidth);
frm.setAttribute('height', Math.max(40,height||par.offsetHeight));
frm.setAttribute('class','cbook');
/*par.appendChild(frm);*/
par.insertBefore(frm,par.firstChild);
frm.src = src;
return frm;
};
/* begin process */
if (document.evaluate) {
var xPathResult = document
.evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]',
document.body,
null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) {
var textNode = xPathResult.snapshotItem(i);
var frm_loc = loc+'?decrypt;mode=postMessage#decrypt=';
var local_str = textNode.data;
var higher_str = textNode.parentNode.parentNode.textContent;
var m = crypted_regex.exec(local_str);
var n = crypted_regex.exec(higher_str);
if (m!=null) {
nodes.push(textNode);
do {
frm_loc += m[0];
} while ((m = crypted_regex.exec(local_str)) != null);
var frm = mkfrm(textNode.parentNode, frm_loc);
} else if (n!=null) { /*for facebook, which breaks up long words*/
nodes.push(textNode);
do {
frm_loc += n[0];
} while ((n = crypted_regex.exec(higher_str)) != null);
var frm = mkfrm(textNode.parentNode.parentNode, frm_loc);
}
}
} else {/*if we ever start caring about IE*/
var matches = document.body.innerHTML.split(html_regex);
while (matches.length > 1) {
matches.shift();
var tag = matches.shift();
/*coded = matches.shift();*/
tags[tag] = [];
}
for (t in tags) {
var elts = document.getElementsByTagName(t);
for (var i=0;elts.length>i;i++) {
/*while (i--) {*/
var m = elts[i].innerHTML.match(crypted_regex);
var dbl_parent = elts[i].innerHTML.match(html_regex);
if (m!=null) if(dbl_parent==null) {
tags[t].push(elts[i]);
var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]);
}
}
}
}
if (active.tagName.toLowerCase() in {textarea:1,input:1}
|| active.contenteditable
) {
var compress = (/twitter/.test(location) ? ';compress=true' : '');
var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101);
var w = window;/*frm.contentWindow;*/
var listener = function(evt) {
if (evt.source == frm.contentWindow) {
var key = 'value';
if (active.contenteditable) {
key = 'innerHTML';
} else {
if (active.getAttribute('placeholder')==active.value) {
if (active.className) {/*facebook*/
active.className = active.className.replace('placeholder','')
}
}
}
/*add space, in to separate a possible first cmessage from the next*/
if (active[key]) active[key]+= ' ';
active[key] += evt.data;
}
};
if (w.addEventListener) {
w.addEventListener('message',listener,false);
} else if (w.attachEvent) {
w.attachEvent('message',listener);
}
}
}
</script>
<script type="text/javascript">
window.t = document.forms[0].elements["txt"];
window.c = document.forms[0].elements["compress"];
window.f = document.forms[0].elements["friendkey"];
window.p = document.getElementById('output');
var dec = document.location.hash.match(/decrypt=(.+)$/);
if (dec!=null) {
- document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]);
- var x = window.parent.location;
- //window.parent.location = x+'#foooo';
+ document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]);
+ var x = window.parent.location;
+ //window.parent.location = x+'#foooo';
}
if (/encode/.test(document.location.hash)) {
- document.forms['encode'].elements['txt'].focus();
- document.forms['encode'].elements['compress'].checked = (
- /compress=true/.test(document.location.search)
- );
+ document.forms['encode'].elements['txt'].focus();
+ document.forms['encode'].elements['compress'].checked = (
+ /compress=true/.test(document.location.search)
+ );
+ Stor.populateKeysOnSelect(document.getElementById('friendkey'));
}
update_bookmarklet();
</script>
</body>
</html>
diff --git a/client/js/local_session.js b/client/js/local_session.js
index 661a3ef..49de6ae 100644
--- a/client/js/local_session.js
+++ b/client/js/local_session.js
@@ -1,121 +1,152 @@
/*
{
CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']}
MY_KEYS: {"s":['{{key1}}']}
PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}}
}
*/
(function() {
var global = this;
-
function hasAttr(obj,key) {
try {
return (typeof(obj[key]) != 'undefined');
} catch(e) {return false;}
}
function NOT(bool) {
return !bool;
}
function StorageWrapper(stor) {
this.KEYS_KEY = 'KEYS';
this.hasKey = function(key) {
return (stor.getItem(key) != null);
}
this.get = function(key,default_val) {
return (this.hasKey(key) ? stor.getItem(key) : default_val);
}
var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}'));
this.set = function(key,value) {
stor.setItem(key,value);
key_dict[key]=1;
stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict));
}
///actually returns a dict in the form {key1:1,key2:1,...}
this.keyDict = function() {
return key_dict;
}
this.del = function(key) {
delete stor[key];
delete key_dict[key];
- stor.setItem(this.KEYS_KEY,M.JSON.stringify(key_dict));
+ stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict));
+ }
+ this.deleteEveryFuckingThing = function() {
+ for (a in key_dict)
+ this.del(a);
}
}
function MyStorage() {
var self = this;
this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]);
//this.sessStor = new StorageWrapper(global.sessionStorage);
this.nsPERSON = 'PERSON_';
this.nsPEOPLE = 'CBOOK_PEOPLE';
this.nsME = 'MY_KEYS';
this.getKeyIdentifier = function(key_base64) {
///first two bytes of the sha256 hash of the key in base64;
- return Base64._keyStr[parseInt(
- ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),
- 16)];
+ var x = parseInt(ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),16);
+ return Base64._keyStr[Math.floor(x/4)];
}
+ this.keyList = function() {
+ var key_list = [/*me-friends divider:*/['','','---------']];
+ var me = JSON.parse(self.permStor.get(self.nsME,'{}'));
+ var friends = JSON.parse(self.permStor.get(self.nsPEOPLE,'{}'));
+
+ for (k in friends) {
+ for (var i=0;i<friends[k].length;i++) {
+ var secret = friends[k][i];
+ var alias = self.getInfo(secret).alias.v;
+ var side = ((secret in me) ?'unshift':'push');
+ key_list[side]([k,secret,alias]);
+ }
+ }
+ return key_list;
+ }
+ this.populateKeysOnSelect = function(select) {
+ var key_list = self.keyList();
+ for (var i=0;i<key_list.length;i++) {
+ var k=key_list[i];
+ var o=document.createElement('option');
+ o.value = k[0]+k[1];
+ o.innerHTML = k[2];
+ select.appendChild(o);
+ }
+ }
this.generateKey = function(frm) {
var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128));
var prefix = self.getKeyIdentifier(newsecret);
var alias = frm.elements['alias'].value;
- var obj = {};
///v:value, p:privacy
- obj[newsecret] = {"alias":{"v":alias,"p":"friends"}};
-
- self.addFriend(newsecret, obj, prefix);
+ var obj = {"alias":{"v":alias,"p":"friends"}};
self.addMyKey(newsecret, obj, prefix);
+ self.addFriend(newsecret, obj, prefix);
+ alert('New key generated.');
}
- this.addMyKey = function(newsecret, obj, prefix) {
- prefix = prefix || self.getKeyIdentifier(newsecret);
- ///TODO NEXT NEXT
+ this.addMyKey = function(secret) {
+ var keys = JSON.parse(self.permStor.get(self.nsME,'{}'));
+ keys[secret]=1;
+ self.permStor.set(self.nsME, JSON.stringify(keys));
}
+
this.addFriend = function(newsecret, obj, prefix) {
prefix = prefix || self.getKeyIdentifier(newsecret);
var key = self.nsPERSON + newsecret;
- if (key in self.permStor.keyDict()) {
+ if (self.permStor.hasKey(key)) {
var old_person = self.permStor.get(key);
if (NOT(obj.alias && obj.alias.v)
|| NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) {
return;
}
}
if (NOT(obj.alias && obj.alias.v)) {
return; //atm, don't support friends w/o aliases
}
self.permStor.set(key, JSON.stringify(obj));
- self.addPrefix(prefix, newsecret);
+ self.addPrefix(prefix, newsecret, self.nsPEOPLE);
}
- this.addPrefix = function(prefix, newsecret) {
- var ppl = JSON.parse(self.permStor.get(self.nsPEOPLE));
+ this.addPrefix = function(prefix, newsecret, namespace) {
+ var ppl = JSON.parse(self.permStor.get(namespace,'{}'));
ppl[prefix] = ppl[prefix] || [];
ppl[prefix].push(newsecret);
+ self.permStor.set(namespace, JSON.stringify(ppl));
+ }
+
+ this.getInfo = function(secret) {
+ return JSON.parse(self.permStor.get(self.nsPERSON+secret,'{}'));
}
this.backupFriends = function() {
}
this.restoreFriends = function(friend_str) {
}
- this.people_keys = this.permStor.get(this.nsPEOPLE, {})
-
}
if (window.localStorage) {
global.Stor = new MyStorage();
global.e = global.Stor;
} else {
throw "No localStorage support in browser (yet)!";
}
})();
\ No newline at end of file
|
schuyler1d/cbook
|
1de64a848b3c1af24ebe646d5b4559ad4b5890dc
|
addFRiend, and almost all generateKey
|
diff --git a/client/js/local_session.js b/client/js/local_session.js
index f84af63..661a3ef 100644
--- a/client/js/local_session.js
+++ b/client/js/local_session.js
@@ -1,80 +1,121 @@
+/*
+ {
+ CBOOK_PEOPLE: {"s":['{{key1}}','{{key2}}']}
+ MY_KEYS: {"s":['{{key1}}']}
+ PERSON_{key1}: {key:{friends:{'alias':"{{alias}}"}}}
+ }
+*/
(function() {
var global = this;
function hasAttr(obj,key) {
try {
return (typeof(obj[key]) != 'undefined');
} catch(e) {return false;}
}
function NOT(bool) {
return !bool;
}
function StorageWrapper(stor) {
this.KEYS_KEY = 'KEYS';
this.hasKey = function(key) {
return (stor.getItem(key) != null);
}
this.get = function(key,default_val) {
return (this.hasKey(key) ? stor.getItem(key) : default_val);
}
var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}'));
this.set = function(key,value) {
stor.setItem(key,value);
key_dict[key]=1;
stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict));
}
///actually returns a dict in the form {key1:1,key2:1,...}
this.keyDict = function() {
return key_dict;
}
this.del = function(key) {
delete stor[key];
delete key_dict[key];
stor.setItem(this.KEYS_KEY,M.JSON.stringify(key_dict));
}
}
function MyStorage() {
+ var self = this;
this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]);
//this.sessStor = new StorageWrapper(global.sessionStorage);
this.nsPERSON = 'PERSON_';
this.nsPEOPLE = 'CBOOK_PEOPLE';
- this.nsME = 'ME_';
+ this.nsME = 'MY_KEYS';
- this.generateKey = function(frm) {
- alert(frm.tagName);
+ this.getKeyIdentifier = function(key_base64) {
+ ///first two bytes of the sha256 hash of the key in base64;
+ return Base64._keyStr[parseInt(
+ ecmaScrypt.sha2.hex_sha256(key_base64).substr(0,2),
+ 16)];
}
- this.addFriend = function() {
-
+ this.generateKey = function(frm) {
+ var newsecret = Base64.encodeBytes(ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128));
+ var prefix = self.getKeyIdentifier(newsecret);
+ var alias = frm.elements['alias'].value;
+ var obj = {};
+ ///v:value, p:privacy
+ obj[newsecret] = {"alias":{"v":alias,"p":"friends"}};
+
+ self.addFriend(newsecret, obj, prefix);
+ self.addMyKey(newsecret, obj, prefix);
+ }
+ this.addMyKey = function(newsecret, obj, prefix) {
+ prefix = prefix || self.getKeyIdentifier(newsecret);
+ ///TODO NEXT NEXT
+ }
+ this.addFriend = function(newsecret, obj, prefix) {
+ prefix = prefix || self.getKeyIdentifier(newsecret);
+ var key = self.nsPERSON + newsecret;
+ if (key in self.permStor.keyDict()) {
+ var old_person = self.permStor.get(key);
+ if (NOT(obj.alias && obj.alias.v)
+ || NOT(confirm('You are about to overwrite a preexisting friend/account in your database, Their alias is '+old_person.alias.v+'. The new alias is '+obj.alias.v))) {
+ return;
+ }
+ }
+ if (NOT(obj.alias && obj.alias.v)) {
+ return; //atm, don't support friends w/o aliases
+ }
+ self.permStor.set(key, JSON.stringify(obj));
+ self.addPrefix(prefix, newsecret);
}
- this.addMyInfo = function() {
-
+ this.addPrefix = function(prefix, newsecret) {
+ var ppl = JSON.parse(self.permStor.get(self.nsPEOPLE));
+ ppl[prefix] = ppl[prefix] || [];
+ ppl[prefix].push(newsecret);
}
this.backupFriends = function() {
}
this.restoreFriends = function(friend_str) {
}
this.people_keys = this.permStor.get(this.nsPEOPLE, {})
}
if (window.localStorage) {
global.Stor = new MyStorage();
global.e = global.Stor;
} else {
throw "No localStorage support in browser (yet)!";
}
})();
\ No newline at end of file
|
schuyler1d/cbook
|
689b9ca69fdce0990b7015b0e45b00cbfce6e54c
|
base64 chars for URLs
|
diff --git a/client/index.html b/client/index.html
index 7bc8428..a99cc7b 100644
--- a/client/index.html
+++ b/client/index.html
@@ -1,205 +1,205 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html>
<head>
<title>CBook</title>
<style type="text/css">
body {background-color:#EDFEFF}
textarea {width:100%;}
.hide,.sec {display:none;}
.sec:target {display:block;}
.small{font-size:9px;}
a.bookmarklet {
text-decoration:none;
text-align:center;
padding:5px;
background-color:#BBBBBB;
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
}
</style>
</head>
<body>
<span id="decrypt_output"></span>
<form id="encode" class="sec" onsubmit="return false;">
<textarea name="txt"></textarea>
<button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button>
for friends of
<select name="friendkey">
<option value="s">mine</option>
</select>
<input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span>
<span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a>
<p id="output"></p>
<!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button-->
</form>
<div id="decode" class="sec"></div>
<div id="setup">
<form id="addfriends" class="sec" action="#addfriends">
<h4>Add Friends</h4>
Site passphrase:
<input type="text" size="30" name="passphrase" />
<textarea rows="8" name="friendlinks"></textarea>
<input type="submit" value="Add Friends"/>
</form>
- <form id="generatekey" class="sec" onsubmit="update_bookmarklet();return false;">
+ <form id="generatekey" class="sec" onsubmit="Stor.generateKey(this);return false;">
<h4>Generate Your Key</h4>
Name or Alias:
<input type="text" size="30" name="alias" /><br />
<input type="submit" value="Generate your Friends-Key" /><br />
<span id="keylinksec" class="hide">
Share this link with all your friends.
<a id="keylink" class="hide" href="#foo">link for friends</a>
</span>
<br />
Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">♔ cbϴϴk</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text.
</form>
</div>
<a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a>
<script type="text/javascript" src="js/base64.js"></script>
<script type="text/javascript" src="js/ecmascrypt_v003.js"></script>
<script type="text/javascript" src="js/local_session.js"></script>
<script type="text/javascript" src="js/base.js"></script>
<script type="text/javascript" id="bookmarklet_source">
function bookmarklet(loc,friends) {
var active = document.activeElement,
tags = {},
nodes = [],
crown = String.fromCharCode(9812),
lt = String.fromCharCode(60),
amp = String.fromCharCode(38),
quot = String.fromCharCode(34),
laq = lt+amp+quot;
var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?',
html_regex_str = lt+'([:\\w]+)[^'+lt+']+';
var html_regex = new RegExp(html_regex_str+crypted_regex_str),
crypted_regex = new RegExp(crypted_regex_str, 'g');
var mkfrm = function(par,src,height) {
if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') {
return;
par.removeChild(par.firstChild);
}
var frm = par.ownerDocument.createElement('iframe');
frm.setAttribute('width', par.offsetWidth);
frm.setAttribute('height', Math.max(40,height||par.offsetHeight));
frm.setAttribute('class','cbook');
/*par.appendChild(frm);*/
par.insertBefore(frm,par.firstChild);
frm.src = src;
return frm;
};
/* begin process */
if (document.evaluate) {
var xPathResult = document
.evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]',
document.body,
null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) {
var textNode = xPathResult.snapshotItem(i);
var frm_loc = loc+'?decrypt;mode=postMessage#decrypt=';
var local_str = textNode.data;
var higher_str = textNode.parentNode.parentNode.textContent;
var m = crypted_regex.exec(local_str);
var n = crypted_regex.exec(higher_str);
if (m!=null) {
nodes.push(textNode);
do {
frm_loc += m[0];
} while ((m = crypted_regex.exec(local_str)) != null);
var frm = mkfrm(textNode.parentNode, frm_loc);
} else if (n!=null) { /*for facebook, which breaks up long words*/
nodes.push(textNode);
do {
frm_loc += n[0];
} while ((n = crypted_regex.exec(higher_str)) != null);
var frm = mkfrm(textNode.parentNode.parentNode, frm_loc);
}
}
} else {/*if we ever start caring about IE*/
var matches = document.body.innerHTML.split(html_regex);
while (matches.length > 1) {
matches.shift();
var tag = matches.shift();
/*coded = matches.shift();*/
tags[tag] = [];
}
for (t in tags) {
var elts = document.getElementsByTagName(t);
for (var i=0;elts.length>i;i++) {
/*while (i--) {*/
var m = elts[i].innerHTML.match(crypted_regex);
var dbl_parent = elts[i].innerHTML.match(html_regex);
if (m!=null) if(dbl_parent==null) {
tags[t].push(elts[i]);
var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]);
}
}
}
}
if (active.tagName.toLowerCase() in {textarea:1,input:1}
|| active.contenteditable
) {
var compress = (/twitter/.test(location) ? ';compress=true' : '');
var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101);
var w = window;/*frm.contentWindow;*/
var listener = function(evt) {
if (evt.source == frm.contentWindow) {
var key = 'value';
if (active.contenteditable) {
key = 'innerHTML';
} else {
if (active.getAttribute('placeholder')==active.value) {
if (active.className) {/*facebook*/
active.className = active.className.replace('placeholder','')
}
}
}
/*add space, in to separate a possible first cmessage from the next*/
if (active[key]) active[key]+= ' ';
active[key] += evt.data;
}
};
if (w.addEventListener) {
w.addEventListener('message',listener,false);
} else if (w.attachEvent) {
w.attachEvent('message',listener);
}
}
}
</script>
<script type="text/javascript">
window.t = document.forms[0].elements["txt"];
window.c = document.forms[0].elements["compress"];
window.f = document.forms[0].elements["friendkey"];
window.p = document.getElementById('output');
var dec = document.location.hash.match(/decrypt=(.+)$/);
if (dec!=null) {
document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]);
var x = window.parent.location;
//window.parent.location = x+'#foooo';
}
if (/encode/.test(document.location.hash)) {
document.forms['encode'].elements['txt'].focus();
document.forms['encode'].elements['compress'].checked = (
/compress=true/.test(document.location.search)
);
}
update_bookmarklet();
</script>
</body>
</html>
diff --git a/client/js/base.js b/client/js/base.js
index a7e5e30..6440e28 100644
--- a/client/js/base.js
+++ b/client/js/base.js
@@ -1,249 +1,243 @@
var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?',
regex_args = ['codec','hash','iv','ciphtext'],
html_regex = '<([:\\w]+)[^<]+';
var crypted_regex = new RegExp(crypted_regex_str,'g');
/*
facebook: document.getElementsByClassName('uiStreamMessage')
twitter:
//document.activeElement to know which element has focus
15chars for IV
1char for addition
4chars for â.â¿ (could make it 3)
'http://skyb.us/' == 15 chars
140=15+1+4+15+105
*/
var global= {
encrypt_key:"99add3674eea0f3a84201b8f65017114",
encrypt_iv:"80a5c7ce51fbeb81a9bad0f44112c17408eb46b172fec9b118bfa6dd2a2772fe",
mode:0,//0:OFB,1:CFB,2:CBC
keysize:16//32 for 256, 24 for 192, 16 for 128
}
function cryptArgs(iv) {
///see http://www.josh-davis.org/ecmascrypt
///NOTE:if CBC, then we need to save the msgsize
var mode = 0; //0:OFB,1:CFB,2:CBC
var keysize = 16; //32 for 256, 24 for 192, 16 for 128
var hexkey = global.encrypt_key;
var iv = iv||global.encrypt_iv;
return [mode,ecmaScrypt.toNumbers(hexkey),keysize,iv];
}
var U2N = new (function() {
/* we'll need to get a lot smarter.
we should be accepting/creating unicode characters within the
character range that HTML considers 'character' text.
http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets
parseInt('10FFFF',16) - parseInt('10000',16) == 1048575
1114111 - 65536 ==
String.fromCharCode(85267) seems to be 'real' first character
*/
this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars
this.compress = function(low_unicode) {
var arr = [];
var c = low_unicode.length;
while (c--) {
arr.unshift(low_unicode.charCodeAt(c));
}
return this.unicode(arr);
}
this.decompress = function(high_unicode) {
var nums = this.nums(high_unicode);
var str = '';
for (var i=0;i<nums.length;i++) {
str += String.fromCharCode(nums[i]);
}
return str;
}
this.lowcoding = function(cipher) {
var outhex = '';
for(var i = 0;i < cipher.length;i++) {
outhex += ecmaScrypt.toHex(cipher.charCodeAt(i));
}
return outhex;
}
this.unicode = function(nums) {
///take nums array of numbers from 0-255
var u_string='';
for (var i=0;i<nums.length;i++) {
var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) );
if (n>65535) {
///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes
throw Error('cannot deal with high chars yet');
}
if (n>2299099) {
throw Error('cannot deal with high unicode compression yet');
//but I think the answer is that we'll have some marker
//for NON-encoded text and then
//
}
///random suspects:
if (n==1759 || n==130) {
throw Error('random suspect--not sure it is culprit');
}
if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars
//console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes');
//throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n);
}
if (8192 < n && n < 8447) { //255 chars
///http://en.wikipedia.org/wiki/Unicode_control_characters
///seem to be grouped all in the 2000 -20FF range
throw Error('Wide fence for control chars. we can be more picky'+n);
}
///Any code D800âDFFF is invalid: UTF-16 conflict (2047 chars)
try {
var c = String.fromCharCode(n);
encodeURIComponent(c);
u_string += c;
} catch(e) {
throw Error('could not encode uri component for char:'+n);
}
}
if (u_string.match(/\s/)!=null) {
throw Error('FAILS BY WHITESPACE');
}
return u_string;
};
this.nums = function(u_string) {
var nums = [];
var m = u_string.length;
for (var i=0;i<m;i++) {
var n = u_string.charCodeAt(i)-this.min;
nums.push(n%256);
var x2 = parseInt(n/256,10);
if (x2 != 0) nums.push(x2);
}
return nums;
};
})();//end U2N
var CBook= {
unicrap:{
chr:'.',
encrypt:function(iv,ciph) {
var compressed = U2N.compress(ciph.cipher);
var compressed_IV = U2N.unicode(iv);
//cheat on making exceptions and just try decrypt
decrypt.apply(null,CBook.unicrap.decrypt(compressed_IV,compressed));
return [compressed_IV, compressed];
},
decrypt:function(iv,ciphtext) {
return [U2N.nums(iv), U2N.decompress(ciphtext)];
}
},
base64:{
chr:',',
encrypt:function(iv,ciph) {
- var iv64 = '';
- for (var i=0;i<iv.length;i++) {
- iv64 += Base64._bytes2chars(iv[i],iv[++i],iv[++i]);
- }
- return [iv64,Base64.encode(ciph.cipher)];
+ return [Base64.encodeBytes(iv),
+ Base64.encode(ciph.cipher)];
},
decrypt:function(iv64,ciphtext) {
- var iv = [];
- for (var i=0;i<iv64.length;i+=4) {
- iv.push.apply(iv,Base64._chars2bytes(iv64.substr(i,4)));
- }
- return [iv,Base64.decode(ciphtext)];
+ return [Base64.decodeBytes(iv64),
+ Base64.decode(ciphtext)];
}
}
/*,hex:{
chr:'_',
encrypt:function(iv,ciph) {
return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)];
},
decrypt:function(iv,ciphtext) {
}
}*/
};//end CBook
function format_post(codec,hash,iv,ciphertext) {
var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':';
//console.log(rv.length);
return rv;
}
function test_unicode(txt,f) {
f = f||function(c) {
return c.match(/([\w\W])/);
};
for (var i=0;i<txt.length;i++) {
var r = f(String.fromCharCode(txt.charCodeAt(i)));
if (r) {
console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i));
}
}
}
function decrypt_message(crypted) {
var x;
var retval = '';
while ((x = crypted_regex.exec(crypted)) != null) {
for (m in CBook) {
if (CBook[m].chr == x[1]) {
try {
retval += decrypt.apply(null,CBook[m].decrypt(x[3],x[4])) + '<br />';
}catch(e) {
retval += 'Failed to decrypt message, likely due to encoding problems<br />';
}
}
}
}
return retval;
}
function encrypt_message(plaintext, mode, key) {
mode = mode || 'hex';
var tries = 200;
var comp = [];
comp.push(CBook[mode].chr, key);
while (--tries) {
try {
comp.push.apply(comp,
CBook[mode].encrypt.apply(null,
encrypt(plaintext)));
break;
} catch(e) {
//console.log(e);
}
}
if (tries == 0) {
throw Error('tried too many times and failed');
}
var rv = format_post.apply(null,comp);
if (window.parent != window && window.postMessage) {
window.parent.postMessage(rv,"*");
}
return rv;
}
function encrypt(plaintext) {
var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128);
var crypt_args = cryptArgs(iv);
crypt_args.unshift(plaintext);
return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args)];
}
function decrypt(iv,ciph_string) {
var crypt_args = cryptArgs(iv);
if (crypt_args[0]==2)
throw Error('if CBC, then we need to save the msgsize');
crypt_args.unshift(ciph_string,0);
var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args);
return plaintext;
}
function update_bookmarklet() {
var bk = document.getElementById('bookmarklet_source').innerHTML;
var target = document.getElementById('bookmarklet');
target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")';
}
function tryGenuine() {
/*will try to show genuinity*/
}
\ No newline at end of file
diff --git a/client/js/base64.js b/client/js/base64.js
index d07d54b..832a287 100644
--- a/client/js/base64.js
+++ b/client/js/base64.js
@@ -1,142 +1,156 @@
/**
*
* Base64 encode / decode
* Based off of http://www.webtoolkit.info/javascript-base64.html
*
**/
var Base64 = {
// private property
- _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/=",
+ _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",
+ encodeBytes: function(byte_ary) {
+ var output = "";
+ for (var i=0;i<byte_ary.length;i++) {
+ output += Base64._bytes2chars(byte_ary[i],byte_ary[++i],byte_ary[++i]);
+ }
+ return output;
+ },
+ decodeBytes: function(input) {
+ var byte_ary = [];
+ for (var i=0;i<input.length;i+=4) {
+ byte_ary.push.apply(byte_ary,Base64._chars2bytes(input.substr(i,4)));
+ }
+ return byte_ary;
+ },
// public method for encoding
encode : function (input) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = Base64._utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
output += this._bytes2chars(chr1,chr2,chr3);
}
return output;
},
// private method changing integers to chars
_bytes2chars : function(chr1,chr2,chr3) {
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
return (this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4));
},
_chars2bytes : function(chars4) {
enc1 = this._keyStr.indexOf(chars4.charAt(0));
enc2 = this._keyStr.indexOf(chars4.charAt(1));
enc3 = this._keyStr.indexOf(chars4.charAt(2));
enc4 = this._keyStr.indexOf(chars4.charAt(3));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
var rv = [chr1];
if (enc3 != 64) rv.push(chr2)
if (enc4 != 64) rv.push(chr3)
return rv
},
// public method for decoding
decode : function (input) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(RegExp('[^'+this._keyStr+']','g'), "");
while (i < input.length) {
var chr=this._chars2bytes(input.substr(i,4));
i+=4;
for (var j=0;j<chr.length;j++) {
output = output + String.fromCharCode(chr[j]);
}
}
output = Base64._utf8_decode(output);
return output;
},
// private method for UTF-8 encoding
_utf8_encode : function (string) {
string = string.replace(/\r\n/g,"\n");
var utftext = "";
for (var n = 0; n < string.length; n++) {
var c = string.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
}
else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
}
else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
},
// private method for UTF-8 decoding
_utf8_decode : function (utftext) {
var string = "";
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
string += String.fromCharCode(c);
i++;
}
else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
}
else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return string;
}
}
\ No newline at end of file
diff --git a/client/js/local_session.js b/client/js/local_session.js
index 17ef3fa..f84af63 100644
--- a/client/js/local_session.js
+++ b/client/js/local_session.js
@@ -1,76 +1,80 @@
(function() {
var global = this;
function hasAttr(obj,key) {
try {
return (typeof(obj[key]) != 'undefined');
} catch(e) {return false;}
}
function NOT(bool) {
return !bool;
}
function StorageWrapper(stor) {
this.KEYS_KEY = 'KEYS';
this.hasKey = function(key) {
return (stor.getItem(key) != null);
}
this.get = function(key,default_val) {
return (this.hasKey(key) ? stor.getItem(key) : default_val);
}
var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}'));
this.set = function(key,value) {
stor.setItem(key,value);
key_dict[key]=1;
stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict));
}
///actually returns a dict in the form {key1:1,key2:1,...}
this.keyDict = function() {
return key_dict;
}
this.del = function(key) {
delete stor[key];
delete key_dict[key];
stor.setItem(this.KEYS_KEY,M.JSON.stringify(key_dict));
}
}
function MyStorage() {
this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]);
//this.sessStor = new StorageWrapper(global.sessionStorage);
this.nsPERSON = 'PERSON_';
this.nsPEOPLE = 'CBOOK_PEOPLE';
this.nsME = 'ME_';
+ this.generateKey = function(frm) {
+ alert(frm.tagName);
+ }
+
this.addFriend = function() {
}
this.addMyInfo = function() {
}
this.backupFriends = function() {
}
this.restoreFriends = function(friend_str) {
}
this.people_keys = this.permStor.get(this.nsPEOPLE, {})
}
if (window.localStorage) {
- global.EphemeralSession = new MyStorage();
- global.e = global.EphemeralSession;
+ global.Stor = new MyStorage();
+ global.e = global.Stor;
} else {
throw "No localStorage support in browser (yet)!";
}
})();
\ No newline at end of file
|
schuyler1d/cbook
|
05604d06e9b6664800ada6de763704a471d7af0d
|
add terminus character ":" so we can find multiple strings in the same text (backwards incompatible)
|
diff --git a/client/index.html b/client/index.html
index 07a8276..7bc8428 100644
--- a/client/index.html
+++ b/client/index.html
@@ -1,194 +1,205 @@
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html>
<head>
<title>CBook</title>
<style type="text/css">
body {background-color:#EDFEFF}
textarea {width:100%;}
.hide,.sec {display:none;}
.sec:target {display:block;}
.small{font-size:9px;}
a.bookmarklet {
text-decoration:none;
text-align:center;
padding:5px;
background-color:#BBBBBB;
-moz-border-radius: 8px;
-webkit-border-radius: 8px;
}
</style>
</head>
<body>
<span id="decrypt_output"></span>
<form id="encode" class="sec" onsubmit="return false;">
<textarea name="txt"></textarea>
<button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button>
for friends of
<select name="friendkey">
<option value="s">mine</option>
</select>
<input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span>
<span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a>
<p id="output"></p>
<!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button-->
</form>
<div id="decode" class="sec"></div>
<div id="setup">
<form id="addfriends" class="sec" action="#addfriends">
<h4>Add Friends</h4>
Site passphrase:
<input type="text" size="30" name="passphrase" />
<textarea rows="8" name="friendlinks"></textarea>
<input type="submit" value="Add Friends"/>
</form>
<form id="generatekey" class="sec" onsubmit="update_bookmarklet();return false;">
<h4>Generate Your Key</h4>
Name or Alias:
<input type="text" size="30" name="alias" /><br />
<input type="submit" value="Generate your Friends-Key" /><br />
<span id="keylinksec" class="hide">
Share this link with all your friends.
<a id="keylink" class="hide" href="#foo">link for friends</a>
</span>
<br />
Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">♔ cbϴϴk</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text.
</form>
</div>
<a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a>
<script type="text/javascript" src="js/base64.js"></script>
<script type="text/javascript" src="js/ecmascrypt_v003.js"></script>
<script type="text/javascript" src="js/local_session.js"></script>
<script type="text/javascript" src="js/base.js"></script>
<script type="text/javascript" id="bookmarklet_source">
function bookmarklet(loc,friends) {
var active = document.activeElement,
tags = {},
nodes = [],
crown = String.fromCharCode(9812),
lt = String.fromCharCode(60),
amp = String.fromCharCode(38),
quot = String.fromCharCode(34),
laq = lt+amp+quot;
- var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+',
+ var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+:?',
html_regex_str = lt+'([:\\w]+)[^'+lt+']+';
var html_regex = new RegExp(html_regex_str+crypted_regex_str),
- crypted_regex = new RegExp(crypted_regex_str);
+ crypted_regex = new RegExp(crypted_regex_str, 'g');
var mkfrm = function(par,src,height) {
if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') {
return;
par.removeChild(par.firstChild);
}
var frm = par.ownerDocument.createElement('iframe');
frm.setAttribute('width', par.offsetWidth);
- frm.setAttribute('height', height||par.offsetHeight);
+ frm.setAttribute('height', Math.max(40,height||par.offsetHeight));
frm.setAttribute('class','cbook');
/*par.appendChild(frm);*/
par.insertBefore(frm,par.firstChild);
frm.src = src;
return frm;
};
/* begin process */
if (document.evaluate) {
var xPathResult = document
.evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]',
document.body,
null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) {
var textNode = xPathResult.snapshotItem(i);
- var m = textNode.data.match(crypted_regex);
- var n = textNode.parentNode.parentNode.textContent.match(crypted_regex);
+
+ var frm_loc = loc+'?decrypt;mode=postMessage#decrypt=';
+ var local_str = textNode.data;
+ var higher_str = textNode.parentNode.parentNode.textContent;
+ var m = crypted_regex.exec(local_str);
+ var n = crypted_regex.exec(higher_str);
if (m!=null) {
nodes.push(textNode);
- var frm = mkfrm(textNode.parentNode, loc+'?decrypt;mode=postMessage#decrypt='+m[0]);
+ do {
+ frm_loc += m[0];
+ } while ((m = crypted_regex.exec(local_str)) != null);
+ var frm = mkfrm(textNode.parentNode, frm_loc);
} else if (n!=null) { /*for facebook, which breaks up long words*/
nodes.push(textNode);
- var frm = mkfrm(textNode.parentNode.parentNode, loc+'?decrypt;mode=postMessage#decrypt='+n[0]);
+ do {
+ frm_loc += n[0];
+ } while ((n = crypted_regex.exec(higher_str)) != null);
+ var frm = mkfrm(textNode.parentNode.parentNode, frm_loc);
}
}
} else {/*if we ever start caring about IE*/
var matches = document.body.innerHTML.split(html_regex);
while (matches.length > 1) {
matches.shift();
var tag = matches.shift();
/*coded = matches.shift();*/
tags[tag] = [];
}
for (t in tags) {
var elts = document.getElementsByTagName(t);
for (var i=0;elts.length>i;i++) {
/*while (i--) {*/
var m = elts[i].innerHTML.match(crypted_regex);
var dbl_parent = elts[i].innerHTML.match(html_regex);
if (m!=null) if(dbl_parent==null) {
tags[t].push(elts[i]);
var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]);
}
}
}
}
if (active.tagName.toLowerCase() in {textarea:1,input:1}
|| active.contenteditable
) {
var compress = (/twitter/.test(location) ? ';compress=true' : '');
var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101);
var w = window;/*frm.contentWindow;*/
var listener = function(evt) {
if (evt.source == frm.contentWindow) {
+ var key = 'value';
if (active.contenteditable) {
- active.innerHTML += evt.data;
+ key = 'innerHTML';
} else {
if (active.getAttribute('placeholder')==active.value) {
- active.value = evt.data;
if (active.className) {/*facebook*/
active.className = active.className.replace('placeholder','')
}
- } else {
- active.value += evt.data;
}
}
+ /*add space, in to separate a possible first cmessage from the next*/
+ if (active[key]) active[key]+= ' ';
+ active[key] += evt.data;
}
};
if (w.addEventListener) {
w.addEventListener('message',listener,false);
} else if (w.attachEvent) {
w.attachEvent('message',listener);
}
}
}
</script>
<script type="text/javascript">
window.t = document.forms[0].elements["txt"];
window.c = document.forms[0].elements["compress"];
window.f = document.forms[0].elements["friendkey"];
window.p = document.getElementById('output');
var dec = document.location.hash.match(/decrypt=(.+)$/);
if (dec!=null) {
document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]);
var x = window.parent.location;
//window.parent.location = x+'#foooo';
}
if (/encode/.test(document.location.hash)) {
document.forms['encode'].elements['txt'].focus();
document.forms['encode'].elements['compress'].checked = (
/compress=true/.test(document.location.search)
);
}
update_bookmarklet();
</script>
</body>
</html>
diff --git a/client/js/base.js b/client/js/base.js
index 6ddbc33..a7e5e30 100644
--- a/client/js/base.js
+++ b/client/js/base.js
@@ -1,247 +1,249 @@
-var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+)',
+var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+):?',
regex_args = ['codec','hash','iv','ciphtext'],
html_regex = '<([:\\w]+)[^<]+';
-var crypted_regex = new RegExp(crypted_regex_str);
+var crypted_regex = new RegExp(crypted_regex_str,'g');
/*
facebook: document.getElementsByClassName('uiStreamMessage')
twitter:
//document.activeElement to know which element has focus
15chars for IV
1char for addition
4chars for â.â¿ (could make it 3)
'http://skyb.us/' == 15 chars
140=15+1+4+15+105
*/
var global= {
encrypt_key:"99add3674eea0f3a84201b8f65017114",
encrypt_iv:"80a5c7ce51fbeb81a9bad0f44112c17408eb46b172fec9b118bfa6dd2a2772fe",
mode:0,//0:OFB,1:CFB,2:CBC
keysize:16//32 for 256, 24 for 192, 16 for 128
}
function cryptArgs(iv) {
///see http://www.josh-davis.org/ecmascrypt
///NOTE:if CBC, then we need to save the msgsize
var mode = 0; //0:OFB,1:CFB,2:CBC
var keysize = 16; //32 for 256, 24 for 192, 16 for 128
var hexkey = global.encrypt_key;
var iv = iv||global.encrypt_iv;
return [mode,ecmaScrypt.toNumbers(hexkey),keysize,iv];
}
var U2N = new (function() {
/* we'll need to get a lot smarter.
we should be accepting/creating unicode characters within the
character range that HTML considers 'character' text.
http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets
parseInt('10FFFF',16) - parseInt('10000',16) == 1048575
1114111 - 65536 ==
String.fromCharCode(85267) seems to be 'real' first character
*/
this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars
this.compress = function(low_unicode) {
var arr = [];
var c = low_unicode.length;
while (c--) {
arr.unshift(low_unicode.charCodeAt(c));
}
return this.unicode(arr);
}
this.decompress = function(high_unicode) {
var nums = this.nums(high_unicode);
var str = '';
for (var i=0;i<nums.length;i++) {
str += String.fromCharCode(nums[i]);
}
return str;
}
this.lowcoding = function(cipher) {
var outhex = '';
for(var i = 0;i < cipher.length;i++) {
outhex += ecmaScrypt.toHex(cipher.charCodeAt(i));
}
return outhex;
}
this.unicode = function(nums) {
///take nums array of numbers from 0-255
var u_string='';
for (var i=0;i<nums.length;i++) {
var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) );
if (n>65535) {
///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes
throw Error('cannot deal with high chars yet');
}
if (n>2299099) {
throw Error('cannot deal with high unicode compression yet');
//but I think the answer is that we'll have some marker
//for NON-encoded text and then
//
}
///random suspects:
if (n==1759 || n==130) {
throw Error('random suspect--not sure it is culprit');
}
if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars
//console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes');
//throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n);
}
if (8192 < n && n < 8447) { //255 chars
///http://en.wikipedia.org/wiki/Unicode_control_characters
///seem to be grouped all in the 2000 -20FF range
throw Error('Wide fence for control chars. we can be more picky'+n);
}
///Any code D800âDFFF is invalid: UTF-16 conflict (2047 chars)
try {
var c = String.fromCharCode(n);
encodeURIComponent(c);
u_string += c;
} catch(e) {
throw Error('could not encode uri component for char:'+n);
}
}
if (u_string.match(/\s/)!=null) {
throw Error('FAILS BY WHITESPACE');
}
return u_string;
};
this.nums = function(u_string) {
var nums = [];
var m = u_string.length;
for (var i=0;i<m;i++) {
var n = u_string.charCodeAt(i)-this.min;
nums.push(n%256);
var x2 = parseInt(n/256,10);
if (x2 != 0) nums.push(x2);
}
return nums;
};
})();//end U2N
var CBook= {
unicrap:{
chr:'.',
encrypt:function(iv,ciph) {
var compressed = U2N.compress(ciph.cipher);
var compressed_IV = U2N.unicode(iv);
//cheat on making exceptions and just try decrypt
decrypt.apply(null,CBook.unicrap.decrypt(compressed_IV,compressed));
return [compressed_IV, compressed];
},
decrypt:function(iv,ciphtext) {
return [U2N.nums(iv), U2N.decompress(ciphtext)];
}
},
base64:{
chr:',',
encrypt:function(iv,ciph) {
var iv64 = '';
for (var i=0;i<iv.length;i++) {
iv64 += Base64._bytes2chars(iv[i],iv[++i],iv[++i]);
}
return [iv64,Base64.encode(ciph.cipher)];
},
decrypt:function(iv64,ciphtext) {
var iv = [];
for (var i=0;i<iv64.length;i+=4) {
iv.push.apply(iv,Base64._chars2bytes(iv64.substr(i,4)));
}
return [iv,Base64.decode(ciphtext)];
}
}
/*,hex:{
chr:'_',
encrypt:function(iv,ciph) {
return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)];
},
decrypt:function(iv,ciphtext) {
}
}*/
};//end CBook
function format_post(codec,hash,iv,ciphertext) {
- var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext;
+ var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext+':';
//console.log(rv.length);
return rv;
}
function test_unicode(txt,f) {
f = f||function(c) {
return c.match(/([\w\W])/);
};
for (var i=0;i<txt.length;i++) {
var r = f(String.fromCharCode(txt.charCodeAt(i)));
if (r) {
console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i));
}
}
}
function decrypt_message(crypted) {
- var x = crypted.match(crypted_regex);
- if (x != null) {
+ var x;
+ var retval = '';
+ while ((x = crypted_regex.exec(crypted)) != null) {
for (m in CBook) {
if (CBook[m].chr == x[1]) {
try {
- return decrypt.apply(null,CBook[m].decrypt(x[3],x[4]));
+ retval += decrypt.apply(null,CBook[m].decrypt(x[3],x[4])) + '<br />';
}catch(e) {
- return 'Failed to decrypt message, likely due to encoding problems';
+ retval += 'Failed to decrypt message, likely due to encoding problems<br />';
}
}
}
- }
+ }
+ return retval;
}
function encrypt_message(plaintext, mode, key) {
mode = mode || 'hex';
var tries = 200;
var comp = [];
comp.push(CBook[mode].chr, key);
while (--tries) {
try {
comp.push.apply(comp,
CBook[mode].encrypt.apply(null,
encrypt(plaintext)));
break;
} catch(e) {
//console.log(e);
}
}
if (tries == 0) {
throw Error('tried too many times and failed');
}
var rv = format_post.apply(null,comp);
if (window.parent != window && window.postMessage) {
window.parent.postMessage(rv,"*");
}
return rv;
}
function encrypt(plaintext) {
var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128);
var crypt_args = cryptArgs(iv);
crypt_args.unshift(plaintext);
return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args)];
}
function decrypt(iv,ciph_string) {
var crypt_args = cryptArgs(iv);
if (crypt_args[0]==2)
throw Error('if CBC, then we need to save the msgsize');
crypt_args.unshift(ciph_string,0);
var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args);
return plaintext;
}
function update_bookmarklet() {
var bk = document.getElementById('bookmarklet_source').innerHTML;
var target = document.getElementById('bookmarklet');
target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")';
}
function tryGenuine() {
/*will try to show genuinity*/
}
\ No newline at end of file
|
schuyler1d/cbook
|
ac5e1a1924e6bd2ac0ae4a37e464480e24c38994
|
encryption/bookmarklet/decryption working; TODO: create/store/load/backup friends keys
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..a9ce179
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+*~
+*.pyc
+#*
diff --git a/client/STREAM_OF_THOUGHTS b/client/STREAM_OF_THOUGHTS
new file mode 100644
index 0000000..6046e52
--- /dev/null
+++ b/client/STREAM_OF_THOUGHTS
@@ -0,0 +1,221 @@
+tools:
+ see where my info can get to (from 'weakest link')
+ see what a certain person can see (of mine)
+
+site:
+ feed for all things for you (rss-like)
+ OAuth
+ twitter annotation
+private-key per friend-group?
+
+-----
+comm issues
+ friends of friends needs to know who friends are
+ OR have a proxy 'friend'
+-----
+importable
+exportable
+(encrypted and unencrypted)
+(partial and whole)
+
+privacy settings (shared)
+
+proxies:
+ OAuth
+ persistant permission, or one-time?
+ http://openidconnect.com/
+
+everyone,
+friends of friends, (proxy)
+friends, (proxy)
+with-permission (you get asked) , (proxy)
+private
+http://developers.facebook.com/docs/authentication/permissions
+
+personal info
+ name
+ alias
+ bio
+ birthday (Month, Day, Year have separate permissions)
+ interested in/looking for
+ religious views
+ political views
+ photo albums
+ posts by me
+ allow friends to post on my wall
+ who can see my wall
+ posts by friends
+ comments on posts
+
+contact info
+ im screen name
+ mobile phone
+ other phone
+ current address
+ website
+ add me as a friend
+ send me a message
+ (each email address)
+
+ web presence
+
+friends/tags/connections
+ friend list
+ family list
+ relationships
+ photos and videos of me
+ current city
+ current (immediate location)
+ hometown
+ education and work
+ activities
+ interests
+ things I like
+
+applications and websites
+ (what you share) (fb section: learn more)
+ what your friends can share
+ blocked applications
+ ignore application invites
+ activity on applications and games dashboards
+ instant personalization pilot program
+ use publicly for other websites
+
+ sky:
+
+search
+block list
+
+
+
+------------------------------------
+site specific
+ sort of like a 'friend'
+ attention levels (ignore X) (sites can obviously customize these things)
+ friend-status
+ friends sharing your content/etc
+
+application specific (with default)
+ what you can share
+ what others can share
+
+SITE-to-SITE
+ public-key
+ contacts
+ picture/icon
+ contact-info
+
+
+Interface:
+ my keys
+ create new key
+ share with friends: (passphrase)
+
+ friends keys
+ add
+ backup/restore
+
+key:name/alias:hash
+
+:desired privacy (friends/friends-of-friends/public/with-permission/private (not shared with anyone) )
+ user email/URL
+
+
+CBOOK_PEOPLE {"s":['key1','key2']}
+*"PERSON_"+hash {key: {fof:{name,email,facebook}, friends:{} } }
+
+{"keys":{"s:kj3l45kj3k4j54":{"friends":{"name":"Schuyler"}}}}
+
+
+Objects
+--------------------
+Friend
+ URI (key, could be email address)
+ pubkey
+ groups (pubkeys)
+
+
+POSTing to the friend URI with
+ shareable-with
+ content
+ uri
+ author(my URI)
+ pubkey (of which the private one is required to decrypt?)
+ other fields (location, comments link, )
+
+GETing with Accept:text/html or whatever
+ public links
+
+GETing with Accept:application/json
+ digest auth
+
+GETing with Accept:application/foaf
+ should return a REDIRECT to the template URLs
+ for
+
+User Views
+--------------
+status updates
+where has my info gone?
+where are my friends (which apps)?
+
+protocols for encrypted tweets:
+{].2j0 k34jl5k3j4l5k34kk4k4kl3l33
+â.â¿ #K$J%#$%J#:L$KJ%#
+â,ë§ K$J%#$%J#:Lãå¶èK$J%#$%J#:L
+support unicode for most languages by doing a min() on the unicode chars, and
+subtracting the value off from all the chars. Then put the min() in the front
+
+14chars for IV
+1char for addition
+4chars for â.â¿ (could make it 3)
+'http://skyb.us/' == 15 chars
+140=17+1+4+15+103
+
+ascii 61-* is ok. avoid [^<&;]
+
+128+12=140
+
+128*128=16384
+
+2299099 is last unicode char I see
+but there are lots of holes
+
+Who do you trust?
+
+DEEPER levels of paranoia:
+--------------------------
+your hosting company
+ you put your SSL private key on the host, so they can pretend to be you
+
+ What to do:
+
+your web browser
+ certificates
+
+your email communication channel
+ Google admits they read your email. How many other companies do the same?
+
+ What to do: use pgp encryption
+
+your operating system
+
+ What to do: well, first how about trying Linux--at least,
+ other people can analyze the source code that it was based on
+ and Linux-people are hippies anyway, right?
+
+ Actually, it's a good first step
+
+
+your compiler
+
+
+
+your computer
+ Who knows what secret instructions Intel and AMD were told to add
+ by the NSA or China. Wait! A lot of these chip and computer
+ factories are IN China....
+
+ What to do?
+ Well, there's open-source hardware. You could get some eproms and
+ punch in the assembly by hand to the.....AHHAHHAH!
diff --git a/client/TODO b/client/TODO
new file mode 100644
index 0000000..53a9f69
--- /dev/null
+++ b/client/TODO
@@ -0,0 +1,3 @@
+1. interface for creating/removing keys, adding friends keys
+2. framewalk in bookmarklet
+3.
\ No newline at end of file
diff --git a/client/index.html b/client/index.html
new file mode 100644
index 0000000..07a8276
--- /dev/null
+++ b/client/index.html
@@ -0,0 +1,194 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE html>
+<html>
+ <head>
+ <title>CBook</title>
+ <style type="text/css">
+ body {background-color:#EDFEFF}
+ textarea {width:100%;}
+ .hide,.sec {display:none;}
+ .sec:target {display:block;}
+ .small{font-size:9px;}
+ a.bookmarklet {
+ text-decoration:none;
+ text-align:center;
+ padding:5px;
+ background-color:#BBBBBB;
+ -moz-border-radius: 8px;
+ -webkit-border-radius: 8px;
+
+ }
+ </style>
+ </head>
+ <body>
+ <span id="decrypt_output"></span>
+ <form id="encode" class="sec" onsubmit="return false;">
+
+ <textarea name="txt"></textarea>
+ <button onclick="p.innerHTML = encrypt_message(t.value,(c.checked?'unicrap':'base64'),f.value);return false;">encrypt</button>
+ for friends of
+ <select name="friendkey">
+ <option value="s">mine</option>
+ </select>
+ <input type="checkbox" name="compress" value="unicrap"><span class="small">dense unicode (for Twitter not Facebook)</span>
+ <span id="authentic"></span><a href="http://github.com/schuyler1d/cbook/issues">?</a>
+ <p id="output"></p>
+ <!--button onclick="f.value = decrypt_message(p.innerHTML);return false;">decrypt</button-->
+ </form>
+ <div id="decode" class="sec"></div>
+ <div id="setup">
+ <form id="addfriends" class="sec" action="#addfriends">
+ <h4>Add Friends</h4>
+ Site passphrase:
+ <input type="text" size="30" name="passphrase" />
+ <textarea rows="8" name="friendlinks"></textarea>
+ <input type="submit" value="Add Friends"/>
+ </form>
+
+ <form id="generatekey" class="sec" onsubmit="update_bookmarklet();return false;">
+ <h4>Generate Your Key</h4>
+ Name or Alias:
+ <input type="text" size="30" name="alias" /><br />
+ <input type="submit" value="Generate your Friends-Key" /><br />
+ <span id="keylinksec" class="hide">
+ Share this link with all your friends.
+ <a id="keylink" class="hide" href="#foo">link for friends</a>
+
+ </span>
+ <br />
+ Drag this bookmarklet, <a class="bookmarklet" id="bookmarklet" href="">♔ cbϴϴk</a> into your browser toolbar. Then run it, when you are on a page with the encrypted messages of your friends or after you click on a text-area to input text.
+
+
+ </form>
+ </div>
+ <a class="sec" href="http://github.com/schuyler1d/cbook/issues">Report a Problem</a>
+
+ <script type="text/javascript" src="js/base64.js"></script>
+ <script type="text/javascript" src="js/ecmascrypt_v003.js"></script>
+ <script type="text/javascript" src="js/local_session.js"></script>
+ <script type="text/javascript" src="js/base.js"></script>
+
+ <script type="text/javascript" id="bookmarklet_source">
+ function bookmarklet(loc,friends) {
+ var active = document.activeElement,
+ tags = {},
+ nodes = [],
+ crown = String.fromCharCode(9812),
+ lt = String.fromCharCode(60),
+ amp = String.fromCharCode(38),
+ quot = String.fromCharCode(34),
+ laq = lt+amp+quot;
+
+ var crypted_regex_str = crown+'[.,_][^>?'+laq+'\'] [^:>?'+laq+'\']+:[^:>?'+laq+'\']+',
+ html_regex_str = lt+'([:\\w]+)[^'+lt+']+';
+
+ var html_regex = new RegExp(html_regex_str+crypted_regex_str),
+ crypted_regex = new RegExp(crypted_regex_str);
+
+ var mkfrm = function(par,src,height) {
+ if (par.firstChild.nodeType==1) if(par.firstChild.tagName.toLowerCase()=='iframe') {
+ return;
+ par.removeChild(par.firstChild);
+ }
+
+ var frm = par.ownerDocument.createElement('iframe');
+ frm.setAttribute('width', par.offsetWidth);
+ frm.setAttribute('height', height||par.offsetHeight);
+ frm.setAttribute('class','cbook');
+ /*par.appendChild(frm);*/
+ par.insertBefore(frm,par.firstChild);
+ frm.src = src;
+ return frm;
+ };
+
+ /* begin process */
+ if (document.evaluate) {
+ var xPathResult = document
+ .evaluate('.//text()[contains(normalize-space(.),'+quot+crown+quot+')]',
+ document.body,
+ null,XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,null);
+ for (var i = 0, l = xPathResult.snapshotLength; l > i; i++) {
+ var textNode = xPathResult.snapshotItem(i);
+ var m = textNode.data.match(crypted_regex);
+ var n = textNode.parentNode.parentNode.textContent.match(crypted_regex);
+ if (m!=null) {
+ nodes.push(textNode);
+ var frm = mkfrm(textNode.parentNode, loc+'?decrypt;mode=postMessage#decrypt='+m[0]);
+ } else if (n!=null) { /*for facebook, which breaks up long words*/
+ nodes.push(textNode);
+ var frm = mkfrm(textNode.parentNode.parentNode, loc+'?decrypt;mode=postMessage#decrypt='+n[0]);
+ }
+ }
+ } else {/*if we ever start caring about IE*/
+ var matches = document.body.innerHTML.split(html_regex);
+ while (matches.length > 1) {
+ matches.shift();
+ var tag = matches.shift();
+ /*coded = matches.shift();*/
+ tags[tag] = [];
+ }
+ for (t in tags) {
+ var elts = document.getElementsByTagName(t);
+ for (var i=0;elts.length>i;i++) {
+ /*while (i--) {*/
+ var m = elts[i].innerHTML.match(crypted_regex);
+ var dbl_parent = elts[i].innerHTML.match(html_regex);
+ if (m!=null) if(dbl_parent==null) {
+ tags[t].push(elts[i]);
+ var frm = mkfrm(elts[i],loc+'?decrypt;mode=postMessage#decrypt='+m[0]);
+ }
+ }
+ }
+ }
+ if (active.tagName.toLowerCase() in {textarea:1,input:1}
+ || active.contenteditable
+ ) {
+ var compress = (/twitter/.test(location) ? ';compress=true' : '');
+ var frm = mkfrm(active.parentNode,loc+'?mode=postMessage'+compress+'#encode',101);
+ var w = window;/*frm.contentWindow;*/
+ var listener = function(evt) {
+ if (evt.source == frm.contentWindow) {
+ if (active.contenteditable) {
+ active.innerHTML += evt.data;
+ } else {
+ if (active.getAttribute('placeholder')==active.value) {
+ active.value = evt.data;
+ if (active.className) {/*facebook*/
+ active.className = active.className.replace('placeholder','')
+ }
+ } else {
+ active.value += evt.data;
+ }
+ }
+ }
+ };
+ if (w.addEventListener) {
+ w.addEventListener('message',listener,false);
+ } else if (w.attachEvent) {
+ w.attachEvent('message',listener);
+ }
+ }
+ }
+ </script>
+ <script type="text/javascript">
+ window.t = document.forms[0].elements["txt"];
+ window.c = document.forms[0].elements["compress"];
+ window.f = document.forms[0].elements["friendkey"];
+ window.p = document.getElementById('output');
+ var dec = document.location.hash.match(/decrypt=(.+)$/);
+ if (dec!=null) {
+ document.getElementById('decrypt_output').innerHTML = decrypt_message(dec[1]);
+ var x = window.parent.location;
+ //window.parent.location = x+'#foooo';
+ }
+
+ if (/encode/.test(document.location.hash)) {
+ document.forms['encode'].elements['txt'].focus();
+ document.forms['encode'].elements['compress'].checked = (
+ /compress=true/.test(document.location.search)
+ );
+ }
+ update_bookmarklet();
+ </script>
+ </body>
+</html>
diff --git a/client/js/base.js b/client/js/base.js
new file mode 100644
index 0000000..6ddbc33
--- /dev/null
+++ b/client/js/base.js
@@ -0,0 +1,247 @@
+var crypted_regex_str = String.fromCharCode(9812)+'([.,_])([^<>?&"\']) ([^:<>?&"\']+):([^:<>?&"\']+)',
+regex_args = ['codec','hash','iv','ciphtext'],
+html_regex = '<([:\\w]+)[^<]+';
+var crypted_regex = new RegExp(crypted_regex_str);
+
+/*
+ facebook: document.getElementsByClassName('uiStreamMessage')
+ twitter:
+ //document.activeElement to know which element has focus
+
+15chars for IV
+1char for addition
+4chars for â.â¿ (could make it 3)
+'http://skyb.us/' == 15 chars
+140=15+1+4+15+105
+*/
+
+var global= {
+ encrypt_key:"99add3674eea0f3a84201b8f65017114",
+ encrypt_iv:"80a5c7ce51fbeb81a9bad0f44112c17408eb46b172fec9b118bfa6dd2a2772fe",
+ mode:0,//0:OFB,1:CFB,2:CBC
+ keysize:16//32 for 256, 24 for 192, 16 for 128
+}
+function cryptArgs(iv) {
+ ///see http://www.josh-davis.org/ecmascrypt
+ ///NOTE:if CBC, then we need to save the msgsize
+ var mode = 0; //0:OFB,1:CFB,2:CBC
+ var keysize = 16; //32 for 256, 24 for 192, 16 for 128
+ var hexkey = global.encrypt_key;
+ var iv = iv||global.encrypt_iv;
+ return [mode,ecmaScrypt.toNumbers(hexkey),keysize,iv];
+}
+
+var U2N = new (function() {
+ /* we'll need to get a lot smarter.
+ we should be accepting/creating unicode characters within the
+ character range that HTML considers 'character' text.
+ http://www.w3.org/TR/2000/WD-xml-2e-20000814.html#charsets
+ parseInt('10FFFF',16) - parseInt('10000',16) == 1048575
+ 1114111 - 65536 ==
+ String.fromCharCode(85267) seems to be 'real' first character
+ */
+ this.min = 61;//131072 = SIP (doesn't seem to work at all) //8239 avoids rtl/ltr codepoints //61 > worst ascii chars
+ this.compress = function(low_unicode) {
+ var arr = [];
+ var c = low_unicode.length;
+ while (c--) {
+ arr.unshift(low_unicode.charCodeAt(c));
+ }
+ return this.unicode(arr);
+ }
+ this.decompress = function(high_unicode) {
+ var nums = this.nums(high_unicode);
+ var str = '';
+ for (var i=0;i<nums.length;i++) {
+ str += String.fromCharCode(nums[i]);
+ }
+ return str;
+ }
+ this.lowcoding = function(cipher) {
+ var outhex = '';
+ for(var i = 0;i < cipher.length;i++) {
+ outhex += ecmaScrypt.toHex(cipher.charCodeAt(i));
+ }
+ return outhex;
+ }
+ this.unicode = function(nums) {
+ ///take nums array of numbers from 0-255
+ var u_string='';
+ for (var i=0;i<nums.length;i++) {
+ var n = this.min+( (nums.length-i <= 1 ) ? nums[i] : nums[i] + (256*nums[++i]) );
+ if (n>65535) {
+ ///http://en.wikipedia.org/wiki/Mapping_of_Unicode_characters#Planes
+ throw Error('cannot deal with high chars yet');
+ }
+ if (n>2299099) {
+ throw Error('cannot deal with high unicode compression yet');
+ //but I think the answer is that we'll have some marker
+ //for NON-encoded text and then
+ //
+ }
+ ///random suspects:
+ if (n==1759 || n==130) {
+ throw Error('random suspect--not sure it is culprit');
+ }
+ if (!(n % 256) || !((n+1)%256)) { //2*256 ==512 chars
+ //console.warn('U+FFFE and U+FFFF are invalid non-coding on all planes');
+ //throw Error('U+FFFE and U+FFFF are invalid non-coding on all planes: '+n);
+ }
+ if (8192 < n && n < 8447) { //255 chars
+ ///http://en.wikipedia.org/wiki/Unicode_control_characters
+ ///seem to be grouped all in the 2000 -20FF range
+ throw Error('Wide fence for control chars. we can be more picky'+n);
+ }
+ ///Any code D800âDFFF is invalid: UTF-16 conflict (2047 chars)
+ try {
+ var c = String.fromCharCode(n);
+ encodeURIComponent(c);
+ u_string += c;
+ } catch(e) {
+ throw Error('could not encode uri component for char:'+n);
+ }
+
+ }
+ if (u_string.match(/\s/)!=null) {
+ throw Error('FAILS BY WHITESPACE');
+ }
+ return u_string;
+ };
+
+ this.nums = function(u_string) {
+ var nums = [];
+ var m = u_string.length;
+ for (var i=0;i<m;i++) {
+ var n = u_string.charCodeAt(i)-this.min;
+ nums.push(n%256);
+ var x2 = parseInt(n/256,10);
+ if (x2 != 0) nums.push(x2);
+ }
+ return nums;
+ };
+
+})();//end U2N
+
+var CBook= {
+ unicrap:{
+ chr:'.',
+ encrypt:function(iv,ciph) {
+ var compressed = U2N.compress(ciph.cipher);
+ var compressed_IV = U2N.unicode(iv);
+ //cheat on making exceptions and just try decrypt
+ decrypt.apply(null,CBook.unicrap.decrypt(compressed_IV,compressed));
+ return [compressed_IV, compressed];
+ },
+ decrypt:function(iv,ciphtext) {
+ return [U2N.nums(iv), U2N.decompress(ciphtext)];
+ }
+ },
+ base64:{
+ chr:',',
+ encrypt:function(iv,ciph) {
+ var iv64 = '';
+ for (var i=0;i<iv.length;i++) {
+ iv64 += Base64._bytes2chars(iv[i],iv[++i],iv[++i]);
+ }
+ return [iv64,Base64.encode(ciph.cipher)];
+ },
+ decrypt:function(iv64,ciphtext) {
+ var iv = [];
+ for (var i=0;i<iv64.length;i+=4) {
+ iv.push.apply(iv,Base64._chars2bytes(iv64.substr(i,4)));
+ }
+ return [iv,Base64.decode(ciphtext)];
+ }
+ }
+ /*,hex:{
+ chr:'_',
+ encrypt:function(iv,ciph) {
+ return [ecmaScrypt.toHex(iv), U2N.lowcoding(ciph.cipher)];
+ },
+ decrypt:function(iv,ciphtext) {
+ }
+ }*/
+};//end CBook
+
+function format_post(codec,hash,iv,ciphertext) {
+ var rv = String.fromCharCode(9812)+codec+hash+' '+iv+':'+ciphertext;
+ //console.log(rv.length);
+ return rv;
+}
+
+function test_unicode(txt,f) {
+ f = f||function(c) {
+ return c.match(/([\w\W])/);
+ };
+ for (var i=0;i<txt.length;i++) {
+ var r = f(String.fromCharCode(txt.charCodeAt(i)));
+ if (r) {
+ console.log('At ('+i+') '+r+' : '+txt.charCodeAt(i));
+ }
+ }
+}
+function decrypt_message(crypted) {
+ var x = crypted.match(crypted_regex);
+ if (x != null) {
+ for (m in CBook) {
+ if (CBook[m].chr == x[1]) {
+ try {
+ return decrypt.apply(null,CBook[m].decrypt(x[3],x[4]));
+ }catch(e) {
+ return 'Failed to decrypt message, likely due to encoding problems';
+ }
+ }
+ }
+ }
+}
+function encrypt_message(plaintext, mode, key) {
+ mode = mode || 'hex';
+ var tries = 200;
+ var comp = [];
+ comp.push(CBook[mode].chr, key);
+ while (--tries) {
+ try {
+ comp.push.apply(comp,
+ CBook[mode].encrypt.apply(null,
+ encrypt(plaintext)));
+ break;
+ } catch(e) {
+ //console.log(e);
+ }
+ }
+ if (tries == 0) {
+ throw Error('tried too many times and failed');
+ }
+ var rv = format_post.apply(null,comp);
+ if (window.parent != window && window.postMessage) {
+ window.parent.postMessage(rv,"*");
+ }
+ return rv;
+}
+
+function encrypt(plaintext) {
+ var iv = ecmaScrypt.generateSharedKey(ecmaScrypt.aes.keySize.SIZE_128);
+ var crypt_args = cryptArgs(iv);
+ crypt_args.unshift(plaintext);
+
+ return [iv, ecmaScrypt.encrypt.apply(ecmaScrypt,crypt_args)];
+}
+
+function decrypt(iv,ciph_string) {
+ var crypt_args = cryptArgs(iv);
+ if (crypt_args[0]==2)
+ throw Error('if CBC, then we need to save the msgsize');
+ crypt_args.unshift(ciph_string,0);
+ var plaintext = ecmaScrypt.decrypt.apply(ecmaScrypt,crypt_args);
+ return plaintext;
+}
+
+function update_bookmarklet() {
+ var bk = document.getElementById('bookmarklet_source').innerHTML;
+ var target = document.getElementById('bookmarklet');
+ target.href = 'javascript:('+bk+')("'+String(document.location).split(/[#?]/)[0]+'")';
+}
+
+function tryGenuine() {
+ /*will try to show genuinity*/
+}
\ No newline at end of file
diff --git a/client/js/base64.js b/client/js/base64.js
new file mode 100644
index 0000000..d07d54b
--- /dev/null
+++ b/client/js/base64.js
@@ -0,0 +1,142 @@
+/**
+*
+* Base64 encode / decode
+* Based off of http://www.webtoolkit.info/javascript-base64.html
+*
+**/
+
+var Base64 = {
+
+ // private property
+ _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_/=",
+
+ // public method for encoding
+ encode : function (input) {
+ var output = "";
+ var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
+ var i = 0;
+
+ input = Base64._utf8_encode(input);
+
+ while (i < input.length) {
+
+ chr1 = input.charCodeAt(i++);
+ chr2 = input.charCodeAt(i++);
+ chr3 = input.charCodeAt(i++);
+ output += this._bytes2chars(chr1,chr2,chr3);
+ }
+
+ return output;
+ },
+ // private method changing integers to chars
+ _bytes2chars : function(chr1,chr2,chr3) {
+ enc1 = chr1 >> 2;
+ enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
+ enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
+ enc4 = chr3 & 63;
+
+ if (isNaN(chr2)) {
+ enc3 = enc4 = 64;
+ } else if (isNaN(chr3)) {
+ enc4 = 64;
+ }
+
+ return (this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
+ this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4));
+ },
+ _chars2bytes : function(chars4) {
+ enc1 = this._keyStr.indexOf(chars4.charAt(0));
+ enc2 = this._keyStr.indexOf(chars4.charAt(1));
+ enc3 = this._keyStr.indexOf(chars4.charAt(2));
+ enc4 = this._keyStr.indexOf(chars4.charAt(3));
+
+ chr1 = (enc1 << 2) | (enc2 >> 4);
+ chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
+ chr3 = ((enc3 & 3) << 6) | enc4;
+ var rv = [chr1];
+ if (enc3 != 64) rv.push(chr2)
+ if (enc4 != 64) rv.push(chr3)
+ return rv
+ },
+ // public method for decoding
+ decode : function (input) {
+ var output = "";
+ var chr1, chr2, chr3;
+ var enc1, enc2, enc3, enc4;
+ var i = 0;
+
+ input = input.replace(RegExp('[^'+this._keyStr+']','g'), "");
+
+ while (i < input.length) {
+ var chr=this._chars2bytes(input.substr(i,4));
+ i+=4;
+ for (var j=0;j<chr.length;j++) {
+ output = output + String.fromCharCode(chr[j]);
+ }
+ }
+
+ output = Base64._utf8_decode(output);
+
+ return output;
+
+ },
+
+ // private method for UTF-8 encoding
+ _utf8_encode : function (string) {
+ string = string.replace(/\r\n/g,"\n");
+ var utftext = "";
+
+ for (var n = 0; n < string.length; n++) {
+
+ var c = string.charCodeAt(n);
+
+ if (c < 128) {
+ utftext += String.fromCharCode(c);
+ }
+ else if((c > 127) && (c < 2048)) {
+ utftext += String.fromCharCode((c >> 6) | 192);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+ else {
+ utftext += String.fromCharCode((c >> 12) | 224);
+ utftext += String.fromCharCode(((c >> 6) & 63) | 128);
+ utftext += String.fromCharCode((c & 63) | 128);
+ }
+
+ }
+
+ return utftext;
+ },
+
+ // private method for UTF-8 decoding
+ _utf8_decode : function (utftext) {
+ var string = "";
+ var i = 0;
+ var c = c1 = c2 = 0;
+
+ while ( i < utftext.length ) {
+
+ c = utftext.charCodeAt(i);
+
+ if (c < 128) {
+ string += String.fromCharCode(c);
+ i++;
+ }
+ else if((c > 191) && (c < 224)) {
+ c2 = utftext.charCodeAt(i+1);
+ string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
+ i += 2;
+ }
+ else {
+ c2 = utftext.charCodeAt(i+1);
+ c3 = utftext.charCodeAt(i+2);
+ string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
+ i += 3;
+ }
+
+ }
+
+ return string;
+ }
+
+}
\ No newline at end of file
diff --git a/client/js/ecmascrypt_v003.js b/client/js/ecmascrypt_v003.js
new file mode 100644
index 0000000..db10255
--- /dev/null
+++ b/client/js/ecmascrypt_v003.js
@@ -0,0 +1,821 @@
+/*
+ * ecmaScrypt - Cryptography Tools for JavaScript
+ *
+ * Copyright (c) 2007 Josh Davis ( http://www.josh-davis.org ),
+ * Laurent Haan ( http://www.progressive-coding.com ),
+ * Johan Sundstrom ( http://ecmanaut.blogspot.com ),
+ * John Resig ( http://ejohn.org )
+ *
+ * Licensed under the MIT License ( http://www.opensource.org/licenses/mit-license.php ) as follows:
+ *
+ * sha2 portions adapted from jsSHA2 ( http://anmar.eu.org/projects/jssha2/ )
+ * Copyright Angel Marin 2003-2004 - http://anmar.eu.org/
+ * Distributed under the BSD License
+ */
+
+var ecmaScrypt = {
+ // encodes a unicode string to UTF8 (8 bit characters are critical to AES functioning properly)
+ encode_utf8:function(s)
+ {
+ try{return unescape(encodeURIComponent(s));}
+ catch(e){throw 'error during utf8 encoding: ecmaScrypt.encode_utf8.';}
+ },
+
+ // decodes a UTF8 string back to unicode
+ decode_utf8:function(s)
+ {
+ try{return decodeURIComponent(escape(s));}
+ catch(e){throw('error during utf8 decoding: ecmaScrypt.decode_utf8. The most likely cause of this is attempting to decrypt with incorrect key or iv, or with the wrong mode.');}
+ },
+
+ //convert a number array to a hex string
+ toHex:function()
+ {
+ var array = [];
+ if(arguments.length == 1 && arguments[0].constructor == Array)
+ array = arguments[0];
+ else
+ array = arguments;
+ var ret = '';
+ for(var i = 0;i < array.length;i++)
+ ret += (array[i] < 16 ? '0' : '') + array[i].toString(16);
+ return ret.toLowerCase();
+ },
+
+ //convert a hex string to a number array
+ toNumbers:function(s)
+ {
+ var ret = [];
+ s.replace(/(..)/g,function(s){
+ ret.push(parseInt(s,16));
+ });
+ return ret;
+ },
+
+ // get a random number in the range [min,max]
+ getRandom:function(min,max)
+ {
+ if(min === null)
+ min = 0;
+ if(max === null)
+ max = 1;
+ return Math.round(Math.random()*max) + min;
+ },
+
+ generateSharedKey:function(len)
+ {
+ if(len === null)
+ len = 16;
+ var key = [];
+ for(var i = 0; i < len*2; i++)
+ key.push(this.getRandom(0,255));
+ return key;
+ },
+
+ generatePrivateKey:function(s,size)
+ {
+ var sha = this.sha2.arr_sha256(s);
+ return sha.slice(0,size);
+ },
+
+ sha2:{
+ chrsz:8, /* bits per input character. 8 - ASCII; 16 - Unicode */
+ hexcase:0,/* hex output format. 0 - lowercase; 1 - uppercase */
+ safe_add:function(x, y)
+ {
+ var lsw = (x & 0xFFFF) + (y & 0xFFFF);
+ var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
+ return (msw << 16) | (lsw & 0xFFFF);
+ },
+ S:function(X, n) {return ( X >>> n ) | (X << (32 - n));},
+ R:function(X, n) {return ( X >>> n );},
+ Ch:function(x, y, z) {return ((x & y) ^ ((~x) & z));},
+ Maj:function(x, y, z) {return ((x & y) ^ (x & z) ^ (y & z));},
+ Sigma0256:function(x) {return (this.S(x, 2) ^ this.S(x, 13) ^ this.S(x, 22));},
+ Sigma1256:function(x) {return (this.S(x, 6) ^ this.S(x, 11) ^ this.S(x, 25));},
+ Gamma0256:function(x) {return (this.S(x, 7) ^ this.S(x, 18) ^ this.R(x, 3));},
+ Gamma1256:function(x) {return (this.S(x, 17) ^ this.S(x, 19) ^ this.R(x, 10));},
+ core_sha256:function(m, l)
+ {
+ var K = [ 0x428A2F98,0x71374491,0xB5C0FBCF,0xE9B5DBA5,0x3956C25B,0x59F111F1,0x923F82A4,0xAB1C5ED5,
+ 0xD807AA98,0x12835B01,0x243185BE,0x550C7DC3,0x72BE5D74,0x80DEB1FE,0x9BDC06A7,0xC19BF174,
+ 0xE49B69C1,0xEFBE4786,0xFC19DC6,0x240CA1CC,0x2DE92C6F,0x4A7484AA,0x5CB0A9DC,0x76F988DA,
+ 0x983E5152,0xA831C66D,0xB00327C8,0xBF597FC7,0xC6E00BF3,0xD5A79147,0x6CA6351,0x14292967,
+ 0x27B70A85,0x2E1B2138,0x4D2C6DFC,0x53380D13,0x650A7354,0x766A0ABB,0x81C2C92E,0x92722C85,
+ 0xA2BFE8A1,0xA81A664B,0xC24B8B70,0xC76C51A3,0xD192E819,0xD6990624,0xF40E3585,0x106AA070,
+ 0x19A4C116,0x1E376C08,0x2748774C,0x34B0BCB5,0x391C0CB3,0x4ED8AA4A,0x5B9CCA4F,0x682E6FF3,
+ 0x748F82EE,0x78A5636F,0x84C87814,0x8CC70208,0x90BEFFFA,0xA4506CEB,0xBEF9A3F7,0xC67178F2];
+ var HASH = [0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A,0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19];
+ var W = [];
+ var a, b, c, d, e, f, g, h, i, j;
+ var T1, T2;
+
+ /* append padding */
+ m[l >> 5] |= 0x80 << (24 - l % 32);
+ m[((l + 64 >> 9) << 4) + 15] = l;
+
+ for ( var i = 0; i<m.length; i+=16 )
+ {
+ a = HASH[0];
+ b = HASH[1];
+ c = HASH[2];
+ d = HASH[3];
+ e = HASH[4];
+ f = HASH[5];
+ g = HASH[6];
+ h = HASH[7];
+
+ for ( var j = 0; j<64; j++)
+ {
+ if (j < 16)
+ W[j] = m[j + i];
+ else
+ W[j] = this.safe_add(this.safe_add(this.safe_add(this.Gamma1256(W[j - 2]), W[j - 7]), this.Gamma0256(W[j - 15])), W[j - 16]);
+
+ T1 = this.safe_add(this.safe_add(this.safe_add(this.safe_add(h, this.Sigma1256(e)), this.Ch(e, f, g)), K[j]), W[j]);
+ T2 = this.safe_add(this.Sigma0256(a), this.Maj(a, b, c));
+
+ h = g;
+ g = f;
+ f = e;
+ e = this.safe_add(d, T1);
+ d = c;
+ c = b;
+ b = a;
+ a = this.safe_add(T1, T2);
+ }
+
+ HASH[0] = this.safe_add(a, HASH[0]);
+ HASH[1] = this.safe_add(b, HASH[1]);
+ HASH[2] = this.safe_add(c, HASH[2]);
+ HASH[3] = this.safe_add(d, HASH[3]);
+ HASH[4] = this.safe_add(e, HASH[4]);
+ HASH[5] = this.safe_add(f, HASH[5]);
+ HASH[6] = this.safe_add(g, HASH[6]);
+ HASH[7] = this.safe_add(h, HASH[7]);
+ }
+ return HASH;
+ },
+
+ str2binb:function(str)
+ {
+ var bin = [];
+ var mask = (1 << this.chrsz) - 1;
+ for(var i = 0; i < str.length * this.chrsz; i += this.chrsz)
+ bin[i>>5] |= (str.charCodeAt(i / this.chrsz) & mask) << (24 - i%32);
+ return bin;
+ },
+
+ binb2str:function(bin)
+ {
+ var str = "";
+ var mask = (1 << this.chrsz) - 1;
+ for(var i = 0; i < bin.length * 32; i += this.chrsz)
+ str += String.fromCharCode((bin[i>>5] >>> (24 - i%32)) & mask);
+ return str;
+ },
+
+ binb2arr:function(bin)
+ {
+ var array = [];
+ var mask = (1 << this.chrsz) - 1;
+ for(var i = 0; i < bin.length * 32; i += this.chrsz)
+ array.push((bin[i>>5] >>> (24 - i%32)) & mask);
+ return array;
+ },
+
+ binb2hex:function(binarray)
+ {
+ var hex_tab = this.hexcase ? "0123456789ABCDEF" : "0123456789abcdef";
+ var str = "";
+ for(var i = 0; i < binarray.length * 4; i++)
+ {
+ str += hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8+4)) & 0xF) +
+ hex_tab.charAt((binarray[i>>2] >> ((3 - i%4)*8 )) & 0xF);
+ }
+ return str;
+ },
+
+ hex_sha256:function(s){return this.binb2hex(this.core_sha256(this.str2binb(s),s.length * this.chrsz));},
+ arr_sha256:function(s){return this.binb2arr(this.core_sha256(this.str2binb(s),s.length * this.chrsz));},
+ str_sha256:function(s){return this.binb2str(this.core_sha256(this.str2binb(s),s.length * this.chrsz));}
+ },
+
+ /*
+ * START AES SECTION
+ */
+ aes:{
+ // structure of valid key sizes
+ keySize:{
+ SIZE_128:16,
+ SIZE_192:24,
+ SIZE_256:32
+ },
+
+ // Rijndael S-box
+ sbox:[
+ 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
+ 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
+ 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
+ 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
+ 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
+ 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
+ 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
+ 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
+ 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
+ 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
+ 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
+ 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
+ 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
+ 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
+ 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
+ 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 ],
+
+ // Rijndael Inverted S-box
+ rsbox:
+ [ 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb
+ , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb
+ , 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e
+ , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25
+ , 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92
+ , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84
+ , 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06
+ , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b
+ , 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73
+ , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e
+ , 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b
+ , 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4
+ , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f
+ , 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef
+ , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61
+ , 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d ],
+
+ /* rotate the word eight bits to the left */
+ rotate:function(word)
+ {
+ var c = word[0];
+ for (var i = 0; i < 3; i++)
+ word[i] = word[i+1];
+ word[3] = c;
+
+ return word;
+ },
+
+ // Rijndael Rcon
+ Rcon:[
+ 0x8d, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8,
+ 0xab, 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3,
+ 0x7d, 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f,
+ 0x25, 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d,
+ 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab,
+ 0x4d, 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d,
+ 0xfa, 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25,
+ 0x4a, 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01,
+ 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d,
+ 0x9a, 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa,
+ 0xef, 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a,
+ 0x94, 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02,
+ 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a,
+ 0x2f, 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef,
+ 0xc5, 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94,
+ 0x33, 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb, 0x8d, 0x01, 0x02, 0x04,
+ 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36, 0x6c, 0xd8, 0xab, 0x4d, 0x9a, 0x2f,
+ 0x5e, 0xbc, 0x63, 0xc6, 0x97, 0x35, 0x6a, 0xd4, 0xb3, 0x7d, 0xfa, 0xef, 0xc5,
+ 0x91, 0x39, 0x72, 0xe4, 0xd3, 0xbd, 0x61, 0xc2, 0x9f, 0x25, 0x4a, 0x94, 0x33,
+ 0x66, 0xcc, 0x83, 0x1d, 0x3a, 0x74, 0xe8, 0xcb ],
+
+ // Key Schedule Core
+ core:function(word,iteration)
+ {
+ /* rotate the 32-bit word 8 bits to the left */
+ word = this.rotate(word);
+ /* apply S-Box substitution on all 4 parts of the 32-bit word */
+ for (var i = 0; i < 4; ++i)
+ word[i] = this.sbox[word[i]];
+ /* XOR the output of the rcon operation with i to the first part (leftmost) only */
+ word[0] = word[0]^this.Rcon[iteration];
+ return word;
+ },
+
+ /* Rijndael's key expansion
+ * expands an 128,192,256 key into an 176,208,240 bytes key
+ *
+ * expandedKey is a pointer to an char array of large enough size
+ * key is a pointer to a non-expanded key
+ */
+ expandKey:function(key,size,expandedKeySize)
+ {
+ /* current expanded keySize, in bytes */
+ var currentSize = 0;
+ var rconIteration = 1;
+ var t = []; // temporary 4-byte variable
+
+ var expandedKey = [];
+ for(var i = 0;i < expandedKeySize;i++)
+ expandedKey[i] = 0;
+
+ /* set the 16,24,32 bytes of the expanded key to the input key */
+ for (var j = 0; j < size; j++)
+ expandedKey[j] = key[j];
+ currentSize += size;
+
+ while (currentSize < expandedKeySize)
+ {
+ /* assign the previous 4 bytes to the temporary value t */
+ for (var k = 0; k < 4; k++)
+ t[k] = expandedKey[(currentSize - 4) + k];
+
+ /* every 16,24,32 bytes we apply the core schedule to t
+ * and increment rconIteration afterwards
+ */
+ if(currentSize % size == 0)
+ t = this.core(t, rconIteration++);
+
+ /* For 256-bit keys, we add an extra sbox to the calculation */
+ if(size == this.keySize.SIZE_256 && ((currentSize % size) == 16))
+ for(var l = 0; l < 4; l++)
+ t[l] = this.sbox[t[l]];
+
+ /* We XOR t with the four-byte block 16,24,32 bytes before the new expanded key.
+ * This becomes the next four bytes in the expanded key.
+ */
+ for(var m = 0; m < 4; m++) {
+ expandedKey[currentSize] = expandedKey[currentSize - size] ^ t[m];
+ currentSize++;
+ }
+ }
+ return expandedKey;
+ },
+
+ // Adds (XORs) the round key to the state
+ addRoundKey:function(state,roundKey)
+ {
+ for (var i = 0; i < 16; i++)
+ state[i] ^= roundKey[i];
+ return state;
+ },
+
+ // Creates a round key from the given expanded key and the
+ // position within the expanded key.
+ createRoundKey:function(expandedKey,roundKeyPointer)
+ {
+ var roundKey = [];
+ for (var i = 0; i < 4; i++)
+ for (var j = 0; j < 4; j++)
+ roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j];
+ return roundKey;
+ },
+
+ // galois multiplication of 8 bit characters a and b
+ galois_multiplication:function(a,b)
+ {
+ var p = 0;
+ for(var counter = 0; counter < 8; counter++)
+ {
+ if((b & 1) == 1)
+ p ^= a;
+ if(p > 0x100) p ^= 0x100;
+ var hi_bit_set = (a & 0x80); //keep p 8 bit
+ a <<= 1;
+ if(a > 0x100) a ^= 0x100; //keep a 8 bit
+ if(hi_bit_set == 0x80)
+ a ^= 0x1b;
+ if(a > 0x100) a ^= 0x100; //keep a 8 bit
+ b >>= 1;
+ if(b > 0x100) b ^= 0x100; //keep b 8 bit
+ }
+ return p;
+ },
+
+ /* substitute all the values from the state with the value in the SBox
+ * using the state value as index for the SBox
+ */
+ subBytes:function(state,isInv)
+ {
+ for (var i = 0; i < 16; i++)
+ state[i] = isInv?this.rsbox[state[i]]:this.sbox[state[i]];
+ return state;
+ },
+
+ /* iterate over the 4 rows and call shiftRow() with that row */
+ shiftRows:function(state,isInv)
+ {
+ for (var i = 0; i < 4; i++)
+ state = this.shiftRow(state,i*4, i,isInv);
+ return state;
+ },
+
+ /* each iteration shifts the row to the left by 1 */
+ shiftRow:function(state,statePointer,nbr,isInv)
+ {
+ for (var i = 0; i < nbr; i++)
+ {
+ if(isInv)
+ {
+ var tmp = state[statePointer + 3];
+ for (var j = 3; j > 0; j--)
+ state[statePointer + j] = state[statePointer + j-1];
+ state[statePointer] = tmp;
+ }
+ else
+ {
+ var tmp = state[statePointer];
+ for (var j = 0; j < 3; j++)
+ state[statePointer + j] = state[statePointer + j+1];
+ state[statePointer + 3] = tmp;
+ }
+ }
+ return state;
+ },
+
+ // galois multipication of the 4x4 matrix
+ mixColumns:function(state,isInv)
+ {
+ var column = [];
+ /* iterate over the 4 columns */
+ for (var i = 0; i < 4; i++)
+ {
+ /* construct one column by iterating over the 4 rows */
+ for (var j = 0; j < 4; j++)
+ column[j] = state[(j*4)+i];
+ /* apply the mixColumn on one column */
+ column = this.mixColumn(column,isInv);
+ /* put the values back into the state */
+ for (var k = 0; k < 4; k++)
+ state[(k*4)+i] = column[k];
+ }
+ return state;
+ },
+
+ // galois multipication of 1 column of the 4x4 matrix
+ mixColumn:function(column,isInv)
+ {
+ var mult = [];
+ if(isInv)
+ mult = [14,9,13,11];
+ else
+ mult = [2,1,1,3];
+ var cpy = [];
+ for(var i = 0; i < 4; i++)
+ cpy[i] = column[i];
+
+ column[0] = this.galois_multiplication(cpy[0],mult[0]) ^
+ this.galois_multiplication(cpy[3],mult[1]) ^
+ this.galois_multiplication(cpy[2],mult[2]) ^
+ this.galois_multiplication(cpy[1],mult[3]);
+ column[1] = this.galois_multiplication(cpy[1],mult[0]) ^
+ this.galois_multiplication(cpy[0],mult[1]) ^
+ this.galois_multiplication(cpy[3],mult[2]) ^
+ this.galois_multiplication(cpy[2],mult[3]);
+ column[2] = this.galois_multiplication(cpy[2],mult[0]) ^
+ this.galois_multiplication(cpy[1],mult[1]) ^
+ this.galois_multiplication(cpy[0],mult[2]) ^
+ this.galois_multiplication(cpy[3],mult[3]);
+ column[3] = this.galois_multiplication(cpy[3],mult[0]) ^
+ this.galois_multiplication(cpy[2],mult[1]) ^
+ this.galois_multiplication(cpy[1],mult[2]) ^
+ this.galois_multiplication(cpy[0],mult[3]);
+ return column;
+ },
+
+ // applies the 4 operations of the forward round in sequence
+ round:function(state, roundKey)
+ {
+ state = this.subBytes(state,false);
+ state = this.shiftRows(state,false);
+ state = this.mixColumns(state,false);
+ state = this.addRoundKey(state, roundKey);
+ return state;
+ },
+
+ // applies the 4 operations of the inverse round in sequence
+ invRound:function(state,roundKey)
+ {
+ state = this.shiftRows(state,true);
+ state = this.subBytes(state,true);
+ state = this.addRoundKey(state, roundKey);
+ state = this.mixColumns(state,true);
+ return state;
+ },
+
+ /*
+ * Perform the initial operations, the standard round, and the final operations
+ * of the forward aes, creating a round key for each round
+ */
+ main:function(state,expandedKey,nbrRounds)
+ {
+ state = this.addRoundKey(state, this.createRoundKey(expandedKey,0));
+ for (var i = 1; i < nbrRounds; i++)
+ state = this.round(state, this.createRoundKey(expandedKey,16*i));
+ state = this.subBytes(state,false);
+ state = this.shiftRows(state,false);
+ state = this.addRoundKey(state, this.createRoundKey(expandedKey,16*nbrRounds));
+ return state;
+ },
+
+ /*
+ * Perform the initial operations, the standard round, and the final operations
+ * of the inverse aes, creating a round key for each round
+ */
+ invMain:function(state, expandedKey, nbrRounds)
+ {
+ state = this.addRoundKey(state, this.createRoundKey(expandedKey,16*nbrRounds));
+ for (var i = nbrRounds-1; i > 0; i--)
+ state = this.invRound(state, this.createRoundKey(expandedKey,16*i));
+ state = this.shiftRows(state,true);
+ state = this.subBytes(state,true);
+ state = this.addRoundKey(state, this.createRoundKey(expandedKey,0));
+ return state;
+ },
+
+ // encrypts a 128 bit input block against the given key of size specified
+ encrypt:function(input,key,size)
+ {
+ var output = [];
+ var nbrRounds; /* the number of rounds */
+ var block = []; /* the 128 bit block to encode */
+ switch (size) /* set the number of rounds */
+ {
+ case this.keySize.SIZE_128:
+ nbrRounds = 10;
+ break;
+ case this.keySize.SIZE_192:
+ nbrRounds = 12;
+ break;
+ case this.keySize.SIZE_256:
+ nbrRounds = 14;
+ break;
+ default:
+ alert('Invalid Key Size Specified:' + size);
+ return null;
+ break;
+ }
+ var expandedKeySize = (16*(nbrRounds+1)); /* the expanded keySize */
+ /* Set the block values, for the block:
+ * a0,0 a0,1 a0,2 a0,3
+ * a1,0 a1,1 a1,2 a1,3
+ * a2,0 a2,1 a2,2 a2,3
+ * a3,0 a3,1 a3,2 a3,3
+ * the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
+ */
+ for (var i = 0; i < 4; i++) /* iterate over the columns */
+ for (var j = 0; j < 4; j++) /* iterate over the rows */
+ block[(i+(j*4))] = input[(i*4)+j];
+
+ /* expand the key into an 176, 208, 240 bytes key */
+ var expandedKey = this.expandKey(key, size, expandedKeySize); /* the expanded key */
+ /* encrypt the block using the expandedKey */
+ block = this.main(block, expandedKey, nbrRounds);
+ for (var k = 0; k < 4; k++) /* unmap the block again into the output */
+ for (var l = 0; l < 4; l++) /* iterate over the rows */
+ output[(k*4)+l] = block[(k+(l*4))];
+ return output;
+ },
+
+ // decrypts a 128 bit input block against the given key of size specified
+ decrypt:function(input, key, size)
+ {
+ var output = [];
+ var nbrRounds; /* the number of rounds */
+ var block = []; /* the 128 bit block to decode */
+ switch (size) /* set the number of rounds */
+ {
+ case this.keySize.SIZE_128:
+ nbrRounds = 10;
+ break;
+ case this.keySize.SIZE_192:
+ nbrRounds = 12;
+ break;
+ case this.keySize.SIZE_256:
+ nbrRounds = 14;
+ break;
+ default:
+ alert('Invalid Key Size Specified: ' + size);
+ return null;
+ break;
+ }
+ var expandedKeySize = (16*(nbrRounds+1)); /* the expanded keySize */
+ /* Set the block values, for the block:
+ * a0,0 a0,1 a0,2 a0,3
+ * a1,0 a1,1 a1,2 a1,3
+ * a2,0 a2,1 a2,2 a2,3
+ * a3,0 a3,1 a3,2 a3,3
+ * the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3
+ */
+ for (var i = 0; i < 4; i++) /* iterate over the columns */
+ for (var j = 0; j < 4; j++) /* iterate over the rows */
+ block[(i+(j*4))] = input[(i*4)+j];
+ /* expand the key into an 176, 208, 240 bytes key */
+ var expandedKey = this.expandKey(key, size, expandedKeySize);
+ /* decrypt the block using the expandedKey */
+ block = this.invMain(block, expandedKey, nbrRounds);
+ for (var k = 0; k < 4; k++)/* unmap the block again into the output */
+ for (var l = 0; l < 4; l++)/* iterate over the rows */
+ output[(k*4)+l] = block[(k+(l*4))];
+ return output;
+ }
+ },
+ /*
+ * END AES SECTION
+ */
+
+ /*
+ * START MODE OF OPERATION SECTION
+ */
+ //structure of supported modes of operation
+ modeOfOperation:{
+ OFB:0,
+ CFB:1,
+ CBC:2
+ },
+
+ // converts a 16 character string into a number array;
+ convertString:function(string,start,end,mode)
+ {
+ if(end - start > 16)
+ end = start + 16;
+ if (mode == this.modeOfOperation.CBC)
+ var array = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
+ else
+ var array = [];
+ var j = 0;
+ for(var i = start;i < end;i++)
+ {
+ array[j] = string.charCodeAt(i);
+ j++;
+ }
+ return array;
+ },
+
+ /*
+ * Mode of Operation Encryption
+ * stringIn - Input String
+ * mode - mode of type modeOfOperation
+ * key - a number array of length 'size'
+ * size - the bit length of the key
+ * iv - the 128 bit number array Initialization Vector
+ */
+ encrypt:function(stringIn,mode,key,size,iv)
+ {
+ stringIn = this.encode_utf8(stringIn);
+ if(key.length%size)
+ {
+ throw 'Key length does not match specified size.';
+ }
+ if(iv.length%16)
+ {
+ throw 'iv length must be 128 bits.';
+ }
+ // the AES input/output
+ var plaintext = [];
+ var input = [];
+ var output = [];
+ var ciphertext = [];
+ //the output cipher string
+ var cipherOut = '';
+ // char firstRound
+ var firstRound = true;
+ if (stringIn !== null)
+ {
+ for (var j = 0;j < Math.ceil(stringIn.length/16); j++)
+ {
+ var start = j*16;
+ var end = j*16+16;
+ if(j*16+16 > stringIn.length)
+ end = stringIn.length;
+ plaintext = this.convertString(stringIn,start,end,mode);
+ if (mode == this.modeOfOperation.CFB)
+ {
+ if (firstRound)
+ {
+ output = this.aes.encrypt(iv, key, size);
+ firstRound = false;
+ }
+ else
+ output = this.aes.encrypt(input, key, size);
+ for (var i = 0; i < 16; i++)
+ ciphertext[i] = plaintext[i] ^ output[i];
+ for(var k = 0;k < end-start;k++)
+ cipherOut += String.fromCharCode(ciphertext[k]);
+ input = ciphertext;
+ }
+ else if (mode == this.modeOfOperation.OFB)
+ {
+ if (firstRound)
+ {
+ output = this.aes.encrypt(iv, key, size);
+ firstRound = false;
+ }
+ else
+ output = this.aes.encrypt(input, key, size);
+ for (var i = 0; i < 16; i++)
+ ciphertext[i] = plaintext[i] ^ output[i];
+ for(var k = 0;k < end-start;k++)
+ cipherOut += String.fromCharCode(ciphertext[k]);
+ input = output;
+ }
+ else if (mode == this.modeOfOperation.CBC)
+ {
+ for (var i = 0; i < 16; i++)
+ input[i] = plaintext[i] ^ ((firstRound) ? iv[i] : ciphertext[i]);
+ firstRound = false;
+ ciphertext = this.aes.encrypt(input, key, size);
+ // always 16 bytes because of the padding for CBC
+ for(var k = 0;k < 16;k++)
+ cipherOut += String.fromCharCode(ciphertext[k]);
+ }
+ }
+ }
+ return {mode:mode,originalsize:stringIn.length,cipher:cipherOut};
+ },
+
+ /*
+ * Mode of Operation Decryption
+ * cipherIn - Encrypted String
+ * originalsize - The unencrypted string length - required for CBC
+ * mode - mode of type modeOfOperation
+ * key - a number array of length 'size'
+ * size - the bit length of the key
+ * iv - the 128 bit number array Initialization Vector
+ */
+ decrypt:function(cipherIn,originalsize,mode,key,size,iv)
+ {
+ if(key.length%size)
+ {
+ throw 'Key length does not match specified size.';
+ return null;
+ }
+ if(iv.length%16)
+ {
+ throw 'iv length must be 128 bits.';
+ }
+ // the AES input/output
+ var ciphertext = [];
+ var input = [];
+ var output = [];
+ var plaintext = [];
+ //the output plain text string
+ var stringOut = '';
+ // char firstRound
+ var firstRound = true;
+ if (cipherIn !== null)
+ {
+ for (var j = 0;j < Math.ceil(cipherIn.length/16); j++)
+ {
+ var start = j*16;
+ var end = j*16+16;
+ if(j*16+16 > cipherIn.length)
+ end = cipherIn.length;
+ ciphertext = this.convertString(cipherIn,start,end,mode);
+ if (mode == this.modeOfOperation.CFB)
+ {
+ if (firstRound)
+ {
+ output = this.aes.encrypt(iv, key, size);
+ firstRound = false;
+ }
+ else
+ output = this.aes.encrypt(input, key, size);
+ for (i = 0; i < 16; i++)
+ plaintext[i] = output[i] ^ ciphertext[i];
+ for(var k = 0;k < end-start;k++)
+ stringOut += String.fromCharCode(plaintext[k]);
+ input = ciphertext;
+ }
+ else if (mode == this.modeOfOperation.OFB)
+ {
+ if (firstRound)
+ {
+ output = this.aes.encrypt(iv, key, size);
+ firstRound = false;
+ }
+ else
+ output = this.aes.encrypt(input, key, size);
+ for (i = 0; i < 16; i++)
+ plaintext[i] = output[i] ^ ciphertext[i];
+ for(var k = 0;k < end-start;k++)
+ stringOut += String.fromCharCode(plaintext[k]);
+ input = output;
+ }
+ else if(mode == this.modeOfOperation.CBC)
+ {
+ output = this.aes.decrypt(ciphertext, key, size);
+ for (i = 0; i < 16; i++)
+ plaintext[i] = ((firstRound) ? iv[i] : input[i]) ^ output[i];
+ firstRound = false;
+ if (originalsize < end)
+ for(var k = 0;k < originalsize-start;k++)
+ stringOut += String.fromCharCode(plaintext[k]);
+ else
+ for(var k = 0;k < end-start;k++)
+ stringOut += String.fromCharCode(plaintext[k]);
+ input = ciphertext;
+ }
+ }
+ }
+ return this.decode_utf8(stringOut);
+ }
+ /*
+ * END MODE OF OPERATION SECTION
+ */
+};
\ No newline at end of file
diff --git a/client/js/local_session.js b/client/js/local_session.js
new file mode 100644
index 0000000..17ef3fa
--- /dev/null
+++ b/client/js/local_session.js
@@ -0,0 +1,76 @@
+(function() {
+ var global = this;
+
+ function hasAttr(obj,key) {
+ try {
+ return (typeof(obj[key]) != 'undefined');
+ } catch(e) {return false;}
+ }
+
+ function NOT(bool) {
+ return !bool;
+ }
+
+ function StorageWrapper(stor) {
+
+ this.KEYS_KEY = 'KEYS';
+ this.hasKey = function(key) {
+ return (stor.getItem(key) != null);
+ }
+ this.get = function(key,default_val) {
+ return (this.hasKey(key) ? stor.getItem(key) : default_val);
+ }
+ var key_dict = JSON.parse(this.get(this.KEYS_KEY,'{}'));
+ this.set = function(key,value) {
+ stor.setItem(key,value);
+ key_dict[key]=1;
+ stor.setItem(this.KEYS_KEY,JSON.stringify(key_dict));
+ }
+
+ ///actually returns a dict in the form {key1:1,key2:1,...}
+ this.keyDict = function() {
+ return key_dict;
+ }
+ this.del = function(key) {
+ delete stor[key];
+ delete key_dict[key];
+ stor.setItem(this.KEYS_KEY,M.JSON.stringify(key_dict));
+ }
+ }
+
+ function MyStorage() {
+ this.permStor = new StorageWrapper(hasAttr(global,'localStorage')?global.localStorage:global.globalStorage[location.hostname]);
+ //this.sessStor = new StorageWrapper(global.sessionStorage);
+ this.nsPERSON = 'PERSON_';
+ this.nsPEOPLE = 'CBOOK_PEOPLE';
+ this.nsME = 'ME_';
+
+ this.addFriend = function() {
+
+ }
+
+ this.addMyInfo = function() {
+
+ }
+
+ this.backupFriends = function() {
+
+ }
+
+ this.restoreFriends = function(friend_str) {
+
+ }
+
+ this.people_keys = this.permStor.get(this.nsPEOPLE, {})
+
+ }
+
+
+ if (window.localStorage) {
+ global.EphemeralSession = new MyStorage();
+ global.e = global.EphemeralSession;
+ } else {
+ throw "No localStorage support in browser (yet)!";
+ }
+
+})();
\ No newline at end of file
|
johnnydresden/ircd-nossl-redirect
|
965286f324af168644d7e94858cab9de2e432484
|
fixups
|
diff --git a/.keepme b/.keepme
new file mode 100644
index 0000000..e69de29
|
OzzyCzech/gpsrinex
|
7069f5de4e04db99f4447e51af5a3bb7249cdf1f
|
Fix format
|
diff --git a/composer.json b/composer.json
index b0b38e3..d67cb55 100644
--- a/composer.json
+++ b/composer.json
@@ -1,32 +1,30 @@
{
"name": "om/gpsrinex",
"description": "GPS RINEX 2.1 navigation file parser",
"keywords": [
"gps",
"RINEX",
"parser"
],
"homepage": "https://ozana.cz",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Roman Ozana",
"email": "[email protected]"
}
],
- "require": {
- },
"autoload": {
"classmap": [
"src"
]
},
"scripts": {
"test": "tester tests -s -p php"
},
"require-dev": {
"nette/tester": "*"
}
}
diff --git a/src/RinexNavigationParser.php b/src/RinexNavigationParser.php
index 0a0c6f2..8ea7a9d 100644
--- a/src/RinexNavigationParser.php
+++ b/src/RinexNavigationParser.php
@@ -1,129 +1,128 @@
<?php
namespace om;
/**
* RINEX Navigation Parser
*
* @copyright Roman Ožana <[email protected]>
* @license MIT
*/
class RinexNavigationParser {
/** @var int */
private $boradcast = 1;
/**
* @param sting $file
* @param callable $callback
* @return string|mixed
* @throws \RuntimeException
*/
public function parseFile($file, $callback = null) {
$body = false; // each file starts with Header
$output = []; // output data
$this->boradcast = 1;
$counter = 0;
if (!$handle = fopen($file, 'r')) {
throw new \RuntimeException('Can\'t open file' . $file . ' for reading');
}
while (!feof($handle)) {
$row = fgets($handle, 4096); // read line from file
if ($body && !empty($row)) {
$partial = $this->parseRow($row); // read line
if ($callback) {
call_user_func($callback, $partial, $counter, $this->boradcast); // call user function for processing line
} else {
$output[$counter][] = $partial; // return whole data
}
if ($this->boradcast === 1) $counter++; // count
}
if (preg_match('/END OF HEADER/', $row)) $body = true; // end of header
}
fclose($handle);
return ($callback) ? null : $output;
}
/**
* @param string $row
* @return string
*/
public function parseRow($row = '') {
- $output = [];
$row = preg_replace('/D([+|-])/', 'E\1', $row);
$data = preg_split("/[\s]+/", $row, -1, PREG_SPLIT_NO_EMPTY);
switch ($this->boradcast++) {
case 1:
return [
'PRN' => $data[0],
'year' => $data[1],
'month' => $data[2],
'day' => $data[3],
'hour' => $data[4],
'minute' => $data[5],
'second' => $data[6],
'SV_clock_bias' => $data[7],
'SV_clock_drift' => $data[8],
'SV_clock_drift_rate' => $data[9],
];
case 2: // BRODCAST ORBIT 1
return [
'IODE' => $data[0],
'Crs' => $data[1],
'Delta_n' => $data[2],
'M0' => $data[3],
];
case 3: // BRODCAST ORBIT 2
return [
'Cuc' => $data[0],
'e' => $data[1],
'Cus' => $data[2],
'sqrtA' => $data[3],
];
case 4: // BRODCAST ORBIT 3
return [
'Toe' => $data[0],
'Cic' => $data[1],
'OMEGA' => $data[2],
'CIS' => $data[3],
];
case 5: // BRODCAST ORBIT 4
return [
'i0' => $data[0],
'Crc' => $data[1],
'omega' => $data[2], // normal is omega
'OMEGA_DOT' => $data[3],
];
case 6: // BRODCAST ORBIT 5
return [
'IDOT' => $data[0],
'Codes_on_L2_ch' => $data[1],
'GPS_week' => $data[2],
'L2_p_data_flag' => $data[3],
];
case 7: // BRODCAST ORBIT 6
return [
'SV_accuracy' => $data[0],
'SV_health' => $data[1],
'TGD' => $data[2],
'IODC' => $data[3],
];
case 8: // BRODCAST ORBIT 6
$this->boradcast = 1;
return [
'Transmission_time' => $data[0],
'Fit_interval' => $data[1],
'spare_01' => $data[2],
'spare_02' => $data[3],
];
}
}
}
|
OzzyCzech/gpsrinex
|
9d06b8dbdf53ba192e1c29f041c659222f0d26b8
|
Reformat
|
diff --git a/src/RinexNavigationParser.php b/src/RinexNavigationParser.php
index 54f822f..0a0c6f2 100644
--- a/src/RinexNavigationParser.php
+++ b/src/RinexNavigationParser.php
@@ -1,130 +1,129 @@
<?php
+
namespace om;
/**
* RINEX Navigation Parser
*
- * @copyright Roman Ožana <[email protected]>
+ * @copyright Roman Ožana <[email protected]>
* @license MIT
- * @package om
*/
class RinexNavigationParser {
- /** @var int */
- private $boradcast = 1;
-
- /**
- * @param sting $file
- * @param callable $callback
- * @throws \RuntimeException
- * @return string|mixed
- */
- public function parseFile($file, $callback = null) {
- $body = false; // each file starts with Header
- $output = array(); // output data
- $this->boradcast = 1;
- $counter = 0;
+ /** @var int */
+ private $boradcast = 1;
- if (!$handle = fopen($file, 'r')) {
- throw new \RuntimeException('Can\'t open file' . $file . ' for reading');
- }
+ /**
+ * @param sting $file
+ * @param callable $callback
+ * @return string|mixed
+ * @throws \RuntimeException
+ */
+ public function parseFile($file, $callback = null) {
+ $body = false; // each file starts with Header
+ $output = []; // output data
+ $this->boradcast = 1;
+ $counter = 0;
- while (!feof($handle)) {
- $row = fgets($handle, 4096); // read line from file
+ if (!$handle = fopen($file, 'r')) {
+ throw new \RuntimeException('Can\'t open file' . $file . ' for reading');
+ }
- if ($body && !empty($row)) {
- $partial = $this->parseRow($row); // read line
+ while (!feof($handle)) {
+ $row = fgets($handle, 4096); // read line from file
+ if ($body && !empty($row)) {
+ $partial = $this->parseRow($row); // read line
- if ($callback) {
- call_user_func($callback, $partial, $counter, $this->boradcast); // call user function for processing line
- } else {
- $output[$counter][] = $partial; // return whole data
- }
+ if ($callback) {
+ call_user_func($callback, $partial, $counter, $this->boradcast); // call user function for processing line
+ } else {
+ $output[$counter][] = $partial; // return whole data
+ }
- if ($this->boradcast === 1) $counter++; // count
- }
+ if ($this->boradcast === 1) $counter++; // count
+ }
- if (preg_match('/END OF HEADER/', $row)) $body = true; // end of header
- }
+ if (preg_match('/END OF HEADER/', $row)) $body = true; // end of header
+ }
- fclose($handle);
- return ($callback) ? null : $output;
- }
+ fclose($handle);
+ return ($callback) ? null : $output;
+ }
- /**
- * @param string $row
- * @return string
- */
- public function parseRow($row = '') {
- $output = array();
- $row = preg_replace('/D([+|-])/', 'E\1', $row);
- $data = preg_split("/[\s]+/", $row, -1, PREG_SPLIT_NO_EMPTY);
+ /**
+ * @param string $row
+ * @return string
+ */
+ public function parseRow($row = '') {
+ $output = [];
+ $row = preg_replace('/D([+|-])/', 'E\1', $row);
+ $data = preg_split("/[\s]+/", $row, -1, PREG_SPLIT_NO_EMPTY);
- switch ($this->boradcast++) {
- case 1:
- return array(
- 'PRN' => $data[0],
- 'year' => $data[1],
- 'month' => $data[2],
- 'day' => $data[3],
- 'hour' => $data[4],
- 'minute' => $data[5],
- 'second' => $data[6],
- 'SV_clock_bias' => $data[7],
- 'SV_clock_drift' => $data[8],
- 'SV_clock_drift_rate' => $data[9],
- );
- case 2: // BRODCAST ORBIT 1
- return array(
- 'IODE' => $data[0],
- 'Crs' => $data[1],
- 'Delta_n' => $data[2],
- 'M0' => $data[3],
- );
- case 3: // BRODCAST ORBIT 2
- return array(
- 'Cuc' => $data[0],
- 'e' => $data[1],
- 'Cus' => $data[2],
- 'sqrtA' => $data[3],
- );
- case 4: // BRODCAST ORBIT 3
- return array(
- 'Toe' => $data[0],
- 'Cic' => $data[1],
- 'OMEGA' => $data[2],
- 'CIS' => $data[3],
- );
- case 5: // BRODCAST ORBIT 4
- return array(
- 'i0' => $data[0],
- 'Crc' => $data[1],
- 'omega' => $data[2], // normal is omega
- 'OMEGA_DOT' => $data[3],
- );
- case 6: // BRODCAST ORBIT 5
- return array(
- 'IDOT' => $data[0],
- 'Codes_on_L2_ch' => $data[1],
- 'GPS_week' => $data[2],
- 'L2_p_data_flag' => $data[3],
- );
- case 7: // BRODCAST ORBIT 6
- return array(
- 'SV_accuracy' => $data[0],
- 'SV_health' => $data[1],
- 'TGD' => $data[2],
- 'IODC' => $data[3],
- );
- case 8: // BRODCAST ORBIT 6
- $this->boradcast = 1;
- return array(
- 'Transmission_time' => $data[0],
- 'Fit_interval' => $data[1],
- 'spare_01' => $data[2],
- 'spare_02' => $data[3],
- );
- }
- }
+ switch ($this->boradcast++) {
+ case 1:
+ return [
+ 'PRN' => $data[0],
+ 'year' => $data[1],
+ 'month' => $data[2],
+ 'day' => $data[3],
+ 'hour' => $data[4],
+ 'minute' => $data[5],
+ 'second' => $data[6],
+ 'SV_clock_bias' => $data[7],
+ 'SV_clock_drift' => $data[8],
+ 'SV_clock_drift_rate' => $data[9],
+ ];
+ case 2: // BRODCAST ORBIT 1
+ return [
+ 'IODE' => $data[0],
+ 'Crs' => $data[1],
+ 'Delta_n' => $data[2],
+ 'M0' => $data[3],
+ ];
+ case 3: // BRODCAST ORBIT 2
+ return [
+ 'Cuc' => $data[0],
+ 'e' => $data[1],
+ 'Cus' => $data[2],
+ 'sqrtA' => $data[3],
+ ];
+ case 4: // BRODCAST ORBIT 3
+ return [
+ 'Toe' => $data[0],
+ 'Cic' => $data[1],
+ 'OMEGA' => $data[2],
+ 'CIS' => $data[3],
+ ];
+ case 5: // BRODCAST ORBIT 4
+ return [
+ 'i0' => $data[0],
+ 'Crc' => $data[1],
+ 'omega' => $data[2], // normal is omega
+ 'OMEGA_DOT' => $data[3],
+ ];
+ case 6: // BRODCAST ORBIT 5
+ return [
+ 'IDOT' => $data[0],
+ 'Codes_on_L2_ch' => $data[1],
+ 'GPS_week' => $data[2],
+ 'L2_p_data_flag' => $data[3],
+ ];
+ case 7: // BRODCAST ORBIT 6
+ return [
+ 'SV_accuracy' => $data[0],
+ 'SV_health' => $data[1],
+ 'TGD' => $data[2],
+ 'IODC' => $data[3],
+ ];
+ case 8: // BRODCAST ORBIT 6
+ $this->boradcast = 1;
+ return [
+ 'Transmission_time' => $data[0],
+ 'Fit_interval' => $data[1],
+ 'spare_01' => $data[2],
+ 'spare_02' => $data[3],
+ ];
+ }
+ }
}
diff --git a/tests/ParserTest.phpt b/tests/ParserTest.phpt
index b793141..a2caa47 100644
--- a/tests/ParserTest.phpt
+++ b/tests/ParserTest.phpt
@@ -1,17 +1,15 @@
<?php
+
use Tester\Assert;
require_once __DIR__ . '/../vendor/autoload.php';
$parser = new \om\RinexNavigationParser();
$data = $parser->parseFile(__DIR__ . '/data/LongNumberExample.obs');
-
-
-
Assert::same('6', $data[0][0]['PRN']);
Assert::same('-.165982783074E-10', $data[0][0]['SV_clock_drift']);
Assert::same('.000000000000E+00', $data[0][0]['SV_clock_drift_rate']);
Assert::same(4, count($data));
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
dc654b6a6386fd68a9d4b2bb78d542b349326321
|
Fix readme.md
|
diff --git a/readme.md b/readme.md
index bede14b..e38af8b 100644
--- a/readme.md
+++ b/readme.md
@@ -1,25 +1,18 @@
# GPS RINEX 2.1 Navigation FILE Parser
-
[](https://github.com/OzzyCzech/gpsrinex/actions)
[](https://packagist.org/packages/om/gpsrinex)
[](https://packagist.org/packages/om/gpsrinex)
[](https://packagist.org/packages/om/gpsrinex)
[](https://packagist.org/packages/om/gpsrinex)
-
-
-[](https://packagist.org/packages/om/icalparser)
-[](https://packagist.org/packages/om/icalparser)
-[](https://packagist.org/packages/om/icalparser)
-
RINEX (Receiver Independent Exchange)
More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX)
[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html)
## TODO
- get information from header
- get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java)
- add
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
fcec59d9e1d71b3a1f15a201dcc7bfa775b8c15a
|
Drop travis support
|
diff --git a/.github/workflows/php.yml b/.github/workflows/php.yml
new file mode 100644
index 0000000..21587ef
--- /dev/null
+++ b/.github/workflows/php.yml
@@ -0,0 +1,40 @@
+name: PHP Tests
+
+on: [ push, pull_request ]
+
+jobs:
+
+ build:
+ strategy:
+ matrix:
+ operating-system: [ ubuntu-latest ]
+ php-versions: [ '7.4', '8.0', '8.1' ]
+ experimental: [ false ]
+ include:
+ - php-versions: '8.2'
+ operating-system: ubuntu-latest
+ experimental: true
+ fail-fast: false
+ runs-on: ${{ matrix.operating-system }}
+ continue-on-error: ${{ matrix.experimental }}
+ steps:
+ - uses: actions/checkout@v2
+
+ - name: Setup PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php-versions }}
+
+ - name: Validate composer.json and composer.lock
+ run: composer validate
+
+ - name: Install dependencies
+ if: "${{ matrix.experimental == false }}"
+ run: composer install --prefer-dist --no-progress --no-suggest
+
+ - name: Install dependencies, ignore php requirements
+ if: "${{ matrix.experimental == true }}"
+ run: composer install --prefer-dist --no-progress --no-suggest --ignore-platform-reqs
+
+ - name: Run test suite
+ run: composer run-script test
\ No newline at end of file
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 0701411..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,9 +0,0 @@
-language: php
-php:
- - 5.4
- - 5.5
-
-script: "vendor/bin/tester tests/"
-
-before_script:
- - composer install --no-interaction --dev --prefer-source
\ No newline at end of file
diff --git a/composer.json b/composer.json
index 2054b62..b0b38e3 100644
--- a/composer.json
+++ b/composer.json
@@ -1,22 +1,32 @@
{
- "name": "om/gpsrinex",
- "description": "GPS RINEX 2.1 navigation file parser",
- "keywords": ["gps", "RINEX", "parser"],
- "homepage": "http://www.omdesign.cz",
- "license": ["BSD-3-Clause"],
- "authors": [
- {
- "name": "Roman Ozana",
- "email": "[email protected]"
- }
- ],
- "require": {
-
- },
- "autoload": {
- "classmap": ["src"]
- },
- "require-dev": {
- "nette/tester": "*"
- }
+ "name": "om/gpsrinex",
+ "description": "GPS RINEX 2.1 navigation file parser",
+ "keywords": [
+ "gps",
+ "RINEX",
+ "parser"
+ ],
+ "homepage": "https://ozana.cz",
+ "license": [
+ "BSD-3-Clause"
+ ],
+ "authors": [
+ {
+ "name": "Roman Ozana",
+ "email": "[email protected]"
+ }
+ ],
+ "require": {
+ },
+ "autoload": {
+ "classmap": [
+ "src"
+ ]
+ },
+ "scripts": {
+ "test": "tester tests -s -p php"
+ },
+ "require-dev": {
+ "nette/tester": "*"
+ }
}
diff --git a/readme.md b/readme.md
index 00e99a8..bede14b 100644
--- a/readme.md
+++ b/readme.md
@@ -1,14 +1,25 @@
# GPS RINEX 2.1 Navigation FILE Parser
-[](https://travis-ci.org/OzzyCzech/gpsrinex) [](https://packagist.org/packages/om/gpsrinex) [](https://packagist.org/packages/om/gpsrinex) [](https://packagist.org/packages/om/gpsrinex) [](https://packagist.org/packages/om/gpsrinex)
+
+[](https://github.com/OzzyCzech/gpsrinex/actions)
+[](https://packagist.org/packages/om/gpsrinex)
+[](https://packagist.org/packages/om/gpsrinex)
+[](https://packagist.org/packages/om/gpsrinex)
+[](https://packagist.org/packages/om/gpsrinex)
+
+
+
+[](https://packagist.org/packages/om/icalparser)
+[](https://packagist.org/packages/om/icalparser)
+[](https://packagist.org/packages/om/icalparser)
RINEX (Receiver Independent Exchange)
More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX)
[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html)
## TODO
- get information from header
- get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java)
- add
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
1d8d24dbe18bca198f6628938d270bb8b177bb80
|
Fix readme
|
diff --git a/readme.md b/readme.md
index f3512a5..00e99a8 100644
--- a/readme.md
+++ b/readme.md
@@ -1,20 +1,14 @@
# GPS RINEX 2.1 Navigation FILE Parser
[](https://travis-ci.org/OzzyCzech/gpsrinex) [](https://packagist.org/packages/om/gpsrinex) [](https://packagist.org/packages/om/gpsrinex) [](https://packagist.org/packages/om/gpsrinex) [](https://packagist.org/packages/om/gpsrinex)
RINEX (Receiver Independent Exchange)
More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX)
[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html)
-- author: Roman Ozana, [email protected]
-- url: www.omdesign.cz
-- version: 1.1
-- license: MIT
-
-
## TODO
- get information from header
- get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java)
- add
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
4d83f67dc82b5ef5b077fbb18a59c9dfc64820b4
|
Fix badges
|
diff --git a/readme.md b/readme.md
index bccadb5..f3512a5 100644
--- a/readme.md
+++ b/readme.md
@@ -1,20 +1,20 @@
# GPS RINEX 2.1 Navigation FILE Parser
-[](https://travis-ci.org/OzzyCzech/gpsrinex) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events)
+[](https://travis-ci.org/OzzyCzech/gpsrinex) [](https://packagist.org/packages/om/gpsrinex) [](https://packagist.org/packages/om/gpsrinex) [](https://packagist.org/packages/om/gpsrinex) [](https://packagist.org/packages/om/gpsrinex)
RINEX (Receiver Independent Exchange)
More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX)
[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html)
- author: Roman Ozana, [email protected]
- url: www.omdesign.cz
- version: 1.1
- license: MIT
## TODO
- get information from header
- get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java)
- add
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
14464abc6ddb90e6e5fbd8a18458a0c97b4571fb
|
MIT to New BSD license
|
diff --git a/LICENSE b/LICENSE
index 458df4f..f69007f 100644
--- a/LICENSE
+++ b/LICENSE
@@ -1,21 +1,24 @@
-The MIT License (MIT)
+Copyright (c) 2014, Roman Ožana
+All rights reserved.
-Copyright (c) 2013 Roman Ožana
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * Neither the name of the <organization> nor the
+ names of its contributors may be used to endorse or promote products
+ derived from this software without specific prior written permission.
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/composer.json b/composer.json
index 6158e3f..2054b62 100644
--- a/composer.json
+++ b/composer.json
@@ -1,20 +1,22 @@
{
"name": "om/gpsrinex",
"description": "GPS RINEX 2.1 navigation file parser",
- "license": "MIT",
+ "keywords": ["gps", "RINEX", "parser"],
+ "homepage": "http://www.omdesign.cz",
+ "license": ["BSD-3-Clause"],
"authors": [
{
"name": "Roman Ozana",
"email": "[email protected]"
}
],
"require": {
},
"autoload": {
"classmap": ["src"]
},
"require-dev": {
"nette/tester": "*"
}
}
|
OzzyCzech/gpsrinex
|
16e2ec8d6d07d966d9ed24347c4154bfc30bf407
|
Fix readme
|
diff --git a/readme.md b/readme.md
index 8140842..bccadb5 100644
--- a/readme.md
+++ b/readme.md
@@ -1,20 +1,20 @@
# GPS RINEX 2.1 Navigation FILE Parser
-[](https://travis-ci.org/OzzyCzech/gpsrinex)[](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events)
+[](https://travis-ci.org/OzzyCzech/gpsrinex) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events)
RINEX (Receiver Independent Exchange)
More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX)
[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html)
- author: Roman Ozana, [email protected]
- url: www.omdesign.cz
- version: 1.1
- license: MIT
## TODO
- get information from header
- get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java)
- add
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
e1335f5c7a0095650b4e5f2ed3a3d7504bdf4269
|
Remove PHP 5.3 support
|
diff --git a/.travis.yml b/.travis.yml
index 764c4ec..0701411 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,10 +1,9 @@
language: php
php:
- - 5.3
- 5.4
- 5.5
script: "vendor/bin/tester tests/"
before_script:
- composer install --no-interaction --dev --prefer-source
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
4fbea10d4bee55428c169e0ae9b50ae4e305bb13
|
Travis status
|
diff --git a/readme.md b/readme.md
index d76e911..8140842 100644
--- a/readme.md
+++ b/readme.md
@@ -1,20 +1,20 @@
# GPS RINEX 2.1 Navigation FILE Parser
-[](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events)
+[](https://travis-ci.org/OzzyCzech/gpsrinex)[](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events)
RINEX (Receiver Independent Exchange)
More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX)
[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html)
- author: Roman Ozana, [email protected]
- url: www.omdesign.cz
- version: 1.1
- license: MIT
## TODO
- get information from header
- get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java)
- add
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
4d67d0ccd461df3bc723b7e738dd3df3ed1a7864
|
Travis tests
|
diff --git a/.travis.yml b/.travis.yml
new file mode 100644
index 0000000..764c4ec
--- /dev/null
+++ b/.travis.yml
@@ -0,0 +1,10 @@
+language: php
+php:
+ - 5.3
+ - 5.4
+ - 5.5
+
+script: "vendor/bin/tester tests/"
+
+before_script:
+ - composer install --no-interaction --dev --prefer-source
\ No newline at end of file
diff --git a/readme.md b/readme.md
index 6db9b8d..d76e911 100644
--- a/readme.md
+++ b/readme.md
@@ -1,18 +1,20 @@
# GPS RINEX 2.1 Navigation FILE Parser
+[](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events) [](https://packagist.org/packages/om/events)
+
RINEX (Receiver Independent Exchange)
More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX)
[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html)
- author: Roman Ozana, [email protected]
- url: www.omdesign.cz
- version: 1.1
- license: MIT
## TODO
- get information from header
- get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java)
- add
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
dba7d60b8c975750749e8129116b26c307384d07
|
Parser finish
|
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..82d55ce
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,9 @@
+.DS_Store
+.DS_Store?
+._*
+*~
+*.MD5
+*.mwb.bak
+.idea
+/vendor/
+composer.lock
diff --git a/composer.json b/composer.json
new file mode 100644
index 0000000..6158e3f
--- /dev/null
+++ b/composer.json
@@ -0,0 +1,20 @@
+{
+ "name": "om/gpsrinex",
+ "description": "GPS RINEX 2.1 navigation file parser",
+ "license": "MIT",
+ "authors": [
+ {
+ "name": "Roman Ozana",
+ "email": "[email protected]"
+ }
+ ],
+ "require": {
+
+ },
+ "autoload": {
+ "classmap": ["src"]
+ },
+ "require-dev": {
+ "nette/tester": "*"
+ }
+}
diff --git a/readme.md b/readme.md
index ee11250..6db9b8d 100644
--- a/readme.md
+++ b/readme.md
@@ -1,8 +1,18 @@
-# THIS IS GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER
+# GPS RINEX 2.1 Navigation FILE Parser
+
+RINEX (Receiver Independent Exchange)
+More information about format [http://en.wikipedia.org/wiki/RINEX](RINEX)
[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html)
- author: Roman Ozana, [email protected]
- url: www.omdesign.cz
- version: 1.1
-- license: MIT
\ No newline at end of file
+- license: MIT
+
+
+## TODO
+
+- get information from header
+- get some inspiration from [java rinex navigation file parser](https://code.google.com/p/gogps/source/browse/src/main/java/org/gogpsproject/parser/rinex/RinexNavigationParser.java)
+- add
\ No newline at end of file
diff --git a/rinexparser.php b/rinexparser.php
deleted file mode 100644
index 028063d..0000000
--- a/rinexparser.php
+++ /dev/null
@@ -1,288 +0,0 @@
-<?php
-/**
- Copyright (c) <2009> <Roman Ozana, [email protected]>
-
- Permission is hereby granted, free of charge, to any person
- obtaining a copy of this software and associated documentation
- files (the "Software"), to deal in the Software without
- restriction, including without limitation the rights to use,
- copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the
- Software is furnished to do so, subject to the following
- conditions:
-
- The above copyright notice and this permission notice shall be
- included in all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
- OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- OTHER DEALINGS IN THE SOFTWARE.
- */
-
-/**
- *
- * GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER
- *
- * (http://gps.wva.net/html.common/rinex.html)
- * @author Roman Ozana, [email protected]
- * @url www.omdesign.cz
- * @version 1.2
- */
-
-/*
-Use example :
-
-require_once('rinexparser.php');
-
-$rinex = new rinexparser();
-
-$rinex->makelist('./data28');
-
-if ($_GET['load']) // is file load
-{
- $data = $rinex->load_file($_GET['load']); // add data
- $rinex->parse($data); // parse data
- $rinex->print_menu(); // printing menu
-}
-
-for ($i=0;$i<$rinex->counter;$i++) // printing RINEX File Navigation data
-{
- $rinex->print_navi($i);
-}
-*/
-
-class rinexparser {
- public $output = '';
- public $counter = 0;
-
- public function load_file($file) {
- $file_text = file_get_content($file); //load file
- return $file_text;
- }
-
- public function makelist($dir = "") {
- $handle = opendir($dir); // open dir handle
- while ( ($file = readdir($handle)) != false ) {
- if ( ($file != '..') && ($file != '.') && (substr($file, -1, 1) == 'N') ) {
- $files[] = $file;
- }
- }
- if (!empty($files)) {
- sort($files);
- echo '<ol>';
- for($i=0;$i<count($files);$i++) {
- echo '<li><a href="'.$_SERVER['PHP_SELF'].'?load='.$dir.'/'.$files[$i].'">'.$files[$i].'</a></li>';
- }
- echo '</ol>';
- }
- }
-
-
- public function parse($data = '') {
- $this->output = '';
- $data = ereg_replace("D([+|-])", "E\\1", $data);
- $data = spliti("\n",$data);
-
- $header_end = false;
-
- foreach ($data as $row) {
- if ($header_end == true and !empty($row)) // read only data
- {
- $vars = preg_split("/[\s]+/", $row,-1, PREG_SPLIT_NO_EMPTY); // parse text file
- //echo '<pre>';print_r($vars);echo '</pre>';
- switch ($brodcast_counter) {
- case 0:
- $this->output[$this->counter]['prn'] = $vars[0];
- $this->output[$this->counter]['year'] = $vars[1];
- $this->output[$this->counter]['month'] = $vars[2];
- $this->output[$this->counter]['day'] = $vars[3];
- $this->output[$this->counter]['hour'] = $vars[4];
- $this->output[$this->counter]['minute'] = $vars[5];
- $this->output[$this->counter]['second'] = $vars[6];
- $this->output[$this->counter]['SV_clock_bias'] = $vars[7];
- $this->output[$this->counter]['SV_clock_drift'] = $vars[8];
- $this->output[$this->counter]['SV_clock_drift_rate'] = $vars[9];
- break;
- case 1: // BRODCAST ORBIT 1
- $this->output[$this->counter]['IODE'] = $vars[0];
- $this->output[$this->counter]['Crs'] = $vars[1];
- $this->output[$this->counter]['Delta_n'] = $vars[2];
- $this->output[$this->counter]['M0'] = $vars[3];
- break;
- case 2: // BRODCAST ORBIT 2
- $this->output[$this->counter]['Cuc'] = $vars[0];
- $this->output[$this->counter]['e'] = $vars[1];
- $this->output[$this->counter]['Cus'] = $vars[2];
- $this->output[$this->counter]['sqrtA'] = $vars[3];
- break;
- case 3: // BRODCAST ORBIT 3
- $this->output[$this->counter]['Toe'] = $vars[0];
- $this->output[$this->counter]['Cic'] = $vars[1];
- $this->output[$this->counter]['OMEGA'] = $vars[2];
- $this->output[$this->counter]['CIS'] = $vars[3];
- break;
- case 4: // BRODCAST ORBIT 4
- $this->output[$this->counter]['i0'] = $vars[0];
- $this->output[$this->counter]['Crc'] = $vars[1];
- $this->output[$this->counter]['omega'] = $vars[2]; // normal is omega
- $this->output[$this->counter]['OMEGA_DOT'] = $vars[3];
- break;
- case 5: // BRODCAST ORBIT 5
- $this->output[$this->counter]['IDOT'] = $vars[0];
- $this->output[$this->counter]['Codes_on_L2_ch'] = $vars[1];
- $this->output[$this->counter]['GPS_week']= $vars[2];
- $this->output[$this->counter]['L2_p_data_flag'] = $vars[3];
- break;
- case 6: // BRODCAST ORBIT 6
- $this->output[$this->counter]['SV_accuracy'] = $vars[0];
- $this->output[$this->counter]['SV_health'] = $vars[1];
- $this->output[$this->counter]['TGD'] = $vars[2];
- $this->output[$this->counter]['IODC'] = $vars[3];
- break;
- case 7: // BRODCAST ORBIT 6
- $this->output[$this->counter]['Transmission_time'] = $vars[0];
- $this->output[$this->counter]['Fit_interval'] = $vars[1];
- $this->output[$this->counter]['spare_01'] = $vars[2];
- $this->output[$this->counter]['spare_02'] = $vars[3];
- $this->counter++;
- $brodcast_counter = -1; // don't forget clear counter
- break;
- default:
- break;
- }
- $brodcast_counter++; // number of brodcast
- } // is after head ?? - read data
- if (stristr($row,'END OF HEADER')) {
- $header_end = true; // end of header
- $brodcast_counter = 0;
- }
- }
- // echo '<pre>';print_r($this->output);echo '</pre>';
- return $this->output;
- }
-
- public function print_menu() {
- echo '<ol>';
- for($i=0;$i<$this->counter;$i++) {
- $gps = $this->output[$i];
- echo '<li><a href="#gps'.$i.$gps['prn'].'">GPS '.$gps['prn'].'</a> - '.$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute'].'</li>';
- }
- echo '</ol>';
- }
-
- public function print_navi($number = 0) {
- if (count($this->output) < $number) {
- return;
- }
- $gps = $this->output[$number];
-
- echo '<h2><a name="gps'.$number.$gps['prn'].'"></a>Navigacni informace GPS : '.$gps['prn'].'</h2>';
- echo '<table border="1" cellspacing="0" cellpadding="7" width="80%">';
- // PRN info
- $this->add_lin('Promenna','Hodnota','Jednotky','th');
- $this->add_lin('GPS',$gps['prn']);
- $this->add_lin('Epocha : Datum a cas',$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute']);
- $this->add_lin('SV clock bias',$gps['SV_clock_bias'],'sec');
- $this->add_lin('SV clock drift',$gps['SV_clock_drift'],'sec/sec');
- $this->add_lin('SV clock drift rate',$gps['SV_clock_drift_rate'],'sec/sec<sup>2</sup>');
- // BRODCAST 01
- $this->add_lin('',' ','');
- $this->add_lin('IODE Issue of data',$gps['IODE']);
- $this->add_lin('C<sub>rs</sub>',$gps['Crs'],'m');
- $this->add_lin('Delta n',$gps['Delta_n'],'radiany/sec');
- $this->add_lin('M<sub>0</sub>',$gps['M0'],'radiany');
- // BRODCAST 02
- $this->add_lin('',' ','');
- $this->add_lin('C<sub>uc</sub>',$gps['Cuc'],'radiany');
- $this->add_lin('Excentricita e',$gps['e'],'-');
- $this->add_lin('C<sub>us</sub>',$gps['Cus'],'radiany');
- $this->add_lin('sqrt(A)',$gps['sqrtA'],'sqrt(m)');
- // BRODCAST 03
- $this->add_lin('',' ','');
- $this->add_lin('T<sub>oe</sub>',$gps['Toe'],'sec of GPS week');
- $this->add_lin('C<sub>ic</sub>',$gps['Cic'],'radiany');
- $this->add_lin('OMEGA',$gps['OMEGA'],'radiany');
- $this->add_lin('CIS',$gps['CIS'],'radiany');
- // BRODCAST 04
- $this->add_lin('',' ','');
- $this->add_lin('i<sub>0</sub>',$gps['i0'],'radiany');
- $this->add_lin('C<sub>rc</sub>',$gps['Crc'],'radiany');
- $this->add_lin('omega',$gps['omega'],'radiany');
- $this->add_lin('OMEGA DOT',$gps['OMEGA_DOT'],'radiany/sec');
- // BRODCAST 05
- $this->add_lin('',' ','');
- $this->add_lin('IDOT',$gps['IDOT'],'radiany/sec');
- $this->add_lin('Codes on L2 channel',$gps['Codes_on_L2_ch']);
- $this->add_lin('GPS week',$gps['GPS_week']);
- $this->add_lin('L2 p data flag',$gps['L2_p_data_flag']);
- // BRODCAST 06
- $this->add_lin('',' ','');
- $this->add_lin('SV accuracy',$gps['SV_accuracy'],'metry');
- $this->add_lin('SV health',$gps['SV_health']);
- $this->add_lin('TGD',$gps['TGD'],'sec');
- $this->add_lin('IODC Issue of Data, Clock',$gps['IODC']);
- // BRODCAST 07
- $this->add_lin('',' ','');
- $this->add_lin('Transmission time of message',$gps['Transmission_time'],'radiany');
- $this->add_lin('Fit interval',$gps['Fit_interval'],'hodin');
- $this->add_lin('Spare',$gps['spare_01']);
- $this->add_lin('Spare',$gps['spare_02']);
- echo '</table>';
- }
-
- public function add_lin($coment, $value, $unit = '',$td = 'td') {
- if (!empty($unit) and $td == 'td') {
- $unit = '('.$unit.')';
- }
- echo "<tr><$td style=&qout;text-align:right;&qout;>$coment</$td><$td>$value</$td><$td>$unit</$td></tr>\n";
- }
- /*
- RINEX file upload not work yet - some errors i don't know
- function storefile($var, $location, $filename=NULL, $maxfilesize=NULL) {
- $ok = false;
-
- // Check file
- $mime = $_FILES[$var]["type"];
- if($mime=="image/jpeg" || $mime=="image/pjpeg") {
- // Mime type is correct
- // Check extension
- $name = $_FILES[$var]["name"];
- $array = explode(".", $name);
- $nr = count($array);
- $ext = $array[$nr-1];
- if($ext=="jpg" || $ext=="jpeg") {
- $ok = true;
- }
- }
-
- if(isset($maxfilesize)) {
- if($_FILES[$var]["size"] > $maxfilesize) {
- $ok = false;
- }
- }
-
- if($ok==true) {
- $tempname = $_FILES[$var]['tmp_name'];
- if(isset($filename)) {
- $uploadpath = $location.$filename;
- } else {
- $uploadpath = $location.$_FILES[$var]['name'];
- }
- if(is_uploaded_file($_FILES[$var]['tmp_name'])) {
- while(move_uploaded_file($tempname, $uploadpath)) {
- // Wait for the script to finish its upload
- }
- }
- return true;
- } else {
- return false;
- }
- }
- */
-
-}
\ No newline at end of file
diff --git a/src/RinexNavigationParser.php b/src/RinexNavigationParser.php
new file mode 100644
index 0000000..a3ee9a7
--- /dev/null
+++ b/src/RinexNavigationParser.php
@@ -0,0 +1,130 @@
+<?php
+namespace om;
+
+/**
+ * RINEX Navigation Parser
+ *
+ * @copyright Roman Ožana <[email protected]>
+ * @license MIT
+ * @package om
+ */
+class RinexNavigationParser {
+
+ /** @var int */
+ private $boradcast = 1;
+
+ /**
+ * @param sting $file
+ * @param callable $callback
+ * @throws \RuntimeException
+ * @return string|mixed
+ */
+ public function parseFile($file, $callback = null) {
+ $body = false; // each file starts with Header
+ $output = array(); // output data
+ $this->boradcast = 1;
+ $counter = 0;
+
+ if (!$handle = fopen($file, "r")) {
+ throw new \RuntimeException('Can\'t open file' . $file . ' fore reading');
+ }
+
+ while (!feof($handle)) {
+ $row = fgets($handle, 4096); // read line from file
+
+ if ($body && !empty($row)) {
+ $partial = $this->parseRow($row); // read line
+
+
+ if ($callback) {
+ call_user_func($callback, $partial, $counter, $this->boradcast); // call user function for processing line
+ } else {
+ $output[$counter][] = $partial; // return whole data
+ }
+
+ if ($this->boradcast === 1) $counter++; // count
+ }
+
+ if (preg_match('/END OF HEADER/', $row)) $body = true; // end of header
+ }
+
+ fclose($handle);
+ return ($callback) ? null : $output;
+ }
+
+ /**
+ * @param string $row
+ * @return string
+ */
+ public function parseRow($row = '') {
+ $output = array();
+ $row = preg_replace('/D([+|-])/', 'E\1', $row);
+ $data = preg_split("/[\s]+/", $row, -1, PREG_SPLIT_NO_EMPTY);
+
+ switch ($this->boradcast++) {
+ case 1:
+ return array(
+ 'PRN' => $data[0],
+ 'year' => $data[1],
+ 'month' => $data[2],
+ 'day' => $data[3],
+ 'hour' => $data[4],
+ 'minute' => $data[5],
+ 'second' => $data[6],
+ 'SV_clock_bias' => $data[7],
+ 'SV_clock_drift' => $data[8],
+ 'SV_clock_drift_rate' => $data[9],
+ );
+ case 2: // BRODCAST ORBIT 1
+ return array(
+ 'IODE' => $data[0],
+ 'Crs' => $data[1],
+ 'Delta_n' => $data[2],
+ 'M0' => $data[3],
+ );
+ case 3: // BRODCAST ORBIT 2
+ return array(
+ 'Cuc' => $data[0],
+ 'e' => $data[1],
+ 'Cus' => $data[2],
+ 'sqrtA' => $data[3],
+ );
+ case 4: // BRODCAST ORBIT 3
+ return array(
+ 'Toe' => $data[0],
+ 'Cic' => $data[1],
+ 'OMEGA' => $data[2],
+ 'CIS' => $data[3],
+ );
+ case 5: // BRODCAST ORBIT 4
+ return array(
+ 'i0' => $data[0],
+ 'Crc' => $data[1],
+ 'omega' => $data[2], // normal is omega
+ 'OMEGA_DOT' => $data[3],
+ );
+ case 6: // BRODCAST ORBIT 5
+ return array(
+ 'IDOT' => $data[0],
+ 'Codes_on_L2_ch' => $data[1],
+ 'GPS_week' => $data[2],
+ 'L2_p_data_flag' => $data[3],
+ );
+ case 7: // BRODCAST ORBIT 6
+ return array(
+ 'SV_accuracy' => $data[0],
+ 'SV_health' => $data[1],
+ 'TGD' => $data[2],
+ 'IODC' => $data[3],
+ );
+ case 8: // BRODCAST ORBIT 6
+ $this->boradcast = 1;
+ return array(
+ 'Transmission_time' => $data[0],
+ 'Fit_interval' => $data[1],
+ 'spare_01' => $data[2],
+ 'spare_02' => $data[3],
+ );
+ }
+ }
+}
\ No newline at end of file
diff --git a/tests/ParserTest.phpt b/tests/ParserTest.phpt
new file mode 100644
index 0000000..b793141
--- /dev/null
+++ b/tests/ParserTest.phpt
@@ -0,0 +1,17 @@
+<?php
+use Tester\Assert;
+
+require_once __DIR__ . '/../vendor/autoload.php';
+
+$parser = new \om\RinexNavigationParser();
+
+$data = $parser->parseFile(__DIR__ . '/data/LongNumberExample.obs');
+
+
+
+
+Assert::same('6', $data[0][0]['PRN']);
+Assert::same('-.165982783074E-10', $data[0][0]['SV_clock_drift']);
+Assert::same('.000000000000E+00', $data[0][0]['SV_clock_drift_rate']);
+
+Assert::same(4, count($data));
\ No newline at end of file
diff --git a/tests/data/LongNumberExample.obs b/tests/data/LongNumberExample.obs
new file mode 100644
index 0000000..37e0639
--- /dev/null
+++ b/tests/data/LongNumberExample.obs
@@ -0,0 +1,40 @@
+ 2.10 N: GPS NAV DATA RINEX VERSION / TYPE
+XXRINEXN V2.10 AIUB 3-SEP-99 15:22 PGM / RUN BY / DATE
+EXAMPLE OF VERSION 2.10 FORMAT COMMENT
+ .1676D-07 .2235D-07 -.1192D-06 -.1192D-06 ION ALPHA
+ .1208D+06 .1310D+06 -.1310D+06 -.1966D+06 ION BETA
+ .133179128170D-06 .107469588780D-12 552960 1025 DELTA-UTC: A0,A1,T,W
+ 13 LEAP SECONDS
+ END OF HEADER
+ 6 99 9 2 17 51 44.0 -.839701388031D-03 -.165982783074D-10 .000000000000D+00
+ .910000000000D+02 .934062500000D+02 .116040547840D-08 .162092304801D+00
+ .484101474285D-05 .626740418375D-02 .652112066746D-05 .515365489006D+04
+ .409904000000D+06 -.242143869400D-07 .329237003460D+00 -.596046447754D-07
+ .111541663136D+01 .326593750000D+03 .206958726335D+01 -.638312302555D-08
+ .307155651409D-09 .000000000000D+00 .102500000000D+04 .000000000000D+00
+ .000000000000D+00 .000000000000D+00 .000000000000D+00 .910000000000D+02
+ .406800000000D+06 .000000000000D+00
+13 99 9 2 19 0 0.0 .490025617182D-03 .204636307899D-11 .000000000000D+00
+ .133000000000D+03 -.963125000000D+02 .146970407622D-08 .292961152146D+01
+ -.498816370964D-05 .200239347760D-02 .928156077862D-05 .515328476143D+04
+ .414000000000D+06 -.279396772385D-07 .243031939942D+01 -.558793544769D-07
+ .110192796930D+01 .271187500000D+03 -.232757915425D+01 -.619632953057D-08
+ -.785747015231D-11 .000000000000D+00 .102500000000D+04 .000000000000D+00
+ .000000000000D+00 .000000000000D+00 .000000000000D+00 .389000000000D+03
+ .410400000000D+06 .000000000000D+00
+ 6 99 9 2 17 51 44.0 -.839701388031D-03 -.165982783074D-10 .000000000000D+00
+ .910000000000D+02 .934062500000D+02 .116040547840D-08 .162092304801D+00
+ .484101474285D-05 .626740418375D-02 .652112066746D-05 .515365489006D+04
+ .409904000000D+06 -.242143869400D-07 .329237003460D+00 -.596046447754D-07
+ .111541663136D+01 .326593750000D+03 .206958726335D+01 -.638312302555D-08
+ .307155651409D-09 .000000000000D+00 .102500000000D+04 .000000000000D+00
+ .000000000000D+00 .000000000000D+00 .000000000000D+00 .910000000000D+02
+ .406800000000D+06 .000000000000D+00
+13 99 9 2 19 0 0.0 .490025617182D-03 .204636307899D-11 .000000000000D+00
+ .133000000000D+03 -.963125000000D+02 .146970407622D-08 .292961152146D+01
+ -.498816370964D-05 .200239347760D-02 .928156077862D-05 .515328476143D+04
+ .414000000000D+06 -.279396772385D-07 .243031939942D+01 -.558793544769D-07
+ .110192796930D+01 .271187500000D+03 -.232757915425D+01 -.619632953057D-08
+ -.785747015231D-11 .000000000000D+00 .102500000000D+04 .000000000000D+00
+ .000000000000D+00 .000000000000D+00 .000000000000D+00 .389000000000D+03
+ .410400000000D+06 .000000000000D+00
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
b1bfc3f2ce59c6ccbb09f591a420f21fd5698687
|
Add license
|
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..458df4f
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,21 @@
+The MIT License (MIT)
+
+Copyright (c) 2013 Roman Ožana
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
|
OzzyCzech/gpsrinex
|
2035bbb98166c71909592bf62f4fffb97bb99879
|
Fix readme
|
diff --git a/README b/README
deleted file mode 100644
index 708da39..0000000
--- a/README
+++ /dev/null
@@ -1,7 +0,0 @@
-THIS IS GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER
-(http://gps.wva.net/html.common/rinex.html)
-
-author: Roman Ozana, [email protected]
-url: www.omdesign.cz
-version: 1.1
-license: MIT
\ No newline at end of file
diff --git a/readme.md b/readme.md
new file mode 100644
index 0000000..ee11250
--- /dev/null
+++ b/readme.md
@@ -0,0 +1,8 @@
+# THIS IS GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER
+
+[http://gps.wva.net/html.common/rinex.html](http://gps.wva.net/html.common/rinex.html)
+
+- author: Roman Ozana, [email protected]
+- url: www.omdesign.cz
+- version: 1.1
+- license: MIT
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
0b67571ce3ba1fe9f6f4d3ba9797eaf7c65a526b
|
add public before every function
|
diff --git a/README b/README
index 98b893b..708da39 100644
--- a/README
+++ b/README
@@ -1 +1,7 @@
-THIS IS GPS RINEX FILE PARSER
\ No newline at end of file
+THIS IS GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER
+(http://gps.wva.net/html.common/rinex.html)
+
+author: Roman Ozana, [email protected]
+url: www.omdesign.cz
+version: 1.1
+license: MIT
\ No newline at end of file
diff --git a/rinexparser.php b/rinexparser.php
index 5d3f468..028063d 100644
--- a/rinexparser.php
+++ b/rinexparser.php
@@ -1,298 +1,288 @@
<?php
-################################################################################
-# DATE : 06.03.2006 #
-# Short description : #
-# #
-# GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER #
-# (http://gps.wva.net/html.common/rinex.html) #
-# #
-# Version info : #
-# #
-# rinexparser CLASS VERSION 1.0 #
-# #
-# Author info : #
-# #
-# ROMAN OŽANA (c) 2006 #
-# ICQ (99950132) #
-# WWW (www.nabito.net) #
-# E-mail ([email protected] ) #
-# #
-# Country: #
-# #
-# CZECH REPUBLIC #
-# #
-# Licence: #
-# #
-# IF YOU WANT USE THIS CODE PLEASE CONNECT AUTHOR, Thank You #
-# #
-# it was written in SCITE #
-################################################################################
+/**
+ Copyright (c) <2009> <Roman Ozana, [email protected]>
+
+ Permission is hereby granted, free of charge, to any person
+ obtaining a copy of this software and associated documentation
+ files (the "Software"), to deal in the Software without
+ restriction, including without limitation the rights to use,
+ copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the
+ Software is furnished to do so, subject to the following
+ conditions:
+
+ The above copyright notice and this permission notice shall be
+ included in all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+ OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+ HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+ WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+ OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+/**
+ *
+ * GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER
+ *
+ * (http://gps.wva.net/html.common/rinex.html)
+ * @author Roman Ozana, [email protected]
+ * @url www.omdesign.cz
+ * @version 1.2
+ */
+
/*
- Use example :
-
- require_once('rinexparser.php');
-
- $rinex = new rinexparser();
-
- $rinex->makelist('./data28');
-
- if ($_GET['load']) // is file load
- {
- $data = $rinex->load_file($_GET['load']); // add data
- $rinex->parse($data); // parse data
- $rinex->print_menu(); // printing menu
- }
-
- for ($i=0;$i<$rinex->counter;$i++) // printing RINEX File Navigation data
- {
- $rinex->print_navi($i);
- }
+Use example :
+
+require_once('rinexparser.php');
+
+$rinex = new rinexparser();
+
+$rinex->makelist('./data28');
+
+if ($_GET['load']) // is file load
+{
+ $data = $rinex->load_file($_GET['load']); // add data
+ $rinex->parse($data); // parse data
+ $rinex->print_menu(); // printing menu
+}
+
+for ($i=0;$i<$rinex->counter;$i++) // printing RINEX File Navigation data
+{
+ $rinex->print_navi($i);
+}
*/
- class rinexparser
- {
- public $output = '';
- public $counter = 0;
-
- function load_file($file)
- {
- $file_text = join ("", file ($file)); //load file
- return $file_text;
- }
-
- function makelist($dir = "")
- {
- $handle = opendir($dir); // open dir handle
- while ( ($file = readdir($handle)) != false )
- {
- if ( ($file != '..') && ($file != '.') && (substr($file, -1, 1) == 'N') )
- {
- $files[] = $file;
- }
- }
- if (!empty($files))
- {
- sort($files);
- echo '<ol>';
- for($i=0;$i<count($files);$i++)
- {
- echo '<li><a href="'.$_SERVER['PHP_SELF'].'?load='.$dir.'/'.$files[$i].'">'.$files[$i].'</a></li>';
- }
- echo '</ol>';
- }
- }
-
-
- function parse($data = '')
- {
- $this->output = '';
- $data = ereg_replace("D([+|-])", "E\\1", $data);
- $data = spliti("\n",$data);
-
- $header_end = false;
-
- foreach ($data as $row)
- {
- if ($header_end == true and !empty($row)) // read only data
- {
- $vars = preg_split("/[\s]+/", $row,-1, PREG_SPLIT_NO_EMPTY); // parse text file
- //echo '<pre>';print_r($vars);echo '</pre>';
- switch ($brodcast_counter)
- {
- case 0:
- $this->output[$this->counter]['prn'] = $vars[0];
- $this->output[$this->counter]['year'] = $vars[1];
- $this->output[$this->counter]['month'] = $vars[2];
- $this->output[$this->counter]['day'] = $vars[3];
- $this->output[$this->counter]['hour'] = $vars[4];
- $this->output[$this->counter]['minute'] = $vars[5];
- $this->output[$this->counter]['second'] = $vars[6];
- $this->output[$this->counter]['SV_clock_bias'] = $vars[7];
- $this->output[$this->counter]['SV_clock_drift'] = $vars[8];
- $this->output[$this->counter]['SV_clock_drift_rate'] = $vars[9];
- break;
- case 1: // BRODCAST ORBIT 1
- $this->output[$this->counter]['IODE'] = $vars[0];
- $this->output[$this->counter]['Crs'] = $vars[1];
- $this->output[$this->counter]['Delta_n'] = $vars[2];
- $this->output[$this->counter]['M0'] = $vars[3];
- break;
- case 2: // BRODCAST ORBIT 2
- $this->output[$this->counter]['Cuc'] = $vars[0];
- $this->output[$this->counter]['e'] = $vars[1];
- $this->output[$this->counter]['Cus'] = $vars[2];
- $this->output[$this->counter]['sqrtA'] = $vars[3];
- break;
- case 3: // BRODCAST ORBIT 3
- $this->output[$this->counter]['Toe'] = $vars[0];
- $this->output[$this->counter]['Cic'] = $vars[1];
- $this->output[$this->counter]['OMEGA'] = $vars[2];
- $this->output[$this->counter]['CIS'] = $vars[3];
- break;
- case 4: // BRODCAST ORBIT 4
- $this->output[$this->counter]['i0'] = $vars[0];
- $this->output[$this->counter]['Crc'] = $vars[1];
- $this->output[$this->counter]['omega'] = $vars[2]; // normal is omega
- $this->output[$this->counter]['OMEGA_DOT'] = $vars[3];
- break;
- case 5: // BRODCAST ORBIT 5
- $this->output[$this->counter]['IDOT'] = $vars[0];
- $this->output[$this->counter]['Codes_on_L2_ch'] = $vars[1];
- $this->output[$this->counter]['GPS_week']= $vars[2];
- $this->output[$this->counter]['L2_p_data_flag'] = $vars[3];
- break;
- case 6: // BRODCAST ORBIT 6
- $this->output[$this->counter]['SV_accuracy'] = $vars[0];
- $this->output[$this->counter]['SV_health'] = $vars[1];
- $this->output[$this->counter]['TGD'] = $vars[2];
- $this->output[$this->counter]['IODC'] = $vars[3];
- break;
- case 7: // BRODCAST ORBIT 6
- $this->output[$this->counter]['Transmission_time'] = $vars[0];
- $this->output[$this->counter]['Fit_interval'] = $vars[1];
- $this->output[$this->counter]['spare_01'] = $vars[2];
- $this->output[$this->counter]['spare_02'] = $vars[3];
- $this->counter++;
- $brodcast_counter = -1; // don't forget clear counter
- break;
- default:
- break;
- }
- $brodcast_counter++; // number of brodcast
- } // is after head ?? - read data
- if (stristr($row,'END OF HEADER'))
- {
- $header_end = true; // end of header
- $brodcast_counter = 0;
- }
- }
- // echo '<pre>';print_r($this->output);echo '</pre>';
- return $this->output;
- }
-
- function print_menu()
- {
- echo '<ol>';
- for($i=0;$i<$this->counter;$i++)
- {
- $gps = $this->output[$i];
- echo '<li><a href="#gps'.$i.$gps['prn'].'">GPS '.$gps['prn'].'</a> - '.$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute'].'</li>';
- }
- echo '</ol>';
- }
-
- function print_navi($number = 0)
- {
- if (count($this->output) < $number)
- {
- return;
- }
- $gps = $this->output[$number];
-
- echo '<h2><a name="gps'.$number.$gps['prn'].'"></a>Navigacni informace GPS : '.$gps['prn'].'</h2>';
- echo '<table border="1" cellspacing="0" cellpadding="7" width="80%">';
- // PRN info
- $this->add_lin('Promenna','Hodnota','Jednotky','th');
- $this->add_lin('GPS',$gps['prn']);
- $this->add_lin('Epocha : Datum a cas',$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute']);
- $this->add_lin('SV clock bias',$gps['SV_clock_bias'],'sec');
- $this->add_lin('SV clock drift',$gps['SV_clock_drift'],'sec/sec');
- $this->add_lin('SV clock drift rate',$gps['SV_clock_drift_rate'],'sec/sec<sup>2</sup>');
- // BRODCAST 01
- $this->add_lin('',' ','');
- $this->add_lin('IODE Issue of data',$gps['IODE']);
- $this->add_lin('C<sub>rs</sub>',$gps['Crs'],'m');
- $this->add_lin('Delta n',$gps['Delta_n'],'radiany/sec');
- $this->add_lin('M<sub>0</sub>',$gps['M0'],'radiany');
- // BRODCAST 02
- $this->add_lin('',' ','');
- $this->add_lin('C<sub>uc</sub>',$gps['Cuc'],'radiany');
- $this->add_lin('Excentricita e',$gps['e'],'-');
- $this->add_lin('C<sub>us</sub>',$gps['Cus'],'radiany');
- $this->add_lin('sqrt(A)',$gps['sqrtA'],'sqrt(m)');
- // BRODCAST 03
- $this->add_lin('',' ','');
- $this->add_lin('T<sub>oe</sub>',$gps['Toe'],'sec of GPS week');
- $this->add_lin('C<sub>ic</sub>',$gps['Cic'],'radiany');
- $this->add_lin('OMEGA',$gps['OMEGA'],'radiany');
- $this->add_lin('CIS',$gps['CIS'],'radiany');
- // BRODCAST 04
- $this->add_lin('',' ','');
- $this->add_lin('i<sub>0</sub>',$gps['i0'],'radiany');
- $this->add_lin('C<sub>rc</sub>',$gps['Crc'],'radiany');
- $this->add_lin('omega',$gps['omega'],'radiany');
- $this->add_lin('OMEGA DOT',$gps['OMEGA_DOT'],'radiany/sec');
- // BRODCAST 05
- $this->add_lin('',' ','');
- $this->add_lin('IDOT',$gps['IDOT'],'radiany/sec');
- $this->add_lin('Codes on L2 channel',$gps['Codes_on_L2_ch']);
- $this->add_lin('GPS week',$gps['GPS_week']);
- $this->add_lin('L2 p data flag',$gps['L2_p_data_flag']);
- // BRODCAST 06
- $this->add_lin('',' ','');
- $this->add_lin('SV accuracy',$gps['SV_accuracy'],'metry');
- $this->add_lin('SV health',$gps['SV_health']);
- $this->add_lin('TGD',$gps['TGD'],'sec');
- $this->add_lin('IODC Issue of Data, Clock',$gps['IODC']);
- // BRODCAST 07
- $this->add_lin('',' ','');
- $this->add_lin('Transmission time of message',$gps['Transmission_time'],'radiany');
- $this->add_lin('Fit interval',$gps['Fit_interval'],'hodin');
- $this->add_lin('Spare',$gps['spare_01']);
- $this->add_lin('Spare',$gps['spare_02']);
- echo '</table>';
- }
-
- function add_lin($coment, $value, $unit = '',$td = 'td')
- {
- if (!empty($unit) and $td == 'td')
- {
- $unit = '('.$unit.')';
- }
- echo "<tr><$td style=&qout;text-align:right;&qout;>$coment</$td><$td>$value</$td><$td>$unit</$td></tr>\n";
- }
+
+class rinexparser {
+ public $output = '';
+ public $counter = 0;
+
+ public function load_file($file) {
+ $file_text = file_get_content($file); //load file
+ return $file_text;
+ }
+
+ public function makelist($dir = "") {
+ $handle = opendir($dir); // open dir handle
+ while ( ($file = readdir($handle)) != false ) {
+ if ( ($file != '..') && ($file != '.') && (substr($file, -1, 1) == 'N') ) {
+ $files[] = $file;
+ }
+ }
+ if (!empty($files)) {
+ sort($files);
+ echo '<ol>';
+ for($i=0;$i<count($files);$i++) {
+ echo '<li><a href="'.$_SERVER['PHP_SELF'].'?load='.$dir.'/'.$files[$i].'">'.$files[$i].'</a></li>';
+ }
+ echo '</ol>';
+ }
+ }
+
+
+ public function parse($data = '') {
+ $this->output = '';
+ $data = ereg_replace("D([+|-])", "E\\1", $data);
+ $data = spliti("\n",$data);
+
+ $header_end = false;
+
+ foreach ($data as $row) {
+ if ($header_end == true and !empty($row)) // read only data
+ {
+ $vars = preg_split("/[\s]+/", $row,-1, PREG_SPLIT_NO_EMPTY); // parse text file
+ //echo '<pre>';print_r($vars);echo '</pre>';
+ switch ($brodcast_counter) {
+ case 0:
+ $this->output[$this->counter]['prn'] = $vars[0];
+ $this->output[$this->counter]['year'] = $vars[1];
+ $this->output[$this->counter]['month'] = $vars[2];
+ $this->output[$this->counter]['day'] = $vars[3];
+ $this->output[$this->counter]['hour'] = $vars[4];
+ $this->output[$this->counter]['minute'] = $vars[5];
+ $this->output[$this->counter]['second'] = $vars[6];
+ $this->output[$this->counter]['SV_clock_bias'] = $vars[7];
+ $this->output[$this->counter]['SV_clock_drift'] = $vars[8];
+ $this->output[$this->counter]['SV_clock_drift_rate'] = $vars[9];
+ break;
+ case 1: // BRODCAST ORBIT 1
+ $this->output[$this->counter]['IODE'] = $vars[0];
+ $this->output[$this->counter]['Crs'] = $vars[1];
+ $this->output[$this->counter]['Delta_n'] = $vars[2];
+ $this->output[$this->counter]['M0'] = $vars[3];
+ break;
+ case 2: // BRODCAST ORBIT 2
+ $this->output[$this->counter]['Cuc'] = $vars[0];
+ $this->output[$this->counter]['e'] = $vars[1];
+ $this->output[$this->counter]['Cus'] = $vars[2];
+ $this->output[$this->counter]['sqrtA'] = $vars[3];
+ break;
+ case 3: // BRODCAST ORBIT 3
+ $this->output[$this->counter]['Toe'] = $vars[0];
+ $this->output[$this->counter]['Cic'] = $vars[1];
+ $this->output[$this->counter]['OMEGA'] = $vars[2];
+ $this->output[$this->counter]['CIS'] = $vars[3];
+ break;
+ case 4: // BRODCAST ORBIT 4
+ $this->output[$this->counter]['i0'] = $vars[0];
+ $this->output[$this->counter]['Crc'] = $vars[1];
+ $this->output[$this->counter]['omega'] = $vars[2]; // normal is omega
+ $this->output[$this->counter]['OMEGA_DOT'] = $vars[3];
+ break;
+ case 5: // BRODCAST ORBIT 5
+ $this->output[$this->counter]['IDOT'] = $vars[0];
+ $this->output[$this->counter]['Codes_on_L2_ch'] = $vars[1];
+ $this->output[$this->counter]['GPS_week']= $vars[2];
+ $this->output[$this->counter]['L2_p_data_flag'] = $vars[3];
+ break;
+ case 6: // BRODCAST ORBIT 6
+ $this->output[$this->counter]['SV_accuracy'] = $vars[0];
+ $this->output[$this->counter]['SV_health'] = $vars[1];
+ $this->output[$this->counter]['TGD'] = $vars[2];
+ $this->output[$this->counter]['IODC'] = $vars[3];
+ break;
+ case 7: // BRODCAST ORBIT 6
+ $this->output[$this->counter]['Transmission_time'] = $vars[0];
+ $this->output[$this->counter]['Fit_interval'] = $vars[1];
+ $this->output[$this->counter]['spare_01'] = $vars[2];
+ $this->output[$this->counter]['spare_02'] = $vars[3];
+ $this->counter++;
+ $brodcast_counter = -1; // don't forget clear counter
+ break;
+ default:
+ break;
+ }
+ $brodcast_counter++; // number of brodcast
+ } // is after head ?? - read data
+ if (stristr($row,'END OF HEADER')) {
+ $header_end = true; // end of header
+ $brodcast_counter = 0;
+ }
+ }
+ // echo '<pre>';print_r($this->output);echo '</pre>';
+ return $this->output;
+ }
+
+ public function print_menu() {
+ echo '<ol>';
+ for($i=0;$i<$this->counter;$i++) {
+ $gps = $this->output[$i];
+ echo '<li><a href="#gps'.$i.$gps['prn'].'">GPS '.$gps['prn'].'</a> - '.$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute'].'</li>';
+ }
+ echo '</ol>';
+ }
+
+ public function print_navi($number = 0) {
+ if (count($this->output) < $number) {
+ return;
+ }
+ $gps = $this->output[$number];
+
+ echo '<h2><a name="gps'.$number.$gps['prn'].'"></a>Navigacni informace GPS : '.$gps['prn'].'</h2>';
+ echo '<table border="1" cellspacing="0" cellpadding="7" width="80%">';
+ // PRN info
+ $this->add_lin('Promenna','Hodnota','Jednotky','th');
+ $this->add_lin('GPS',$gps['prn']);
+ $this->add_lin('Epocha : Datum a cas',$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute']);
+ $this->add_lin('SV clock bias',$gps['SV_clock_bias'],'sec');
+ $this->add_lin('SV clock drift',$gps['SV_clock_drift'],'sec/sec');
+ $this->add_lin('SV clock drift rate',$gps['SV_clock_drift_rate'],'sec/sec<sup>2</sup>');
+ // BRODCAST 01
+ $this->add_lin('',' ','');
+ $this->add_lin('IODE Issue of data',$gps['IODE']);
+ $this->add_lin('C<sub>rs</sub>',$gps['Crs'],'m');
+ $this->add_lin('Delta n',$gps['Delta_n'],'radiany/sec');
+ $this->add_lin('M<sub>0</sub>',$gps['M0'],'radiany');
+ // BRODCAST 02
+ $this->add_lin('',' ','');
+ $this->add_lin('C<sub>uc</sub>',$gps['Cuc'],'radiany');
+ $this->add_lin('Excentricita e',$gps['e'],'-');
+ $this->add_lin('C<sub>us</sub>',$gps['Cus'],'radiany');
+ $this->add_lin('sqrt(A)',$gps['sqrtA'],'sqrt(m)');
+ // BRODCAST 03
+ $this->add_lin('',' ','');
+ $this->add_lin('T<sub>oe</sub>',$gps['Toe'],'sec of GPS week');
+ $this->add_lin('C<sub>ic</sub>',$gps['Cic'],'radiany');
+ $this->add_lin('OMEGA',$gps['OMEGA'],'radiany');
+ $this->add_lin('CIS',$gps['CIS'],'radiany');
+ // BRODCAST 04
+ $this->add_lin('',' ','');
+ $this->add_lin('i<sub>0</sub>',$gps['i0'],'radiany');
+ $this->add_lin('C<sub>rc</sub>',$gps['Crc'],'radiany');
+ $this->add_lin('omega',$gps['omega'],'radiany');
+ $this->add_lin('OMEGA DOT',$gps['OMEGA_DOT'],'radiany/sec');
+ // BRODCAST 05
+ $this->add_lin('',' ','');
+ $this->add_lin('IDOT',$gps['IDOT'],'radiany/sec');
+ $this->add_lin('Codes on L2 channel',$gps['Codes_on_L2_ch']);
+ $this->add_lin('GPS week',$gps['GPS_week']);
+ $this->add_lin('L2 p data flag',$gps['L2_p_data_flag']);
+ // BRODCAST 06
+ $this->add_lin('',' ','');
+ $this->add_lin('SV accuracy',$gps['SV_accuracy'],'metry');
+ $this->add_lin('SV health',$gps['SV_health']);
+ $this->add_lin('TGD',$gps['TGD'],'sec');
+ $this->add_lin('IODC Issue of Data, Clock',$gps['IODC']);
+ // BRODCAST 07
+ $this->add_lin('',' ','');
+ $this->add_lin('Transmission time of message',$gps['Transmission_time'],'radiany');
+ $this->add_lin('Fit interval',$gps['Fit_interval'],'hodin');
+ $this->add_lin('Spare',$gps['spare_01']);
+ $this->add_lin('Spare',$gps['spare_02']);
+ echo '</table>';
+ }
+
+ public function add_lin($coment, $value, $unit = '',$td = 'td') {
+ if (!empty($unit) and $td == 'td') {
+ $unit = '('.$unit.')';
+ }
+ echo "<tr><$td style=&qout;text-align:right;&qout;>$coment</$td><$td>$value</$td><$td>$unit</$td></tr>\n";
+ }
/*
RINEX file upload not work yet - some errors i don't know
function storefile($var, $location, $filename=NULL, $maxfilesize=NULL) {
$ok = false;
// Check file
$mime = $_FILES[$var]["type"];
if($mime=="image/jpeg" || $mime=="image/pjpeg") {
// Mime type is correct
// Check extension
$name = $_FILES[$var]["name"];
$array = explode(".", $name);
$nr = count($array);
$ext = $array[$nr-1];
if($ext=="jpg" || $ext=="jpeg") {
$ok = true;
}
}
if(isset($maxfilesize)) {
if($_FILES[$var]["size"] > $maxfilesize) {
$ok = false;
}
}
if($ok==true) {
$tempname = $_FILES[$var]['tmp_name'];
if(isset($filename)) {
$uploadpath = $location.$filename;
} else {
$uploadpath = $location.$_FILES[$var]['name'];
}
if(is_uploaded_file($_FILES[$var]['tmp_name'])) {
while(move_uploaded_file($tempname, $uploadpath)) {
// Wait for the script to finish its upload
}
}
return true;
} else {
return false;
}
}
*/
-
- }
-?>
\ No newline at end of file
+
+}
\ No newline at end of file
|
OzzyCzech/gpsrinex
|
8f49a400da2039e304d8fc5b2edf75530d6ef737
|
Add parser
|
diff --git a/README b/README
index e69de29..98b893b 100644
--- a/README
+++ b/README
@@ -0,0 +1 @@
+THIS IS GPS RINEX FILE PARSER
\ No newline at end of file
diff --git a/rinexparser.php b/rinexparser.php
new file mode 100644
index 0000000..5d3f468
--- /dev/null
+++ b/rinexparser.php
@@ -0,0 +1,298 @@
+<?php
+################################################################################
+# DATE : 06.03.2006 #
+# Short description : #
+# #
+# GPS RINEX 2.1 NAVIGATION MESSAGE FILE PARSER #
+# (http://gps.wva.net/html.common/rinex.html) #
+# #
+# Version info : #
+# #
+# rinexparser CLASS VERSION 1.0 #
+# #
+# Author info : #
+# #
+# ROMAN OŽANA (c) 2006 #
+# ICQ (99950132) #
+# WWW (www.nabito.net) #
+# E-mail ([email protected] ) #
+# #
+# Country: #
+# #
+# CZECH REPUBLIC #
+# #
+# Licence: #
+# #
+# IF YOU WANT USE THIS CODE PLEASE CONNECT AUTHOR, Thank You #
+# #
+# it was written in SCITE #
+################################################################################
+/*
+ Use example :
+
+ require_once('rinexparser.php');
+
+ $rinex = new rinexparser();
+
+ $rinex->makelist('./data28');
+
+ if ($_GET['load']) // is file load
+ {
+ $data = $rinex->load_file($_GET['load']); // add data
+ $rinex->parse($data); // parse data
+ $rinex->print_menu(); // printing menu
+ }
+
+ for ($i=0;$i<$rinex->counter;$i++) // printing RINEX File Navigation data
+ {
+ $rinex->print_navi($i);
+ }
+*/
+ class rinexparser
+ {
+ public $output = '';
+ public $counter = 0;
+
+ function load_file($file)
+ {
+ $file_text = join ("", file ($file)); //load file
+ return $file_text;
+ }
+
+ function makelist($dir = "")
+ {
+ $handle = opendir($dir); // open dir handle
+ while ( ($file = readdir($handle)) != false )
+ {
+ if ( ($file != '..') && ($file != '.') && (substr($file, -1, 1) == 'N') )
+ {
+ $files[] = $file;
+ }
+ }
+ if (!empty($files))
+ {
+ sort($files);
+ echo '<ol>';
+ for($i=0;$i<count($files);$i++)
+ {
+ echo '<li><a href="'.$_SERVER['PHP_SELF'].'?load='.$dir.'/'.$files[$i].'">'.$files[$i].'</a></li>';
+ }
+ echo '</ol>';
+ }
+ }
+
+
+ function parse($data = '')
+ {
+ $this->output = '';
+ $data = ereg_replace("D([+|-])", "E\\1", $data);
+ $data = spliti("\n",$data);
+
+ $header_end = false;
+
+ foreach ($data as $row)
+ {
+ if ($header_end == true and !empty($row)) // read only data
+ {
+ $vars = preg_split("/[\s]+/", $row,-1, PREG_SPLIT_NO_EMPTY); // parse text file
+ //echo '<pre>';print_r($vars);echo '</pre>';
+ switch ($brodcast_counter)
+ {
+ case 0:
+ $this->output[$this->counter]['prn'] = $vars[0];
+ $this->output[$this->counter]['year'] = $vars[1];
+ $this->output[$this->counter]['month'] = $vars[2];
+ $this->output[$this->counter]['day'] = $vars[3];
+ $this->output[$this->counter]['hour'] = $vars[4];
+ $this->output[$this->counter]['minute'] = $vars[5];
+ $this->output[$this->counter]['second'] = $vars[6];
+ $this->output[$this->counter]['SV_clock_bias'] = $vars[7];
+ $this->output[$this->counter]['SV_clock_drift'] = $vars[8];
+ $this->output[$this->counter]['SV_clock_drift_rate'] = $vars[9];
+ break;
+ case 1: // BRODCAST ORBIT 1
+ $this->output[$this->counter]['IODE'] = $vars[0];
+ $this->output[$this->counter]['Crs'] = $vars[1];
+ $this->output[$this->counter]['Delta_n'] = $vars[2];
+ $this->output[$this->counter]['M0'] = $vars[3];
+ break;
+ case 2: // BRODCAST ORBIT 2
+ $this->output[$this->counter]['Cuc'] = $vars[0];
+ $this->output[$this->counter]['e'] = $vars[1];
+ $this->output[$this->counter]['Cus'] = $vars[2];
+ $this->output[$this->counter]['sqrtA'] = $vars[3];
+ break;
+ case 3: // BRODCAST ORBIT 3
+ $this->output[$this->counter]['Toe'] = $vars[0];
+ $this->output[$this->counter]['Cic'] = $vars[1];
+ $this->output[$this->counter]['OMEGA'] = $vars[2];
+ $this->output[$this->counter]['CIS'] = $vars[3];
+ break;
+ case 4: // BRODCAST ORBIT 4
+ $this->output[$this->counter]['i0'] = $vars[0];
+ $this->output[$this->counter]['Crc'] = $vars[1];
+ $this->output[$this->counter]['omega'] = $vars[2]; // normal is omega
+ $this->output[$this->counter]['OMEGA_DOT'] = $vars[3];
+ break;
+ case 5: // BRODCAST ORBIT 5
+ $this->output[$this->counter]['IDOT'] = $vars[0];
+ $this->output[$this->counter]['Codes_on_L2_ch'] = $vars[1];
+ $this->output[$this->counter]['GPS_week']= $vars[2];
+ $this->output[$this->counter]['L2_p_data_flag'] = $vars[3];
+ break;
+ case 6: // BRODCAST ORBIT 6
+ $this->output[$this->counter]['SV_accuracy'] = $vars[0];
+ $this->output[$this->counter]['SV_health'] = $vars[1];
+ $this->output[$this->counter]['TGD'] = $vars[2];
+ $this->output[$this->counter]['IODC'] = $vars[3];
+ break;
+ case 7: // BRODCAST ORBIT 6
+ $this->output[$this->counter]['Transmission_time'] = $vars[0];
+ $this->output[$this->counter]['Fit_interval'] = $vars[1];
+ $this->output[$this->counter]['spare_01'] = $vars[2];
+ $this->output[$this->counter]['spare_02'] = $vars[3];
+ $this->counter++;
+ $brodcast_counter = -1; // don't forget clear counter
+ break;
+ default:
+ break;
+ }
+ $brodcast_counter++; // number of brodcast
+ } // is after head ?? - read data
+ if (stristr($row,'END OF HEADER'))
+ {
+ $header_end = true; // end of header
+ $brodcast_counter = 0;
+ }
+ }
+ // echo '<pre>';print_r($this->output);echo '</pre>';
+ return $this->output;
+ }
+
+ function print_menu()
+ {
+ echo '<ol>';
+ for($i=0;$i<$this->counter;$i++)
+ {
+ $gps = $this->output[$i];
+ echo '<li><a href="#gps'.$i.$gps['prn'].'">GPS '.$gps['prn'].'</a> - '.$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute'].'</li>';
+ }
+ echo '</ol>';
+ }
+
+ function print_navi($number = 0)
+ {
+ if (count($this->output) < $number)
+ {
+ return;
+ }
+ $gps = $this->output[$number];
+
+ echo '<h2><a name="gps'.$number.$gps['prn'].'"></a>Navigacni informace GPS : '.$gps['prn'].'</h2>';
+ echo '<table border="1" cellspacing="0" cellpadding="7" width="80%">';
+ // PRN info
+ $this->add_lin('Promenna','Hodnota','Jednotky','th');
+ $this->add_lin('GPS',$gps['prn']);
+ $this->add_lin('Epocha : Datum a cas',$gps['day'].'.'.$gps['month'].'.'.$gps['year'].' v '.$gps['hour'].':'.$gps['minute']);
+ $this->add_lin('SV clock bias',$gps['SV_clock_bias'],'sec');
+ $this->add_lin('SV clock drift',$gps['SV_clock_drift'],'sec/sec');
+ $this->add_lin('SV clock drift rate',$gps['SV_clock_drift_rate'],'sec/sec<sup>2</sup>');
+ // BRODCAST 01
+ $this->add_lin('',' ','');
+ $this->add_lin('IODE Issue of data',$gps['IODE']);
+ $this->add_lin('C<sub>rs</sub>',$gps['Crs'],'m');
+ $this->add_lin('Delta n',$gps['Delta_n'],'radiany/sec');
+ $this->add_lin('M<sub>0</sub>',$gps['M0'],'radiany');
+ // BRODCAST 02
+ $this->add_lin('',' ','');
+ $this->add_lin('C<sub>uc</sub>',$gps['Cuc'],'radiany');
+ $this->add_lin('Excentricita e',$gps['e'],'-');
+ $this->add_lin('C<sub>us</sub>',$gps['Cus'],'radiany');
+ $this->add_lin('sqrt(A)',$gps['sqrtA'],'sqrt(m)');
+ // BRODCAST 03
+ $this->add_lin('',' ','');
+ $this->add_lin('T<sub>oe</sub>',$gps['Toe'],'sec of GPS week');
+ $this->add_lin('C<sub>ic</sub>',$gps['Cic'],'radiany');
+ $this->add_lin('OMEGA',$gps['OMEGA'],'radiany');
+ $this->add_lin('CIS',$gps['CIS'],'radiany');
+ // BRODCAST 04
+ $this->add_lin('',' ','');
+ $this->add_lin('i<sub>0</sub>',$gps['i0'],'radiany');
+ $this->add_lin('C<sub>rc</sub>',$gps['Crc'],'radiany');
+ $this->add_lin('omega',$gps['omega'],'radiany');
+ $this->add_lin('OMEGA DOT',$gps['OMEGA_DOT'],'radiany/sec');
+ // BRODCAST 05
+ $this->add_lin('',' ','');
+ $this->add_lin('IDOT',$gps['IDOT'],'radiany/sec');
+ $this->add_lin('Codes on L2 channel',$gps['Codes_on_L2_ch']);
+ $this->add_lin('GPS week',$gps['GPS_week']);
+ $this->add_lin('L2 p data flag',$gps['L2_p_data_flag']);
+ // BRODCAST 06
+ $this->add_lin('',' ','');
+ $this->add_lin('SV accuracy',$gps['SV_accuracy'],'metry');
+ $this->add_lin('SV health',$gps['SV_health']);
+ $this->add_lin('TGD',$gps['TGD'],'sec');
+ $this->add_lin('IODC Issue of Data, Clock',$gps['IODC']);
+ // BRODCAST 07
+ $this->add_lin('',' ','');
+ $this->add_lin('Transmission time of message',$gps['Transmission_time'],'radiany');
+ $this->add_lin('Fit interval',$gps['Fit_interval'],'hodin');
+ $this->add_lin('Spare',$gps['spare_01']);
+ $this->add_lin('Spare',$gps['spare_02']);
+ echo '</table>';
+ }
+
+ function add_lin($coment, $value, $unit = '',$td = 'td')
+ {
+ if (!empty($unit) and $td == 'td')
+ {
+ $unit = '('.$unit.')';
+ }
+ echo "<tr><$td style=&qout;text-align:right;&qout;>$coment</$td><$td>$value</$td><$td>$unit</$td></tr>\n";
+ }
+ /*
+ RINEX file upload not work yet - some errors i don't know
+ function storefile($var, $location, $filename=NULL, $maxfilesize=NULL) {
+ $ok = false;
+
+ // Check file
+ $mime = $_FILES[$var]["type"];
+ if($mime=="image/jpeg" || $mime=="image/pjpeg") {
+ // Mime type is correct
+ // Check extension
+ $name = $_FILES[$var]["name"];
+ $array = explode(".", $name);
+ $nr = count($array);
+ $ext = $array[$nr-1];
+ if($ext=="jpg" || $ext=="jpeg") {
+ $ok = true;
+ }
+ }
+
+ if(isset($maxfilesize)) {
+ if($_FILES[$var]["size"] > $maxfilesize) {
+ $ok = false;
+ }
+ }
+
+ if($ok==true) {
+ $tempname = $_FILES[$var]['tmp_name'];
+ if(isset($filename)) {
+ $uploadpath = $location.$filename;
+ } else {
+ $uploadpath = $location.$_FILES[$var]['name'];
+ }
+ if(is_uploaded_file($_FILES[$var]['tmp_name'])) {
+ while(move_uploaded_file($tempname, $uploadpath)) {
+ // Wait for the script to finish its upload
+ }
+ }
+ return true;
+ } else {
+ return false;
+ }
+ }
+ */
+
+ }
+?>
\ No newline at end of file
|
indeyets/php_threads
|
9c30a20dae5e8ae5ceeefbc8a3a24be0f15148a5
|
fix threads on posix-systems
|
diff --git a/threads.c b/threads.c
index 8d52870..afee36d 100755
--- a/threads.c
+++ b/threads.c
@@ -1,771 +1,774 @@
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2003 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Shane Caraveo <[email protected]> |
| Author: Alan Knowles <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */
#define THR_DEBUG
#ifdef THR_DEBUG
#define THR_PRINTF(v) printf v; fflush(stdout);
#else
#define THR_PRINTF(v)
#endif
//#define USE_SERIALIZE
#include "php.h"
#include "php_globals.h"
#include "php_main.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_threads.h"
#ifdef USE_SERIALIZE
# include "ext/standard/php_smart_str.h"
# include "ext/standard/php_var.h"
#endif
#ifndef ZTS
/* ZTS REQUIRED */
#endif
/* Our shared vars storage */
THR_SHARED_VARS *shared_vars = NULL;
ZEND_DECLARE_MODULE_GLOBALS(threads)
/* True global resources - no need for thread safety here */
static int le_threads;
/* {{{ threads_functions[]
*
* Every user visible function must have an entry in threads_functions[].
*/
function_entry threads_functions[] = {
PHP_FE(thread_start, NULL)
PHP_FE(thread_include, NULL)
PHP_FE(thread_set, NULL)
PHP_FE(thread_isset, NULL)
PHP_FE(thread_unset, NULL)
PHP_FE(thread_get, NULL)
PHP_FE(thread_mutex_init,NULL)
PHP_FE(thread_mutex_destroy,NULL)
PHP_FE(thread_lock, NULL)
PHP_FE(thread_lock_try, NULL)
PHP_FE(thread_unlock, NULL)
{NULL, NULL, NULL} /* Must be the last line in threads_functions[] */
};
/* }}} */
/* {{{ threads_module_entry
*/
zend_module_entry threads_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"threads",
threads_functions,
PHP_MINIT(threads),
PHP_MSHUTDOWN(threads),
PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(threads),
#if ZEND_MODULE_API_NO >= 20010901
"0.1", /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_THREADS
ZEND_GET_MODULE(threads)
#endif
/* {{{ PHP_INI
*/
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals)
STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals)
PHP_INI_END()
*/
/* }}} */
/* {{{ _join_children
*/
static void _php_threads_join_children(void *data)
{
/* TODO: join or wait for children to end */
THR_THREAD *thread = (THR_THREAD *) data;
THR_PRINTF(("threads:_php_threads_join_children\n"));
#ifdef TSRM_WIN32
thr_wait_exit(thread);
#endif
#ifdef PTHREADS
pthread_join(thread->thread, NULL);
#endif
thr_close_event(thread->start_event);
//efree chrashes at shutdown, so "normal" free will be used
//TSRM_FETCH seems to crash
//efree(thread);
THR_PRINTF(("threads:_php_threads_join_children ready\n"));
thread = NULL;
}
/* }}} */
/* {{{ php_threads_init_globals
*/
static void _php_threads_init_globals(zend_threads_globals *threads_globals)
{
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(threads)
{
THR_PRINTF(("thread:minit\n"));
ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL);
/* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
*/
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(threads)
{
/* uncomment this line if you have INI entries
UNREGISTER_INI_ENTRIES();
*/
/* TODO: initialize some kind of shared memory for shared vars */
THR_PRINTF(("module shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(threads)
{
/* TODO: initialize a list for child threads */
THR_PRINTF(("thread:rinit\n"));
THREADS_G(self) = NULL;
//shared_vars = NULL;
if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
THR_PRINTF(("thread:rinit VARS\n"));
shared_vars->rwlock = thr_create_rwlock();
zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
}
//zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1);
zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0);
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(threads)
{
/* destroying the THREADS_G(children) makes this thread wait for
all THREADS_G(children) to exit */
THR_PRINTF(("thread:rshutdown\n"));
if(THREADS_G(children).count >= 1) {
THR_PRINTF(("thread:THREADS_G(children) gefunden\n"));
//TODO: wait for THREADS_G(children) to be executed; send KILL signal
//zend_hash_destroy(&THREADS_G(children));
zend_llist_destroy(&THREADS_G(children));
}
if (!THREADS_G(self)) {
THR_PRINTF(("thread:rshutdown:thread_self\n"));
/* since self was never set, this is the master thread */
//zend_hash_destroy(&shared_vars->vars);
//thr_close_rwlock(shared_vars->rwlock);
/* Daniel: Of course this will only be called if there are some shared vars */
if(shared_vars && shared_vars->vars.nNumOfElements > 0) {
THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements));
}
zend_hash_destroy(&shared_vars->vars);
thr_close_rwlock(shared_vars->rwlock);
free(shared_vars);
} else {
//thr_wait_exit(THREADS_G(self));
//Nothing to do at this point
//thr_thread_exit(0);
}
THR_PRINTF(("request shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(threads)
{
php_info_print_table_start();
php_info_print_table_header(2, "Threads support", "enabled");
php_info_print_table_end();
/* Remove comments if you have entries in php.ini
DISPLAY_INI_ENTRIES();
*/
}
/* }}} */
THR_THREAD_PROC(phpthreads_create)
{
zval *result = NULL;
zend_file_handle file_handle;
// zval ret_val;
zval *local_retval = NULL;
zend_op_array *orig_op_array = NULL;
zend_op_array *op_array = NULL;
zval callback;
zval args;
zval *argv[1];
int callback_len = 0;
THR_THREAD *thread = (THR_THREAD *) data;
TSRMLS_FETCH();
THREADS_G(self) = thread;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/*
TODO: copy system level data now. We need copy the global zend
structures so that this thread has it's own copy of them.
*/
SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated);
/* copy our arguments */
COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback);
COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]);
argv[0] = &args;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
thr_set_event(thread->start_event);
php_request_startup(TSRMLS_C);
#ifdef PHP_WIN32
//UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC);
#endif
THR_PRINTF(("Call User Func ??????\n\n==================n\n"));
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb");
file_handle.filename = SG(request_info).path_translated;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
EG(exit_status) = 0;
//PG(during_request_startup) = 0;
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
// EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
//zend_execute(op_array TSRMLS_CC);
orig_op_array = EG(active_op_array);
// new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/
zend_destroy_file_handle(&file_handle TSRMLS_CC);
if (EG(active_op_array)) {
EG(return_value_ptr_ptr) = &local_retval;
/* start the thread in php user land! Instead of calling
php_execute_script, we've copied the stuff and can now
simply call into a user function */
//retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS);
//zend_execute(EG(active_op_array) TSRMLS_CC);
if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) {
zend_error(E_ERROR, "Problem Starting thread with callback");
}
zval_dtor(&callback);
zval_dtor(&args);
//zval_dtor(&ret_val);
//zval_ptr_dtor(EG(return_value_ptr_ptr));
local_retval = NULL;
#ifdef ZEND_ENGINE_2
destroy_op_array(EG(active_op_array) TSRMLS_CC);
#else
destroy_op_array(EG(active_op_array));
#endif
efree(op_array);
EG(active_op_array) = orig_op_array;
}
php_request_shutdown(NULL);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string function_name, [any args])
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_start)
{
zval *callback;
THR_THREAD *thread = NULL;
zval *args;
int threadid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) {
return;
}
thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = callback;
thread->parent_tls = tsrm_ls;
thread->args[0] = (void *) args;
threadid = thr_thread_create(thread, (void *) phpthreads_create);
/* we wait here until the child thread has copied the
parent threads data */
thr_wait_event(thread->start_event,THR_INFINITE);
zend_llist_add_element(&THREADS_G(children), (void *)thread);
// zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread);
RETURN_TRUE;
}
/* }}} */
/* THR_THREAD_PROC(phpthreads_include) { */
void phpthreads_include (void * data) {
zval *result = NULL;
zend_op_array *op_array;
int callback_len = 0;
zend_file_handle file_handle;
THR_THREAD *thread = (THR_THREAD *) data;
/* void **thr_data = thread->args; */
char *script_file;
/* Threads should be detached if necessary or set by user
#ifdef PTHREADS
pthread_detach(pthread_self());
#endif
*/
/*char *script_file = (char *)estrdup((char *) thr_data[0]);*/
//THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1];
TSRMLS_FETCH();
script_file = (char *) thread->args[0];
THR_PRINTF(("starting thread %s \n", script_file))
//thread->args[0] = NULL;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/* do standard stuff just like cli sapi */
php_request_startup(TSRMLS_C);
THREADS_G(self) = thread; /* is ok */
//shared_vars = vars; /* is ok */
THR_PRINTF(("I'm done doing the unsafe stuff\n"));
+ thread->start_event = thr_create_event();
thr_set_event(thread->start_event);
SG(request_info).path_translated = script_file;
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(script_file, "rb");
file_handle.filename = script_file;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
THR_PRINTF(("sent - running script \n"));
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
+
zend_destroy_file_handle(&file_handle TSRMLS_CC);
+ if (NULL == op_array) {
+ THR_PRINTF(("zend_compile_file() failed\n"));
+ ts_free_thread();
+ thr_thread_exit(0);
+ }
+
EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
zend_execute(op_array TSRMLS_CC);
destroy_op_array(op_array TSRMLS_CC);
efree(op_array);
op_array = NULL;
efree(*EG(return_value_ptr_ptr));
//php_execute_script(&file_handle TSRMLS_CC);
THR_PRINTF(("done running script \n"));
/* self destruct DOES NOT WORK FOR SOME REASON! */
php_request_shutdown(NULL); /* NOW IT WORKS */
THR_PRINTF(("done request shutdown \n"));
/* found in tsrm.c and is extremly useful */
ts_free_thread();
//free(thread);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string filename)
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_include)
{
char *script_file=NULL;
char *script_file_in;
int len;
int threadid;
THR_THREAD *thread = NULL;
//THR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) {
RETURN_FALSE;
}
// if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
// shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
// shared_vars->rwlock = thr_create_rwlock();
// zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
// vars = shared_vars;
// }
- script_file= (char *) emalloc(len + 1);
+ script_file= (char *) malloc(len + 1);
strncpy(script_file , script_file_in, len+1);
/* avoid emalloc ... - it gets totally confused with the threading stuff */
thread = (THR_THREAD *) malloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = NULL;
thread->parent_tls = tsrm_ls;
thread->args[0] = script_file;
thread->args[1] = NULL;
THR_PRINTF(("value of args is %x\n", thread->args));
thread->id = thr_thread_create(thread, (void *) phpthreads_include);
/* we wait here until the child thread has copied the
parent threads data */
-
- THR_PRINTF(("done creating thread - waiting for all clear \n"))
-
- /* waiting for thread to start... */
-#ifdef TSRM_WIN32
+ THR_PRINTF(("done creating thread - waiting for thread to start\n"))
thr_wait_event(thread->start_event, THR_INFINITE);
-#endif
- THR_PRINTF(("got message that thread had finished initializing \n"))
-
+ THR_PRINTF(("got message that thread had finished initializing\n"))
+
// thread->args[0] = NULL;
//zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL);
- zend_llist_add_element(&THREADS_G(children), (void *)thread);
+ zend_llist_add_element(&THREADS_G(children), (void *)thread);
free(thread);
- efree(script_file);
+ free(script_file);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_set(string name, mixed variable)
set a value into shared thread storage */
PHP_FUNCTION(thread_set)
{
char *name;
unsigned int len;
zval *var;
zval *newvar = NULL, **xvar=NULL;
THR_SHARED_VARS *vars = shared_vars;
#ifdef USE_SERIALIZE
smart_str new_var = {0};
char *ser_str = NULL;
php_serialize_data_t var_hash;
#else
zval *target;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread:thread_set==%s==\n", name));
#ifdef USE_SERIALIZE
/* serialize variables that will be shared */
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
ser_str = estrndup(new_var.c,new_var.len);
thr_acquire_write_lock(shared_vars->rwlock);
zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL);
thr_release_write_lock(shared_vars->rwlock);
THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str));
smart_str_free(&new_var);
#else
/* attempt to save an actual zval to avoid serialization overhead,
and to allow for resources to be shared (if possible?) */
/* TODO: need to make a complete copy of var */
thr_acquire_write_lock(shared_vars->rwlock);
switch(Z_TYPE_PP(&var)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
THR_PRINTF(("RESOURCE ====================================================\n"));
break;
case IS_OBJECT:
THR_PRINTF(("OBJECT ====================================================\n"));
//TODO: Special Handling for Objects
break;
default:
//TODO: This doesn't work for calls like thread_set('var', 'value')
//Only for calls like thread_set('var', $var);
/*MAKE_STD_ZVAL(target);
*target = *var;
zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode
zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL);
break;
}
/*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) {
if(Z_TYPE_PP(xvar) == IS_STRING) {
convert_to_string_ex(xvar);
}
THR_PRINTF(("thread_set: hash find ok \n"));
}*/
thr_release_write_lock(shared_vars->rwlock);
#endif
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed thread_get(string name[, int wait])
get a value from shared thread storage */
PHP_FUNCTION(thread_get)
{
char *name;
unsigned int len;
#ifdef USE_SERIALIZE
char *new_var;
zval *tmp = NULL;
#else
zval **tmp;
#endif
//Not neededTHR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread_get: Trying to return %s\n", name));
#ifdef USE_SERIALIZE
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) {
php_unserialize_data_t var_hash;
const char *p = (const char*)new_var;
MAKE_STD_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) {
zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C));
RETVAL_FALSE;
}
REPLACE_ZVAL_VALUE(&return_value, tmp, 0);
zval_copy_ctor(return_value);
INIT_PZVAL(return_value);
FREE_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
THR_PRINTF(("thread_get: successfully returned %s\n", name));
} else {
THR_PRINTF(("thread_get: not successfully found %s\n", name));
}
thr_release_read_lock(shared_vars->rwlock);
#else
/* for some reason, we cannot get zval's back if set from a different
thread */
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) {
switch(Z_TYPE_PP(tmp)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
break;
case IS_OBJECT:
//TODO: Special Handling for Objects
break;
default:
REPLACE_ZVAL_VALUE(&return_value, *tmp, 1);
break;
}
}
thr_release_read_lock(shared_vars->rwlock);
#endif
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_isset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
THR_PRINTF(("thread_isset: %s exists\n", name));
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_unset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
THR_PRINTF(("thread_unset: unsetting %s \n", name));
zend_hash_del(&shared_vars->vars, name, len + 1);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_init(string name)
create a mutex resource */
PHP_FUNCTION(thread_mutex_init)
{
/* NOTE: we create the mutex, stuff it into shared thread storage
under the provided name. Any thread can then use that mutex
by using the name of the mutex, rather than the value */
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_destroy(string name)
destroy a mutex resource */
PHP_FUNCTION(thread_mutex_destroy)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock(string name)
blocking lock on a mutex */
PHP_FUNCTION(thread_lock)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock_try(string name)
non-blocking lock on a mutex */
PHP_FUNCTION(thread_lock_try)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_unlock(string name)
unlock a locked mutex */
PHP_FUNCTION(thread_unlock)
{
RETURN_FALSE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
indeyets/php_threads
|
50a0b68b7073935dc00facfee3c4516bde2a9ee4
|
fix declaration
|
diff --git a/threadapi.h b/threadapi.h
index 350c4e8..db09bd8 100644
--- a/threadapi.h
+++ b/threadapi.h
@@ -1,118 +1,118 @@
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2003 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Shane Caraveo <[email protected]> |
| Author: Alan Knowles <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef THREADAPI_H
#define THREADAPI_H
#include "TSRM.h"
#ifdef TSRM_WIN32
# define THR_THREAD_T HANDLE
# define THR_THREAD_PROC(a) void a(void *data)
# define THR_THREAD_PROC_P void *
# define THR_EVENT HANDLE
# define THR_WAIT_ABANDONED WAIT_ABANDONED
# define THR_WAIT_DONE WAIT_OBJECT_0
# define THR_WAIT_TIMEOUT WAIT_TIMEOUT
# define THR_INFINITE INFINITE
# define THR_NOWAIT 0
#elif defined(PTHREADS)
# define THR_THREAD_T pthread_t
-# define THR_THREAD_PROC(a) void *a(void *data)
+# define THR_THREAD_PROC(a) void a(void *data)
# define THR_THREAD_PROC_P void *
typedef struct _cond_var {
pthread_cond_t *cond;
pthread_mutex_t *mutex;
} _thr_cond_var;
# define THR_COND_VAR _thr_cond_var
# define THR_EVENT _thr_cond_var *
# define THR_WAIT_ABANDONED WAIT_ABANDONED
# define THR_WAIT_DONE WAIT_OBJECT_0
# define THR_WAIT_TIMEOUT WAIT_TIMEOUT
# define THR_INFINITE -1
# define THR_NOWAIT 0
/* TODO: finish other platforms */
#elif defined(NETWARE)
#elif defined(GNUPTH)
#elif defined(NSAPI)
#elif defined(PI3WEB)
#elif defined(TSRM_ST)
#endif
typedef struct _read_write_lock {
MUTEX_T lock;
THR_EVENT event;
unsigned int count;
unsigned int reset;
} THR_RW_LOCK;
THR_RW_LOCK *thr_create_rwlock(void);
void thr_close_rwlock(THR_RW_LOCK *rwlock);
void thr_acquire_write_lock(THR_RW_LOCK *rwlock);
void thr_release_write_lock(THR_RW_LOCK *rwlock);
void thr_acquire_read_lock(THR_RW_LOCK *rwlock);
void thr_release_read_lock(THR_RW_LOCK *rwlock);
/* EXPERIMENTAL
this stuff is used only in the threads extension for now,
but TSRM is realy the proper place for it */
/* create an event or condition var */
THR_EVENT thr_create_event(void);
/* wait for an event or condition to be signaled. timeout in
milliseconds */
int thr_wait_event(THR_EVENT event, int timeout);
/* signal an event */
int thr_set_event(THR_EVENT event);
/* reset an event */
int thr_reset_event(THR_EVENT event);
/* free or close an event */
void thr_close_event(THR_EVENT event);
/* EXPERIMENTAL
this stuff is used only in the threads extension for now,
but TSRM is realy the proper place for it */
/* XXX will have to think about this more. Right now
this structure is used to pass zend structures to the
thread so that the thread can make copies, it also is
used for result data. It is not persisted past the
thread creation. */
typedef struct _THR_thread {
THR_THREAD_T thread;
unsigned long id;
unsigned long exitcode;
void ***parent_tls; /* set to tsrm_ls */
void *callback; /* holds php function name */
void *args[2]; /* holds variable number of args*/
- THR_EVENT start_event;
+ THR_EVENT start_event;
} THR_THREAD;
int thr_thread_create(THR_THREAD *thread, THR_THREAD_PROC_P callback);
void thr_thread_exit(unsigned int retval);
void thr_wait_exit(THR_THREAD *thread);
#endif /* THREADAPI_H */
\ No newline at end of file
diff --git a/threads.c b/threads.c
index 6b431a6..8d52870 100755
--- a/threads.c
+++ b/threads.c
@@ -1,770 +1,770 @@
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2003 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Shane Caraveo <[email protected]> |
| Author: Alan Knowles <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */
#define THR_DEBUG
#ifdef THR_DEBUG
#define THR_PRINTF(v) printf v; fflush(stdout);
#else
#define THR_PRINTF(v)
#endif
//#define USE_SERIALIZE
#include "php.h"
#include "php_globals.h"
#include "php_main.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_threads.h"
#ifdef USE_SERIALIZE
# include "ext/standard/php_smart_str.h"
# include "ext/standard/php_var.h"
#endif
#ifndef ZTS
/* ZTS REQUIRED */
#endif
/* Our shared vars storage */
THR_SHARED_VARS *shared_vars = NULL;
ZEND_DECLARE_MODULE_GLOBALS(threads)
/* True global resources - no need for thread safety here */
static int le_threads;
/* {{{ threads_functions[]
*
* Every user visible function must have an entry in threads_functions[].
*/
function_entry threads_functions[] = {
PHP_FE(thread_start, NULL)
PHP_FE(thread_include, NULL)
PHP_FE(thread_set, NULL)
PHP_FE(thread_isset, NULL)
PHP_FE(thread_unset, NULL)
PHP_FE(thread_get, NULL)
PHP_FE(thread_mutex_init,NULL)
PHP_FE(thread_mutex_destroy,NULL)
PHP_FE(thread_lock, NULL)
PHP_FE(thread_lock_try, NULL)
PHP_FE(thread_unlock, NULL)
{NULL, NULL, NULL} /* Must be the last line in threads_functions[] */
};
/* }}} */
/* {{{ threads_module_entry
*/
zend_module_entry threads_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"threads",
threads_functions,
PHP_MINIT(threads),
PHP_MSHUTDOWN(threads),
PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(threads),
#if ZEND_MODULE_API_NO >= 20010901
"0.1", /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_THREADS
ZEND_GET_MODULE(threads)
#endif
/* {{{ PHP_INI
*/
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals)
STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals)
PHP_INI_END()
*/
/* }}} */
/* {{{ _join_children
*/
static void _php_threads_join_children(void *data)
{
/* TODO: join or wait for children to end */
THR_THREAD *thread = (THR_THREAD *) data;
THR_PRINTF(("threads:_php_threads_join_children\n"));
#ifdef TSRM_WIN32
thr_wait_exit(thread);
#endif
#ifdef PTHREADS
pthread_join(thread->thread, NULL);
#endif
thr_close_event(thread->start_event);
//efree chrashes at shutdown, so "normal" free will be used
//TSRM_FETCH seems to crash
//efree(thread);
THR_PRINTF(("threads:_php_threads_join_children ready\n"));
thread = NULL;
}
/* }}} */
/* {{{ php_threads_init_globals
*/
static void _php_threads_init_globals(zend_threads_globals *threads_globals)
{
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(threads)
{
THR_PRINTF(("thread:minit\n"));
ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL);
/* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
*/
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(threads)
{
/* uncomment this line if you have INI entries
UNREGISTER_INI_ENTRIES();
*/
/* TODO: initialize some kind of shared memory for shared vars */
THR_PRINTF(("module shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(threads)
{
/* TODO: initialize a list for child threads */
THR_PRINTF(("thread:rinit\n"));
THREADS_G(self) = NULL;
//shared_vars = NULL;
if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
THR_PRINTF(("thread:rinit VARS\n"));
shared_vars->rwlock = thr_create_rwlock();
zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
}
//zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1);
zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0);
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(threads)
{
/* destroying the THREADS_G(children) makes this thread wait for
all THREADS_G(children) to exit */
THR_PRINTF(("thread:rshutdown\n"));
if(THREADS_G(children).count >= 1) {
THR_PRINTF(("thread:THREADS_G(children) gefunden\n"));
//TODO: wait for THREADS_G(children) to be executed; send KILL signal
//zend_hash_destroy(&THREADS_G(children));
zend_llist_destroy(&THREADS_G(children));
}
if (!THREADS_G(self)) {
THR_PRINTF(("thread:rshutdown:thread_self\n"));
/* since self was never set, this is the master thread */
//zend_hash_destroy(&shared_vars->vars);
//thr_close_rwlock(shared_vars->rwlock);
/* Daniel: Of course this will only be called if there are some shared vars */
if(shared_vars && shared_vars->vars.nNumOfElements > 0) {
THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements));
}
zend_hash_destroy(&shared_vars->vars);
thr_close_rwlock(shared_vars->rwlock);
free(shared_vars);
} else {
//thr_wait_exit(THREADS_G(self));
//Nothing to do at this point
//thr_thread_exit(0);
}
THR_PRINTF(("request shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(threads)
{
php_info_print_table_start();
php_info_print_table_header(2, "Threads support", "enabled");
php_info_print_table_end();
/* Remove comments if you have entries in php.ini
DISPLAY_INI_ENTRIES();
*/
}
/* }}} */
-THR_THREAD_PROC(phpthreads_create) {
-
+THR_THREAD_PROC(phpthreads_create)
+{
zval *result = NULL;
zend_file_handle file_handle;
// zval ret_val;
zval *local_retval = NULL;
zend_op_array *orig_op_array = NULL;
zend_op_array *op_array = NULL;
zval callback;
zval args;
zval *argv[1];
int callback_len = 0;
THR_THREAD *thread = (THR_THREAD *) data;
TSRMLS_FETCH();
THREADS_G(self) = thread;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/*
TODO: copy system level data now. We need copy the global zend
structures so that this thread has it's own copy of them.
*/
SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated);
/* copy our arguments */
COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback);
COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]);
argv[0] = &args;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
thr_set_event(thread->start_event);
php_request_startup(TSRMLS_C);
#ifdef PHP_WIN32
//UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC);
#endif
THR_PRINTF(("Call User Func ??????\n\n==================n\n"));
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb");
file_handle.filename = SG(request_info).path_translated;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
EG(exit_status) = 0;
//PG(during_request_startup) = 0;
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
// EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
//zend_execute(op_array TSRMLS_CC);
orig_op_array = EG(active_op_array);
// new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/
zend_destroy_file_handle(&file_handle TSRMLS_CC);
if (EG(active_op_array)) {
EG(return_value_ptr_ptr) = &local_retval;
/* start the thread in php user land! Instead of calling
php_execute_script, we've copied the stuff and can now
simply call into a user function */
//retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS);
//zend_execute(EG(active_op_array) TSRMLS_CC);
if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) {
zend_error(E_ERROR, "Problem Starting thread with callback");
}
zval_dtor(&callback);
zval_dtor(&args);
//zval_dtor(&ret_val);
//zval_ptr_dtor(EG(return_value_ptr_ptr));
local_retval = NULL;
#ifdef ZEND_ENGINE_2
destroy_op_array(EG(active_op_array) TSRMLS_CC);
#else
destroy_op_array(EG(active_op_array));
#endif
efree(op_array);
EG(active_op_array) = orig_op_array;
}
php_request_shutdown(NULL);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string function_name, [any args])
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_start)
{
zval *callback;
THR_THREAD *thread = NULL;
zval *args;
int threadid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) {
return;
}
thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = callback;
thread->parent_tls = tsrm_ls;
thread->args[0] = (void *) args;
threadid = thr_thread_create(thread, (void *) phpthreads_create);
/* we wait here until the child thread has copied the
parent threads data */
thr_wait_event(thread->start_event,THR_INFINITE);
zend_llist_add_element(&THREADS_G(children), (void *)thread);
// zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread);
RETURN_TRUE;
}
/* }}} */
/* THR_THREAD_PROC(phpthreads_include) { */
void phpthreads_include (void * data) {
zval *result = NULL;
zend_op_array *op_array;
int callback_len = 0;
zend_file_handle file_handle;
THR_THREAD *thread = (THR_THREAD *) data;
/* void **thr_data = thread->args; */
char *script_file;
/* Threads should be detached if necessary or set by user
#ifdef PTHREADS
pthread_detach(pthread_self());
#endif
*/
/*char *script_file = (char *)estrdup((char *) thr_data[0]);*/
//THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1];
TSRMLS_FETCH();
script_file = (char *) thread->args[0];
THR_PRINTF(("starting thread %s \n", script_file))
//thread->args[0] = NULL;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/* do standard stuff just like cli sapi */
php_request_startup(TSRMLS_C);
THREADS_G(self) = thread; /* is ok */
//shared_vars = vars; /* is ok */
THR_PRINTF(("I'm done doing the unsafe stuff\n"));
thr_set_event(thread->start_event);
SG(request_info).path_translated = script_file;
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(script_file, "rb");
file_handle.filename = script_file;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
THR_PRINTF(("sent - running script \n"));
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
zend_destroy_file_handle(&file_handle TSRMLS_CC);
EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
zend_execute(op_array TSRMLS_CC);
destroy_op_array(op_array TSRMLS_CC);
efree(op_array);
op_array = NULL;
efree(*EG(return_value_ptr_ptr));
//php_execute_script(&file_handle TSRMLS_CC);
THR_PRINTF(("done running script \n"));
/* self destruct DOES NOT WORK FOR SOME REASON! */
php_request_shutdown(NULL); /* NOW IT WORKS */
THR_PRINTF(("done request shutdown \n"));
/* found in tsrm.c and is extremly useful */
ts_free_thread();
//free(thread);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string filename)
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_include)
{
char *script_file=NULL;
char *script_file_in;
int len;
int threadid;
THR_THREAD *thread = NULL;
//THR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) {
RETURN_FALSE;
}
// if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
// shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
// shared_vars->rwlock = thr_create_rwlock();
// zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
// vars = shared_vars;
// }
script_file= (char *) emalloc(len + 1);
strncpy(script_file , script_file_in, len+1);
/* avoid emalloc ... - it gets totally confused with the threading stuff */
thread = (THR_THREAD *) malloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = NULL;
thread->parent_tls = tsrm_ls;
thread->args[0] = script_file;
thread->args[1] = NULL;
THR_PRINTF(("value of args is %x\n", thread->args));
thread->id = thr_thread_create(thread, (void *) phpthreads_include);
/* we wait here until the child thread has copied the
parent threads data */
THR_PRINTF(("done creating thread - waiting for all clear \n"))
/* waiting for thread to start... */
#ifdef TSRM_WIN32
thr_wait_event(thread->start_event, THR_INFINITE);
#endif
THR_PRINTF(("got message that thread had finished initializing \n"))
// thread->args[0] = NULL;
//zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL);
zend_llist_add_element(&THREADS_G(children), (void *)thread);
free(thread);
efree(script_file);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_set(string name, mixed variable)
set a value into shared thread storage */
PHP_FUNCTION(thread_set)
{
char *name;
unsigned int len;
zval *var;
zval *newvar = NULL, **xvar=NULL;
THR_SHARED_VARS *vars = shared_vars;
#ifdef USE_SERIALIZE
smart_str new_var = {0};
char *ser_str = NULL;
php_serialize_data_t var_hash;
#else
zval *target;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread:thread_set==%s==\n", name));
#ifdef USE_SERIALIZE
/* serialize variables that will be shared */
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
ser_str = estrndup(new_var.c,new_var.len);
thr_acquire_write_lock(shared_vars->rwlock);
zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL);
thr_release_write_lock(shared_vars->rwlock);
THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str));
smart_str_free(&new_var);
#else
/* attempt to save an actual zval to avoid serialization overhead,
and to allow for resources to be shared (if possible?) */
/* TODO: need to make a complete copy of var */
thr_acquire_write_lock(shared_vars->rwlock);
switch(Z_TYPE_PP(&var)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
THR_PRINTF(("RESOURCE ====================================================\n"));
break;
case IS_OBJECT:
THR_PRINTF(("OBJECT ====================================================\n"));
//TODO: Special Handling for Objects
break;
default:
//TODO: This doesn't work for calls like thread_set('var', 'value')
//Only for calls like thread_set('var', $var);
/*MAKE_STD_ZVAL(target);
*target = *var;
zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode
zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL);
break;
}
/*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) {
if(Z_TYPE_PP(xvar) == IS_STRING) {
convert_to_string_ex(xvar);
}
THR_PRINTF(("thread_set: hash find ok \n"));
}*/
thr_release_write_lock(shared_vars->rwlock);
#endif
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed thread_get(string name[, int wait])
get a value from shared thread storage */
PHP_FUNCTION(thread_get)
{
char *name;
unsigned int len;
#ifdef USE_SERIALIZE
char *new_var;
zval *tmp = NULL;
#else
zval **tmp;
#endif
//Not neededTHR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread_get: Trying to return %s\n", name));
#ifdef USE_SERIALIZE
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) {
php_unserialize_data_t var_hash;
const char *p = (const char*)new_var;
MAKE_STD_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) {
zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C));
RETVAL_FALSE;
}
REPLACE_ZVAL_VALUE(&return_value, tmp, 0);
zval_copy_ctor(return_value);
INIT_PZVAL(return_value);
FREE_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
THR_PRINTF(("thread_get: successfully returned %s\n", name));
} else {
THR_PRINTF(("thread_get: not successfully found %s\n", name));
}
thr_release_read_lock(shared_vars->rwlock);
#else
/* for some reason, we cannot get zval's back if set from a different
thread */
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) {
switch(Z_TYPE_PP(tmp)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
break;
case IS_OBJECT:
//TODO: Special Handling for Objects
break;
default:
REPLACE_ZVAL_VALUE(&return_value, *tmp, 1);
break;
}
}
thr_release_read_lock(shared_vars->rwlock);
#endif
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_isset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
THR_PRINTF(("thread_isset: %s exists\n", name));
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_unset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
THR_PRINTF(("thread_unset: unsetting %s \n", name));
zend_hash_del(&shared_vars->vars, name, len + 1);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_init(string name)
create a mutex resource */
PHP_FUNCTION(thread_mutex_init)
{
/* NOTE: we create the mutex, stuff it into shared thread storage
under the provided name. Any thread can then use that mutex
by using the name of the mutex, rather than the value */
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_destroy(string name)
destroy a mutex resource */
PHP_FUNCTION(thread_mutex_destroy)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock(string name)
blocking lock on a mutex */
PHP_FUNCTION(thread_lock)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock_try(string name)
non-blocking lock on a mutex */
PHP_FUNCTION(thread_lock_try)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_unlock(string name)
unlock a locked mutex */
PHP_FUNCTION(thread_unlock)
{
RETURN_FALSE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
|
indeyets/php_threads
|
99adb489bc2ca80cf52e0d8e45a233d62cfbb61b
|
function is void. no need to return values
|
diff --git a/threads.c b/threads.c
index f18669d..6b431a6 100755
--- a/threads.c
+++ b/threads.c
@@ -1,771 +1,771 @@
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2003 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Shane Caraveo <[email protected]> |
| Author: Alan Knowles <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */
#define THR_DEBUG
#ifdef THR_DEBUG
#define THR_PRINTF(v) printf v; fflush(stdout);
#else
-#define THR_PRINTF(v)
+#define THR_PRINTF(v)
#endif
//#define USE_SERIALIZE
#include "php.h"
#include "php_globals.h"
#include "php_main.h"
#include "php_ini.h"
#include "ext/standard/info.h"
-#include "php_threads.h"
+#include "php_threads.h"
#ifdef USE_SERIALIZE
# include "ext/standard/php_smart_str.h"
# include "ext/standard/php_var.h"
#endif
#ifndef ZTS
/* ZTS REQUIRED */
#endif
-
-
-/* Our shared vars storage */
-THR_SHARED_VARS *shared_vars = NULL;
-
+
+
+/* Our shared vars storage */
+THR_SHARED_VARS *shared_vars = NULL;
+
ZEND_DECLARE_MODULE_GLOBALS(threads)
-
+
/* True global resources - no need for thread safety here */
static int le_threads;
/* {{{ threads_functions[]
*
* Every user visible function must have an entry in threads_functions[].
*/
function_entry threads_functions[] = {
PHP_FE(thread_start, NULL)
PHP_FE(thread_include, NULL)
- PHP_FE(thread_set, NULL)
- PHP_FE(thread_isset, NULL)
+ PHP_FE(thread_set, NULL)
+ PHP_FE(thread_isset, NULL)
PHP_FE(thread_unset, NULL)
PHP_FE(thread_get, NULL)
PHP_FE(thread_mutex_init,NULL)
PHP_FE(thread_mutex_destroy,NULL)
PHP_FE(thread_lock, NULL)
PHP_FE(thread_lock_try, NULL)
PHP_FE(thread_unlock, NULL)
{NULL, NULL, NULL} /* Must be the last line in threads_functions[] */
};
/* }}} */
/* {{{ threads_module_entry
*/
zend_module_entry threads_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"threads",
threads_functions,
PHP_MINIT(threads),
PHP_MSHUTDOWN(threads),
PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(threads),
#if ZEND_MODULE_API_NO >= 20010901
"0.1", /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_THREADS
ZEND_GET_MODULE(threads)
#endif
/* {{{ PHP_INI
*/
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals)
STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals)
PHP_INI_END()
*/
/* }}} */
/* {{{ _join_children
*/
static void _php_threads_join_children(void *data)
-{
+{
/* TODO: join or wait for children to end */
- THR_THREAD *thread = (THR_THREAD *) data;
-
- THR_PRINTF(("threads:_php_threads_join_children\n"));
+ THR_THREAD *thread = (THR_THREAD *) data;
+
+ THR_PRINTF(("threads:_php_threads_join_children\n"));
#ifdef TSRM_WIN32
thr_wait_exit(thread);
#endif
#ifdef PTHREADS
pthread_join(thread->thread, NULL);
-#endif
+#endif
thr_close_event(thread->start_event);
-
-
- //efree chrashes at shutdown, so "normal" free will be used
- //TSRM_FETCH seems to crash
- //efree(thread);
- THR_PRINTF(("threads:_php_threads_join_children ready\n"));
-
- thread = NULL;
-}
-
-
+
+
+ //efree chrashes at shutdown, so "normal" free will be used
+ //TSRM_FETCH seems to crash
+ //efree(thread);
+ THR_PRINTF(("threads:_php_threads_join_children ready\n"));
+
+ thread = NULL;
+}
+
+
/* }}} */
/* {{{ php_threads_init_globals
*/
static void _php_threads_init_globals(zend_threads_globals *threads_globals)
{
- return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(threads)
{
THR_PRINTF(("thread:minit\n"));
ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL);
/* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
- */
-
-
+ */
+
+
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(threads)
{
/* uncomment this line if you have INI entries
UNREGISTER_INI_ENTRIES();
*/
/* TODO: initialize some kind of shared memory for shared vars */
THR_PRINTF(("module shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(threads)
{
/* TODO: initialize a list for child threads */
THR_PRINTF(("thread:rinit\n"));
THREADS_G(self) = NULL;
//shared_vars = NULL;
-
- if (!shared_vars) {
- /* only the master thread creates this */
- /* avoid emalloc ... - it gets totally confused with the threading stuff */
- shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
- THR_PRINTF(("thread:rinit VARS\n"));
- shared_vars->rwlock = thr_create_rwlock();
- zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
- }
-
+
+ if (!shared_vars) {
+ /* only the master thread creates this */
+ /* avoid emalloc ... - it gets totally confused with the threading stuff */
+ shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
+ THR_PRINTF(("thread:rinit VARS\n"));
+ shared_vars->rwlock = thr_create_rwlock();
+ zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
+ }
+
//zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1);
zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0);
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(threads)
{
/* destroying the THREADS_G(children) makes this thread wait for
all THREADS_G(children) to exit */
- THR_PRINTF(("thread:rshutdown\n"));
+ THR_PRINTF(("thread:rshutdown\n"));
if(THREADS_G(children).count >= 1) {
- THR_PRINTF(("thread:THREADS_G(children) gefunden\n"));
- //TODO: wait for THREADS_G(children) to be executed; send KILL signal
- //zend_hash_destroy(&THREADS_G(children));
- zend_llist_destroy(&THREADS_G(children));
+ THR_PRINTF(("thread:THREADS_G(children) gefunden\n"));
+ //TODO: wait for THREADS_G(children) to be executed; send KILL signal
+ //zend_hash_destroy(&THREADS_G(children));
+ zend_llist_destroy(&THREADS_G(children));
}
if (!THREADS_G(self)) {
- THR_PRINTF(("thread:rshutdown:thread_self\n"));
+ THR_PRINTF(("thread:rshutdown:thread_self\n"));
/* since self was never set, this is the master thread */
- //zend_hash_destroy(&shared_vars->vars);
- //thr_close_rwlock(shared_vars->rwlock);
- /* Daniel: Of course this will only be called if there are some shared vars */
- if(shared_vars && shared_vars->vars.nNumOfElements > 0) {
- THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements));
- }
- zend_hash_destroy(&shared_vars->vars);
- thr_close_rwlock(shared_vars->rwlock);
- free(shared_vars);
-
- } else {
- //thr_wait_exit(THREADS_G(self));
- //Nothing to do at this point
- //thr_thread_exit(0);
+ //zend_hash_destroy(&shared_vars->vars);
+ //thr_close_rwlock(shared_vars->rwlock);
+ /* Daniel: Of course this will only be called if there are some shared vars */
+ if(shared_vars && shared_vars->vars.nNumOfElements > 0) {
+ THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements));
+ }
+ zend_hash_destroy(&shared_vars->vars);
+ thr_close_rwlock(shared_vars->rwlock);
+ free(shared_vars);
+
+ } else {
+ //thr_wait_exit(THREADS_G(self));
+ //Nothing to do at this point
+ //thr_thread_exit(0);
}
THR_PRINTF(("request shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(threads)
{
php_info_print_table_start();
php_info_print_table_header(2, "Threads support", "enabled");
php_info_print_table_end();
/* Remove comments if you have entries in php.ini
DISPLAY_INI_ENTRIES();
*/
}
/* }}} */
-
-THR_THREAD_PROC(phpthreads_create) {
-
- zval *result = NULL;
+
+THR_THREAD_PROC(phpthreads_create) {
+
+ zval *result = NULL;
zend_file_handle file_handle;
// zval ret_val;
zval *local_retval = NULL;
zend_op_array *orig_op_array = NULL;
zend_op_array *op_array = NULL;
zval callback;
zval args;
zval *argv[1];
int callback_len = 0;
THR_THREAD *thread = (THR_THREAD *) data;
TSRMLS_FETCH();
THREADS_G(self) = thread;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/*
TODO: copy system level data now. We need copy the global zend
structures so that this thread has it's own copy of them.
*/
SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated);
/* copy our arguments */
COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback);
COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]);
- argv[0] = &args;
+ argv[0] = &args;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
thr_set_event(thread->start_event);
php_request_startup(TSRMLS_C);
#ifdef PHP_WIN32
//UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC);
#endif
THR_PRINTF(("Call User Func ??????\n\n==================n\n"));
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb");
file_handle.filename = SG(request_info).path_translated;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
EG(exit_status) = 0;
//PG(during_request_startup) = 0;
-
- op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
-
-// EG(return_value_ptr_ptr) = &result;
- EG(active_op_array) = op_array;
-
- //zend_execute(op_array TSRMLS_CC);
-
+
+ op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
+
+// EG(return_value_ptr_ptr) = &result;
+ EG(active_op_array) = op_array;
+
+ //zend_execute(op_array TSRMLS_CC);
+
orig_op_array = EG(active_op_array);
// new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/
zend_destroy_file_handle(&file_handle TSRMLS_CC);
if (EG(active_op_array)) {
EG(return_value_ptr_ptr) = &local_retval;
/* start the thread in php user land! Instead of calling
php_execute_script, we've copied the stuff and can now
simply call into a user function */
//retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS);
//zend_execute(EG(active_op_array) TSRMLS_CC);
if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) {
zend_error(E_ERROR, "Problem Starting thread with callback");
}
zval_dtor(&callback);
zval_dtor(&args);
//zval_dtor(&ret_val);
- //zval_ptr_dtor(EG(return_value_ptr_ptr));
+ //zval_ptr_dtor(EG(return_value_ptr_ptr));
local_retval = NULL;
#ifdef ZEND_ENGINE_2
destroy_op_array(EG(active_op_array) TSRMLS_CC);
#else
destroy_op_array(EG(active_op_array));
#endif
efree(op_array);
EG(active_op_array) = orig_op_array;
}
php_request_shutdown(NULL);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string function_name, [any args])
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_start)
{
zval *callback;
THR_THREAD *thread = NULL;
zval *args;
int threadid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) {
return;
}
thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = callback;
thread->parent_tls = tsrm_ls;
thread->args[0] = (void *) args;
threadid = thr_thread_create(thread, (void *) phpthreads_create);
/* we wait here until the child thread has copied the
parent threads data */
thr_wait_event(thread->start_event,THR_INFINITE);
- zend_llist_add_element(&THREADS_G(children), (void *)thread);
+ zend_llist_add_element(&THREADS_G(children), (void *)thread);
// zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread);
RETURN_TRUE;
}
/* }}} */
/* THR_THREAD_PROC(phpthreads_include) { */
void phpthreads_include (void * data) {
-
- zval *result = NULL;
- zend_op_array *op_array;
+
+ zval *result = NULL;
+ zend_op_array *op_array;
int callback_len = 0;
zend_file_handle file_handle;
THR_THREAD *thread = (THR_THREAD *) data;
/* void **thr_data = thread->args; */
char *script_file;
/* Threads should be detached if necessary or set by user
#ifdef PTHREADS
pthread_detach(pthread_self());
#endif
*/
/*char *script_file = (char *)estrdup((char *) thr_data[0]);*/
//THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1];
TSRMLS_FETCH();
script_file = (char *) thread->args[0];
THR_PRINTF(("starting thread %s \n", script_file))
//thread->args[0] = NULL;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/* do standard stuff just like cli sapi */
php_request_startup(TSRMLS_C);
-
+
THREADS_G(self) = thread; /* is ok */
//shared_vars = vars; /* is ok */
THR_PRINTF(("I'm done doing the unsafe stuff\n"));
thr_set_event(thread->start_event);
SG(request_info).path_translated = script_file;
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(script_file, "rb");
file_handle.filename = script_file;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
THR_PRINTF(("sent - running script \n"));
-
- op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
- zend_destroy_file_handle(&file_handle TSRMLS_CC);
-
- EG(return_value_ptr_ptr) = &result;
- EG(active_op_array) = op_array;
-
- zend_execute(op_array TSRMLS_CC);
-
- destroy_op_array(op_array TSRMLS_CC);
- efree(op_array);
+
+ op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
+ zend_destroy_file_handle(&file_handle TSRMLS_CC);
+
+ EG(return_value_ptr_ptr) = &result;
+ EG(active_op_array) = op_array;
+
+ zend_execute(op_array TSRMLS_CC);
+
+ destroy_op_array(op_array TSRMLS_CC);
+ efree(op_array);
op_array = NULL;
- efree(*EG(return_value_ptr_ptr));
-
- //php_execute_script(&file_handle TSRMLS_CC);
+ efree(*EG(return_value_ptr_ptr));
+
+ //php_execute_script(&file_handle TSRMLS_CC);
THR_PRINTF(("done running script \n"));
-
+
/* self destruct DOES NOT WORK FOR SOME REASON! */
-
- php_request_shutdown(NULL); /* NOW IT WORKS */
-
- THR_PRINTF(("done request shutdown \n"));
-
- /* found in tsrm.c and is extremly useful */
- ts_free_thread();
- //free(thread);
- thr_thread_exit(0);
+ php_request_shutdown(NULL); /* NOW IT WORKS */
+
+ THR_PRINTF(("done request shutdown \n"));
+
+ /* found in tsrm.c and is extremly useful */
+ ts_free_thread();
+
+ //free(thread);
+ thr_thread_exit(0);
}
/* {{{ proto string thread_start(string filename)
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_include)
{
char *script_file=NULL;
char *script_file_in;
int len;
int threadid;
THR_THREAD *thread = NULL;
//THR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) {
RETURN_FALSE;
}
// if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
// shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
// shared_vars->rwlock = thr_create_rwlock();
// zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
// vars = shared_vars;
// }
script_file= (char *) emalloc(len + 1);
strncpy(script_file , script_file_in, len+1);
/* avoid emalloc ... - it gets totally confused with the threading stuff */
thread = (THR_THREAD *) malloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = NULL;
thread->parent_tls = tsrm_ls;
thread->args[0] = script_file;
thread->args[1] = NULL;
THR_PRINTF(("value of args is %x\n", thread->args));
thread->id = thr_thread_create(thread, (void *) phpthreads_include);
/* we wait here until the child thread has copied the
parent threads data */
- THR_PRINTF(("done creating thread - waiting for all clear \n"))
+ THR_PRINTF(("done creating thread - waiting for all clear \n"))
-
+
/* waiting for thread to start... */
#ifdef TSRM_WIN32
thr_wait_event(thread->start_event, THR_INFINITE);
#endif
THR_PRINTF(("got message that thread had finished initializing \n"))
-// thread->args[0] = NULL;
-
- //zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL);
- zend_llist_add_element(&THREADS_G(children), (void *)thread);
-
- free(thread);
- efree(script_file);
+// thread->args[0] = NULL;
+
+ //zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL);
+ zend_llist_add_element(&THREADS_G(children), (void *)thread);
+
+ free(thread);
+ efree(script_file);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_set(string name, mixed variable)
set a value into shared thread storage */
PHP_FUNCTION(thread_set)
{
char *name;
unsigned int len;
- zval *var;
+ zval *var;
zval *newvar = NULL, **xvar=NULL;
THR_SHARED_VARS *vars = shared_vars;
#ifdef USE_SERIALIZE
smart_str new_var = {0};
char *ser_str = NULL;
- php_serialize_data_t var_hash;
-#else
- zval *target;
+ php_serialize_data_t var_hash;
+#else
+ zval *target;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) {
RETURN_FALSE;
- }
-
+ }
+
THR_PRINTF(("thread:thread_set==%s==\n", name));
#ifdef USE_SERIALIZE
/* serialize variables that will be shared */
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
ser_str = estrndup(new_var.c,new_var.len);
thr_acquire_write_lock(shared_vars->rwlock);
zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL);
thr_release_write_lock(shared_vars->rwlock);
-
- THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str));
-
+
+ THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str));
+
smart_str_free(&new_var);
#else
/* attempt to save an actual zval to avoid serialization overhead,
and to allow for resources to be shared (if possible?) */
/* TODO: need to make a complete copy of var */
- thr_acquire_write_lock(shared_vars->rwlock);
-
- switch(Z_TYPE_PP(&var)) {
- case IS_RESOURCE:
- //TODO: special Handling for Resources
- THR_PRINTF(("RESOURCE ====================================================\n"));
- break;
- case IS_OBJECT:
- THR_PRINTF(("OBJECT ====================================================\n"));
- //TODO: Special Handling for Objects
- break;
+ thr_acquire_write_lock(shared_vars->rwlock);
+
+ switch(Z_TYPE_PP(&var)) {
+ case IS_RESOURCE:
+ //TODO: special Handling for Resources
+ THR_PRINTF(("RESOURCE ====================================================\n"));
+ break;
+ case IS_OBJECT:
+ THR_PRINTF(("OBJECT ====================================================\n"));
+ //TODO: Special Handling for Objects
+ break;
default:
//TODO: This doesn't work for calls like thread_set('var', 'value')
- //Only for calls like thread_set('var', $var);
- /*MAKE_STD_ZVAL(target);
- *target = *var;
zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode
- zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL);
- break;
-
- }
-
+ //Only for calls like thread_set('var', $var);
+ /*MAKE_STD_ZVAL(target);
+ *target = *var;
+ zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode
+ zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL);
+ break;
+
+ }
+
/*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) {
- if(Z_TYPE_PP(xvar) == IS_STRING) {
- convert_to_string_ex(xvar);
- }
- THR_PRINTF(("thread_set: hash find ok \n"));
- }*/
-
-
- thr_release_write_lock(shared_vars->rwlock);
+ if(Z_TYPE_PP(xvar) == IS_STRING) {
+ convert_to_string_ex(xvar);
+ }
+ THR_PRINTF(("thread_set: hash find ok \n"));
+ }*/
+
+
+ thr_release_write_lock(shared_vars->rwlock);
#endif
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed thread_get(string name[, int wait])
get a value from shared thread storage */
PHP_FUNCTION(thread_get)
{
- char *name;
- unsigned int len;
+ char *name;
+ unsigned int len;
#ifdef USE_SERIALIZE
char *new_var;
zval *tmp = NULL;
#else
zval **tmp;
#endif
//Not neededTHR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
- }
-
- THR_PRINTF(("thread_get: Trying to return %s\n", name));
+ }
+
+ THR_PRINTF(("thread_get: Trying to return %s\n", name));
#ifdef USE_SERIALIZE
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) {
php_unserialize_data_t var_hash;
const char *p = (const char*)new_var;
MAKE_STD_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) {
zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C));
RETVAL_FALSE;
}
-
-
+
+
REPLACE_ZVAL_VALUE(&return_value, tmp, 0);
- zval_copy_ctor(return_value);
- INIT_PZVAL(return_value);
+ zval_copy_ctor(return_value);
+ INIT_PZVAL(return_value);
FREE_ZVAL(tmp);
- PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
+ PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
THR_PRINTF(("thread_get: successfully returned %s\n", name));
- } else {
- THR_PRINTF(("thread_get: not successfully found %s\n", name));
+ } else {
+ THR_PRINTF(("thread_get: not successfully found %s\n", name));
}
thr_release_read_lock(shared_vars->rwlock);
#else
/* for some reason, we cannot get zval's back if set from a different
thread */
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) {
- switch(Z_TYPE_PP(tmp)) {
- case IS_RESOURCE:
- //TODO: special Handling for Resources
- break;
- case IS_OBJECT:
- //TODO: Special Handling for Objects
- break;
- default:
- REPLACE_ZVAL_VALUE(&return_value, *tmp, 1);
- break;
-
- }
- }
- thr_release_read_lock(shared_vars->rwlock);
+ switch(Z_TYPE_PP(tmp)) {
+ case IS_RESOURCE:
+ //TODO: special Handling for Resources
+ break;
+ case IS_OBJECT:
+ //TODO: Special Handling for Objects
+ break;
+ default:
+ REPLACE_ZVAL_VALUE(&return_value, *tmp, 1);
+ break;
+
+ }
+ }
+ thr_release_read_lock(shared_vars->rwlock);
#endif
}
/* }}} */
-
-/* {{{ proto boolean thread_isset(string name)
- check existense of a shared var */
-PHP_FUNCTION(thread_isset)
-{
-
- char *name;
- unsigned int len;
-
- if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
- RETURN_FALSE;
- }
-
- if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
- THR_PRINTF(("thread_isset: %s exists\n", name));
- RETURN_TRUE;
- } else {
- RETURN_FALSE;
- }
-
-}
-/* }}} */
-
-
-/* {{{ proto boolean thread_isset(string name)
- check existense of a shared var */
-PHP_FUNCTION(thread_unset)
-{
-
- char *name;
- unsigned int len;
-
- if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
- RETURN_FALSE;
- }
-
- if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
- THR_PRINTF(("thread_unset: unsetting %s \n", name));
- zend_hash_del(&shared_vars->vars, name, len + 1);
- }
-
- RETURN_TRUE;
-
-}
-/* }}} */
-
+
+/* {{{ proto boolean thread_isset(string name)
+ check existense of a shared var */
+PHP_FUNCTION(thread_isset)
+{
+
+ char *name;
+ unsigned int len;
+
+ if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
+ RETURN_FALSE;
+ }
+
+ if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
+ THR_PRINTF(("thread_isset: %s exists\n", name));
+ RETURN_TRUE;
+ } else {
+ RETURN_FALSE;
+ }
+
+}
+/* }}} */
+
+
+/* {{{ proto boolean thread_isset(string name)
+ check existense of a shared var */
+PHP_FUNCTION(thread_unset)
+{
+
+ char *name;
+ unsigned int len;
+
+ if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
+ RETURN_FALSE;
+ }
+
+ if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
+ THR_PRINTF(("thread_unset: unsetting %s \n", name));
+ zend_hash_del(&shared_vars->vars, name, len + 1);
+ }
+
+ RETURN_TRUE;
+
+}
+/* }}} */
+
/* {{{ proto boolean thread_mutex_init(string name)
create a mutex resource */
PHP_FUNCTION(thread_mutex_init)
{
/* NOTE: we create the mutex, stuff it into shared thread storage
under the provided name. Any thread can then use that mutex
by using the name of the mutex, rather than the value */
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_destroy(string name)
destroy a mutex resource */
PHP_FUNCTION(thread_mutex_destroy)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock(string name)
blocking lock on a mutex */
PHP_FUNCTION(thread_lock)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock_try(string name)
non-blocking lock on a mutex */
PHP_FUNCTION(thread_lock_try)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_unlock(string name)
unlock a locked mutex */
PHP_FUNCTION(thread_unlock)
{
RETURN_FALSE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
indeyets/php_threads
|
dc967a8c0dba076b665f1f5d2303a62300508bb1
|
Added Windows binaries
|
diff --git a/bin/php_threads.dll-debug b/bin/php_threads.dll-debug
new file mode 100755
index 0000000..6208e49
Binary files /dev/null and b/bin/php_threads.dll-debug differ
diff --git a/bin/php_threads.dll-nodebug b/bin/php_threads.dll-nodebug
new file mode 100755
index 0000000..375a078
Binary files /dev/null and b/bin/php_threads.dll-nodebug differ
|
indeyets/php_threads
|
2eb0161224e17868070785c2119eb190b311865f
|
Fixed most of the memleaks of the test script
|
diff --git a/threads.c b/threads.c
index 8f0a37e..f18669d 100755
--- a/threads.c
+++ b/threads.c
@@ -1,747 +1,747 @@
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2003 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Shane Caraveo <[email protected]> |
| Author: Alan Knowles <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */
#define THR_DEBUG
#ifdef THR_DEBUG
#define THR_PRINTF(v) printf v; fflush(stdout);
#else
#define THR_PRINTF(v)
#endif
//#define USE_SERIALIZE
#include "php.h"
#include "php_globals.h"
#include "php_main.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_threads.h"
#ifdef USE_SERIALIZE
# include "ext/standard/php_smart_str.h"
# include "ext/standard/php_var.h"
#endif
#ifndef ZTS
/* ZTS REQUIRED */
#endif
/* Our shared vars storage */
THR_SHARED_VARS *shared_vars = NULL;
ZEND_DECLARE_MODULE_GLOBALS(threads)
/* True global resources - no need for thread safety here */
static int le_threads;
/* {{{ threads_functions[]
*
* Every user visible function must have an entry in threads_functions[].
*/
function_entry threads_functions[] = {
PHP_FE(thread_start, NULL)
PHP_FE(thread_include, NULL)
PHP_FE(thread_set, NULL)
PHP_FE(thread_isset, NULL)
PHP_FE(thread_unset, NULL)
PHP_FE(thread_get, NULL)
PHP_FE(thread_mutex_init,NULL)
PHP_FE(thread_mutex_destroy,NULL)
PHP_FE(thread_lock, NULL)
PHP_FE(thread_lock_try, NULL)
PHP_FE(thread_unlock, NULL)
{NULL, NULL, NULL} /* Must be the last line in threads_functions[] */
};
/* }}} */
/* {{{ threads_module_entry
*/
zend_module_entry threads_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"threads",
threads_functions,
PHP_MINIT(threads),
PHP_MSHUTDOWN(threads),
PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(threads),
#if ZEND_MODULE_API_NO >= 20010901
"0.1", /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_THREADS
ZEND_GET_MODULE(threads)
#endif
/* {{{ PHP_INI
*/
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals)
STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals)
PHP_INI_END()
*/
/* }}} */
/* {{{ _join_children
*/
static void _php_threads_join_children(void *data)
{
/* TODO: join or wait for children to end */
THR_THREAD *thread = (THR_THREAD *) data;
THR_PRINTF(("threads:_php_threads_join_children\n"));
#ifdef TSRM_WIN32
thr_wait_exit(thread);
#endif
#ifdef PTHREADS
pthread_join(thread->thread, NULL);
#endif
thr_close_event(thread->start_event);
//efree chrashes at shutdown, so "normal" free will be used
//TSRM_FETCH seems to crash
//efree(thread);
THR_PRINTF(("threads:_php_threads_join_children ready\n"));
thread = NULL;
}
/* }}} */
/* {{{ php_threads_init_globals
*/
static void _php_threads_init_globals(zend_threads_globals *threads_globals)
{
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(threads)
{
THR_PRINTF(("thread:minit\n"));
ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL);
/* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
*/
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(threads)
{
/* uncomment this line if you have INI entries
UNREGISTER_INI_ENTRIES();
*/
/* TODO: initialize some kind of shared memory for shared vars */
THR_PRINTF(("module shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(threads)
{
/* TODO: initialize a list for child threads */
THR_PRINTF(("thread:rinit\n"));
THREADS_G(self) = NULL;
//shared_vars = NULL;
if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
THR_PRINTF(("thread:rinit VARS\n"));
shared_vars->rwlock = thr_create_rwlock();
zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
}
//zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1);
zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0);
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(threads)
{
/* destroying the THREADS_G(children) makes this thread wait for
all THREADS_G(children) to exit */
THR_PRINTF(("thread:rshutdown\n"));
if(THREADS_G(children).count >= 1) {
THR_PRINTF(("thread:THREADS_G(children) gefunden\n"));
//TODO: wait for THREADS_G(children) to be executed; send KILL signal
//zend_hash_destroy(&THREADS_G(children));
zend_llist_destroy(&THREADS_G(children));
}
if (!THREADS_G(self)) {
THR_PRINTF(("thread:rshutdown:thread_self\n"));
/* since self was never set, this is the master thread */
//zend_hash_destroy(&shared_vars->vars);
//thr_close_rwlock(shared_vars->rwlock);
/* Daniel: Of course this will only be called if there are some shared vars */
if(shared_vars && shared_vars->vars.nNumOfElements > 0) {
THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements));
}
zend_hash_destroy(&shared_vars->vars);
thr_close_rwlock(shared_vars->rwlock);
free(shared_vars);
} else {
//thr_wait_exit(THREADS_G(self));
- THR_PRINTF(("its a meeeeeee\n"));
+ //Nothing to do at this point
//thr_thread_exit(0);
}
THR_PRINTF(("request shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(threads)
{
php_info_print_table_start();
php_info_print_table_header(2, "Threads support", "enabled");
php_info_print_table_end();
/* Remove comments if you have entries in php.ini
DISPLAY_INI_ENTRIES();
*/
}
/* }}} */
THR_THREAD_PROC(phpthreads_create) {
zval *result = NULL;
zend_file_handle file_handle;
// zval ret_val;
zval *local_retval = NULL;
zend_op_array *orig_op_array = NULL;
zend_op_array *op_array = NULL;
zval callback;
zval args;
zval *argv[1];
int callback_len = 0;
THR_THREAD *thread = (THR_THREAD *) data;
TSRMLS_FETCH();
THREADS_G(self) = thread;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/*
TODO: copy system level data now. We need copy the global zend
structures so that this thread has it's own copy of them.
*/
SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated);
/* copy our arguments */
COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback);
COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]);
argv[0] = &args;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
thr_set_event(thread->start_event);
php_request_startup(TSRMLS_C);
#ifdef PHP_WIN32
//UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC);
#endif
THR_PRINTF(("Call User Func ??????\n\n==================n\n"));
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb");
file_handle.filename = SG(request_info).path_translated;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
EG(exit_status) = 0;
//PG(during_request_startup) = 0;
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
// EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
//zend_execute(op_array TSRMLS_CC);
orig_op_array = EG(active_op_array);
// new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/
zend_destroy_file_handle(&file_handle TSRMLS_CC);
if (EG(active_op_array)) {
EG(return_value_ptr_ptr) = &local_retval;
/* start the thread in php user land! Instead of calling
php_execute_script, we've copied the stuff and can now
simply call into a user function */
//retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS);
//zend_execute(EG(active_op_array) TSRMLS_CC);
if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) {
zend_error(E_ERROR, "Problem Starting thread with callback");
}
zval_dtor(&callback);
zval_dtor(&args);
//zval_dtor(&ret_val);
//zval_ptr_dtor(EG(return_value_ptr_ptr));
local_retval = NULL;
#ifdef ZEND_ENGINE_2
destroy_op_array(EG(active_op_array) TSRMLS_CC);
#else
destroy_op_array(EG(active_op_array));
#endif
efree(op_array);
EG(active_op_array) = orig_op_array;
}
php_request_shutdown(NULL);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string function_name, [any args])
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_start)
{
zval *callback;
THR_THREAD *thread = NULL;
zval *args;
int threadid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) {
return;
}
thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = callback;
thread->parent_tls = tsrm_ls;
thread->args[0] = (void *) args;
threadid = thr_thread_create(thread, (void *) phpthreads_create);
/* we wait here until the child thread has copied the
parent threads data */
thr_wait_event(thread->start_event,THR_INFINITE);
zend_llist_add_element(&THREADS_G(children), (void *)thread);
// zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread);
RETURN_TRUE;
}
/* }}} */
/* THR_THREAD_PROC(phpthreads_include) { */
void phpthreads_include (void * data) {
zval *result = NULL;
zend_op_array *op_array;
int callback_len = 0;
zend_file_handle file_handle;
THR_THREAD *thread = (THR_THREAD *) data;
/* void **thr_data = thread->args; */
char *script_file;
/* Threads should be detached if necessary or set by user
#ifdef PTHREADS
pthread_detach(pthread_self());
#endif
*/
/*char *script_file = (char *)estrdup((char *) thr_data[0]);*/
//THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1];
TSRMLS_FETCH();
script_file = (char *) thread->args[0];
THR_PRINTF(("starting thread %s \n", script_file))
//thread->args[0] = NULL;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/* do standard stuff just like cli sapi */
php_request_startup(TSRMLS_C);
THREADS_G(self) = thread; /* is ok */
//shared_vars = vars; /* is ok */
THR_PRINTF(("I'm done doing the unsafe stuff\n"));
thr_set_event(thread->start_event);
SG(request_info).path_translated = script_file;
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(script_file, "rb");
file_handle.filename = script_file;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
THR_PRINTF(("sent - running script \n"));
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
zend_destroy_file_handle(&file_handle TSRMLS_CC);
EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
zend_execute(op_array TSRMLS_CC);
destroy_op_array(op_array TSRMLS_CC);
efree(op_array);
op_array = NULL;
efree(*EG(return_value_ptr_ptr));
//php_execute_script(&file_handle TSRMLS_CC);
THR_PRINTF(("done running script \n"));
/* self destruct DOES NOT WORK FOR SOME REASON! */
php_request_shutdown(NULL); /* NOW IT WORKS */
THR_PRINTF(("done request shutdown \n"));
/* found in tsrm.c and is extremly useful */
ts_free_thread();
//free(thread);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string filename)
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_include)
{
char *script_file=NULL;
char *script_file_in;
int len;
int threadid;
THR_THREAD *thread = NULL;
//THR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) {
RETURN_FALSE;
}
// if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
// shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
// shared_vars->rwlock = thr_create_rwlock();
// zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
// vars = shared_vars;
// }
script_file= (char *) emalloc(len + 1);
strncpy(script_file , script_file_in, len+1);
/* avoid emalloc ... - it gets totally confused with the threading stuff */
thread = (THR_THREAD *) malloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = NULL;
thread->parent_tls = tsrm_ls;
thread->args[0] = script_file;
thread->args[1] = NULL;
THR_PRINTF(("value of args is %x\n", thread->args));
thread->id = thr_thread_create(thread, (void *) phpthreads_include);
/* we wait here until the child thread has copied the
parent threads data */
THR_PRINTF(("done creating thread - waiting for all clear \n"))
/* waiting for thread to start... */
#ifdef TSRM_WIN32
thr_wait_event(thread->start_event, THR_INFINITE);
#endif
THR_PRINTF(("got message that thread had finished initializing \n"))
// thread->args[0] = NULL;
//zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL);
zend_llist_add_element(&THREADS_G(children), (void *)thread);
free(thread);
efree(script_file);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_set(string name, mixed variable)
set a value into shared thread storage */
PHP_FUNCTION(thread_set)
{
char *name;
unsigned int len;
zval *var;
zval *newvar = NULL, **xvar=NULL;
THR_SHARED_VARS *vars = shared_vars;
#ifdef USE_SERIALIZE
smart_str new_var = {0};
char *ser_str = NULL;
php_serialize_data_t var_hash;
#else
zval *target;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread:thread_set==%s==\n", name));
#ifdef USE_SERIALIZE
/* serialize variables that will be shared */
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
ser_str = estrndup(new_var.c,new_var.len);
thr_acquire_write_lock(shared_vars->rwlock);
zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL);
thr_release_write_lock(shared_vars->rwlock);
THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str));
smart_str_free(&new_var);
#else
/* attempt to save an actual zval to avoid serialization overhead,
and to allow for resources to be shared (if possible?) */
/* TODO: need to make a complete copy of var */
thr_acquire_write_lock(shared_vars->rwlock);
switch(Z_TYPE_PP(&var)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
THR_PRINTF(("RESOURCE ====================================================\n"));
break;
case IS_OBJECT:
THR_PRINTF(("OBJECT ====================================================\n"));
//TODO: Special Handling for Objects
break;
default:
//TODO: This doesn't work for calls like thread_set('var', 'value')
//Only for calls like thread_set('var', $var);
/*MAKE_STD_ZVAL(target);
*target = *var;
zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode
zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL);
break;
}
/*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) {
if(Z_TYPE_PP(xvar) == IS_STRING) {
convert_to_string_ex(xvar);
}
THR_PRINTF(("thread_set: hash find ok \n"));
}*/
thr_release_write_lock(shared_vars->rwlock);
#endif
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed thread_get(string name[, int wait])
get a value from shared thread storage */
PHP_FUNCTION(thread_get)
{
char *name;
unsigned int len;
#ifdef USE_SERIALIZE
char *new_var;
zval *tmp = NULL;
#else
zval **tmp;
#endif
//Not neededTHR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread_get: Trying to return %s\n", name));
#ifdef USE_SERIALIZE
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) {
php_unserialize_data_t var_hash;
const char *p = (const char*)new_var;
MAKE_STD_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) {
zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C));
RETVAL_FALSE;
}
REPLACE_ZVAL_VALUE(&return_value, tmp, 0);
zval_copy_ctor(return_value);
INIT_PZVAL(return_value);
FREE_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
THR_PRINTF(("thread_get: successfully returned %s\n", name));
} else {
THR_PRINTF(("thread_get: not successfully found %s\n", name));
}
thr_release_read_lock(shared_vars->rwlock);
#else
/* for some reason, we cannot get zval's back if set from a different
thread */
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) {
switch(Z_TYPE_PP(tmp)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
break;
case IS_OBJECT:
//TODO: Special Handling for Objects
break;
default:
REPLACE_ZVAL_VALUE(&return_value, *tmp, 1);
break;
}
}
thr_release_read_lock(shared_vars->rwlock);
#endif
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_isset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
THR_PRINTF(("thread_isset: %s exists\n", name));
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_unset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
THR_PRINTF(("thread_unset: unsetting %s \n", name));
zend_hash_del(&shared_vars->vars, name, len + 1);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_init(string name)
create a mutex resource */
PHP_FUNCTION(thread_mutex_init)
{
/* NOTE: we create the mutex, stuff it into shared thread storage
under the provided name. Any thread can then use that mutex
by using the name of the mutex, rather than the value */
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_destroy(string name)
destroy a mutex resource */
PHP_FUNCTION(thread_mutex_destroy)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock(string name)
blocking lock on a mutex */
PHP_FUNCTION(thread_lock)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock_try(string name)
non-blocking lock on a mutex */
PHP_FUNCTION(thread_lock_try)
|
indeyets/php_threads
|
12f7f0b48daac4bfe3aa144829c30b37a88cc319
|
Fixed most of the memleaks of the test script
|
diff --git a/threadapi.c b/threadapi.c
index 55c3871..686ec9c 100644
--- a/threadapi.c
+++ b/threadapi.c
@@ -1,334 +1,335 @@
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2003 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Shane Caraveo <[email protected]> |
| Author: Alan Knowles <[email protected]> |
+----------------------------------------------------------------------+
*/
#include "threadapi.h"
#include <stdio.h>
#include "zend.h"
#ifdef TSRM_WIN32
#include <process.h>
#endif
THR_RW_LOCK *thr_create_rwlock(void)
{
THR_RW_LOCK *l = (THR_RW_LOCK *)malloc(sizeof(THR_RW_LOCK));
#ifdef TSRM_WIN32
l->lock = tsrm_mutex_alloc();
l->event = thr_create_event();
#elif defined(PTHREADS)
l->lock = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
pthread_mutex_init(l->lock,NULL);
l->event = thr_create_event();
#else
#endif
l->count = 0;
l->reset = 0;
return l;
}
void thr_close_rwlock(THR_RW_LOCK *rwlock)
{
#ifdef TSRM_WIN32
tsrm_mutex_free(rwlock->lock);
thr_close_event(rwlock->event);
#elif defined(PTHREADS)
pthread_mutex_destroy(rwlock->lock);
thr_close_event(rwlock->event);
+ free(rwlock->lock);
#else
#endif
free(rwlock);
}
void thr_acquire_write_lock(THR_RW_LOCK *rwlock)
{
#ifdef TSRM_WIN32
HANDLE muxHandle[2];
muxHandle[0] = rwlock->event;
muxHandle[1] = rwlock->lock;
WaitForSingleObject(rwlock->lock,INFINITE);
while (rwlock->count != 0) {
rwlock->reset = 0;
ReleaseMutex(rwlock->lock);
WaitForMultipleObjects(2, muxHandle, TRUE, INFINITE);
if (rwlock->reset == 0) {
rwlock->reset = 1;
ResetEvent(rwlock->event);
}
}
rwlock->count = -1;
ReleaseMutex(rwlock->lock);
#elif defined(PTHREADS)
pthread_mutex_lock(rwlock->lock);
while (rwlock->count != 0)
pthread_cond_wait(rwlock->event->cond, rwlock->lock);
rwlock->count = -1;
pthread_mutex_unlock(rwlock->lock);
#else
#endif
}
void thr_release_write_lock(THR_RW_LOCK *rwlock)
{
#ifdef TSRM_WIN32
WaitForSingleObject(rwlock->lock, INFINITE);
rwlock->count = 0;
SetEvent(rwlock->event);
ReleaseMutex(rwlock->lock);
#elif defined(PTHREADS)
pthread_mutex_lock(rwlock->lock);
rwlock->count = 0;
pthread_cond_broadcast(rwlock->event->cond);
pthread_mutex_unlock(rwlock->lock);
#else
#endif
}
void thr_acquire_read_lock(THR_RW_LOCK *rwlock)
{
#ifdef TSRM_WIN32
HANDLE muxHandle[2];
muxHandle[0] = rwlock->event;
muxHandle[1] = rwlock->lock;
WaitForSingleObject(rwlock->lock,INFINITE);
while (rwlock->count < 0) {
rwlock->reset = 0;
ReleaseMutex(rwlock->lock);
WaitForMultipleObjects(2, muxHandle, TRUE, INFINITE);
if (rwlock->reset == 0) {
rwlock->reset = 1;
ResetEvent(rwlock->event);
}
}
++rwlock->count;
ReleaseMutex(rwlock->lock);
#elif defined(PTHREADS)
pthread_mutex_lock(rwlock->lock);
while (rwlock->count < 0)
pthread_cond_wait(rwlock->event->cond, rwlock->lock);
++rwlock->count;
pthread_mutex_unlock(rwlock->lock);
#else
#endif
}
void thr_release_read_lock(THR_RW_LOCK *rwlock)
{
#ifdef TSRM_WIN32
WaitForSingleObject(rwlock->lock, INFINITE);
--rwlock->count;
if (!rwlock->count) SetEvent(rwlock->event);
ReleaseMutex(rwlock->lock);
#elif defined(PTHREADS)
pthread_mutex_lock(rwlock->lock);
--rwlock->count;
if (!rwlock->count)
pthread_cond_broadcast(rwlock->event->cond);
pthread_mutex_unlock(rwlock->lock);
#else
#endif
}
/* create an event or condition var */
THR_EVENT thr_create_event(void)
{
#ifdef TSRM_WIN32
return CreateEvent(NULL,FALSE,FALSE,NULL);
#elif defined(PTHREADS)
THR_EVENT c = (THR_EVENT) malloc(sizeof(THR_COND_VAR));
c->mutex = (pthread_mutex_t *) malloc(sizeof(pthread_mutex_t));
c->cond = (pthread_cond_t *) malloc(sizeof(pthread_cond_t));
pthread_mutex_init(c->mutex,NULL);
pthread_cond_init(c->cond,NULL);
return c;
#elif defined(NETWARE)
return NULL;
#elif defined(GNUPTH)
return NULL;
#elif defined(NSAPI)
return NULL;
#elif defined(PI3WEB)
return NULL;
#elif defined(TSRM_ST)
return NULL;
#else
return NULL;
#endif
}
int thr_wait_event(THR_EVENT event, int timeout)
{
#ifdef TSRM_WIN32
return WaitForSingleObject(event, timeout);
#elif defined(PTHREADS)
if (timeout == THR_INFINITE) {
int ret;
pthread_mutex_lock(event->mutex);
ret=pthread_cond_wait(event->cond, event->mutex);
pthread_mutex_unlock(event->mutex);
return ret;
} else {
int ret;
struct timespec ts_timeout;
struct timeval now;
gettimeofday(&now);
ts_timeout.tv_sec = now.tv_sec;
ts_timeout.tv_nsec = now.tv_usec + timeout;
pthread_mutex_lock(event->mutex);
ret = pthread_cond_timedwait(event->cond, event->mutex, &ts_timeout);
pthread_mutex_unlock(event->mutex);
return ret;
}
#elif defined(NETWARE)
return -1;
#elif defined(GNUPTH)
return -1;
#elif defined(NSAPI)
return -1;
#elif defined(PI3WEB)
return -1;
#elif defined(TSRM_ST)
return -1;
#else
return -1;
#endif
}
int thr_set_event(THR_EVENT event)
{
#ifdef TSRM_WIN32
return SetEvent(event);
#elif defined(PTHREADS)
int ret;
pthread_mutex_lock(event->mutex);
ret =pthread_cond_broadcast(event->cond);
pthread_mutex_unlock(event->mutex);
return ret;
#elif defined(NETWARE)
return -1;
#elif defined(GNUPTH)
return -1;
#elif defined(NSAPI)
return -1;
#elif defined(PI3WEB)
return -1;
#elif defined(TSRM_ST)
return -1;
#else
return -1;
#endif
}
int thr_reset_event(THR_EVENT event)
{
#ifdef TSRM_WIN32
return ResetEvent(event);
#elif defined(PTHREADS)
/* no need to reset condition variables */
return -1;
#elif defined(NETWARE)
return -1;
#elif defined(GNUPTH)
return -1;
#elif defined(NSAPI)
return -1;
#elif defined(PI3WEB)
return -1;
#elif defined(TSRM_ST)
return -1;
#else
return -1;
#endif
}
void thr_close_event(THR_EVENT event)
{
#ifdef TSRM_WIN32
CloseHandle(event);
#elif defined(PTHREADS)
pthread_cond_destroy(event->cond);
pthread_mutex_destroy(event->mutex);
free(event->cond);
free(event->mutex);
- /* free(event); */
+ free(event);
#elif defined(NETWARE)
#elif defined(GNUPTH)
#elif defined(NSAPI)
#elif defined(PI3WEB)
#elif defined(TSRM_ST)
#else
return;
#endif
}
int thr_thread_create(THR_THREAD *thread, THR_THREAD_PROC_P callback)
{
thread->id = 0;
#ifdef TSRM_WIN32
thread->thread=(HANDLE)_beginthreadex(NULL,0,callback,(void *)thread,0,&thread->id);
#elif defined(PTHREADS)
pthread_create( &(thread->thread), NULL, callback, (void *)thread);
#elif defined(NETWARE)
#elif defined(GNUPTH)
#elif defined(NSAPI)
#elif defined(PI3WEB)
#elif defined(TSRM_ST)
#endif
return thread->id;
}
void thr_thread_exit(unsigned int retval)
{
#ifdef TSRM_WIN32
_endthreadex(retval);
#elif defined(PTHREADS)
pthread_exit((void *) &retval);
#elif defined(NETWARE)
#elif defined(GNUPTH)
#elif defined(NSAPI)
#elif defined(PI3WEB)
#elif defined(TSRM_ST)
#else
return;
#endif
}
void thr_wait_exit(THR_THREAD *thread)
{
#ifdef TSRM_WIN32
WaitForSingleObject(thread->thread, THR_INFINITE);
#elif defined(PTHREADS)
pthread_join(thread->thread,NULL);
#elif defined(NETWARE)
#elif defined(GNUPTH)
#elif defined(NSAPI)
#elif defined(PI3WEB)
#elif defined(TSRM_ST)
#else
return;
#endif
}
diff --git a/threads.c b/threads.c
old mode 100644
new mode 100755
index 74e1d92..8f0a37e
--- a/threads.c
+++ b/threads.c
@@ -1,754 +1,771 @@
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2003 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Shane Caraveo <[email protected]> |
| Author: Alan Knowles <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
-# include "config.h"
+#include "config.h"
#endif
/* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */
#define THR_DEBUG
-
+
#ifdef THR_DEBUG
-# define THR_PRINTF(v) printf v; fflush(stdout);
+#define THR_PRINTF(v) printf v; fflush(stdout);
#else
-# define THR_PRINTF(v)
+#define THR_PRINTF(v)
#endif
//#define USE_SERIALIZE
#include "php.h"
#include "php_globals.h"
#include "php_main.h"
#include "php_ini.h"
#include "ext/standard/info.h"
-#include "php_threads.h"
+#include "php_threads.h"
#ifdef USE_SERIALIZE
# include "ext/standard/php_smart_str.h"
# include "ext/standard/php_var.h"
#endif
#ifndef ZTS
-# error ZTS is required
+/* ZTS REQUIRED */
#endif
-
-
-/* Our shared vars storage */
-THR_SHARED_VARS *shared_vars = NULL;
-
+
+
+/* Our shared vars storage */
+THR_SHARED_VARS *shared_vars = NULL;
+
ZEND_DECLARE_MODULE_GLOBALS(threads)
-
+
/* True global resources - no need for thread safety here */
static int le_threads;
/* {{{ threads_functions[]
*
* Every user visible function must have an entry in threads_functions[].
*/
function_entry threads_functions[] = {
PHP_FE(thread_start, NULL)
PHP_FE(thread_include, NULL)
- PHP_FE(thread_set, NULL)
- PHP_FE(thread_isset, NULL)
+ PHP_FE(thread_set, NULL)
+ PHP_FE(thread_isset, NULL)
PHP_FE(thread_unset, NULL)
PHP_FE(thread_get, NULL)
PHP_FE(thread_mutex_init,NULL)
PHP_FE(thread_mutex_destroy,NULL)
PHP_FE(thread_lock, NULL)
PHP_FE(thread_lock_try, NULL)
PHP_FE(thread_unlock, NULL)
{NULL, NULL, NULL} /* Must be the last line in threads_functions[] */
};
/* }}} */
/* {{{ threads_module_entry
*/
zend_module_entry threads_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"threads",
threads_functions,
PHP_MINIT(threads),
PHP_MSHUTDOWN(threads),
PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(threads),
#if ZEND_MODULE_API_NO >= 20010901
"0.1", /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_THREADS
ZEND_GET_MODULE(threads)
#endif
/* {{{ PHP_INI
*/
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals)
STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals)
PHP_INI_END()
*/
/* }}} */
/* {{{ _join_children
*/
static void _php_threads_join_children(void *data)
-{
+{
/* TODO: join or wait for children to end */
- THR_THREAD *thread = (THR_THREAD *) data;
-
- THR_PRINTF(("threads:_php_threads_join_children\n"));
+ THR_THREAD *thread = (THR_THREAD *) data;
+
+ THR_PRINTF(("threads:_php_threads_join_children\n"));
+#ifdef TSRM_WIN32
thr_wait_exit(thread);
+#endif
+#ifdef PTHREADS
+ pthread_join(thread->thread, NULL);
+#endif
+
thr_close_event(thread->start_event);
-
- //efree chrashes at shutdown, so "normal" free will be used
- //TSRM_FETCH seems to crash
- //efree(thread);
- //free(thread);
-
- thread = NULL;
-}
-
-
+
+
+ //efree chrashes at shutdown, so "normal" free will be used
+ //TSRM_FETCH seems to crash
+ //efree(thread);
+ THR_PRINTF(("threads:_php_threads_join_children ready\n"));
+
+ thread = NULL;
+}
+
+
/* }}} */
/* {{{ php_threads_init_globals
*/
-
+
static void _php_threads_init_globals(zend_threads_globals *threads_globals)
{
+ return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(threads)
{
THR_PRINTF(("thread:minit\n"));
ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL);
- /* If you have INI entries, uncomment these lines
+ /* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
- */
-
-
+ */
+
+
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(threads)
{
/* uncomment this line if you have INI entries
UNREGISTER_INI_ENTRIES();
- */
+ */
/* TODO: initialize some kind of shared memory for shared vars */
THR_PRINTF(("module shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(threads)
{
/* TODO: initialize a list for child threads */
- THR_PRINTF(("thread:rinit\n"));;
+ THR_PRINTF(("thread:rinit\n"));
THREADS_G(self) = NULL;
//shared_vars = NULL;
-
- if (!shared_vars) {
- /* only the master thread creates this */
- /* avoid emalloc ... - it gets totally confused with the threading stuff */
- shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
- shared_vars->rwlock = thr_create_rwlock();
- zend_hash_init(&shared_vars->vars, 0, NULL, NULL, 0);
- }
-
+
+ if (!shared_vars) {
+ /* only the master thread creates this */
+ /* avoid emalloc ... - it gets totally confused with the threading stuff */
+ shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
+ THR_PRINTF(("thread:rinit VARS\n"));
+ shared_vars->rwlock = thr_create_rwlock();
+ zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
+ }
+
+ //zend_hash_init(&THREADS_G(children), 0, NULL, _php_threads_join_children, 1);
zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0);
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(threads)
{
/* destroying the THREADS_G(children) makes this thread wait for
all THREADS_G(children) to exit */
- THR_PRINTF(("thread:rshutdown\n"));
-
- if (THREADS_G(children).count >= 1) {
- THR_PRINTF(("thread:children found\n"));
- //TODO: wait for children to be executed; send KILL signal
- zend_llist_destroy(&THREADS_G(children));
+ THR_PRINTF(("thread:rshutdown\n"));
+ if(THREADS_G(children).count >= 1) {
+ THR_PRINTF(("thread:THREADS_G(children) gefunden\n"));
+ //TODO: wait for THREADS_G(children) to be executed; send KILL signal
+ //zend_hash_destroy(&THREADS_G(children));
+ zend_llist_destroy(&THREADS_G(children));
}
-
if (!THREADS_G(self)) {
+ THR_PRINTF(("thread:rshutdown:thread_self\n"));
/* since self was never set, this is the master thread */
- THR_PRINTF(("thread:rshutdown:master\n"));
-
- THR_PRINTF(("thread:rshutdown:shared vars found: %d\n", shared_vars->vars.nNumOfElements));
- if (shared_vars && shared_vars->vars.nNumOfElements > 0) {
- // Daniel: Of course this will only be called if there are some shared vars
- // TODO: iteate over hash and delete items
- THR_PRINTF(("TODO: delete items from storage\n"));
- }
- zend_hash_destroy(&shared_vars->vars);
- thr_close_rwlock(shared_vars->rwlock);
- free(shared_vars);
- } else {
- THR_PRINTF(("thread:rshutdown:child\n"));
- //thr_wait_exit(THREADS_G(self));
- //Currently Nothing to do here
- //thr_thread_exit(0);
+ //zend_hash_destroy(&shared_vars->vars);
+ //thr_close_rwlock(shared_vars->rwlock);
+ /* Daniel: Of course this will only be called if there are some shared vars */
+ if(shared_vars && shared_vars->vars.nNumOfElements > 0) {
+ THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements));
+ }
+ zend_hash_destroy(&shared_vars->vars);
+ thr_close_rwlock(shared_vars->rwlock);
+ free(shared_vars);
+
+ } else {
+ //thr_wait_exit(THREADS_G(self));
+ THR_PRINTF(("its a meeeeeee\n"));
+ //thr_thread_exit(0);
}
-
THR_PRINTF(("request shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(threads)
{
- php_info_print_table_start();
+ php_info_print_table_start();
php_info_print_table_header(2, "Threads support", "enabled");
php_info_print_table_end();
/* Remove comments if you have entries in php.ini
DISPLAY_INI_ENTRIES();
*/
}
/* }}} */
+
-
-THR_THREAD_PROC(phpthreads_create) {
-
- zval *result = NULL;
+THR_THREAD_PROC(phpthreads_create) {
+
+ zval *result = NULL;
zend_file_handle file_handle;
// zval ret_val;
zval *local_retval = NULL;
zend_op_array *orig_op_array = NULL;
zend_op_array *op_array = NULL;
zval callback;
zval args;
zval *argv[1];
int callback_len = 0;
THR_THREAD *thread = (THR_THREAD *) data;
TSRMLS_FETCH();
THREADS_G(self) = thread;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
- /*
+ /*
TODO: copy system level data now. We need copy the global zend
- structures so that this thread has it's own copy of them.
+ structures so that this thread has it's own copy of them.
*/
SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated);
/* copy our arguments */
COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback);
COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]);
- argv[0] = &args;
- /* notify we're done copying, don't touch 'thread' after this,
+ argv[0] = &args;
+ /* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
- thr_set_event(thread->start_event);
+ thr_set_event(thread->start_event);
php_request_startup(TSRMLS_C);
#ifdef PHP_WIN32
//UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC);
#endif
- THR_PRINTF(("Call User Func\n"));
+ THR_PRINTF(("Call User Func ??????\n\n==================n\n"));
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb");
- file_handle.filename = SG(request_info).path_translated;
-
+ file_handle.filename = SG(request_info).path_translated;
+
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
EG(exit_status) = 0;
//PG(during_request_startup) = 0;
-
- op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
-
-// EG(return_value_ptr_ptr) = &result;
- EG(active_op_array) = op_array;
-
- //zend_execute(op_array TSRMLS_CC);
-
+
+ op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
+
+// EG(return_value_ptr_ptr) = &result;
+ EG(active_op_array) = op_array;
+
+ //zend_execute(op_array TSRMLS_CC);
+
orig_op_array = EG(active_op_array);
// new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/
zend_destroy_file_handle(&file_handle TSRMLS_CC);
if (EG(active_op_array)) {
EG(return_value_ptr_ptr) = &local_retval;
- /* start the thread in php user land! Instead of calling
+ /* start the thread in php user land! Instead of calling
php_execute_script, we've copied the stuff and can now
simply call into a user function */
-
+
//retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS);
//zend_execute(EG(active_op_array) TSRMLS_CC);
if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) {
zend_error(E_ERROR, "Problem Starting thread with callback");
}
zval_dtor(&callback);
zval_dtor(&args);
//zval_dtor(&ret_val);
- //zval_ptr_dtor(EG(return_value_ptr_ptr));
+ //zval_ptr_dtor(EG(return_value_ptr_ptr));
local_retval = NULL;
-
+
#ifdef ZEND_ENGINE_2
destroy_op_array(EG(active_op_array) TSRMLS_CC);
#else
destroy_op_array(EG(active_op_array));
#endif
efree(op_array);
EG(active_op_array) = orig_op_array;
}
php_request_shutdown(NULL);
-
+
thr_thread_exit(0);
-}
+}
/* {{{ proto string thread_start(string function_name, [any args])
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_start)
{
zval *callback;
THR_THREAD *thread = NULL;
zval *args;
int threadid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) {
return;
}
thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = callback;
thread->parent_tls = tsrm_ls;
thread->args[0] = (void *) args;
threadid = thr_thread_create(thread, (void *) phpthreads_create);
/* we wait here until the child thread has copied the
parent threads data */
thr_wait_event(thread->start_event,THR_INFINITE);
- zend_llist_add_element(&THREADS_G(children), (void *)thread);
- RETURN_TRUE;
+ zend_llist_add_element(&THREADS_G(children), (void *)thread);
+// zend_hash_index_update(&THREADS_G(children), threadid, (void *)thread);
+ RETURN_TRUE;
}
/* }}} */
/* THR_THREAD_PROC(phpthreads_include) { */
void phpthreads_include (void * data) {
-
- zval *result = NULL;
- zend_op_array *op_array;
+
+ zval *result = NULL;
+ zend_op_array *op_array;
int callback_len = 0;
zend_file_handle file_handle;
THR_THREAD *thread = (THR_THREAD *) data;
/* void **thr_data = thread->args; */
- char *script_file;
- int len = 0;
+ char *script_file;
+/* Threads should be detached if necessary or set by user
+#ifdef PTHREADS
+ pthread_detach(pthread_self());
+#endif
+*/
/*char *script_file = (char *)estrdup((char *) thr_data[0]);*/
//THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1];
TSRMLS_FETCH();
- len = strlen((char *) thread->args[0]);
- script_file= (char *) malloc(len + 1);
- strncpy(script_file , (char *) thread->args[0], len+1);
+ script_file = (char *) thread->args[0];
+ THR_PRINTF(("starting thread %s \n", script_file))
- thread->args[0] = NULL;
+ //thread->args[0] = NULL;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
-
+
/* do standard stuff just like cli sapi */
php_request_startup(TSRMLS_C);
-
+
THREADS_G(self) = thread; /* is ok */
//shared_vars = vars; /* is ok */
-
- THR_PRINTF(("I'm done doing the unsafe stuff\n"));
+
+ THR_PRINTF(("I'm done doing the unsafe stuff\n"));
thr_set_event(thread->start_event);
-
+
SG(request_info).path_translated = script_file;
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(script_file, "rb");
- file_handle.filename = (char *)emalloc(len +1);
- strncpy(file_handle.filename, script_file, len+1);
-
+ file_handle.filename = script_file;
+
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
- file_handle.free_filename = 1;
- /* notify we're done copying, don't touch 'thread' after this,
+ file_handle.free_filename = 0;
+ /* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
-
- THR_PRINTF(("sent - running script \n"));
-
- op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
- zend_destroy_file_handle(&file_handle TSRMLS_CC);
-
- EG(return_value_ptr_ptr) = &result;
- EG(active_op_array) = op_array;
-
- zend_execute(op_array TSRMLS_CC);
-
- destroy_op_array(op_array TSRMLS_CC);
- efree(op_array);
+
+ THR_PRINTF(("sent - running script \n"));
+
+ op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
+ zend_destroy_file_handle(&file_handle TSRMLS_CC);
+
+ EG(return_value_ptr_ptr) = &result;
+ EG(active_op_array) = op_array;
+
+ zend_execute(op_array TSRMLS_CC);
+
+ destroy_op_array(op_array TSRMLS_CC);
+ efree(op_array);
op_array = NULL;
-
- //php_execute_script(&file_handle TSRMLS_CC);
-
- THR_PRINTF(("done running script \n"));
-
+ efree(*EG(return_value_ptr_ptr));
+
+ //php_execute_script(&file_handle TSRMLS_CC);
+
+ THR_PRINTF(("done running script \n"));
+
/* self destruct DOES NOT WORK FOR SOME REASON! */
+
+ php_request_shutdown(NULL); /* NOW IT WORKS */
+
+ THR_PRINTF(("done request shutdown \n"));
+
+ /* found in tsrm.c and is extremly useful */
+ ts_free_thread();
- php_request_shutdown(NULL); /* NOW IT WORKS */
-
- THR_PRINTF(("done request shutdown \n"));
+ //free(thread);
+ thr_thread_exit(0);
- free(script_file);
- /* found in tsrm.c and is extremly useful */
- ts_free_thread();
-
- //free(thread);
- thr_thread_exit(0);
-
-}
+}
/* {{{ proto string thread_start(string filename)
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_include)
{
char *script_file=NULL;
char *script_file_in;
int len;
int threadid;
THR_THREAD *thread = NULL;
//THR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) {
RETURN_FALSE;
- }
-
+ }
+
// if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
// shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
// shared_vars->rwlock = thr_create_rwlock();
// zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
// vars = shared_vars;
// }
- script_file= (char *) malloc(len + 1);
+ script_file= (char *) emalloc(len + 1);
strncpy(script_file , script_file_in, len+1);
/* avoid emalloc ... - it gets totally confused with the threading stuff */
thread = (THR_THREAD *) malloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = NULL;
thread->parent_tls = tsrm_ls;
thread->args[0] = script_file;
thread->args[1] = NULL;
THR_PRINTF(("value of args is %x\n", thread->args));
-
- threadid = thr_thread_create(thread, (void *) phpthreads_include);
+
+ thread->id = thr_thread_create(thread, (void *) phpthreads_include);
/* we wait here until the child thread has copied the
parent threads data */
+
+ THR_PRINTF(("done creating thread - waiting for all clear \n"))
- THR_PRINTF(("done creating thread - waiting for all clear \n"))
-
+
/* waiting for thread to start... */
- thr_wait_event(thread->start_event,THR_INFINITE);
+#ifdef TSRM_WIN32
+ thr_wait_event(thread->start_event, THR_INFINITE);
+#endif
+
THR_PRINTF(("got message that thread had finished initializing \n"))
- zend_llist_add_element(&THREADS_G(children), (void *)thread);
- free(script_file);
- thread->parent_tls = NULL;
- free(thread);
+// thread->args[0] = NULL;
+
+ //zend_hash_index_update(&THREADS_G(children), threadid, (void *) thread, sizeof(THR_THREAD *), NULL);
+ zend_llist_add_element(&THREADS_G(children), (void *)thread);
+
+ free(thread);
+ efree(script_file);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_set(string name, mixed variable)
set a value into shared thread storage */
PHP_FUNCTION(thread_set)
{
char *name;
unsigned int len;
- zval *var;
+ zval *var;
zval *newvar = NULL, **xvar=NULL;
THR_SHARED_VARS *vars = shared_vars;
-#ifdef USE_SERIALIZE
+#ifdef USE_SERIALIZE
smart_str new_var = {0};
char *ser_str = NULL;
- php_serialize_data_t var_hash;
-#else
- zval *target;
+ php_serialize_data_t var_hash;
+#else
+ zval *target;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) {
RETURN_FALSE;
- }
-
+ }
+
THR_PRINTF(("thread:thread_set==%s==\n", name));
-#ifdef USE_SERIALIZE
+#ifdef USE_SERIALIZE
/* serialize variables that will be shared */
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
ser_str = estrndup(new_var.c,new_var.len);
thr_acquire_write_lock(shared_vars->rwlock);
zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL);
thr_release_write_lock(shared_vars->rwlock);
-
- THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str));
-
+
+ THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str));
+
smart_str_free(&new_var);
#else
/* attempt to save an actual zval to avoid serialization overhead,
and to allow for resources to be shared (if possible?) */
/* TODO: need to make a complete copy of var */
- thr_acquire_write_lock(shared_vars->rwlock);
-
- switch(Z_TYPE_PP(&var)) {
- case IS_RESOURCE:
- //TODO: special Handling for Resources
- THR_PRINTF(("RESOURCE IS NOT ALLOWED\n"));
- break;
- case IS_OBJECT:
- THR_PRINTF(("OBJECT IS NOT ALLOWED\n"));
- //TODO: Special Handling for Objects
- break;
+ thr_acquire_write_lock(shared_vars->rwlock);
+
+ switch(Z_TYPE_PP(&var)) {
+ case IS_RESOURCE:
+ //TODO: special Handling for Resources
+ THR_PRINTF(("RESOURCE ====================================================\n"));
+ break;
+ case IS_OBJECT:
+ THR_PRINTF(("OBJECT ====================================================\n"));
+ //TODO: Special Handling for Objects
+ break;
default:
- MAKE_STD_ZVAL(target);
- *target = *var;
- zval_copy_ctor(target);
- zend_hash_update(&shared_vars->vars, name, len+1, (void *) &target, sizeof(zval *),NULL);
- break;
-
- }
-
+ //TODO: This doesn't work for calls like thread_set('var', 'value')
+ //Only for calls like thread_set('var', $var);
+ /*MAKE_STD_ZVAL(target);
+ *target = *var;
zval_copy_ctor(target);*/ //Commenting this in does produce memleaks reported by DEBUG-mode
+ zend_hash_update(&shared_vars->vars, name, len+1, (void *) &var, sizeof(zval *),NULL);
+ break;
+
+ }
+
/*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) {
- if(Z_TYPE_PP(xvar) == IS_STRING) {
- convert_to_string_ex(xvar);
- }
- THR_PRINTF(("thread_set: hash find ok \n"));
- }*/
-
-
- thr_release_write_lock(shared_vars->rwlock);
+ if(Z_TYPE_PP(xvar) == IS_STRING) {
+ convert_to_string_ex(xvar);
+ }
+ THR_PRINTF(("thread_set: hash find ok \n"));
+ }*/
+
+
+ thr_release_write_lock(shared_vars->rwlock);
#endif
- RETURN_TRUE;
+ RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed thread_get(string name[, int wait])
get a value from shared thread storage */
PHP_FUNCTION(thread_get)
{
- char *name;
- unsigned int len;
+ char *name;
+ unsigned int len;
#ifdef USE_SERIALIZE
char *new_var;
zval *tmp = NULL;
#else
zval **tmp;
#endif
//Not neededTHR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
- }
-
- THR_PRINTF(("thread_get: Trying to return %s\n", name));
+ }
+
+ THR_PRINTF(("thread_get: Trying to return %s\n", name));
#ifdef USE_SERIALIZE
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) {
php_unserialize_data_t var_hash;
const char *p = (const char*)new_var;
MAKE_STD_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) {
zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C));
RETVAL_FALSE;
}
-
-
+
+
REPLACE_ZVAL_VALUE(&return_value, tmp, 0);
- zval_copy_ctor(return_value);
- INIT_PZVAL(return_value);
+ zval_copy_ctor(return_value);
+ INIT_PZVAL(return_value);
FREE_ZVAL(tmp);
- PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
+ PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
THR_PRINTF(("thread_get: successfully returned %s\n", name));
- } else {
- THR_PRINTF(("thread_get: not successfully found %s\n", name));
+ } else {
+ THR_PRINTF(("thread_get: not successfully found %s\n", name));
}
thr_release_read_lock(shared_vars->rwlock);
#else
- /* for some reason, we cannot get zval's back if set from a different
+ /* for some reason, we cannot get zval's back if set from a different
thread */
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) {
- switch(Z_TYPE_PP(tmp)) {
- case IS_RESOURCE:
- //TODO: special Handling for Resources
- break;
- case IS_OBJECT:
- //TODO: Special Handling for Objects
- break;
- default:
- REPLACE_ZVAL_VALUE(&return_value, *tmp, 1);
- break;
-
- }
- }
- thr_release_read_lock(shared_vars->rwlock);
+ switch(Z_TYPE_PP(tmp)) {
+ case IS_RESOURCE:
+ //TODO: special Handling for Resources
+ break;
+ case IS_OBJECT:
+ //TODO: Special Handling for Objects
+ break;
+ default:
+ REPLACE_ZVAL_VALUE(&return_value, *tmp, 1);
+ break;
+
+ }
+ }
+ thr_release_read_lock(shared_vars->rwlock);
#endif
}
/* }}} */
-
-/* {{{ proto boolean thread_isset(string name)
- check existense of a shared var */
-PHP_FUNCTION(thread_isset)
-{
-
- char *name;
- unsigned int len;
-
- if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
- RETURN_FALSE;
- }
-
- if(zend_hash_exists(&shared_vars->vars, name, len+1)) {
- THR_PRINTF(("thread_isset: %s exists\n", name));
- RETURN_TRUE;
- } else {
- RETURN_FALSE;
- }
-
-}
-/* }}} */
-
-
-/* {{{ proto boolean thread_isset(string name)
- check existense of a shared var */
-PHP_FUNCTION(thread_unset)
-{
-
- char *name;
- unsigned int len;
-
- if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
- RETURN_FALSE;
- }
-
- if(zend_hash_exists(&shared_vars->vars, name, len+1)) {
- THR_PRINTF(("thread_unset: unsetting %s \n", name));
- zend_hash_del(&shared_vars->vars, name, len+1);
- }
-
- RETURN_TRUE;
-
-}
-/* }}} */
-
+
+/* {{{ proto boolean thread_isset(string name)
+ check existense of a shared var */
+PHP_FUNCTION(thread_isset)
+{
+
+ char *name;
+ unsigned int len;
+
+ if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
+ RETURN_FALSE;
+ }
+
+ if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
+ THR_PRINTF(("thread_isset: %s exists\n", name));
+ RETURN_TRUE;
+ } else {
+ RETURN_FALSE;
+ }
+
+}
+/* }}} */
+
+
+/* {{{ proto boolean thread_isset(string name)
+ check existense of a shared var */
+PHP_FUNCTION(thread_unset)
+{
+
+ char *name;
+ unsigned int len;
+
+ if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
+ RETURN_FALSE;
+ }
+
+ if(zend_hash_exists(&shared_vars->vars, name, len + 1)) {
+ THR_PRINTF(("thread_unset: unsetting %s \n", name));
+ zend_hash_del(&shared_vars->vars, name, len + 1);
+ }
+
+ RETURN_TRUE;
+
+}
+/* }}} */
+
/* {{{ proto boolean thread_mutex_init(string name)
create a mutex resource */
PHP_FUNCTION(thread_mutex_init)
{
/* NOTE: we create the mutex, stuff it into shared thread storage
under the provided name. Any thread can then use that mutex
by using the name of the mutex, rather than the value */
- RETURN_FALSE;
+ RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_destroy(string name)
destroy a mutex resource */
PHP_FUNCTION(thread_mutex_destroy)
{
- RETURN_FALSE;
+ RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock(string name)
blocking lock on a mutex */
PHP_FUNCTION(thread_lock)
{
- RETURN_FALSE;
+ RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock_try(string name)
non-blocking lock on a mutex */
PHP_FUNCTION(thread_lock_try)
{
- RETURN_FALSE;
+ RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_unlock(string name)
unlock a locked mutex */
PHP_FUNCTION(thread_unlock)
{
- RETURN_FALSE;
+ RETURN_FALSE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
-
|
indeyets/php_threads
|
e54404efdb1421316578a78a77694f221797f681
|
A bit better memory management abd fixes of thread_isset/_unset
|
diff --git a/threads.c b/threads.c
index cbc388e..74e1d92 100644
--- a/threads.c
+++ b/threads.c
@@ -1,745 +1,754 @@
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2003 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Shane Caraveo <[email protected]> |
| Author: Alan Knowles <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif
/* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */
#define THR_DEBUG
#ifdef THR_DEBUG
# define THR_PRINTF(v) printf v; fflush(stdout);
#else
# define THR_PRINTF(v)
#endif
//#define USE_SERIALIZE
#include "php.h"
#include "php_globals.h"
#include "php_main.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_threads.h"
#ifdef USE_SERIALIZE
# include "ext/standard/php_smart_str.h"
# include "ext/standard/php_var.h"
#endif
#ifndef ZTS
# error ZTS is required
#endif
/* Our shared vars storage */
THR_SHARED_VARS *shared_vars = NULL;
ZEND_DECLARE_MODULE_GLOBALS(threads)
/* True global resources - no need for thread safety here */
static int le_threads;
/* {{{ threads_functions[]
*
* Every user visible function must have an entry in threads_functions[].
*/
function_entry threads_functions[] = {
PHP_FE(thread_start, NULL)
PHP_FE(thread_include, NULL)
PHP_FE(thread_set, NULL)
PHP_FE(thread_isset, NULL)
PHP_FE(thread_unset, NULL)
PHP_FE(thread_get, NULL)
PHP_FE(thread_mutex_init,NULL)
PHP_FE(thread_mutex_destroy,NULL)
PHP_FE(thread_lock, NULL)
PHP_FE(thread_lock_try, NULL)
PHP_FE(thread_unlock, NULL)
{NULL, NULL, NULL} /* Must be the last line in threads_functions[] */
};
/* }}} */
/* {{{ threads_module_entry
*/
zend_module_entry threads_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"threads",
threads_functions,
PHP_MINIT(threads),
PHP_MSHUTDOWN(threads),
PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(threads),
#if ZEND_MODULE_API_NO >= 20010901
"0.1", /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_THREADS
ZEND_GET_MODULE(threads)
#endif
/* {{{ PHP_INI
*/
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals)
STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals)
PHP_INI_END()
*/
/* }}} */
/* {{{ _join_children
*/
static void _php_threads_join_children(void *data)
{
/* TODO: join or wait for children to end */
THR_THREAD *thread = (THR_THREAD *) data;
THR_PRINTF(("threads:_php_threads_join_children\n"));
thr_wait_exit(thread);
thr_close_event(thread->start_event);
//efree chrashes at shutdown, so "normal" free will be used
//TSRM_FETCH seems to crash
//efree(thread);
//free(thread);
thread = NULL;
}
/* }}} */
/* {{{ php_threads_init_globals
*/
static void _php_threads_init_globals(zend_threads_globals *threads_globals)
{
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(threads)
{
THR_PRINTF(("thread:minit\n"));
ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL);
/* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
*/
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(threads)
{
/* uncomment this line if you have INI entries
UNREGISTER_INI_ENTRIES();
*/
/* TODO: initialize some kind of shared memory for shared vars */
THR_PRINTF(("module shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(threads)
{
/* TODO: initialize a list for child threads */
THR_PRINTF(("thread:rinit\n"));;
THREADS_G(self) = NULL;
//shared_vars = NULL;
if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
shared_vars->rwlock = thr_create_rwlock();
zend_hash_init(&shared_vars->vars, 0, NULL, NULL, 0);
}
zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0);
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(threads)
{
/* destroying the THREADS_G(children) makes this thread wait for
all THREADS_G(children) to exit */
THR_PRINTF(("thread:rshutdown\n"));
if (THREADS_G(children).count >= 1) {
THR_PRINTF(("thread:children found\n"));
//TODO: wait for children to be executed; send KILL signal
zend_llist_destroy(&THREADS_G(children));
}
if (!THREADS_G(self)) {
/* since self was never set, this is the master thread */
THR_PRINTF(("thread:rshutdown:master\n"));
THR_PRINTF(("thread:rshutdown:shared vars found: %d\n", shared_vars->vars.nNumOfElements));
if (shared_vars && shared_vars->vars.nNumOfElements > 0) {
// Daniel: Of course this will only be called if there are some shared vars
// TODO: iteate over hash and delete items
THR_PRINTF(("TODO: delete items from storage\n"));
}
zend_hash_destroy(&shared_vars->vars);
thr_close_rwlock(shared_vars->rwlock);
+ free(shared_vars);
} else {
THR_PRINTF(("thread:rshutdown:child\n"));
//thr_wait_exit(THREADS_G(self));
//Currently Nothing to do here
//thr_thread_exit(0);
}
THR_PRINTF(("request shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(threads)
{
php_info_print_table_start();
php_info_print_table_header(2, "Threads support", "enabled");
php_info_print_table_end();
/* Remove comments if you have entries in php.ini
DISPLAY_INI_ENTRIES();
*/
}
/* }}} */
THR_THREAD_PROC(phpthreads_create) {
zval *result = NULL;
zend_file_handle file_handle;
// zval ret_val;
zval *local_retval = NULL;
zend_op_array *orig_op_array = NULL;
zend_op_array *op_array = NULL;
zval callback;
zval args;
zval *argv[1];
int callback_len = 0;
THR_THREAD *thread = (THR_THREAD *) data;
TSRMLS_FETCH();
THREADS_G(self) = thread;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/*
TODO: copy system level data now. We need copy the global zend
structures so that this thread has it's own copy of them.
*/
SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated);
/* copy our arguments */
COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback);
COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]);
argv[0] = &args;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
thr_set_event(thread->start_event);
php_request_startup(TSRMLS_C);
#ifdef PHP_WIN32
//UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC);
#endif
THR_PRINTF(("Call User Func\n"));
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb");
file_handle.filename = SG(request_info).path_translated;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
EG(exit_status) = 0;
//PG(during_request_startup) = 0;
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
// EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
//zend_execute(op_array TSRMLS_CC);
orig_op_array = EG(active_op_array);
// new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/
zend_destroy_file_handle(&file_handle TSRMLS_CC);
if (EG(active_op_array)) {
EG(return_value_ptr_ptr) = &local_retval;
/* start the thread in php user land! Instead of calling
php_execute_script, we've copied the stuff and can now
simply call into a user function */
//retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS);
//zend_execute(EG(active_op_array) TSRMLS_CC);
if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) {
zend_error(E_ERROR, "Problem Starting thread with callback");
}
zval_dtor(&callback);
zval_dtor(&args);
//zval_dtor(&ret_val);
//zval_ptr_dtor(EG(return_value_ptr_ptr));
local_retval = NULL;
#ifdef ZEND_ENGINE_2
destroy_op_array(EG(active_op_array) TSRMLS_CC);
#else
destroy_op_array(EG(active_op_array));
#endif
efree(op_array);
EG(active_op_array) = orig_op_array;
}
php_request_shutdown(NULL);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string function_name, [any args])
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_start)
{
zval *callback;
THR_THREAD *thread = NULL;
zval *args;
int threadid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) {
return;
}
thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = callback;
thread->parent_tls = tsrm_ls;
thread->args[0] = (void *) args;
threadid = thr_thread_create(thread, (void *) phpthreads_create);
/* we wait here until the child thread has copied the
parent threads data */
thr_wait_event(thread->start_event,THR_INFINITE);
zend_llist_add_element(&THREADS_G(children), (void *)thread);
RETURN_TRUE;
}
/* }}} */
/* THR_THREAD_PROC(phpthreads_include) { */
void phpthreads_include (void * data) {
zval *result = NULL;
- zend_op_array *op_array;
+ zend_op_array *op_array;
int callback_len = 0;
zend_file_handle file_handle;
THR_THREAD *thread = (THR_THREAD *) data;
/* void **thr_data = thread->args; */
char *script_file;
+ int len = 0;
/*char *script_file = (char *)estrdup((char *) thr_data[0]);*/
//THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1];
TSRMLS_FETCH();
- script_file = (char *) thread->args[0];
- THR_PRINTF(("starting thread %s \n", script_file))
+ len = strlen((char *) thread->args[0]);
+ script_file= (char *) malloc(len + 1);
+ strncpy(script_file , (char *) thread->args[0], len+1);
thread->args[0] = NULL;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/* do standard stuff just like cli sapi */
php_request_startup(TSRMLS_C);
THREADS_G(self) = thread; /* is ok */
//shared_vars = vars; /* is ok */
THR_PRINTF(("I'm done doing the unsafe stuff\n"));
thr_set_event(thread->start_event);
SG(request_info).path_translated = script_file;
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(script_file, "rb");
- file_handle.filename = script_file;
+ file_handle.filename = (char *)emalloc(len +1);
+ strncpy(file_handle.filename, script_file, len+1);
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 1;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
THR_PRINTF(("sent - running script \n"));
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
zend_destroy_file_handle(&file_handle TSRMLS_CC);
EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
zend_execute(op_array TSRMLS_CC);
destroy_op_array(op_array TSRMLS_CC);
efree(op_array);
op_array = NULL;
//php_execute_script(&file_handle TSRMLS_CC);
THR_PRINTF(("done running script \n"));
/* self destruct DOES NOT WORK FOR SOME REASON! */
php_request_shutdown(NULL); /* NOW IT WORKS */
THR_PRINTF(("done request shutdown \n"));
+ free(script_file);
/* found in tsrm.c and is extremly useful */
ts_free_thread();
- free(thread);
+ //free(thread);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string filename)
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_include)
{
char *script_file=NULL;
char *script_file_in;
int len;
int threadid;
THR_THREAD *thread = NULL;
//THR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) {
RETURN_FALSE;
}
// if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
// shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
// shared_vars->rwlock = thr_create_rwlock();
// zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
// vars = shared_vars;
// }
- script_file= (char *) emalloc(len + 1);
+ script_file= (char *) malloc(len + 1);
strncpy(script_file , script_file_in, len+1);
/* avoid emalloc ... - it gets totally confused with the threading stuff */
thread = (THR_THREAD *) malloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = NULL;
thread->parent_tls = tsrm_ls;
thread->args[0] = script_file;
thread->args[1] = NULL;
THR_PRINTF(("value of args is %x\n", thread->args));
threadid = thr_thread_create(thread, (void *) phpthreads_include);
/* we wait here until the child thread has copied the
parent threads data */
THR_PRINTF(("done creating thread - waiting for all clear \n"))
/* waiting for thread to start... */
thr_wait_event(thread->start_event,THR_INFINITE);
THR_PRINTF(("got message that thread had finished initializing \n"))
zend_llist_add_element(&THREADS_G(children), (void *)thread);
+
+ free(script_file);
+ thread->parent_tls = NULL;
+ free(thread);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_set(string name, mixed variable)
set a value into shared thread storage */
PHP_FUNCTION(thread_set)
{
char *name;
unsigned int len;
zval *var;
zval *newvar = NULL, **xvar=NULL;
THR_SHARED_VARS *vars = shared_vars;
#ifdef USE_SERIALIZE
smart_str new_var = {0};
char *ser_str = NULL;
php_serialize_data_t var_hash;
#else
zval *target;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread:thread_set==%s==\n", name));
#ifdef USE_SERIALIZE
/* serialize variables that will be shared */
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
ser_str = estrndup(new_var.c,new_var.len);
thr_acquire_write_lock(shared_vars->rwlock);
zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL);
thr_release_write_lock(shared_vars->rwlock);
THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str));
smart_str_free(&new_var);
#else
/* attempt to save an actual zval to avoid serialization overhead,
and to allow for resources to be shared (if possible?) */
/* TODO: need to make a complete copy of var */
thr_acquire_write_lock(shared_vars->rwlock);
switch(Z_TYPE_PP(&var)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
THR_PRINTF(("RESOURCE IS NOT ALLOWED\n"));
break;
case IS_OBJECT:
THR_PRINTF(("OBJECT IS NOT ALLOWED\n"));
//TODO: Special Handling for Objects
break;
default:
MAKE_STD_ZVAL(target);
*target = *var;
zval_copy_ctor(target);
zend_hash_update(&shared_vars->vars, name, len+1, (void *) &target, sizeof(zval *),NULL);
break;
}
/*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) {
if(Z_TYPE_PP(xvar) == IS_STRING) {
convert_to_string_ex(xvar);
}
THR_PRINTF(("thread_set: hash find ok \n"));
}*/
thr_release_write_lock(shared_vars->rwlock);
#endif
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed thread_get(string name[, int wait])
get a value from shared thread storage */
PHP_FUNCTION(thread_get)
{
char *name;
unsigned int len;
#ifdef USE_SERIALIZE
char *new_var;
zval *tmp = NULL;
#else
zval **tmp;
#endif
//Not neededTHR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread_get: Trying to return %s\n", name));
#ifdef USE_SERIALIZE
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) {
php_unserialize_data_t var_hash;
const char *p = (const char*)new_var;
MAKE_STD_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) {
zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C));
RETVAL_FALSE;
}
REPLACE_ZVAL_VALUE(&return_value, tmp, 0);
zval_copy_ctor(return_value);
INIT_PZVAL(return_value);
FREE_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
THR_PRINTF(("thread_get: successfully returned %s\n", name));
} else {
THR_PRINTF(("thread_get: not successfully found %s\n", name));
}
thr_release_read_lock(shared_vars->rwlock);
#else
/* for some reason, we cannot get zval's back if set from a different
thread */
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) {
switch(Z_TYPE_PP(tmp)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
break;
case IS_OBJECT:
//TODO: Special Handling for Objects
break;
default:
REPLACE_ZVAL_VALUE(&return_value, *tmp, 1);
break;
}
}
thr_release_read_lock(shared_vars->rwlock);
#endif
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_isset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
- if(zend_hash_exists(&shared_vars->vars, name, len)) {
+ if(zend_hash_exists(&shared_vars->vars, name, len+1)) {
THR_PRINTF(("thread_isset: %s exists\n", name));
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_unset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
- if(zend_hash_exists(&shared_vars->vars, name, len)) {
+ if(zend_hash_exists(&shared_vars->vars, name, len+1)) {
THR_PRINTF(("thread_unset: unsetting %s \n", name));
- zend_hash_del(&shared_vars->vars, name, len);
+ zend_hash_del(&shared_vars->vars, name, len+1);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_init(string name)
create a mutex resource */
PHP_FUNCTION(thread_mutex_init)
{
/* NOTE: we create the mutex, stuff it into shared thread storage
under the provided name. Any thread can then use that mutex
by using the name of the mutex, rather than the value */
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_destroy(string name)
destroy a mutex resource */
PHP_FUNCTION(thread_mutex_destroy)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock(string name)
blocking lock on a mutex */
PHP_FUNCTION(thread_lock)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock_try(string name)
non-blocking lock on a mutex */
PHP_FUNCTION(thread_lock_try)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_unlock(string name)
unlock a locked mutex */
PHP_FUNCTION(thread_unlock)
{
RETURN_FALSE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
indeyets/php_threads
|
220c97ab34377488f09492674d4516f0a45a077a
|
Cleanup
|
diff --git a/threads.c b/threads.c
index 6b4e345..7b66a20 100644
--- a/threads.c
+++ b/threads.c
@@ -1,746 +1,741 @@
/*
+----------------------------------------------------------------------+
| PHP Version 4 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2003 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 2.02 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available at through the world-wide-web at |
| http://www.php.net/license/2_02.txt. |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Shane Caraveo <[email protected]> |
| Author: Alan Knowles <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* debugging - use THR_PRINTF(("somthing %s", string)); - note the double brackets.. */
#define THR_DEBUG
#ifdef THR_DEBUG
#define THR_PRINTF(v) printf v; fflush(stdout);
#else
#define THR_PRINTF(v)
#endif
//#define USE_SERIALIZE
#include "php.h"
#include "php_globals.h"
#include "php_main.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_threads.h"
#ifdef USE_SERIALIZE
# include "ext/standard/php_smart_str.h"
# include "ext/standard/php_var.h"
#endif
#ifndef ZTS
/* ZTS REQUIRED */
#endif
/* Our shared vars storage */
THR_SHARED_VARS *shared_vars = NULL;
ZEND_DECLARE_MODULE_GLOBALS(threads)
/* True global resources - no need for thread safety here */
static int le_threads;
/* {{{ threads_functions[]
*
* Every user visible function must have an entry in threads_functions[].
*/
function_entry threads_functions[] = {
PHP_FE(thread_start, NULL)
PHP_FE(thread_include, NULL)
PHP_FE(thread_set, NULL)
PHP_FE(thread_isset, NULL)
PHP_FE(thread_unset, NULL)
PHP_FE(thread_get, NULL)
PHP_FE(thread_mutex_init,NULL)
PHP_FE(thread_mutex_destroy,NULL)
PHP_FE(thread_lock, NULL)
PHP_FE(thread_lock_try, NULL)
PHP_FE(thread_unlock, NULL)
{NULL, NULL, NULL} /* Must be the last line in threads_functions[] */
};
/* }}} */
/* {{{ threads_module_entry
*/
zend_module_entry threads_module_entry = {
#if ZEND_MODULE_API_NO >= 20010901
STANDARD_MODULE_HEADER,
#endif
"threads",
threads_functions,
PHP_MINIT(threads),
PHP_MSHUTDOWN(threads),
PHP_RINIT(threads), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(threads), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(threads),
#if ZEND_MODULE_API_NO >= 20010901
"0.1", /* Replace with version number for your extension */
#endif
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_THREADS
ZEND_GET_MODULE(threads)
#endif
/* {{{ PHP_INI
*/
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("threads.global_value", "42", PHP_INI_ALL, OnUpdateInt, global_value, zend_threads_globals, threads_globals)
STD_PHP_INI_ENTRY("threads.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_threads_globals, threads_globals)
PHP_INI_END()
*/
/* }}} */
/* {{{ _join_children
*/
static void _php_threads_join_children(void *data)
{
/* TODO: join or wait for children to end */
THR_THREAD *thread = (THR_THREAD *) data;
THR_PRINTF(("threads:_php_threads_join_children\n"));
thr_wait_exit(thread);
- THR_PRINTF(("threads:_php_threads_join_children thr_wait_exit over\n"));
- thr_close_event(thread->start_event);
- THR_PRINTF(("threads:_php_threads_join_children close_event over\n"));
+
+ thr_close_event(thread->start_event);
//efree chrashes at shutdown, so "normal" free will be used
//TSRM_FETCH seems to crash
//efree(thread);
- THR_PRINTF(("threads:_php_threads_join_children free ready\n"));
-
//free(thread);
- THR_PRINTF(("threads:_php_threads_join_children free over\n"));
thread = NULL;
}
/* }}} */
/* {{{ php_threads_init_globals
*/
static void _php_threads_init_globals(zend_threads_globals *threads_globals)
{
}
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(threads)
{
THR_PRINTF(("thread:minit\n"));
ZEND_INIT_MODULE_GLOBALS(threads, _php_threads_init_globals, NULL);
/* If you have INI entries, uncomment these lines
REGISTER_INI_ENTRIES();
*/
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(threads)
{
/* uncomment this line if you have INI entries
UNREGISTER_INI_ENTRIES();
*/
/* TODO: initialize some kind of shared memory for shared vars */
THR_PRINTF(("module shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(threads)
{
/* TODO: initialize a list for child threads */
THR_PRINTF(("thread:rinit\n"));;
THREADS_G(self) = NULL;
//shared_vars = NULL;
if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
- THR_PRINTF(("thread:rinit VARS\n"));
shared_vars->rwlock = thr_create_rwlock();
zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
}
zend_llist_init(&THREADS_G(children), sizeof(THR_THREAD),_php_threads_join_children, 0);
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(threads)
{
/* destroying the THREADS_G(children) makes this thread wait for
all THREADS_G(children) to exit */
THR_PRINTF(("thread:rshutdown\n"));
if(THREADS_G(children).count >= 1) {
- THR_PRINTF(("thread:THREADS_G(children) gefunden\n"));
- //TODO: wait for THREADS_G(children) to be executed; send KILL signal
+ THR_PRINTF(("thread:children found\n"));
+ //TODO: wait for children to be executed; send KILL signal
zend_llist_destroy(&THREADS_G(children));
}
if (!THREADS_G(self)) {
THR_PRINTF(("thread:rshutdown:thread_self\n"));
/* since self was never set, this is the master thread */
//zend_hash_destroy(&shared_vars->vars);
//thr_close_rwlock(shared_vars->rwlock);
/* Daniel: Of course this will only be called if there are some shared vars */
if(shared_vars && shared_vars->vars.nNumOfElements > 0) {
THR_PRINTF(("thread:shared vars found: %d\n", shared_vars->vars.nNumOfElements));
zend_hash_destroy(&shared_vars->vars);
thr_close_rwlock(shared_vars->rwlock);
}
} else {
//thr_wait_exit(THREADS_G(self));
- THR_PRINTF(("its a meeeeeee\n"));
+ //Currently Nothing to do here
//thr_thread_exit(0);
}
THR_PRINTF(("request shutdown in thread\n"));
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(threads)
{
php_info_print_table_start();
php_info_print_table_header(2, "Threads support", "enabled");
php_info_print_table_end();
/* Remove comments if you have entries in php.ini
DISPLAY_INI_ENTRIES();
*/
}
/* }}} */
THR_THREAD_PROC(phpthreads_create) {
zval *result = NULL;
zend_file_handle file_handle;
// zval ret_val;
zval *local_retval = NULL;
zend_op_array *orig_op_array = NULL;
zend_op_array *op_array = NULL;
zval callback;
zval args;
zval *argv[1];
int callback_len = 0;
THR_THREAD *thread = (THR_THREAD *) data;
TSRMLS_FETCH();
THREADS_G(self) = thread;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/*
TODO: copy system level data now. We need copy the global zend
structures so that this thread has it's own copy of them.
*/
SG(request_info).path_translated = estrdup(THR_SG(thread->parent_tls,request_info).path_translated);
/* copy our arguments */
COPY_PZVAL_TO_ZVAL(callback,(zval *)thread->callback);
COPY_PZVAL_TO_ZVAL(args,(zval *)thread->args[0]);
argv[0] = &args;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
thr_set_event(thread->start_event);
php_request_startup(TSRMLS_C);
#ifdef PHP_WIN32
//UpdateIniFromRegistry(SG(request_info).path_translated TSRMLS_CC);
#endif
- THR_PRINTF(("Call User Func ??????\n\n==================n\n"));
+ THR_PRINTF(("Call User Func\n"));
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(SG(request_info).path_translated, "rb");
file_handle.filename = SG(request_info).path_translated;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 0;
EG(exit_status) = 0;
//PG(during_request_startup) = 0;
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
// EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
//zend_execute(op_array TSRMLS_CC);
orig_op_array = EG(active_op_array);
// new_op_array= EG(active_op_array) = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);*/
zend_destroy_file_handle(&file_handle TSRMLS_CC);
if (EG(active_op_array)) {
EG(return_value_ptr_ptr) = &local_retval;
/* start the thread in php user land! Instead of calling
php_execute_script, we've copied the stuff and can now
simply call into a user function */
//retval = (zend_execute_scripts(ZEND_REQUIRE TSRMLS_CC, NULL, 3, prepend_file_p, primary_file, append_file_p) == SUCCESS);
//zend_execute(EG(active_op_array) TSRMLS_CC);
if (!call_user_function(EG(function_table), NULL, &callback, local_retval, 1, argv TSRMLS_CC )) {
zend_error(E_ERROR, "Problem Starting thread with callback");
}
zval_dtor(&callback);
zval_dtor(&args);
//zval_dtor(&ret_val);
//zval_ptr_dtor(EG(return_value_ptr_ptr));
local_retval = NULL;
#ifdef ZEND_ENGINE_2
destroy_op_array(EG(active_op_array) TSRMLS_CC);
#else
destroy_op_array(EG(active_op_array));
#endif
efree(op_array);
EG(active_op_array) = orig_op_array;
}
php_request_shutdown(NULL);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string function_name, [any args])
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_start)
{
zval *callback;
THR_THREAD *thread = NULL;
zval *args;
int threadid;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "z|z", &callback, &args) == FAILURE) {
return;
}
thread = (THR_THREAD *) emalloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = callback;
thread->parent_tls = tsrm_ls;
thread->args[0] = (void *) args;
threadid = thr_thread_create(thread, (void *) phpthreads_create);
/* we wait here until the child thread has copied the
parent threads data */
thr_wait_event(thread->start_event,THR_INFINITE);
zend_llist_add_element(&THREADS_G(children), (void *)thread);
RETURN_TRUE;
}
/* }}} */
/* THR_THREAD_PROC(phpthreads_include) { */
void phpthreads_include (void * data) {
zval *result = NULL;
zend_op_array *op_array;
int callback_len = 0;
zend_file_handle file_handle;
THR_THREAD *thread = (THR_THREAD *) data;
/* void **thr_data = thread->args; */
char *script_file;
/*char *script_file = (char *)estrdup((char *) thr_data[0]);*/
//THR_SHARED_VARS *vars = (THR_SHARED_VARS *) thread->args[1];
TSRMLS_FETCH();
script_file = (char *) thread->args[0];
THR_PRINTF(("starting thread %s \n", script_file))
thread->args[0] = NULL;
/* we need to have the same context as the parent thread */
SG(server_context) = THR_SG(thread->parent_tls,server_context);
/* do standard stuff just like cli sapi */
php_request_startup(TSRMLS_C);
THREADS_G(self) = thread; /* is ok */
//shared_vars = vars; /* is ok */
THR_PRINTF(("I'm done doing the unsafe stuff\n"));
thr_set_event(thread->start_event);
SG(request_info).path_translated = script_file;
/* this can be an issue we have to deal with somehow */
SG(headers_sent) = 1;
SG(request_info).no_headers = 1;
file_handle.handle.fp = VCWD_FOPEN(script_file, "rb");
file_handle.filename = script_file;
file_handle.type = ZEND_HANDLE_FP;
file_handle.opened_path = NULL;
file_handle.free_filename = 1;
/* notify we're done copying, don't touch 'thread' after this,
it will be invalid memory! */
THR_PRINTF(("sent - running script \n"));
op_array = zend_compile_file(&file_handle, ZEND_INCLUDE TSRMLS_CC);
zend_destroy_file_handle(&file_handle TSRMLS_CC);
EG(return_value_ptr_ptr) = &result;
EG(active_op_array) = op_array;
- zend_execute(op_array TSRMLS_CC);
+ zend_execute(op_array TSRMLS_CC);
destroy_op_array(op_array TSRMLS_CC);
efree(op_array);
op_array = NULL;
//php_execute_script(&file_handle TSRMLS_CC);
THR_PRINTF(("done running script \n"));
/* self destruct DOES NOT WORK FOR SOME REASON! */
php_request_shutdown(NULL); /* NOW IT WORKS */
THR_PRINTF(("done request shutdown \n"));
/* found in tsrm.c and is extremly useful */
ts_free_thread();
free(thread);
thr_thread_exit(0);
}
/* {{{ proto string thread_start(string filename)
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(thread_include)
{
char *script_file=NULL;
char *script_file_in;
int len;
int threadid;
THR_THREAD *thread = NULL;
//THR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &script_file_in,&len) == FAILURE) {
RETURN_FALSE;
}
// if (!shared_vars) {
/* only the master thread creates this */
/* avoid emalloc ... - it gets totally confused with the threading stuff */
// shared_vars = (THR_SHARED_VARS *) malloc(sizeof(THR_SHARED_VARS));
// shared_vars->rwlock = thr_create_rwlock();
// zend_hash_init(&shared_vars->vars, 0, NULL, NULL,0);
// vars = shared_vars;
// }
script_file= (char *) emalloc(len + 1);
strncpy(script_file , script_file_in, len+1);
/* avoid emalloc ... - it gets totally confused with the threading stuff */
thread = (THR_THREAD *) malloc(sizeof(THR_THREAD));
thread->start_event = thr_create_event();
thread->callback = NULL;
thread->parent_tls = tsrm_ls;
thread->args[0] = script_file;
thread->args[1] = NULL;
THR_PRINTF(("value of args is %x\n", thread->args));
threadid = thr_thread_create(thread, (void *) phpthreads_include);
/* we wait here until the child thread has copied the
parent threads data */
THR_PRINTF(("done creating thread - waiting for all clear \n"))
/* waiting for thread to start... */
thr_wait_event(thread->start_event,THR_INFINITE);
THR_PRINTF(("got message that thread had finished initializing \n"))
zend_llist_add_element(&THREADS_G(children), (void *)thread);
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_set(string name, mixed variable)
set a value into shared thread storage */
PHP_FUNCTION(thread_set)
{
char *name;
unsigned int len;
zval *var;
zval *newvar = NULL, **xvar=NULL;
THR_SHARED_VARS *vars = shared_vars;
#ifdef USE_SERIALIZE
smart_str new_var = {0};
char *ser_str = NULL;
php_serialize_data_t var_hash;
#else
zval *target;
#endif
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sz", &name,&len,&var) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread:thread_set==%s==\n", name));
#ifdef USE_SERIALIZE
/* serialize variables that will be shared */
PHP_VAR_SERIALIZE_INIT(var_hash);
php_var_serialize(&new_var, &var, &var_hash TSRMLS_CC);
PHP_VAR_SERIALIZE_DESTROY(var_hash);
ser_str = estrndup(new_var.c,new_var.len);
thr_acquire_write_lock(shared_vars->rwlock);
zend_hash_update(&shared_vars->vars, name, len+1, ser_str, new_var.len + 1,NULL);
thr_release_write_lock(shared_vars->rwlock);
THR_PRINTF(("thread_set: setting serialized var:\n %s \n\n\n", ser_str));
smart_str_free(&new_var);
#else
/* attempt to save an actual zval to avoid serialization overhead,
and to allow for resources to be shared (if possible?) */
/* TODO: need to make a complete copy of var */
thr_acquire_write_lock(shared_vars->rwlock);
switch(Z_TYPE_PP(&var)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
- THR_PRINTF(("RESOURCE ====================================================\n"));
+ THR_PRINTF(("RESOURCE IS NOT ALLOWED\n"));
break;
case IS_OBJECT:
- THR_PRINTF(("OBJECT ====================================================\n"));
+ THR_PRINTF(("OBJECT IS NOT ALLOWED\n"));
//TODO: Special Handling for Objects
break;
default:
MAKE_STD_ZVAL(target);
*target = *var;
zval_copy_ctor(target);
zend_hash_update(&shared_vars->vars, name, len+1, (void *) &target, sizeof(zval *),NULL);
break;
}
/*if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &xvar) == SUCCESS) {
if(Z_TYPE_PP(xvar) == IS_STRING) {
convert_to_string_ex(xvar);
}
THR_PRINTF(("thread_set: hash find ok \n"));
}*/
thr_release_write_lock(shared_vars->rwlock);
#endif
RETURN_TRUE;
}
/* }}} */
/* {{{ proto mixed thread_get(string name[, int wait])
get a value from shared thread storage */
PHP_FUNCTION(thread_get)
{
char *name;
unsigned int len;
#ifdef USE_SERIALIZE
char *new_var;
zval *tmp = NULL;
#else
zval **tmp;
#endif
//Not neededTHR_SHARED_VARS *vars = shared_vars;
if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
THR_PRINTF(("thread_get: Trying to return %s\n", name));
#ifdef USE_SERIALIZE
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **) &new_var) == SUCCESS) {
php_unserialize_data_t var_hash;
const char *p = (const char*)new_var;
MAKE_STD_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_INIT(var_hash);
if (!php_var_unserialize(&tmp, &p, p+strlen(p), &var_hash TSRMLS_CC)) {
zend_error(E_WARNING, "%s(): message corrupted", get_active_function_name(TSRMLS_C));
RETVAL_FALSE;
}
REPLACE_ZVAL_VALUE(&return_value, tmp, 0);
zval_copy_ctor(return_value);
INIT_PZVAL(return_value);
FREE_ZVAL(tmp);
PHP_VAR_UNSERIALIZE_DESTROY(var_hash);
THR_PRINTF(("thread_get: successfully returned %s\n", name));
} else {
THR_PRINTF(("thread_get: not successfully found %s\n", name));
}
thr_release_read_lock(shared_vars->rwlock);
#else
/* for some reason, we cannot get zval's back if set from a different
thread */
thr_acquire_read_lock(shared_vars->rwlock);
if (zend_hash_find(&shared_vars->vars, name, len+1, (void **)&tmp) == SUCCESS) {
switch(Z_TYPE_PP(tmp)) {
case IS_RESOURCE:
//TODO: special Handling for Resources
break;
case IS_OBJECT:
//TODO: Special Handling for Objects
break;
default:
REPLACE_ZVAL_VALUE(&return_value, *tmp, 1);
break;
}
}
thr_release_read_lock(shared_vars->rwlock);
#endif
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_isset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
if(zend_hash_exists(&shared_vars->vars, name, len)) {
THR_PRINTF(("thread_isset: %s exists\n", name));
RETURN_TRUE;
} else {
RETURN_FALSE;
}
}
/* }}} */
/* {{{ proto boolean thread_isset(string name)
check existense of a shared var */
PHP_FUNCTION(thread_unset)
{
char *name;
unsigned int len;
if(zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s", &name,&len) == FAILURE) {
RETURN_FALSE;
}
if(zend_hash_exists(&shared_vars->vars, name, len)) {
THR_PRINTF(("thread_unset: unsetting %s \n", name));
zend_hash_del(&shared_vars->vars, name, len);
}
RETURN_TRUE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_init(string name)
create a mutex resource */
PHP_FUNCTION(thread_mutex_init)
{
/* NOTE: we create the mutex, stuff it into shared thread storage
under the provided name. Any thread can then use that mutex
by using the name of the mutex, rather than the value */
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_mutex_destroy(string name)
destroy a mutex resource */
PHP_FUNCTION(thread_mutex_destroy)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock(string name)
blocking lock on a mutex */
PHP_FUNCTION(thread_lock)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_lock_try(string name)
non-blocking lock on a mutex */
PHP_FUNCTION(thread_lock_try)
{
RETURN_FALSE;
}
/* }}} */
/* {{{ proto boolean thread_unlock(string name)
unlock a locked mutex */
PHP_FUNCTION(thread_unlock)
{
RETURN_FALSE;
}
/* }}} */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
edheil/shoesca
|
fc39e23d1e6b4afd24fefe717ed1aa625512dcdc
|
fix bug where it'd fail to properly initialize a nonexistent configuration
|
diff --git a/shoesca.rb b/shoesca.rb
index d99439a..8386cd5 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,580 +1,580 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/error', :error
url '/license', :license
url '/config', :config
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@gradients = false
@@error = nil
@@forum_cache = {}
@@bbs_cache = {}
@@use_threads = true
@@config = {}
# PAGES
def login
@@bbs = nil
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
- @@config = store['config']
+ @@config = store['config'] || {}
end
if @@config['auto_login'] and username and password
visit "/do_login/#{username}/#{password}"
end
setup_keypress
add_actions( ["\n", '[enter] login', Proc.new {
visit "/do_login/#{@username_line.text}/#{@password_line.text}"}
],
['l', '[l]icense', '/license'],
['c', '[c]onfig', '/config'],
['q', '[q]uit', '/quit'] )
@content = page_box do
header_box( "Login")
section_box do
flow { para "username:"; @username_line = app.edit_line "#{ username }" }
flow { para "password:"; @password_line = app.edit_line "#{ password }",
:secret => true }
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
end
end
def do_login(username, password)
setup_keypress
@page = page_box do
para "logging in..."
end
threadingly do
rescuingly do
info "making connection"
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do | store |
if @@config['save_username']
store['username']=username
else
store.delete('username')
end
if @@config['save_password']
store['password'] = password
else
store.delete('password')
end
end
visit '/load_bbs'
end
end
end
def config
setup_keypress
if @@bbs
add_actions ['b', '[b]ack to bbs', '/bbs']
else
add_actions ['b', '[b]ack to login', '/']
end
add_actions ['q', '[q]uit', '/quit']
@c = {}
page_box do
header_box( "Configuration" )
section_box do
button "Save configuration", :align => 'right' do
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['config'] ||= {}
@c.each do | key, control |
store['config'][key] = @@config[key] = @c[key].checked
end
end
alert "configuration saved."
end
end
chunk_section_box("Login Configuration", true) do
@c['save_username'] =
option_box("save username") do | me |
@auto_login.checked = false unless me.checked?
end
@c['save_password'] =
option_box("save password") do | me |
@auto_login.checked = false unless me.checked?
end
@c['auto_login'] =
option_box("log in automatically") do | me |
if me.checked?
@c['save_username'].checked = true
@c['save_password'].checked = true
end
end
end
chunk_section_box("Cosmetic Configuration", true) do
@c['gradients'] = option_box("gradients")
@c['white_bkg'] = option_box("white background")
end
end
YAML::Store.new('bbsconfig.yaml').transaction do |store|
@c.each do | key, control |
store['config'] ||= {}
@c[key].checked = store['config'][key]
end
end
end
def error
setup_keypress
add_actions( ['q', '[q]uit', '/quit'],
['b', '[b]ack to login', '/']
)
page_box do
header_box "Error"
section_box do
para @@error
end
end
end
def license
setup_keypress
info "license"
add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
page_box do
header_box("License")
section_box do
para LICENSE
end
end
end
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
threadingly do
rescuingly do
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
end
end
def bbs
setup_keypress
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
if forums_todo.length > 0
add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
add_actions (['c', '[c]onfig', '/config'],
[ 'q', '[q]uit', '/quit' ])
page_box do
header_box( "Forums")
[ ["Unread", forums_todo, false ],
["Subscribed", forums_joined, true ],
["Zapped", forums_all, true ]].each do | group |
group_name, ordered_ids, hidden = *group
if ordered_ids.length > 0
chunk_section_box(group_name, hidden) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
threadingly do
rescuingly do
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
end
end
def forum(id)
setup_keypress
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"])
if msgs_unread.length > 0
add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
else
add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
end
add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
page_box do
header_box(cache[:name])
[ [ "Unread", msgs_unread, false ],
[ "Read", msgs_read, true ]].each do | group |
group_name, ordered_ids, hidden = *group
if ordered_ids.length > 0
chunk_section_box(group_name, hidden) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
if post # bizarrely, sometimes we have a noteid with no post headers
chunk_box do
para link("#{ post_id }\n#{post[:author]}\n#{post[:date]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
end
def foruminfo(id)
setup_keypress
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
add_actions( [ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ] )
threadingly do
rescuingly do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
@page.clear do
header_box
section_box do
caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
end
def message(forum_id,msgnum, direction)
setup_keypress
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
add_actions [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
# this is one of the few times we don't have a separate
# page for doing network stuff.
threadingly do
rescuingly do
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@page.clear do
header_box
section_box do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def quit
info "quit"
exit()
end
def quit_from_forum(id)
info "quit_from_forum"
page_box do
"Quitting..."
end
recording_last_read(id) do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
page_box
page_box do
para "leaving forum #{id}..."
end
recording_last_read(id) do
visit '/bbs'
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
page_box do
para "leaving forum #{forum_id}.."
end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
todo_list = @@bbs_cache[:todo].keys.sort
recording_last_read(forum_id) do
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
recording_last_read(old_id) do
visit "/enter_forum/#{new_id}"
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
threadingly do
rescuingly do
msg = get_message(forum_id, msgnum)
old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
@page.clear do
section_box do
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
threadingly do
rescuingly do
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
# UTILITY METHODS
def threadingly
if @@use_threads
Thread.new { yield }
else
yield
|
edheil/shoesca
|
cf0b33d8c233df0937d6154887e2dcc5535c3f69
|
configuration screen, cosmetic options
|
diff --git a/shoesca.rb b/shoesca.rb
index a5e25f8..d99439a 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,693 +1,782 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/error', :error
url '/license', :license
+ url '/config', :config
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@gradients = false
@@error = nil
@@forum_cache = {}
@@bbs_cache = {}
@@use_threads = true
+ @@config = {}
# PAGES
def login
- setup_keypress
+
@@bbs = nil
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
+ @@config = store['config']
end
+ if @@config['auto_login'] and username and password
+ visit "/do_login/#{username}/#{password}"
+ end
+
+ setup_keypress
+
add_actions( ["\n", '[enter] login', Proc.new {
visit "/do_login/#{@username_line.text}/#{@password_line.text}"}
],
['l', '[l]icense', '/license'],
+ ['c', '[c]onfig', '/config'],
['q', '[q]uit', '/quit'] )
@content = page_box do
header_box( "Login")
section_box do
flow { para "username:"; @username_line = app.edit_line "#{ username }" }
flow { para "password:"; @password_line = app.edit_line "#{ password }",
:secret => true }
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
end
end
def do_login(username, password)
setup_keypress
@page = page_box do
para "logging in..."
end
threadingly do
rescuingly do
+ info "making connection"
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
- YAML::Store.new('bbsconfig.yaml').transaction do |store|
- store['username'], store['password'] = username, password
- visit '/load_bbs'
+ YAML::Store.new('bbsconfig.yaml').transaction do | store |
+ if @@config['save_username']
+ store['username']=username
+ else
+ store.delete('username')
+ end
+ if @@config['save_password']
+ store['password'] = password
+ else
+ store.delete('password')
+ end
+ end
+ visit '/load_bbs'
+ end
+ end
+ end
+
+ def config
+ setup_keypress
+ if @@bbs
+ add_actions ['b', '[b]ack to bbs', '/bbs']
+ else
+ add_actions ['b', '[b]ack to login', '/']
+ end
+ add_actions ['q', '[q]uit', '/quit']
+ @c = {}
+ page_box do
+ header_box( "Configuration" )
+ section_box do
+ button "Save configuration", :align => 'right' do
+ YAML::Store.new('bbsconfig.yaml').transaction do |store|
+ store['config'] ||= {}
+ @c.each do | key, control |
+ store['config'][key] = @@config[key] = @c[key].checked
+ end
+ end
+ alert "configuration saved."
+ end
+ end
+ chunk_section_box("Login Configuration", true) do
+ @c['save_username'] =
+ option_box("save username") do | me |
+ @auto_login.checked = false unless me.checked?
+ end
+ @c['save_password'] =
+ option_box("save password") do | me |
+ @auto_login.checked = false unless me.checked?
end
+ @c['auto_login'] =
+ option_box("log in automatically") do | me |
+ if me.checked?
+ @c['save_username'].checked = true
+ @c['save_password'].checked = true
+ end
+ end
+ end
+ chunk_section_box("Cosmetic Configuration", true) do
+ @c['gradients'] = option_box("gradients")
+ @c['white_bkg'] = option_box("white background")
+ end
+ end
+ YAML::Store.new('bbsconfig.yaml').transaction do |store|
+ @c.each do | key, control |
+ store['config'] ||= {}
+ @c[key].checked = store['config'][key]
end
end
end
+
def error
setup_keypress
add_actions( ['q', '[q]uit', '/quit'],
['b', '[b]ack to login', '/']
)
page_box do
header_box "Error"
section_box do
para @@error
end
end
end
def license
setup_keypress
info "license"
add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
page_box do
header_box("License")
section_box do
para LICENSE
end
end
end
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
threadingly do
rescuingly do
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
end
end
def bbs
setup_keypress
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
if forums_todo.length > 0
add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
- add_actions [ 'q', '[q]uit', '/quit' ]
+ add_actions (['c', '[c]onfig', '/config'],
+ [ 'q', '[q]uit', '/quit' ])
page_box do
header_box( "Forums")
[ ["Unread", forums_todo, false ],
["Subscribed", forums_joined, true ],
["Zapped", forums_all, true ]].each do | group |
group_name, ordered_ids, hidden = *group
if ordered_ids.length > 0
chunk_section_box(group_name, hidden) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
threadingly do
rescuingly do
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
end
end
def forum(id)
setup_keypress
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"])
if msgs_unread.length > 0
add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
else
add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
end
add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
page_box do
header_box(cache[:name])
[ [ "Unread", msgs_unread, false ],
[ "Read", msgs_read, true ]].each do | group |
group_name, ordered_ids, hidden = *group
if ordered_ids.length > 0
chunk_section_box(group_name, hidden) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
if post # bizarrely, sometimes we have a noteid with no post headers
chunk_box do
para link("#{ post_id }\n#{post[:author]}\n#{post[:date]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
end
def foruminfo(id)
setup_keypress
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
add_actions( [ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ] )
threadingly do
rescuingly do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
@page.clear do
header_box
section_box do
caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
end
def message(forum_id,msgnum, direction)
setup_keypress
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
add_actions [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
# this is one of the few times we don't have a separate
# page for doing network stuff.
threadingly do
rescuingly do
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@page.clear do
header_box
section_box do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def quit
info "quit"
exit()
end
def quit_from_forum(id)
info "quit_from_forum"
page_box do
"Quitting..."
end
recording_last_read(id) do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
page_box
page_box do
para "leaving forum #{id}..."
end
recording_last_read(id) do
visit '/bbs'
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
page_box do
para "leaving forum #{forum_id}.."
end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
todo_list = @@bbs_cache[:todo].keys.sort
recording_last_read(forum_id) do
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
recording_last_read(old_id) do
visit "/enter_forum/#{new_id}"
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
threadingly do
rescuingly do
msg = get_message(forum_id, msgnum)
old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
@page.clear do
section_box do
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
threadingly do
rescuingly do
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
# UTILITY METHODS
def threadingly
if @@use_threads
Thread.new { yield }
else
yield
end
end
def rescuingly
debug "begin rescue block..."
begin
yield
rescue Exception => err
debug "rescuing #{err.message}"
@@error = err
visit '/error'
end
debug "end rescue block..."
end
# DISPLAY HELPER METHODS
def page_box
st = nil
- background black
+ if @@config['white_bkg']
+ background white
+ else
+ background black
+ end
stack :margin => 20 do
background(randcolor(:dark), :curve => 20)
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
def section_box
st = nil
stack :margin => 10 do
background randcolor(:light, 0.5), :curve => 20
st = stack :margin => 10 do
yield if block_given?
end
end
st
end
def chunk_section_box(text, hidden=true)
the_flow = nil
section_box do
flow(:click => Proc.new { the_flow.toggle },
:margin => 20
) do
background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 20
caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
end
the_flow = flow :hidden => hidden do
yield
end
end
end
def header_box(text = "")
linklist ||= @action_links
section_box do
flow do
flow( :width => -200) do
para *action_links
end
flow( :width => 200) do
tagline( text, :stroke => randcolor(:realdark),
:margin => 20, :align => 'right')
end
end
end
end
+ def option_box(text)
+ the_check = nil
+ chunk_box do
+ flow do
+ the_check = check { | me | yield me }
+ para text
+ end
+ end
+ the_check
+ end
+
def chunk_box
stack :width => 200 do
background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 10, :margin => 20
stack :margin => 20 do
yield if block_given?
end
end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
when :light: [0.8, 0.4]
when :realdark: [ 0.1, 0.2]
else [0.5, 0.6]
end
r, g, b = [ ( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target ]
- if @@gradients
+ if @@config['gradients']
rgb(r, g, b, alpha)..rgb(r, g, b, alpha * 0.3)
else
rgb(r, g, b, alpha)
end
end
# BBS INTERACTION HELPER METHODS
def recording_last_read(forum_id)
if should_record_last_read(forum_id)
clear do
page_box do
para "recording last read message..."
end
end
threadingly do
rescuingly do
record_last_read(forum_id)
yield
end
end
else
yield
end
end
def should_record_last_read(forum_id)
forum_id = forum_id.to_i
info "should_record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
cached[:first_unread] != cached[:server_first_unread]
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
# KEYBOARD INTERACTION HELPER METHODS
def add_actions( *actions)
@page_actions ||= []
@page_actions = @page_actions + actions
end
def action_links
@page_actions ||= []
linklist = []
@page_actions.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == @page_actions.last
end
linklist
end
def setup_keypress
@page_actions ||= []
keypress do | key |
found = @page_actions.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
end
end
Shoes.app :width => 850
|
edheil/shoesca
|
d831c0a16e9b497759865dcbe5b51d1f1e53af9b
|
organize methods into sections
|
diff --git a/shoesca.rb b/shoesca.rb
index 004f420..a5e25f8 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,690 +1,693 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/error', :error
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
- @@gradients = true
+ @@gradients = false
@@error = nil
@@forum_cache = {}
@@bbs_cache = {}
@@use_threads = true
- def threadingly
- if @@use_threads
- Thread.new { yield }
- else
- yield
- end
- end
-
- def rescuingly
- debug "begin rescue block..."
- begin
- yield
- rescue Exception => err
- debug "rescuing #{err.message}"
- @@error = err
- visit '/error'
- end
- debug "end rescue block..."
- end
-
- def page_box
- st = nil
- background black
- stack :margin => 20 do
- background(randcolor(:dark), :curve => 20)
- st = stack :margin => 20 do
- yield if block_given?
- end
- end
- st
- end
-
- def section_box
- st = nil
- stack :margin => 10 do
- background randcolor(:light, 0.5), :curve => 20
- st = stack :margin => 10 do
- yield if block_given?
- end
- end
- st
- end
-
- def chunk_section_box(text, hidden=true)
- the_flow = nil
- section_box do
- flow(:click => Proc.new { the_flow.toggle },
- :margin => 20
- ) do
- background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 20
- caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
- end
- the_flow = flow :hidden => hidden do
- yield
- end
- end
- end
-
- def header_box(text = "")
- linklist ||= @action_links
- section_box do
- flow do
- flow( :width => -200) do
- para *action_links
- end
- flow( :width => 200) do
- tagline( text, :stroke => randcolor(:realdark),
- :margin => 20, :align => 'right')
- end
- end
- end
- end
+ # PAGES
- def chunk_box
- stack :width => 200 do
- background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 10, :margin => 20
- stack :margin => 20 do
- yield if block_given?
- end
+ def login
+ setup_keypress
+ @@bbs = nil
+ username, password = nil, nil
+ YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
+ username, password = store['username'], store['password']
end
- end
- def randcolor(bias=nil, alpha = 1.0)
- target, range = case bias
- when :dark: [ 0.3, 0.3 ]
- when :light: [0.8, 0.4]
- when :realdark: [ 0.1, 0.2]
- else [0.5, 0.6]
- end
- r, g, b = [ ( (rand - 0.5) * range ) + target,
- ( (rand - 0.5) * range ) + target,
- ( (rand - 0.5) * range ) + target ]
+ add_actions( ["\n", '[enter] login', Proc.new {
+ visit "/do_login/#{@username_line.text}/#{@password_line.text}"}
+ ],
+ ['l', '[l]icense', '/license'],
+ ['q', '[q]uit', '/quit'] )
- if @@gradients
- rgb(r, g, b, alpha)..rgb(r, g, b, alpha * 0.3)
- else
- rgb(r, g, b, alpha)
- end
- end
-
-
- def license
- setup_keypress
- info "license"
- add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
- page_box do
- header_box("License")
+ @content = page_box do
+ header_box( "Login")
section_box do
- para LICENSE
- end
- end
- end
-
- def recording_last_read(forum_id)
- if should_record_last_read(forum_id)
- clear do
- page_box do
- para "recording last read message..."
- end
- end
- threadingly do
- rescuingly do
- record_last_read(forum_id)
- yield
+ flow { para "username:"; @username_line = app.edit_line "#{ username }" }
+ flow { para "password:"; @password_line = app.edit_line "#{ password }",
+ :secret => true }
+ button "login" do
+ visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
- else
- yield
- end
- end
-
- def should_record_last_read(forum_id)
- forum_id = forum_id.to_i
- info "should_record_last_read for #{forum_id}"
- cached = @@forum_cache[forum_id]
- cached[:first_unread] != cached[:server_first_unread]
- end
-
- def record_last_read(forum_id)
- forum_id = forum_id.to_i
- info "record_last_read for #{forum_id}"
- cached = @@forum_cache[forum_id]
- forum = @@bbs.jump(forum_id)
- forum.first_unread = cached[:first_unread]
- cached[:server_first_unread] = cached[:first_unread]
-
- if cached[:first_unread] > cached[:noteids].last
- @@bbs_cache[:todo].delete(forum_id)
- end
-
- if cached[:first_unread] <= cached[:noteids].last
- @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
- end
- end
-
- def quit_from_forum(id)
- info "quit_from_forum"
- page_box do
- "Quitting..."
- end
- recording_last_read(id) do
- exit()
end
end
- def quit
- info "quit"
- exit()
- end
-
def do_login(username, password)
setup_keypress
@page = page_box do
para "logging in..."
end
threadingly do
rescuingly do
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
visit '/load_bbs'
end
end
end
end
def error
setup_keypress
add_actions( ['q', '[q]uit', '/quit'],
['b', '[b]ack to login', '/']
)
page_box do
header_box "Error"
section_box do
para @@error
end
end
end
- def login
+ def license
setup_keypress
- @@bbs = nil
- username, password = nil, nil
- YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
- username, password = store['username'], store['password']
- end
-
- add_actions( ["\n", '[enter] login', Proc.new {
- visit "/do_login/#{@username_line.text}/#{@password_line.text}"}
- ],
- ['l', '[l]icense', '/license'],
- ['q', '[q]uit', '/quit'] )
-
- @content = page_box do
- header_box( "Login")
+ info "license"
+ add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
+ page_box do
+ header_box("License")
section_box do
- flow { para "username:"; @username_line = app.edit_line "#{ username }" }
- flow { para "password:"; @password_line = app.edit_line "#{ password }",
- :secret => true }
- button "login" do
- visit "/do_login/#{@username_line.text}/#{@password_line.text}"
- end
+ para LICENSE
end
end
end
-
- def quit
- page_box do
- exit()
- end
- end
-
- def leave_forum(id)
- info "leave forum #{id}"
- page_box
- page_box do
- para "leaving forum #{id}..."
- end
- recording_last_read(id) do
- visit '/bbs'
- end
- end
-
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
threadingly do
rescuingly do
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
end
end
def bbs
setup_keypress
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
if forums_todo.length > 0
add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
add_actions [ 'q', '[q]uit', '/quit' ]
page_box do
header_box( "Forums")
[ ["Unread", forums_todo, false ],
["Subscribed", forums_joined, true ],
["Zapped", forums_all, true ]].each do | group |
group_name, ordered_ids, hidden = *group
if ordered_ids.length > 0
chunk_section_box(group_name, hidden) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
- def goto_next_from(forum_id)
- forum_id = forum_id.to_i
- # id is forum to jump *from*
- page_box do
- para "leaving forum #{forum_id}.."
- end
- cache = @@forum_cache[forum_id]
- cache[:first_unread] = cache[:noteids].last + 1
-
- todo_list = @@bbs_cache[:todo].keys.sort
- recording_last_read(forum_id) do
- if todo_list.length > 0
- visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
- else
- visit "/bbs"
- end
- end
- end
-
- def switch_forum(old_id, new_id)
- old_id, new_id = old_id.to_i, new_id.to_i
- recording_last_read(old_id) do
- visit "/enter_forum/#{new_id}"
- end
- end
-
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
threadingly do
rescuingly do
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
end
end
def forum(id)
setup_keypress
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"])
if msgs_unread.length > 0
add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
else
add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
end
add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
page_box do
header_box(cache[:name])
[ [ "Unread", msgs_unread, false ],
[ "Read", msgs_read, true ]].each do | group |
group_name, ordered_ids, hidden = *group
if ordered_ids.length > 0
chunk_section_box(group_name, hidden) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
if post # bizarrely, sometimes we have a noteid with no post headers
chunk_box do
- para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
+ para link("#{ post_id }\n#{post[:author]}\n#{post[:date]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
end
def foruminfo(id)
setup_keypress
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
add_actions( [ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ] )
threadingly do
rescuingly do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
@page.clear do
header_box
section_box do
caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
end
- def mark_unread(forum_id,msgnum)
- forum_id = forum_id.to_i; msgnum = msgnum.to_i
- cache = @@forum_cache[forum_id]
- if msgnum < cache[:first_unread]
- cache[:first_unread] = msgnum
- end
- visit "/forum/#{forum_id}"
- end
-
- def add_actions( *actions)
- @page_actions ||= []
- @page_actions = @page_actions + actions
- end
-
- def action_links
- @page_actions ||= []
- linklist = []
- @page_actions.each do | item |
- linklist << link(item[1], :click => item[2] )
- linklist << " " unless item == @page_actions.last
- end
- linklist
- end
-
- def setup_keypress
- @page_actions ||= []
- keypress do | key |
- found = @page_actions.assoc(key)
- if found
- action = found[2]
- if action.respond_to? :call
- action.call
- else
- info "visiting <#{action}>"
- visit action
- end
- end
- end
- end
-
-
- def get_message(forum_id, msgnum)
- msg = {}
- post = @@bbs.jump(forum_id).read(msgnum)
- [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
- msg[:message_id] = msgnum
- msg[:forum_id] = forum_id
- msg
- end
-
def message(forum_id,msgnum, direction)
setup_keypress
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
add_actions [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
# this is one of the few times we don't have a separate
# page for doing network stuff.
threadingly do
rescuingly do
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@page.clear do
header_box
section_box do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
-
+
+ def quit
+ info "quit"
+ exit()
+ end
+
+ def quit_from_forum(id)
+ info "quit_from_forum"
+ page_box do
+ "Quitting..."
+ end
+ recording_last_read(id) do
+ exit()
+ end
+ end
+
+ def leave_forum(id)
+ info "leave forum #{id}"
+ page_box
+ page_box do
+ para "leaving forum #{id}..."
+ end
+ recording_last_read(id) do
+ visit '/bbs'
+ end
+ end
+
+ def goto_next_from(forum_id)
+ forum_id = forum_id.to_i
+ # id is forum to jump *from*
+ page_box do
+ para "leaving forum #{forum_id}.."
+ end
+ cache = @@forum_cache[forum_id]
+ cache[:first_unread] = cache[:noteids].last + 1
+
+ todo_list = @@bbs_cache[:todo].keys.sort
+ recording_last_read(forum_id) do
+ if todo_list.length > 0
+ visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
+ else
+ visit "/bbs"
+ end
+ end
+ end
+
+ def switch_forum(old_id, new_id)
+ old_id, new_id = old_id.to_i, new_id.to_i
+ recording_last_read(old_id) do
+ visit "/enter_forum/#{new_id}"
+ end
+ end
+
+ def mark_unread(forum_id,msgnum)
+ forum_id = forum_id.to_i; msgnum = msgnum.to_i
+ cache = @@forum_cache[forum_id]
+ if msgnum < cache[:first_unread]
+ cache[:first_unread] = msgnum
+ end
+ visit "/forum/#{forum_id}"
+ end
+
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
threadingly do
rescuingly do
msg = get_message(forum_id, msgnum)
old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
@page.clear do
section_box do
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
threadingly do
rescuingly do
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
+
+
+ # UTILITY METHODS
+
+ def threadingly
+ if @@use_threads
+ Thread.new { yield }
+ else
+ yield
+ end
+ end
+
+ def rescuingly
+ debug "begin rescue block..."
+ begin
+ yield
+ rescue Exception => err
+ debug "rescuing #{err.message}"
+ @@error = err
+ visit '/error'
+ end
+ debug "end rescue block..."
+ end
+
+ # DISPLAY HELPER METHODS
+
+ def page_box
+ st = nil
+ background black
+ stack :margin => 20 do
+ background(randcolor(:dark), :curve => 20)
+ st = stack :margin => 20 do
+ yield if block_given?
+ end
+ end
+ st
+ end
+
+ def section_box
+ st = nil
+ stack :margin => 10 do
+ background randcolor(:light, 0.5), :curve => 20
+ st = stack :margin => 10 do
+ yield if block_given?
+ end
+ end
+ st
+ end
+
+ def chunk_section_box(text, hidden=true)
+ the_flow = nil
+ section_box do
+ flow(:click => Proc.new { the_flow.toggle },
+ :margin => 20
+ ) do
+ background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 20
+ caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
+ end
+ the_flow = flow :hidden => hidden do
+ yield
+ end
+ end
+ end
+
+ def header_box(text = "")
+ linklist ||= @action_links
+ section_box do
+ flow do
+ flow( :width => -200) do
+ para *action_links
+ end
+ flow( :width => 200) do
+ tagline( text, :stroke => randcolor(:realdark),
+ :margin => 20, :align => 'right')
+ end
+ end
+ end
+ end
+
+ def chunk_box
+ stack :width => 200 do
+ background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 10, :margin => 20
+ stack :margin => 20 do
+ yield if block_given?
+ end
+ end
+ end
+
+ def randcolor(bias=nil, alpha = 1.0)
+ target, range = case bias
+ when :dark: [ 0.3, 0.3 ]
+ when :light: [0.8, 0.4]
+ when :realdark: [ 0.1, 0.2]
+ else [0.5, 0.6]
+ end
+ r, g, b = [ ( (rand - 0.5) * range ) + target,
+ ( (rand - 0.5) * range ) + target,
+ ( (rand - 0.5) * range ) + target ]
+
+ if @@gradients
+ rgb(r, g, b, alpha)..rgb(r, g, b, alpha * 0.3)
+ else
+ rgb(r, g, b, alpha)
+ end
+ end
+
+ # BBS INTERACTION HELPER METHODS
+
+ def recording_last_read(forum_id)
+ if should_record_last_read(forum_id)
+ clear do
+ page_box do
+ para "recording last read message..."
+ end
+ end
+ threadingly do
+ rescuingly do
+ record_last_read(forum_id)
+ yield
+ end
+ end
+ else
+ yield
+ end
+ end
+
+ def should_record_last_read(forum_id)
+ forum_id = forum_id.to_i
+ info "should_record_last_read for #{forum_id}"
+ cached = @@forum_cache[forum_id]
+ cached[:first_unread] != cached[:server_first_unread]
+ end
+
+ def record_last_read(forum_id)
+ forum_id = forum_id.to_i
+ info "record_last_read for #{forum_id}"
+ cached = @@forum_cache[forum_id]
+ forum = @@bbs.jump(forum_id)
+ forum.first_unread = cached[:first_unread]
+ cached[:server_first_unread] = cached[:first_unread]
+
+ if cached[:first_unread] > cached[:noteids].last
+ @@bbs_cache[:todo].delete(forum_id)
+ end
+
+ if cached[:first_unread] <= cached[:noteids].last
+ @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
+ end
+ end
+
+ def get_message(forum_id, msgnum)
+ msg = {}
+ post = @@bbs.jump(forum_id).read(msgnum)
+ [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
+ msg[:message_id] = msgnum
+ msg[:forum_id] = forum_id
+ msg
+ end
+
+ # KEYBOARD INTERACTION HELPER METHODS
+
+ def add_actions( *actions)
+ @page_actions ||= []
+ @page_actions = @page_actions + actions
+ end
+
+ def action_links
+ @page_actions ||= []
+ linklist = []
+ @page_actions.each do | item |
+ linklist << link(item[1], :click => item[2] )
+ linklist << " " unless item == @page_actions.last
+ end
+ linklist
+ end
+
+ def setup_keypress
+ @page_actions ||= []
+ keypress do | key |
+ found = @page_actions.assoc(key)
+ if found
+ action = found[2]
+ if action.respond_to? :call
+ action.call
+ else
+ info "visiting <#{action}>"
+ visit action
+ end
+ end
+ end
+ end
+
end
Shoes.app :width => 850
|
edheil/shoesca
|
82ea9a78f46407caa2a90ffac63b6c8e52be8fd1
|
pretty gradients auto-show only "unread", ever.
|
diff --git a/shoesca.rb b/shoesca.rb
index a133a60..004f420 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,689 +1,690 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/error', :error
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
+ @@gradients = true
@@error = nil
@@forum_cache = {}
@@bbs_cache = {}
@@use_threads = true
def threadingly
if @@use_threads
Thread.new { yield }
else
yield
end
end
def rescuingly
debug "begin rescue block..."
begin
yield
rescue Exception => err
debug "rescuing #{err.message}"
@@error = err
visit '/error'
end
debug "end rescue block..."
end
def page_box
st = nil
background black
stack :margin => 20 do
- background randcolor(:dark), :curve => 20
+ background(randcolor(:dark), :curve => 20)
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
-
def section_box
st = nil
- stack :margin => 20 do
+ stack :margin => 10 do
background randcolor(:light, 0.5), :curve => 20
- st = stack :margin => 20 do
+ st = stack :margin => 10 do
yield if block_given?
end
end
st
end
def chunk_section_box(text, hidden=true)
the_flow = nil
section_box do
flow(:click => Proc.new { the_flow.toggle },
:margin => 20
) do
- background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20
+ background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 20
caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
end
the_flow = flow :hidden => hidden do
yield
end
end
end
def header_box(text = "")
linklist ||= @action_links
section_box do
flow do
flow( :width => -200) do
para *action_links
end
flow( :width => 200) do
tagline( text, :stroke => randcolor(:realdark),
:margin => 20, :align => 'right')
end
end
end
end
def chunk_box
stack :width => 200 do
- background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20
+ background rgb(1.0, 1.0, 1.0, 0.5)..rgb(1.0, 1.0, 1.0, 0.2), :curve => 10, :margin => 20
stack :margin => 20 do
yield if block_given?
end
end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
when :light: [0.8, 0.4]
when :realdark: [ 0.1, 0.2]
else [0.5, 0.6]
end
- rgb( ( (rand - 0.5) * range ) + target,
- ( (rand - 0.5) * range ) + target,
- ( (rand - 0.5) * range ) + target,
- alpha)
+ r, g, b = [ ( (rand - 0.5) * range ) + target,
+ ( (rand - 0.5) * range ) + target,
+ ( (rand - 0.5) * range ) + target ]
+
+ if @@gradients
+ rgb(r, g, b, alpha)..rgb(r, g, b, alpha * 0.3)
+ else
+ rgb(r, g, b, alpha)
+ end
end
def license
setup_keypress
info "license"
add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
page_box do
header_box("License")
section_box do
para LICENSE
end
end
end
def recording_last_read(forum_id)
if should_record_last_read(forum_id)
clear do
page_box do
para "recording last read message..."
end
end
threadingly do
rescuingly do
record_last_read(forum_id)
yield
end
end
else
yield
end
end
def should_record_last_read(forum_id)
forum_id = forum_id.to_i
info "should_record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
cached[:first_unread] != cached[:server_first_unread]
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
def quit_from_forum(id)
info "quit_from_forum"
page_box do
"Quitting..."
end
recording_last_read(id) do
exit()
end
end
def quit
info "quit"
exit()
end
def do_login(username, password)
setup_keypress
@page = page_box do
para "logging in..."
end
threadingly do
rescuingly do
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
visit '/load_bbs'
end
end
end
end
def error
setup_keypress
add_actions( ['q', '[q]uit', '/quit'],
['b', '[b]ack to login', '/']
)
page_box do
header_box "Error"
section_box do
para @@error
end
end
end
def login
setup_keypress
@@bbs = nil
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
add_actions( ["\n", '[enter] login', Proc.new {
visit "/do_login/#{@username_line.text}/#{@password_line.text}"}
],
['l', '[l]icense', '/license'],
['q', '[q]uit', '/quit'] )
@content = page_box do
header_box( "Login")
section_box do
flow { para "username:"; @username_line = app.edit_line "#{ username }" }
flow { para "password:"; @password_line = app.edit_line "#{ password }",
:secret => true }
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
end
end
def quit
page_box do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
page_box
page_box do
para "leaving forum #{id}..."
end
recording_last_read(id) do
visit '/bbs'
end
end
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
threadingly do
rescuingly do
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
end
end
def bbs
setup_keypress
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
if forums_todo.length > 0
add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
add_actions [ 'q', '[q]uit', '/quit' ]
- open_shown = false
page_box do
header_box( "Forums")
- [ ["Unread", forums_todo ],
- ["Subscribed", forums_joined ],
- ["Zapped", forums_all ]].each do | group |
- group_name, ordered_ids = *group
+ [ ["Unread", forums_todo, false ],
+ ["Subscribed", forums_joined, true ],
+ ["Zapped", forums_all, true ]].each do | group |
+ group_name, ordered_ids, hidden = *group
if ordered_ids.length > 0
- chunk_section_box(group_name, open_shown) do
+ chunk_section_box(group_name, hidden) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
- open_shown = true
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
page_box do
para "leaving forum #{forum_id}.."
end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
todo_list = @@bbs_cache[:todo].keys.sort
recording_last_read(forum_id) do
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
recording_last_read(old_id) do
visit "/enter_forum/#{new_id}"
end
end
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
threadingly do
rescuingly do
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
end
end
def forum(id)
setup_keypress
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"])
if msgs_unread.length > 0
add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
else
add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
end
add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
- open_shown = false
page_box do
header_box(cache[:name])
- [ [ "Unread", msgs_unread, ],
- [ "Read", msgs_read, ]].each do | pair |
- group_name, ordered_ids = *pair
+ [ [ "Unread", msgs_unread, false ],
+ [ "Read", msgs_read, true ]].each do | group |
+ group_name, ordered_ids, hidden = *group
if ordered_ids.length > 0
- chunk_section_box(group_name, open_shown) do
+ chunk_section_box(group_name, hidden) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
if post # bizarrely, sometimes we have a noteid with no post headers
chunk_box do
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
- open_shown = true
end
end
end
end
def foruminfo(id)
setup_keypress
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
add_actions( [ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ] )
threadingly do
rescuingly do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
@page.clear do
header_box
section_box do
caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def add_actions( *actions)
@page_actions ||= []
@page_actions = @page_actions + actions
end
def action_links
@page_actions ||= []
linklist = []
@page_actions.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == @page_actions.last
end
linklist
end
def setup_keypress
@page_actions ||= []
keypress do | key |
found = @page_actions.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
setup_keypress
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
add_actions [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
# this is one of the few times we don't have a separate
# page for doing network stuff.
threadingly do
rescuingly do
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@page.clear do
header_box
section_box do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
threadingly do
rescuingly do
msg = get_message(forum_id, msgnum)
old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
@page.clear do
section_box do
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
threadingly do
rescuingly do
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
end
Shoes.app :width => 850
|
edheil/shoesca
|
08fb07f3f2ba4fc6b4b879361e63eec8a7183138
|
generalized error rescue. still doesn't seem to deal with network failures well though.
|
diff --git a/shoesca.rb b/shoesca.rb
index 9b18a19..a133a60 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,653 +1,689 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
- url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
+ url '/error', :error
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
+ @@error = nil
@@forum_cache = {}
@@bbs_cache = {}
@@use_threads = true
def threadingly
if @@use_threads
Thread.new { yield }
else
yield
end
end
+ def rescuingly
+ debug "begin rescue block..."
+ begin
+ yield
+ rescue Exception => err
+ debug "rescuing #{err.message}"
+ @@error = err
+ visit '/error'
+ end
+ debug "end rescue block..."
+ end
+
def page_box
st = nil
background black
stack :margin => 20 do
background randcolor(:dark), :curve => 20
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
def section_box
st = nil
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
def chunk_section_box(text, hidden=true)
the_flow = nil
section_box do
flow(:click => Proc.new { the_flow.toggle },
:margin => 20
) do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20
caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
end
the_flow = flow :hidden => hidden do
yield
end
end
end
def header_box(text = "")
linklist ||= @action_links
section_box do
flow do
flow( :width => -200) do
para *action_links
end
flow( :width => 200) do
tagline( text, :stroke => randcolor(:realdark),
:margin => 20, :align => 'right')
end
end
end
end
def chunk_box
stack :width => 200 do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20
stack :margin => 20 do
yield if block_given?
end
end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
when :light: [0.8, 0.4]
when :realdark: [ 0.1, 0.2]
else [0.5, 0.6]
end
rgb( ( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
alpha)
end
def license
setup_keypress
info "license"
add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
page_box do
header_box("License")
section_box do
para LICENSE
end
end
end
def recording_last_read(forum_id)
if should_record_last_read(forum_id)
clear do
page_box do
para "recording last read message..."
end
end
threadingly do
- record_last_read(forum_id)
- yield
+ rescuingly do
+ record_last_read(forum_id)
+ yield
+ end
end
else
yield
end
end
def should_record_last_read(forum_id)
forum_id = forum_id.to_i
info "should_record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
cached[:first_unread] != cached[:server_first_unread]
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
def quit_from_forum(id)
info "quit_from_forum"
page_box do
"Quitting..."
end
recording_last_read(id) do
exit()
end
end
def quit
info "quit"
exit()
end
def do_login(username, password)
setup_keypress
@page = page_box do
para "logging in..."
end
threadingly do
- begin
+ rescuingly do
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
+ visit '/load_bbs'
end
- visit '/load_bbs'
- rescue StandardError => err
- @@bbs = nil
- add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
- @page.clear do
- header_box("Error")
- section_box do
- para "error logging in: #{err.message}"
- end
- end
+ end
+ end
+ end
+
+ def error
+ setup_keypress
+ add_actions( ['q', '[q]uit', '/quit'],
+ ['b', '[b]ack to login', '/']
+ )
+ page_box do
+ header_box "Error"
+ section_box do
+ para @@error
end
end
end
def login
setup_keypress
+ @@bbs = nil
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
add_actions( ["\n", '[enter] login', Proc.new {
visit "/do_login/#{@username_line.text}/#{@password_line.text}"}
],
['l', '[l]icense', '/license'],
['q', '[q]uit', '/quit'] )
@content = page_box do
header_box( "Login")
section_box do
flow { para "username:"; @username_line = app.edit_line "#{ username }" }
flow { para "password:"; @password_line = app.edit_line "#{ password }",
:secret => true }
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
end
end
def quit
page_box do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
page_box
page_box do
para "leaving forum #{id}..."
end
recording_last_read(id) do
visit '/bbs'
end
end
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
threadingly do
- @@bbs_cache[:all] = @@bbs.forums('all')
- @@bbs_cache[:todo] = @@bbs.forums('todo')
- @@bbs_cache[:joined] = @@bbs.forums('joined')
- visit '/bbs'
+ rescuingly do
+ @@bbs_cache[:all] = @@bbs.forums('all')
+ @@bbs_cache[:todo] = @@bbs.forums('todo')
+ @@bbs_cache[:joined] = @@bbs.forums('joined')
+ visit '/bbs'
+ end
end
end
def bbs
setup_keypress
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
if forums_todo.length > 0
add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
add_actions [ 'q', '[q]uit', '/quit' ]
open_shown = false
page_box do
header_box( "Forums")
[ ["Unread", forums_todo ],
["Subscribed", forums_joined ],
["Zapped", forums_all ]].each do | group |
group_name, ordered_ids = *group
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
open_shown = true
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
page_box do
para "leaving forum #{forum_id}.."
end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
todo_list = @@bbs_cache[:todo].keys.sort
recording_last_read(forum_id) do
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
recording_last_read(old_id) do
visit "/enter_forum/#{new_id}"
end
end
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
threadingly do
- # we pull stuff into forum_cache only when we enter a new forum.
- forum = @@bbs.jump(id)
- cache = {}
- first_unread = forum.first_unread.to_i
- info "first_unread: #{ first_unread.inspect }"
- cache[:server_first_unread] = first_unread
- cache[:first_unread] = first_unread
- info "first unread: #{first_unread.inspect}"
- info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
- noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
- cache[:noteids] = forum.noteids(noterange).sort
- if cache[:noteids].length == 0 # uh oh
- noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
+ rescuingly do
+ # we pull stuff into forum_cache only when we enter a new forum.
+ forum = @@bbs.jump(id)
+ cache = {}
+ first_unread = forum.first_unread.to_i
+ info "first_unread: #{ first_unread.inspect }"
+ cache[:server_first_unread] = first_unread
+ cache[:first_unread] = first_unread
+ info "first unread: #{first_unread.inspect}"
+ info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
+ noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
+ if cache[:noteids].length == 0 # uh oh
+ noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
+ cache[:noteids] = forum.noteids(noterange).sort
+ end
+ info "noterange: #{noterange}"
+ cache[:post_headers] = forum.post_headers(noterange)
+ cache[:name] = forum.name
+ cache[:post_ok] = forum.post?
+ cache[:admin] = forum.admin
+ cache[:anonymous] = forum.anonymous
+ cache[:private] = forum.private
+ @@forum_cache[id] = cache
+ visit "/forum/#{id}"
end
- info "noterange: #{noterange}"
- cache[:post_headers] = forum.post_headers(noterange)
- cache[:name] = forum.name
- cache[:post_ok] = forum.post?
- cache[:admin] = forum.admin
- cache[:anonymous] = forum.anonymous
- cache[:private] = forum.private
- @@forum_cache[id] = cache
- visit "/forum/#{id}"
end
end
def forum(id)
setup_keypress
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"])
if msgs_unread.length > 0
add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
else
add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
end
add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
open_shown = false
page_box do
header_box(cache[:name])
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
if post # bizarrely, sometimes we have a noteid with no post headers
chunk_box do
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
open_shown = true
end
end
end
end
def foruminfo(id)
setup_keypress
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
add_actions( [ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ] )
threadingly do
- @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
- info = @@forum_cache[:forum_info]
- the_body = info[:body]
- body_urls = the_body.scan(URLRE)
- @page.clear do
- header_box
- section_box do
- caption "Forum moderator is #{@@forum_cache[id][:admin]}."
- caption "Forum info last updated #{info[:date]} by #{info[:from]}"
- para "#{info[:body]}"
- body_urls.each do | a_url |
- para link(a_url, :click => a_url)
+ rescuingly do
+ @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
+ info = @@forum_cache[:forum_info]
+ the_body = info[:body]
+ body_urls = the_body.scan(URLRE)
+ @page.clear do
+ header_box
+ section_box do
+ caption "Forum moderator is #{@@forum_cache[id][:admin]}."
+ caption "Forum info last updated #{info[:date]} by #{info[:from]}"
+ para "#{info[:body]}"
+ body_urls.each do | a_url |
+ para link(a_url, :click => a_url)
+ end
end
end
end
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def add_actions( *actions)
@page_actions ||= []
@page_actions = @page_actions + actions
end
def action_links
@page_actions ||= []
linklist = []
@page_actions.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == @page_actions.last
end
linklist
end
def setup_keypress
@page_actions ||= []
keypress do | key |
found = @page_actions.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
setup_keypress
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
add_actions [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
+
+ # this is one of the few times we don't have a separate
+ # page for doing network stuff.
+
threadingly do
- msg = get_message(forum_id, msgnum)
- body_urls = msg[:body].scan(URLRE)
- authority = " (#{msg[:authority]})" if msg[:authority]
- @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
- "#{msg[:body]}" +
- "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
-
- @page.clear do
- header_box
- section_box do
- para @whole_message
- body_urls.each do | a_url |
- para link(a_url, :click => a_url)
+ rescuingly do
+ msg = get_message(forum_id, msgnum)
+ body_urls = msg[:body].scan(URLRE)
+ authority = " (#{msg[:authority]})" if msg[:authority]
+ @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
+ "#{msg[:body]}" +
+ "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
+
+ @page.clear do
+ header_box
+ section_box do
+ para @whole_message
+ body_urls.each do | a_url |
+ para link(a_url, :click => a_url)
+ end
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
threadingly do
- msg = get_message(forum_id, msgnum)
- old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
- quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
- @page.clear do
- section_box do
- para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
- tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
- @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
- button "post" do
- text = @post_box.text
- new_post = @@bbs.jump(forum_id).post(text)
- recording_last_read(forum_id) do
- visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ rescuingly do
+ msg = get_message(forum_id, msgnum)
+ old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
+ quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
+ @page.clear do
+ section_box do
+ para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
+ tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
+ @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
+ button "post" do
+ text = @post_box.text
+ new_post = @@bbs.jump(forum_id).post(text)
+ recording_last_read(forum_id) do
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ end
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
threadingly do
- new_post = @@bbs.jump(forum_id).post(text)
- recording_last_read(forum_id) do
- visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ rescuingly do
+ new_post = @@bbs.jump(forum_id).post(text)
+ recording_last_read(forum_id) do
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ end
end
end
end
end
end
end
end
Shoes.app :width => 850
|
edheil/shoesca
|
57da3bc93520396560800044e23ae9a5d4843a41
|
cosmetics on license page
|
diff --git a/shoesca.rb b/shoesca.rb
index aab25bc..9b18a19 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,652 +1,653 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
@@use_threads = true
def threadingly
if @@use_threads
Thread.new { yield }
else
yield
end
end
def page_box
st = nil
background black
stack :margin => 20 do
background randcolor(:dark), :curve => 20
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
def section_box
st = nil
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
def chunk_section_box(text, hidden=true)
the_flow = nil
section_box do
flow(:click => Proc.new { the_flow.toggle },
:margin => 20
) do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20
caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
end
the_flow = flow :hidden => hidden do
yield
end
end
end
def header_box(text = "")
linklist ||= @action_links
section_box do
flow do
flow( :width => -200) do
para *action_links
end
flow( :width => 200) do
tagline( text, :stroke => randcolor(:realdark),
:margin => 20, :align => 'right')
end
end
end
end
def chunk_box
stack :width => 200 do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20
stack :margin => 20 do
yield if block_given?
end
end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
when :light: [0.8, 0.4]
when :realdark: [ 0.1, 0.2]
else [0.5, 0.6]
end
rgb( ( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
alpha)
end
def license
+ setup_keypress
info "license"
+ add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
page_box do
+ header_box("License")
section_box do
- background aliceblue, :curve => 20
- para link('back', :click => '/login')
para LICENSE
end
end
end
def recording_last_read(forum_id)
if should_record_last_read(forum_id)
clear do
page_box do
para "recording last read message..."
end
end
threadingly do
record_last_read(forum_id)
yield
end
else
yield
end
end
def should_record_last_read(forum_id)
forum_id = forum_id.to_i
info "should_record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
cached[:first_unread] != cached[:server_first_unread]
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
def quit_from_forum(id)
info "quit_from_forum"
page_box do
"Quitting..."
end
recording_last_read(id) do
exit()
end
end
def quit
info "quit"
exit()
end
def do_login(username, password)
setup_keypress
@page = page_box do
para "logging in..."
end
threadingly do
begin
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
end
visit '/load_bbs'
rescue StandardError => err
@@bbs = nil
add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
@page.clear do
header_box("Error")
section_box do
para "error logging in: #{err.message}"
end
end
end
end
end
def login
setup_keypress
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
add_actions( ["\n", '[enter] login', Proc.new {
visit "/do_login/#{@username_line.text}/#{@password_line.text}"}
],
['l', '[l]icense', '/license'],
['q', '[q]uit', '/quit'] )
@content = page_box do
header_box( "Login")
section_box do
flow { para "username:"; @username_line = app.edit_line "#{ username }" }
flow { para "password:"; @password_line = app.edit_line "#{ password }",
:secret => true }
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
end
end
def quit
page_box do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
page_box
page_box do
para "leaving forum #{id}..."
end
recording_last_read(id) do
visit '/bbs'
end
end
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
threadingly do
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
end
def bbs
setup_keypress
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
if forums_todo.length > 0
add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
add_actions [ 'q', '[q]uit', '/quit' ]
open_shown = false
page_box do
header_box( "Forums")
[ ["Unread", forums_todo ],
["Subscribed", forums_joined ],
["Zapped", forums_all ]].each do | group |
group_name, ordered_ids = *group
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
open_shown = true
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
page_box do
para "leaving forum #{forum_id}.."
end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
todo_list = @@bbs_cache[:todo].keys.sort
recording_last_read(forum_id) do
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
recording_last_read(old_id) do
visit "/enter_forum/#{new_id}"
end
end
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
threadingly do
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
end
def forum(id)
setup_keypress
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"])
if msgs_unread.length > 0
add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
else
add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
end
add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
open_shown = false
page_box do
header_box(cache[:name])
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
if post # bizarrely, sometimes we have a noteid with no post headers
chunk_box do
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
open_shown = true
end
end
end
end
def foruminfo(id)
setup_keypress
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
add_actions( [ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ] )
threadingly do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
@page.clear do
header_box
section_box do
caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def add_actions( *actions)
@page_actions ||= []
@page_actions = @page_actions + actions
end
def action_links
@page_actions ||= []
linklist = []
@page_actions.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == @page_actions.last
end
linklist
end
def setup_keypress
@page_actions ||= []
keypress do | key |
found = @page_actions.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
setup_keypress
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
add_actions [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
threadingly do
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@page.clear do
header_box
section_box do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
threadingly do
msg = get_message(forum_id, msgnum)
old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
@page.clear do
section_box do
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
threadingly do
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
Shoes.app :width => 850
|
edheil/shoesca
|
51bb904277c9cb64c4f74730b5fb411364dac0cd
|
simplify and unify the keystroke action / link code
|
diff --git a/shoesca.rb b/shoesca.rb
index 954e1ec..aab25bc 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,658 +1,652 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
@@use_threads = true
def threadingly
if @@use_threads
Thread.new { yield }
else
yield
end
end
def page_box
st = nil
background black
stack :margin => 20 do
background randcolor(:dark), :curve => 20
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
def section_box
st = nil
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
st = stack :margin => 20 do
- info "yielding..."
yield if block_given?
end
end
st
end
def chunk_section_box(text, hidden=true)
the_flow = nil
section_box do
flow(:click => Proc.new { the_flow.toggle },
:margin => 20
) do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20
caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
end
the_flow = flow :hidden => hidden do
yield
end
end
end
- def header_box(linklist=[], text = "")
+ def header_box(text = "")
+ linklist ||= @action_links
section_box do
flow do
flow( :width => -200) do
- para *linklist
+ para *action_links
end
flow( :width => 200) do
tagline( text, :stroke => randcolor(:realdark),
:margin => 20, :align => 'right')
end
end
end
end
def chunk_box
stack :width => 200 do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20
stack :margin => 20 do
yield if block_given?
end
end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
when :light: [0.8, 0.4]
when :realdark: [ 0.1, 0.2]
else [0.5, 0.6]
end
rgb( ( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
alpha)
end
def license
info "license"
page_box do
section_box do
background aliceblue, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
end
def recording_last_read(forum_id)
if should_record_last_read(forum_id)
clear do
page_box do
para "recording last read message..."
end
end
threadingly do
record_last_read(forum_id)
yield
end
else
yield
end
end
def should_record_last_read(forum_id)
forum_id = forum_id.to_i
info "should_record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
cached[:first_unread] != cached[:server_first_unread]
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
def quit_from_forum(id)
info "quit_from_forum"
page_box do
"Quitting..."
end
recording_last_read(id) do
exit()
end
end
def quit
info "quit"
exit()
end
def do_login(username, password)
- debug "do_login"
+ setup_keypress
@page = page_box do
para "logging in..."
end
threadingly do
begin
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
end
visit '/load_bbs'
rescue StandardError => err
- debug "error: #{err.message}"
@@bbs = nil
- linklist, keypressproc = actions([['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']])
- keypress { | key | keypressproc.call(key) }
+ add_actions( ['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit'])
@page.clear do
- header_box(linklist, "Error")
+ header_box("Error")
section_box do
para "error logging in: #{err.message}"
end
end
end
end
end
def login
+ setup_keypress
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
-
- actionlist = [["\n", '[enter] login', Proc.new {
+
+ add_actions( ["\n", '[enter] login', Proc.new {
visit "/do_login/#{@username_line.text}/#{@password_line.text}"}
],
- ['l', '[l]icense', '/license'],
- ['q', '[q]uit', '/quit']]
- linklist, keypressproc = actions(actionlist)
- keypress { | key | keypressproc.call(key) }
+ ['l', '[l]icense', '/license'],
+ ['q', '[q]uit', '/quit'] )
@content = page_box do
- header_box(linklist, "Login")
+ header_box( "Login")
section_box do
flow { para "username:"; @username_line = app.edit_line "#{ username }" }
flow { para "password:"; @password_line = app.edit_line "#{ password }",
:secret => true }
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
end
end
def quit
page_box do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
page_box
page_box do
para "leaving forum #{id}..."
end
recording_last_read(id) do
visit '/bbs'
end
end
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
threadingly do
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
end
def bbs
+ setup_keypress
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
- action_list = []
if forums_todo.length > 0
- action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
+ add_actions [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
- action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
+ add_actions [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
- action_list << [ 'q', '[q]uit', '/quit' ]
+ add_actions [ 'q', '[q]uit', '/quit' ]
- linklist, keypressproc = actions( action_keypress )
- list { | key | keypressproc.call(key) }
open_shown = false
page_box do
- header_box( linklist, "Forums")
+ header_box( "Forums")
[ ["Unread", forums_todo ],
["Subscribed", forums_joined ],
["Zapped", forums_all ]].each do | group |
group_name, ordered_ids = *group
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
open_shown = true
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
page_box do
para "leaving forum #{forum_id}.."
end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
todo_list = @@bbs_cache[:todo].keys.sort
recording_last_read(forum_id) do
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
recording_last_read(old_id) do
visit "/enter_forum/#{new_id}"
end
end
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
threadingly do
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
end
def forum(id)
+ setup_keypress
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
- actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"],
- [ 'i', '[i]nfo', "/foruminfo/#{id}"],
- [ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
- [ 'f', 'read [f]orward',
- "/message/#{id}/#{noteids.first}/forward"],
- [ 'b', 'read [b]ackward',
- "/message/#{id}/#{noteids.last}/backward"],
- [ 'g', '[g]oto next forum with unread messages',
- "/goto_next_from/#{id}"]]
+ add_actions( [ 'e', '[e]nter msg', "/new_post/#{id}"],
+ [ 'i', '[i]nfo', "/foruminfo/#{id}"],
+ [ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
+ [ 'f', 'read [f]orward',
+ "/message/#{id}/#{noteids.first}/forward"],
+ [ 'b', 'read [b]ackward',
+ "/message/#{id}/#{noteids.last}/backward"],
+ [ 'g', '[g]oto next forum with unread messages',
+ "/goto_next_from/#{id}"])
if msgs_unread.length > 0
- actionlist << [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
+ add_actions [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
else
- actionlist << [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
+ add_actions [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
end
- actionlist << [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
-
- linklist, keypressproc = actions(actionlist)
+ add_actions [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
- keypress { | key | keypressproc.call(key) }
open_shown = false
page_box do
- header_box(linklist, cache[:name])
+ header_box(cache[:name])
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
if post # bizarrely, sometimes we have a noteid with no post headers
chunk_box do
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
open_shown = true
end
end
end
end
def foruminfo(id)
+ setup_keypress
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
- linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
- [ 'p', '[e]nter msg', "/new_post/#{id}"],
- [ "q", "[q]uit", "/quit_from_forum/#{id}" ]
- ]
- keypress { | key | keypressproc.call(key) }
+ add_actions( [ 'b', '[b]ack', "/forum/#{id}"],
+ [ 'p', '[e]nter msg', "/new_post/#{id}"],
+ [ "q", "[q]uit", "/quit_from_forum/#{id}" ] )
threadingly do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
@page.clear do
- section_box do
- para *linklist
- end
+ header_box
section_box do
caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
- def actions(list)
+ def add_actions( *actions)
+ @page_actions ||= []
+ @page_actions = @page_actions + actions
+ end
+
+ def action_links
+ @page_actions ||= []
linklist = []
- list.each do | item |
+ @page_actions.each do | item |
linklist << link(item[1], :click => item[2] )
- linklist << " " unless item == list.last
+ linklist << " " unless item == @page_actions.last
end
+ linklist
+ end
- keypressproc = Proc.new do | key |
- found = list.assoc(key)
+ def setup_keypress
+ @page_actions ||= []
+ keypress do | key |
+ found = @page_actions.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
- return linklist, keypressproc
end
+
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
+ setup_keypress
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
- action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
+ add_actions [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
- action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
+ add_actions [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
- action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
- action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
- action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
- action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
- action_list << [ "c", "[c]opy to clipboard",
+ add_actions [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
+ add_actions [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
+ add_actions [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
+ add_actions [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
+ add_actions [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
- action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
+ add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
- action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
+ add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
- action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
+ add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
- action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
+ add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
- action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
+ add_actions [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
- action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
+ add_actions [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
- action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
+ add_actions [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
- action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
+ add_actions [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
- action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
-
- linklist, keypressproc = actions(action_list)
- keypress { | key |
- keypressproc.call(key)
- }
+ add_actions [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
threadingly do
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@page.clear do
- section_box do
- para *linklist
- end
+ header_box
section_box do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
threadingly do
msg = get_message(forum_id, msgnum)
old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
@page.clear do
section_box do
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
threadingly do
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
Shoes.app :width => 850
|
edheil/shoesca
|
20489ac36187f2bb3ec193adde1e7f1f00c1007a
|
single on/off switch for threading fix login error display cosmetics
|
diff --git a/shoesca.rb b/shoesca.rb
index 0bad89f..954e1ec 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,647 +1,658 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
+ @@use_threads = true
+
+ def threadingly
+ if @@use_threads
+ Thread.new { yield }
+ else
+ yield
+ end
+ end
def page_box
st = nil
background black
stack :margin => 20 do
background randcolor(:dark), :curve => 20
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
def section_box
st = nil
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
st = stack :margin => 20 do
info "yielding..."
yield if block_given?
end
end
st
end
def chunk_section_box(text, hidden=true)
the_flow = nil
section_box do
flow(:click => Proc.new { the_flow.toggle },
:margin => 20
) do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20
caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
end
the_flow = flow :hidden => hidden do
yield
end
end
end
def header_box(linklist=[], text = "")
section_box do
flow do
flow( :width => -200) do
para *linklist
end
flow( :width => 200) do
tagline( text, :stroke => randcolor(:realdark),
:margin => 20, :align => 'right')
end
end
end
end
def chunk_box
stack :width => 200 do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20
stack :margin => 20 do
yield if block_given?
end
end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
when :light: [0.8, 0.4]
when :realdark: [ 0.1, 0.2]
else [0.5, 0.6]
end
rgb( ( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
alpha)
end
def license
info "license"
page_box do
section_box do
background aliceblue, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
end
def recording_last_read(forum_id)
if should_record_last_read(forum_id)
clear do
page_box do
para "recording last read message..."
end
end
- Thread.new do
+ threadingly do
record_last_read(forum_id)
yield
end
else
yield
end
end
def should_record_last_read(forum_id)
forum_id = forum_id.to_i
info "should_record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
cached[:first_unread] != cached[:server_first_unread]
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
def quit_from_forum(id)
info "quit_from_forum"
page_box do
"Quitting..."
end
recording_last_read(id) do
exit()
end
end
def quit
info "quit"
exit()
end
- def login_error(error)
- stack do
- para err.message
- link("try again",:click => '/')
- end
- end
-
def do_login(username, password)
- page_box do
+ debug "do_login"
+ @page = page_box do
para "logging in..."
end
- Thread.new do
+ threadingly do
begin
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
end
visit '/load_bbs'
- rescue RuntimeError => err
+ rescue StandardError => err
debug "error: #{err.message}"
@@bbs = nil
- visit "/login_error/#{err.message}"
+ linklist, keypressproc = actions([['b', '[b]ack', '/' ], ['q', '[q]uit', '/quit']])
+ keypress { | key | keypressproc.call(key) }
+ @page.clear do
+ header_box(linklist, "Error")
+ section_box do
+ para "error logging in: #{err.message}"
+ end
+ end
end
end
end
def login
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
- keypress do | key |
- if key == "\n"
- visit "/do_login/#{@username_line.text}/#{@password_line.text}"
- end
- end
+ actionlist = [["\n", '[enter] login', Proc.new {
+ visit "/do_login/#{@username_line.text}/#{@password_line.text}"}
+ ],
+ ['l', '[l]icense', '/license'],
+ ['q', '[q]uit', '/quit']]
+ linklist, keypressproc = actions(actionlist)
+ keypress { | key | keypressproc.call(key) }
+
@content = page_box do
+ header_box(linklist, "Login")
section_box do
- tagline "Login", :stroke => randcolor(:realdark), :align => right
- para "username:"
- @username_line = app.edit_line "#{ username }"
- para "password:"
- @password_line = app.edit_line "#{ password }", :secret => true
+ flow { para "username:"; @username_line = app.edit_line "#{ username }" }
+ flow { para "password:"; @password_line = app.edit_line "#{ password }",
+ :secret => true }
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
- para(link( 'license', :click => '/license' ))
end
end
end
def quit
page_box do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
page_box
page_box do
para "leaving forum #{id}..."
end
recording_last_read(id) do
visit '/bbs'
end
end
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
- Thread.new do
+ threadingly do
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
end
def bbs
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
- linklist, keypressproc = actions( action_list )
- keypress { | key | keypressproc.call(key) }
+ linklist, keypressproc = actions( action_keypress )
+ list { | key | keypressproc.call(key) }
open_shown = false
page_box do
header_box( linklist, "Forums")
[ ["Unread", forums_todo ],
["Subscribed", forums_joined ],
["Zapped", forums_all ]].each do | group |
group_name, ordered_ids = *group
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
open_shown = true
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
page_box do
para "leaving forum #{forum_id}.."
end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
todo_list = @@bbs_cache[:todo].keys.sort
recording_last_read(forum_id) do
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
recording_last_read(old_id) do
visit "/enter_forum/#{new_id}"
end
end
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
- Thread.new do
+ threadingly do
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
end
def forum(id)
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"]]
if msgs_unread.length > 0
actionlist << [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
else
actionlist << [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
end
actionlist << [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
linklist, keypressproc = actions(actionlist)
keypress { | key | keypressproc.call(key) }
open_shown = false
page_box do
header_box(linklist, cache[:name])
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
if post # bizarrely, sometimes we have a noteid with no post headers
chunk_box do
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
open_shown = true
end
end
end
end
def foruminfo(id)
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
- Thread.new do
+ threadingly do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
@page.clear do
section_box do
para *linklist
end
section_box do
caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
- Thread.new do
+ threadingly do
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@page.clear do
section_box do
para *linklist
end
section_box do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
- Thread.new do
+ threadingly do
msg = get_message(forum_id, msgnum)
old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
@page.clear do
section_box do
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
- Thread.new do
+ threadingly do
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
Shoes.app :width => 850
|
edheil/shoesca
|
cf3a51e065acdeca2578e960a09228f474285ea8
|
guard against getting a noteno with no post header
|
diff --git a/shoesca.rb b/shoesca.rb
index 9f4381f..0bad89f 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,646 +1,647 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
def page_box
st = nil
background black
stack :margin => 20 do
background randcolor(:dark), :curve => 20
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
def section_box
st = nil
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
st = stack :margin => 20 do
info "yielding..."
yield if block_given?
end
end
st
end
def chunk_section_box(text, hidden=true)
the_flow = nil
section_box do
flow(:click => Proc.new { the_flow.toggle },
:margin => 20
) do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20
caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
end
the_flow = flow :hidden => hidden do
yield
end
end
end
def header_box(linklist=[], text = "")
section_box do
flow do
flow( :width => -200) do
para *linklist
end
flow( :width => 200) do
tagline( text, :stroke => randcolor(:realdark),
:margin => 20, :align => 'right')
end
end
end
end
def chunk_box
stack :width => 200 do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20
stack :margin => 20 do
yield if block_given?
end
end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
when :light: [0.8, 0.4]
when :realdark: [ 0.1, 0.2]
else [0.5, 0.6]
end
rgb( ( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
alpha)
end
def license
info "license"
page_box do
section_box do
background aliceblue, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
end
def recording_last_read(forum_id)
if should_record_last_read(forum_id)
clear do
page_box do
para "recording last read message..."
end
end
Thread.new do
record_last_read(forum_id)
yield
end
else
yield
end
end
def should_record_last_read(forum_id)
forum_id = forum_id.to_i
info "should_record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
cached[:first_unread] != cached[:server_first_unread]
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
def quit_from_forum(id)
info "quit_from_forum"
page_box do
"Quitting..."
end
recording_last_read(id) do
exit()
end
end
def quit
info "quit"
exit()
end
def login_error(error)
stack do
para err.message
link("try again",:click => '/')
end
end
def do_login(username, password)
page_box do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
end
visit '/load_bbs'
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
visit "/login_error/#{err.message}"
end
end
end
def login
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
keypress do | key |
if key == "\n"
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
@content = page_box do
section_box do
tagline "Login", :stroke => randcolor(:realdark), :align => right
para "username:"
@username_line = app.edit_line "#{ username }"
para "password:"
@password_line = app.edit_line "#{ password }", :secret => true
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
para(link( 'license', :click => '/license' ))
end
end
end
def quit
page_box do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
page_box
page_box do
para "leaving forum #{id}..."
end
recording_last_read(id) do
visit '/bbs'
end
end
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
Thread.new do
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
end
def bbs
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
linklist, keypressproc = actions( action_list )
keypress { | key | keypressproc.call(key) }
open_shown = false
page_box do
header_box( linklist, "Forums")
[ ["Unread", forums_todo ],
["Subscribed", forums_joined ],
["Zapped", forums_all ]].each do | group |
group_name, ordered_ids = *group
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
open_shown = true
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
page_box do
para "leaving forum #{forum_id}.."
end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
todo_list = @@bbs_cache[:todo].keys.sort
recording_last_read(forum_id) do
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
recording_last_read(old_id) do
visit "/enter_forum/#{new_id}"
end
end
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
Thread.new do
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
end
def forum(id)
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
-
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"]]
if msgs_unread.length > 0
actionlist << [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
else
actionlist << [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
end
actionlist << [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
linklist, keypressproc = actions(actionlist)
keypress { | key | keypressproc.call(key) }
open_shown = false
page_box do
header_box(linklist, cache[:name])
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
- chunk_box do
- para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
- para post[:subject]
+ if post # bizarrely, sometimes we have a noteid with no post headers
+ chunk_box do
+ para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
+ para post[:subject]
+ end
end
end
end
open_shown = true
end
end
end
end
def foruminfo(id)
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
Thread.new do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
@page.clear do
section_box do
para *linklist
end
section_box do
caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
Thread.new do
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@page.clear do
section_box do
para *linklist
end
section_box do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
Thread.new do
msg = get_message(forum_id, msgnum)
old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
@page.clear do
section_box do
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
Thread.new do
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
Shoes.app :width => 850
|
edheil/shoesca
|
13341983043360f9133b2319844de734f60a6f95
|
remove unneeded first_unread page
|
diff --git a/shoesca.rb b/shoesca.rb
index 110ed9d..9f4381f 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,664 +1,646 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
- url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
def page_box
st = nil
background black
stack :margin => 20 do
background randcolor(:dark), :curve => 20
st = stack :margin => 20 do
yield if block_given?
end
end
st
end
def section_box
st = nil
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
st = stack :margin => 20 do
info "yielding..."
yield if block_given?
end
end
st
end
def chunk_section_box(text, hidden=true)
the_flow = nil
section_box do
flow(:click => Proc.new { the_flow.toggle },
:margin => 20
) do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20
caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
end
the_flow = flow :hidden => hidden do
yield
end
end
end
def header_box(linklist=[], text = "")
section_box do
flow do
flow( :width => -200) do
para *linklist
end
flow( :width => 200) do
tagline( text, :stroke => randcolor(:realdark),
:margin => 20, :align => 'right')
end
end
end
end
def chunk_box
stack :width => 200 do
background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20
stack :margin => 20 do
yield if block_given?
end
end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
when :light: [0.8, 0.4]
when :realdark: [ 0.1, 0.2]
else [0.5, 0.6]
end
rgb( ( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
alpha)
end
def license
info "license"
page_box do
section_box do
background aliceblue, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
end
def recording_last_read(forum_id)
if should_record_last_read(forum_id)
clear do
page_box do
para "recording last read message..."
end
end
Thread.new do
record_last_read(forum_id)
yield
end
else
yield
end
end
def should_record_last_read(forum_id)
forum_id = forum_id.to_i
info "should_record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
cached[:first_unread] != cached[:server_first_unread]
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
def quit_from_forum(id)
info "quit_from_forum"
page_box do
"Quitting..."
end
recording_last_read(id) do
exit()
end
end
def quit
info "quit"
exit()
end
def login_error(error)
stack do
para err.message
link("try again",:click => '/')
end
end
def do_login(username, password)
page_box do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
end
visit '/load_bbs'
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
visit "/login_error/#{err.message}"
end
end
end
def login
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
keypress do | key |
if key == "\n"
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
@content = page_box do
section_box do
tagline "Login", :stroke => randcolor(:realdark), :align => right
para "username:"
@username_line = app.edit_line "#{ username }"
para "password:"
@password_line = app.edit_line "#{ password }", :secret => true
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
para(link( 'license', :click => '/license' ))
end
end
end
def quit
page_box do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
page_box
page_box do
para "leaving forum #{id}..."
end
recording_last_read(id) do
visit '/bbs'
end
end
def load_bbs
info "load_bbs"
page_box do
para "loading forums..."
end
Thread.new do
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
end
def bbs
info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
linklist, keypressproc = actions( action_list )
keypress { | key | keypressproc.call(key) }
open_shown = false
page_box do
header_box( linklist, "Forums")
[ ["Unread", forums_todo ],
["Subscribed", forums_joined ],
["Zapped", forums_all ]].each do | group |
group_name, ordered_ids = *group
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.each do | id |
data = forums[id]
chunk_box do
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
open_shown = true
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
page_box do
para "leaving forum #{forum_id}.."
end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
todo_list = @@bbs_cache[:todo].keys.sort
recording_last_read(forum_id) do
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
recording_last_read(old_id) do
visit "/enter_forum/#{new_id}"
end
end
def enter_forum(id)
page_box do
para "loading forum #{id}..."
end
info "enter_forum #{id}"
id = id.to_i
Thread.new do
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
end
def forum(id)
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
- "/goto_next_from/#{id}"],
- [ ' ', '[ ]first unread', "/first_unread/#{id}"],
- [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
- ]
+ "/goto_next_from/#{id}"]]
+ if msgs_unread.length > 0
+ actionlist << [ ' ', '[ ]first unread', "/message/#{id}/#{msgs_unread[0]}/forward"]
+ else
+ actionlist << [ ' ', '[ ]forum list', "/leave_forum/#{id}"]
+ end
+ actionlist << [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
linklist, keypressproc = actions(actionlist)
keypress { | key | keypressproc.call(key) }
open_shown = false
page_box do
header_box(linklist, cache[:name])
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
chunk_section_box(group_name, open_shown) do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
chunk_box do
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
open_shown = true
end
end
end
end
def foruminfo(id)
id = id.to_i
info "foruminfo #{id}"
@page = page_box do
para "loading info for forum #{id}..."
end
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
- [ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
Thread.new do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
@page.clear do
section_box do
para *linklist
end
section_box do
caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
end
- def first_unread(forum_id)
- info "first_unread for forum_id #{forum_id}"
- forum_id = forum_id.to_i
- cache = @@forum_cache[forum_id]
-
- page_box do
- para "finding first unread message in forum #{forum_id}..."
- end
-
- noteids = cache[:noteids]
- first_unread_msg = cache[:first_unread]
- first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
- if first_unread_found
- visit "/message/#{forum_id}/#{first_unread_found}/forward"
- else
- visit "/leave_forum/#{forum_id}"
- end
- end
-
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
@page = page_box do
para "loading messge #{msgnum} in forum #{forum_id}"
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
Thread.new do
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@page.clear do
section_box do
para *linklist
end
section_box do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@page = page_box do
"loading message #{msgnum} in forum #{forum_id} to reply to..."
end
Thread.new do
msg = get_message(forum_id, msgnum)
old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
@page.clear do
section_box do
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
def new_post(forum_id)
@page = page_box do
section_box do
tagline "New Post", :stroke => randcolor(:realdark), :align => right
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
@page.clear do
para "posting message..."
end
Thread.new do
new_post = @@bbs.jump(forum_id).post(text)
recording_last_read(forum_id) do
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
end
end
end
Shoes.app :width => 850
|
edheil/shoesca
|
aeeb0f23619f24141cf655cbf44520244ce29aa5
|
bring threading back where appropriate
|
diff --git a/shoesca.rb b/shoesca.rb
index 7ddc773..110ed9d 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,571 +1,664 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
- def show_page
- info "show_page"
+ def page_box
+ st = nil
background black
stack :margin => 20 do
background randcolor(:dark), :curve => 20
- stack :margin => 20 do
+ st = stack :margin => 20 do
yield if block_given?
end
end
+ st
end
- def show_section
- info "show_section: background"
+
+ def section_box
+ st = nil
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
- stack :margin => 20 do
+ st = stack :margin => 20 do
info "yielding..."
yield if block_given?
end
end
+ st
end
-
- def show_chunk(coloring=nil)
- coloring ||= rgb(1.0, 1.0, 1.0, 0.5)
+
+ def chunk_section_box(text, hidden=true)
+ the_flow = nil
+ section_box do
+ flow(:click => Proc.new { the_flow.toggle },
+ :margin => 20
+ ) do
+ background rgb(1.0, 1.0, 1.0, 0.5), :curve => 20
+ caption text, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
+ end
+ the_flow = flow :hidden => hidden do
+ yield
+ end
+ end
+ end
+
+ def header_box(linklist=[], text = "")
+ section_box do
+ flow do
+ flow( :width => -200) do
+ para *linklist
+ end
+ flow( :width => 200) do
+ tagline( text, :stroke => randcolor(:realdark),
+ :margin => 20, :align => 'right')
+ end
+ end
+ end
+ end
+
+ def chunk_box
stack :width => 200 do
- background coloring, :curve => 10, :margin => 10
+ background rgb(1.0, 1.0, 1.0, 0.5), :curve => 10, :margin => 20
stack :margin => 20 do
yield if block_given?
end
end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
- when :light: [0.8, 0.4]
- when :realdark: [ 0.1, 0.2]
- else [0.5, 0.6]
- end
+ when :light: [0.8, 0.4]
+ when :realdark: [ 0.1, 0.2]
+ else [0.5, 0.6]
+ end
rgb( ( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
alpha)
end
def license
info "license"
- show_page do
- show_section do
+ page_box do
+ section_box do
background aliceblue, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
end
+ def recording_last_read(forum_id)
+ if should_record_last_read(forum_id)
+ clear do
+ page_box do
+ para "recording last read message..."
+ end
+ end
+ Thread.new do
+ record_last_read(forum_id)
+ yield
+ end
+ else
+ yield
+ end
+ end
+
+ def should_record_last_read(forum_id)
+ forum_id = forum_id.to_i
+ info "should_record_last_read for #{forum_id}"
+ cached = @@forum_cache[forum_id]
+ cached[:first_unread] != cached[:server_first_unread]
+ end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
- if cached
- if cached[:first_unread] != cached[:server_first_unread]
- forum = @@bbs.jump(forum_id)
- forum.first_unread = cached[:first_unread]
- cached[:server_first_unread] = cached[:first_unread]
-
- if cached[:first_unread] > cached[:noteids].last
- @@bbs_cache[:todo].delete(forum_id)
- end
-
- if cached[:first_unread] <= cached[:noteids].last
- @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
- end
- end
+ forum = @@bbs.jump(forum_id)
+ forum.first_unread = cached[:first_unread]
+ cached[:server_first_unread] = cached[:first_unread]
+
+ if cached[:first_unread] > cached[:noteids].last
+ @@bbs_cache[:todo].delete(forum_id)
+ end
+
+ if cached[:first_unread] <= cached[:noteids].last
+ @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
def quit_from_forum(id)
info "quit_from_forum"
- record_last_read(id)
- exit()
+ page_box do
+ "Quitting..."
+ end
+ recording_last_read(id) do
+ exit()
+ end
end
def quit
info "quit"
exit()
end
def login_error(error)
stack do
para err.message
link("try again",:click => '/')
end
end
def do_login(username, password)
- begin
- @@bbs = Raccdoc::Connection.new(:user => username, :password => password,
- :host => HOST,
- :port => PORT
- )
- YAML::Store.new('bbsconfig.yaml').transaction do |store|
- store['username'], store['password'] = username, password
+ page_box do
+ para "logging in..."
+ end
+ Thread.new do
+ begin
+ @@bbs = Raccdoc::Connection.new(:user => username, :password => password,
+ :host => HOST,
+ :port => PORT
+ )
+ YAML::Store.new('bbsconfig.yaml').transaction do |store|
+ store['username'], store['password'] = username, password
+ end
+ visit '/load_bbs'
+ rescue RuntimeError => err
+ debug "error: #{err.message}"
+ @@bbs = nil
+ visit "/login_error/#{err.message}"
end
- visit '/load_bbs'
- rescue RuntimeError => err
- debug "error: #{err.message}"
- @@bbs = nil
- visit "/login_error/#{err.message}"
end
end
def login
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
keypress do | key |
if key == "\n"
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
-
- show_page do
- show_section do
+ @content = page_box do
+ section_box do
tagline "Login", :stroke => randcolor(:realdark), :align => right
para "username:"
@username_line = app.edit_line "#{ username }"
para "password:"
@password_line = app.edit_line "#{ password }", :secret => true
-
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
-
para(link( 'license', :click => '/license' ))
end
end
end
def quit
- show_page do
+ page_box do
exit()
end
end
def leave_forum(id)
info "leave forum #{id}"
- show_page
- record_last_read(id)
- visit '/bbs'
+ page_box
+ page_box do
+ para "leaving forum #{id}..."
+ end
+ recording_last_read(id) do
+ visit '/bbs'
+ end
end
+
def load_bbs
- show_page
- @@bbs_cache[:all] = @@bbs.forums('all')
- @@bbs_cache[:todo] = @@bbs.forums('todo')
- @@bbs_cache[:joined] = @@bbs.forums('joined')
- visit '/bbs'
+ info "load_bbs"
+ page_box do
+ para "loading forums..."
+ end
+ Thread.new do
+ @@bbs_cache[:all] = @@bbs.forums('all')
+ @@bbs_cache[:todo] = @@bbs.forums('todo')
+ @@bbs_cache[:joined] = @@bbs.forums('joined')
+ visit '/bbs'
+ end
end
def bbs
+ info "bbs"
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
linklist, keypressproc = actions( action_list )
keypress { | key | keypressproc.call(key) }
- show_page do
- show_section do
- para *linklist
- end
- #flow(:margin_left => 20, :margin_top => 20) { para *linklist }
- # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
- # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
- [ ["Unread", forums_todo, ivory],
- ["Subscribed", forums_joined, lightgrey],
- ["Zapped", forums_all, darkslateblue]].each do | group |
- group_name, ordered_ids, coloring = *group
+ open_shown = false
+ page_box do
+ header_box( linklist, "Forums")
+ [ ["Unread", forums_todo ],
+ ["Subscribed", forums_joined ],
+ ["Zapped", forums_all ]].each do | group |
+ group_name, ordered_ids = *group
if ordered_ids.length > 0
- show_section do
- info "doing #{group_name}"
- caption( group_name,
- :align => 'right',
- :margin => 20 )
- flow do
- ordered_ids.each do | id |
- data = forums[id]
- show_chunk do
- para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
- end
+ chunk_section_box(group_name, open_shown) do
+ ordered_ids.each do | id |
+ data = forums[id]
+ chunk_box do
+ para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
+ open_shown = true
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
+ page_box do
+ para "leaving forum #{forum_id}.."
+ end
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
- record_last_read(forum_id)
+
todo_list = @@bbs_cache[:todo].keys.sort
- if todo_list.length > 0
- visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
- else
- visit "/bbs"
+ recording_last_read(forum_id) do
+ if todo_list.length > 0
+ visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
+ else
+ visit "/bbs"
+ end
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
- record_last_read(old_id)
- visit "/enter_forum/#{new_id}"
+ recording_last_read(old_id) do
+ visit "/enter_forum/#{new_id}"
+ end
end
def enter_forum(id)
+ page_box do
+ para "loading forum #{id}..."
+ end
info "enter_forum #{id}"
id = id.to_i
- # we pull stuff into forum_cache only when we enter a new forum.
- forum = @@bbs.jump(id)
- cache = {}
- first_unread = forum.first_unread.to_i
- info "first_unread: #{ first_unread.inspect }"
- cache[:server_first_unread] = first_unread
- cache[:first_unread] = first_unread
- info "first unread: #{first_unread.inspect}"
- info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
- noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
- cache[:noteids] = forum.noteids(noterange).sort
- if cache[:noteids].length == 0 # uh oh
- noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
+ Thread.new do
+ # we pull stuff into forum_cache only when we enter a new forum.
+ forum = @@bbs.jump(id)
+ cache = {}
+ first_unread = forum.first_unread.to_i
+ info "first_unread: #{ first_unread.inspect }"
+ cache[:server_first_unread] = first_unread
+ cache[:first_unread] = first_unread
+ info "first unread: #{first_unread.inspect}"
+ info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
+ noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
+ if cache[:noteids].length == 0 # uh oh
+ noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
+ cache[:noteids] = forum.noteids(noterange).sort
+ end
+ info "noterange: #{noterange}"
+ cache[:post_headers] = forum.post_headers(noterange)
+ cache[:name] = forum.name
+ cache[:post_ok] = forum.post?
+ cache[:admin] = forum.admin
+ cache[:anonymous] = forum.anonymous
+ cache[:private] = forum.private
+ @@forum_cache[id] = cache
+ visit "/forum/#{id}"
end
- info "noterange: #{noterange}"
- cache[:post_headers] = forum.post_headers(noterange)
- cache[:name] = forum.name
- cache[:post_ok] = forum.post?
- cache[:admin] = forum.admin
- cache[:anonymous] = forum.anonymous
- cache[:private] = forum.private
- @@forum_cache[id] = cache
- visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
+ actionlist = [[ 'e', '[e]nter msg', "/new_post/#{id}"],
+ [ 'i', '[i]nfo', "/foruminfo/#{id}"],
+ [ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
+ [ 'f', 'read [f]orward',
+ "/message/#{id}/#{noteids.first}/forward"],
+ [ 'b', 'read [b]ackward',
+ "/message/#{id}/#{noteids.last}/backward"],
+ [ 'g', '[g]oto next forum with unread messages',
+ "/goto_next_from/#{id}"],
+ [ ' ', '[ ]first unread', "/first_unread/#{id}"],
+ [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
+ ]
- linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
- [ 'i', '[i]nfo', "/foruminfo/#{id}"],
- [ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
- [ 'f', 'read [f]orward',
- "/message/#{id}/#{noteids.first}/forward"],
- [ 'b', 'read [b]ackward',
- "/message/#{id}/#{noteids.last}/backward"],
- [ 'g', '[g]oto next forum with unread messages',
- "/goto_next_from/#{id}"],
- [ ' ', '[ ]first unread', "/first_unread/#{id}"],
- [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
- ] )
+ linklist, keypressproc = actions(actionlist)
keypress { | key | keypressproc.call(key) }
- show_page do
- show_section do
- para *linklist
- tagline( cache[:name], :stroke => randcolor(:realdark),
- :margin => 20, :align => 'right')
- end
+ open_shown = false
+ page_box do
+ header_box(linklist, cache[:name])
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
- show_section do
- caption group_name, :align => 'right', :stroke => randcolor(:realdark)
- flow do
- ordered_ids.reverse.each do | post_id |
- post = posts[post_id.to_s]
- show_chunk do
- para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
- para post[:subject]
- end
+ chunk_section_box(group_name, open_shown) do
+ ordered_ids.reverse.each do | post_id |
+ post = posts[post_id.to_s]
+ chunk_box do
+ para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
+ para post[:subject]
end
end
end
+ open_shown = true
end
end
end
end
def foruminfo(id)
id = id.to_i
info "foruminfo #{id}"
+ @page = page_box do
+ para "loading info for forum #{id}..."
+ end
+
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
-
- show_page do
- para *linklist
+
+ Thread.new do
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
- show_section do
- caption "Forum moderator is #{@@forum_cache[id][:admin]}."
- caption "Forum info last updated #{info[:date]} by #{info[:from]}"
- para "#{info[:body]}"
- body_urls.each do | a_url |
- para link(a_url, :click => a_url)
+ @page.clear do
+ section_box do
+ para *linklist
+ end
+ section_box do
+ caption "Forum moderator is #{@@forum_cache[id][:admin]}."
+ caption "Forum info last updated #{info[:date]} by #{info[:from]}"
+ para "#{info[:body]}"
+ body_urls.each do | a_url |
+ para link(a_url, :click => a_url)
+ end
end
end
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
forum_id = forum_id.to_i
cache = @@forum_cache[forum_id]
- show_page do
+ page_box do
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
- show_page
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
+ @page = page_box do
+ para "loading messge #{msgnum} in forum #{forum_id}"
+ end
+
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
- show_page do
- show_section do
- para *linklist
- end
- msg = get_message(forum_id, msgnum)
- body_urls = msg[:body].scan(URLRE)
- authority = " (#{msg[:authority]})" if msg[:authority]
- @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
- "#{msg[:body]}" +
- "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
-
- show_section do
+ Thread.new do
+ msg = get_message(forum_id, msgnum)
+ body_urls = msg[:body].scan(URLRE)
+ authority = " (#{msg[:authority]})" if msg[:authority]
+ @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
+ "#{msg[:body]}" +
+ "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
+
+ @page.clear do
+ section_box do
+ para *linklist
+ end
+ section_box do
para @whole_message
- body_urls.each do | a_url |
- para link(a_url, :click => a_url)
+ body_urls.each do | a_url |
+ para link(a_url, :click => a_url)
+ end
end
end
end
-
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
+
end
def new_reply(forum_id, msgnum)
- @post = @@bbs.jump(forum_id).read(msgnum)
- old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
- quote = "#{@post.author} wrote:\n#{old_body}\n\n"
- show_page do
- tagline "New Post", :stroke => randcolor(:realdark), :align => 'right'
- para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
- @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
- button "post" do
- text = @post_box.text
- new_post = @@bbs.jump(forum_id).post(text)
- record_last_read(forum_id)
- visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ @page = page_box do
+ "loading message #{msgnum} in forum #{forum_id} to reply to..."
+ end
+
+ Thread.new do
+ msg = get_message(forum_id, msgnum)
+ old_body = msg[:body].split("\n").map{ |line| "> #{line}" }.join("\n")
+ quote = "#{msg[:author]} wrote:\n#{old_body}\n\n"
+ @page.clear do
+ section_box do
+ para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
+ tagline "Post to forum #{forum_id}", :stroke => randcolor(:realdark), :align => 'right'
+ @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
+ button "post" do
+ text = @post_box.text
+ new_post = @@bbs.jump(forum_id).post(text)
+ recording_last_read(forum_id) do
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ end
+ end
+ end
end
end
end
def new_post(forum_id)
- show_page do
- tagline "New Post", :stroke => randcolor(:realdark), :align => right
- para link("back", :click => "/forum/#{forum_id}")
- @post_box = edit_box :width => 500, :height => 300, :margin => 20
- button "post" do
- text = @post_box.text
- new_post = @@bbs.jump(forum_id).post(text)
- record_last_read(forum_id)
- visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ @page = page_box do
+ section_box do
+ tagline "New Post", :stroke => randcolor(:realdark), :align => right
+ para link("back", :click => "/forum/#{forum_id}")
+ @post_box = edit_box :width => 500, :height => 300, :margin => 20
+ button "post" do
+ text = @post_box.text
+ @page.clear do
+ para "posting message..."
+ end
+ Thread.new do
+ new_post = @@bbs.jump(forum_id).post(text)
+ recording_last_read(forum_id) do
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ end
+ end
+ end
end
end
end
end
-
-Shoes.app :width => 800
+Shoes.app :width => 850
|
edheil/shoesca
|
04a4822278035c3753185f9d4fd489dc902396fc
|
abstract out page painting
|
diff --git a/shoesca.rb b/shoesca.rb
index 8cd8895..7ddc773 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,549 +1,571 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
- def tweakcolor(r, g, b, v)
+ def show_page
+ info "show_page"
+ background black
+ stack :margin => 20 do
+ background randcolor(:dark), :curve => 20
+ stack :margin => 20 do
+ yield if block_given?
+ end
+ end
+ end
+ def show_section
+ info "show_section: background"
+ stack :margin => 20 do
+ background randcolor(:light, 0.5), :curve => 20
+ stack :margin => 20 do
+ info "yielding..."
+ yield if block_given?
+ end
+ end
+ end
+
+ def show_chunk(coloring=nil)
+ coloring ||= rgb(1.0, 1.0, 1.0, 0.5)
+ stack :width => 200 do
+ background coloring, :curve => 10, :margin => 10
+ stack :margin => 20 do
+ yield if block_given?
+ end
+ end
end
def randcolor(bias=nil, alpha = 1.0)
target, range = case bias
when :dark: [ 0.3, 0.3 ]
when :light: [0.8, 0.4]
when :realdark: [ 0.1, 0.2]
else [0.5, 0.6]
end
rgb( ( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
( (rand - 0.5) * range ) + target,
alpha)
end
def license
info "license"
- background black
- stack :margin => 20 do
- background aliceblue, :curve => 20
- para link('back', :click => '/login')
- para LICENSE
+ show_page do
+ show_section do
+ background aliceblue, :curve => 20
+ para link('back', :click => '/login')
+ para LICENSE
+ end
end
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
if cached
if cached[:first_unread] != cached[:server_first_unread]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
end
end
def quit_from_forum(id)
info "quit_from_forum"
record_last_read(id)
exit()
end
def quit
info "quit"
exit()
end
def login_error(error)
stack do
para err.message
link("try again",:click => '/')
end
end
def do_login(username, password)
begin
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
end
visit '/load_bbs'
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
visit "/login_error/#{err.message}"
end
end
def login
- background black
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
-
- stack :margin => 20 do
- background randcolor(:light), :curve => 20
- stack :margin => 20 do
+
+ keypress do | key |
+ if key == "\n"
+ visit "/do_login/#{@username_line.text}/#{@password_line.text}"
+ end
+ end
+
+ show_page do
+ show_section do
tagline "Login", :stroke => randcolor(:realdark), :align => right
para "username:"
- @username_line = edit_line "#{ username }"
+ @username_line = app.edit_line "#{ username }"
para "password:"
- @password_line = edit_line "#{ password }", :secret => true
+ @password_line = app.edit_line "#{ password }", :secret => true
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
para(link( 'license', :click => '/license' ))
end
-
- keypress do | key |
- if key == "\n"
- visit "/do_login/#{@username_line.text}/#{@password_line.text}"
- end
- end
end
end
def quit
- exit()
+ show_page do
+ exit()
+ end
end
def leave_forum(id)
info "leave forum #{id}"
+ show_page
record_last_read(id)
visit '/bbs'
end
def load_bbs
- background black
+ show_page
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
def bbs
- background black
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
linklist, keypressproc = actions( action_list )
keypress { | key | keypressproc.call(key) }
- stack :margin => 20 do
- background randcolor(:light, 0.5), :curve => 20
- flow(:margin_left => 20, :margin_top => 20) { para *linklist }
+ show_page do
+ show_section do
+ para *linklist
+ end
+ #flow(:margin_left => 20, :margin_top => 20) { para *linklist }
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo, ivory],
["Subscribed", forums_joined, lightgrey],
["Zapped", forums_all, darkslateblue]].each do | group |
group_name, ordered_ids, coloring = *group
- stack :margin => 20 do
- background randcolor(:light, 0.5), :curve => 20
- caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
- flow do
- coloring = rgb(1.0,1.0,1.0, 0.5)
- ordered_ids.each do | id |
- data = forums[id]
- stack :width => 200, :margin => 20 do
- background coloring, :curve => 10
- para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
+ if ordered_ids.length > 0
+ show_section do
+ info "doing #{group_name}"
+ caption( group_name,
+ :align => 'right',
+ :margin => 20 )
+ flow do
+ ordered_ids.each do | id |
+ data = forums[id]
+ show_chunk do
+ para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
+ end
end
end
end
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
record_last_read(forum_id)
todo_list = @@bbs_cache[:todo].keys.sort
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
record_last_read(old_id)
visit "/enter_forum/#{new_id}"
end
def enter_forum(id)
info "enter_forum #{id}"
id = id.to_i
- background black
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
- background black
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
- stack :margin => 20 do
- background randcolor(:dark), :curve => 20
- flow(:margin => 20) { para *linklist }
- tagline( cache[:name], :stroke => randcolor(:realdark),
- :margin => 20, :align => 'right')
+ show_page do
+ show_section do
+ para *linklist
+ tagline( cache[:name], :stroke => randcolor(:realdark),
+ :margin => 20, :align => 'right')
+ end
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
- stack :margin => 20 do
- background randcolor(nil, 0.5), :curve => 20
- caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
- flow do
- ordered_ids.reverse.each do | post_id |
- post = posts[post_id.to_s]
- stack :margin => 20, :width => 200 do
- background rgb(1.0,1.0,1.0, 0.5), :curve => 10
- para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
- para post[:subject]
+ if ordered_ids.length > 0
+ show_section do
+ caption group_name, :align => 'right', :stroke => randcolor(:realdark)
+ flow do
+ ordered_ids.reverse.each do | post_id |
+ post = posts[post_id.to_s]
+ show_chunk do
+ para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
+ para post[:subject]
+ end
end
end
end
end
end
end
end
def foruminfo(id)
+ id = id.to_i
info "foruminfo #{id}"
- background black
-
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
- stack :margin => 20 do
- background blanchedalmond, :curve => 20
- flow(:margin_left => 20, :margin_top => 20) { para *linklist }
+ show_page do
+ para *linklist
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
- stack :margin => 20 do
- background lightgrey, :curve => 10
- caption "Forum moderator is #{@@forum_cache[:admin]}."
+ show_section do
+ caption "Forum moderator is #{@@forum_cache[id][:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
forum_id = forum_id.to_i
- background black
cache = @@forum_cache[forum_id]
- stack :margin => 20 do
- background blanchedalmond, :curve => 20
+ show_page do
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
+ show_page
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
- background black
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
-
+
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
+ show_page do
+ show_section do
+ para *linklist
+ end
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
- stack :margin => 20 do
- background randcolor(:dark), :curve => 20
- flow(:margin_left => 20, :margin_top => 20) { para *linklist }
- stack :margin => 20 do
- background rgb(1.0,1.0,1.0,0.8), :curve => 20
+ show_section do
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
+
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
- background black
- stack :margin => 20 do
- background randcolor(:light, 0.5), :curve => 20
- stack :margin => 20 do
- tagline "New Post", :stroke => randcolor(:realdark), :align => 'right'
- para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
- @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
- button "post" do
- text = @post_box.text
- new_post = @@bbs.jump(forum_id).post(text)
- visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
- end
+ show_page do
+ tagline "New Post", :stroke => randcolor(:realdark), :align => 'right'
+ para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
+ @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
+ button "post" do
+ text = @post_box.text
+ new_post = @@bbs.jump(forum_id).post(text)
+ record_last_read(forum_id)
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
def new_post(forum_id)
- background black
- stack :margin => 20 do
- background randcolor(:light, 0.5), :curve => 20
- stack :margin => 20 do
- tagline "New Post", :stroke => randcolor(:realdark), :align => right
- para link("back", :click => "/forum/#{forum_id}")
- @post_box = edit_box :width => 500, :height => 300, :margin => 20
- button "post" do
- text = @post_box.text
- new_post = @@bbs.jump(forum_id).post(text)
- visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
- end
+ show_page do
+ tagline "New Post", :stroke => randcolor(:realdark), :align => right
+ para link("back", :click => "/forum/#{forum_id}")
+ @post_box = edit_box :width => 500, :height => 300, :margin => 20
+ button "post" do
+ text = @post_box.text
+ new_post = @@bbs.jump(forum_id).post(text)
+ record_last_read(forum_id)
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
5d23c9172a739ab1f7337b2336755ce50f38dc9f
|
more cosmetics
|
diff --git a/shoesca.rb b/shoesca.rb
index 5bbf1e2..8cd8895 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,547 +1,549 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
+ def tweakcolor(r, g, b, v)
+
+ end
+
def randcolor(bias=nil, alpha = 1.0)
- if bias == :dark
- rgb( (rand/2 + 0.2), (rand/2 + 0.2), (rand/2 + 0.2), alpha )
- elsif bias == :light
- rgb( (rand/2 + 0.5), (rand/2 + 0.5), (rand/2 + 0.5), alpha )
- elsif bias == :realdark
- rgb( rand/4, rand/4, rand/4, alpha)
- else
- rgb( rand * 0.8 + 0.2, rand * 0.8 + 0.2, rand * 0.8 + 0.2, alpha )
- end
+ target, range = case bias
+ when :dark: [ 0.3, 0.3 ]
+ when :light: [0.8, 0.4]
+ when :realdark: [ 0.1, 0.2]
+ else [0.5, 0.6]
+ end
+ rgb( ( (rand - 0.5) * range ) + target,
+ ( (rand - 0.5) * range ) + target,
+ ( (rand - 0.5) * range ) + target,
+ alpha)
end
+
def license
info "license"
background black
stack :margin => 20 do
background aliceblue, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
if cached
if cached[:first_unread] != cached[:server_first_unread]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
end
end
def quit_from_forum(id)
info "quit_from_forum"
record_last_read(id)
exit()
end
def quit
info "quit"
exit()
end
def login_error(error)
stack do
para err.message
link("try again",:click => '/')
end
end
def do_login(username, password)
begin
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
end
visit '/load_bbs'
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
visit "/login_error/#{err.message}"
end
end
def login
background black
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
stack :margin => 20 do
background randcolor(:light), :curve => 20
stack :margin => 20 do
- tagline "Login", :stroke => randcolor(:realdark)
+ tagline "Login", :stroke => randcolor(:realdark), :align => right
para "username:"
@username_line = edit_line "#{ username }"
para "password:"
@password_line = edit_line "#{ password }", :secret => true
button "login" do
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
para(link( 'license', :click => '/license' ))
end
keypress do | key |
if key == "\n"
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
end
end
def quit
exit()
end
def leave_forum(id)
info "leave forum #{id}"
record_last_read(id)
visit '/bbs'
end
def load_bbs
background black
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
def bbs
background black
-
- @mainstack = stack :margin => 20 do
- background aliceblue, :curve => 20
- para "loading bbs..."
- end
-
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
linklist, keypressproc = actions( action_list )
keypress { | key | keypressproc.call(key) }
- @mainstack.clear do
+ stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
flow(:margin_left => 20, :margin_top => 20) { para *linklist }
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo, ivory],
["Subscribed", forums_joined, lightgrey],
["Zapped", forums_all, darkslateblue]].each do | group |
group_name, ordered_ids, coloring = *group
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
flow do
coloring = rgb(1.0,1.0,1.0, 0.5)
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
background coloring, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
record_last_read(forum_id)
todo_list = @@bbs_cache[:todo].keys.sort
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
record_last_read(old_id)
visit "/enter_forum/#{new_id}"
end
def enter_forum(id)
info "enter_forum #{id}"
id = id.to_i
background black
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
background black
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
- @mainstack = stack :margin => 20 do
- background blanchedalmond, :curve => 20
- para "loading forum #{id}..."
- end
-
- @mainstack.clear do
- background blanchedalmond, :curve => 20
- tagline cache[:name], :stroke => randcolor(:realdark), :margin => 20
- flow(:margin_left => 20, :margin_top => 20) { para *linklist }
+ stack :margin => 20 do
+ background randcolor(:dark), :curve => 20
+ flow(:margin => 20) { para *linklist }
+ tagline( cache[:name], :stroke => randcolor(:realdark),
+ :margin => 20, :align => 'right')
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
stack :margin => 20 do
- background randcolor(:light, 0.5), :curve => 20
+ background randcolor(nil, 0.5), :curve => 20
caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
flow do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background rgb(1.0,1.0,1.0, 0.5), :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
def foruminfo(id)
info "foruminfo #{id}"
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
stack :margin => 20 do
background blanchedalmond, :curve => 20
flow(:margin_left => 20, :margin_top => 20) { para *linklist }
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
stack :margin => 20 do
background lightgrey, :curve => 10
caption "Forum moderator is #{@@forum_cache[:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
forum_id = forum_id.to_i
background black
cache = @@forum_cache[forum_id]
stack :margin => 20 do
background blanchedalmond, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack :margin => 20 do
- background randcolor, :curve => 20
+ background randcolor(:dark), :curve => 20
flow(:margin_left => 20, :margin_top => 20) { para *linklist }
stack :margin => 20 do
background rgb(1.0,1.0,1.0,0.8), :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
- tagline "New Post", :stroke => randcolor(:realdark)
- para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
- @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
- button "post" do
- text = @post_box.text
- new_post = @@bbs.jump(forum_id).post(text)
- visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ stack :margin => 20 do
+ tagline "New Post", :stroke => randcolor(:realdark), :align => 'right'
+ para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
+ @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
+ button "post" do
+ text = @post_box.text
+ new_post = @@bbs.jump(forum_id).post(text)
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ end
end
end
end
def new_post(forum_id)
background black
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
- tagline "New Post", :stroke => randcolor(:realdark)
- para link("back", :click => "/forum/#{forum_id}")
- @post_box = edit_box :width => 500, :height => 300, :margin => 20
- button "post" do
- text = @post_box.text
- new_post = @@bbs.jump(forum_id).post(text)
- visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ stack :margin => 20 do
+ tagline "New Post", :stroke => randcolor(:realdark), :align => right
+ para link("back", :click => "/forum/#{forum_id}")
+ @post_box = edit_box :width => 500, :height => 300, :margin => 20
+ button "post" do
+ text = @post_box.text
+ new_post = @@bbs.jump(forum_id).post(text)
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
+ end
end
end
end
end
+
+
Shoes.app :width => 800
|
edheil/shoesca
|
b749bd4ff767cd0c4436367432bc664f674bc443
|
cosmetics
|
diff --git a/shoesca.rb b/shoesca.rb
index 6931c19..5bbf1e2 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,546 +1,547 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/login_error/(.+)', :login_error
url '/bbs', :bbs
url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
def randcolor(bias=nil, alpha = 1.0)
if bias == :dark
rgb( (rand/2 + 0.2), (rand/2 + 0.2), (rand/2 + 0.2), alpha )
elsif bias == :light
rgb( (rand/2 + 0.5), (rand/2 + 0.5), (rand/2 + 0.5), alpha )
elsif bias == :realdark
rgb( rand/4, rand/4, rand/4, alpha)
else
rgb( rand * 0.8 + 0.2, rand * 0.8 + 0.2, rand * 0.8 + 0.2, alpha )
end
end
def license
info "license"
background black
stack :margin => 20 do
background aliceblue, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
if cached
if cached[:first_unread] != cached[:server_first_unread]
forum = @@bbs.jump(forum_id)
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
if cached[:first_unread] > cached[:noteids].last
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
end
end
def quit_from_forum(id)
info "quit_from_forum"
record_last_read(id)
exit()
end
def quit
info "quit"
exit()
end
def login_error(error)
stack do
para err.message
link("try again",:click => '/')
end
end
def do_login(username, password)
begin
@@bbs = Raccdoc::Connection.new(:user => username, :password => password,
:host => HOST,
:port => PORT
)
YAML::Store.new('bbsconfig.yaml').transaction do |store|
store['username'], store['password'] = username, password
end
visit '/load_bbs'
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
visit "/login_error/#{err.message}"
end
end
def login
background black
username, password = nil, nil
YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
username, password = store['username'], store['password']
end
stack :margin => 20 do
background randcolor(:light), :curve => 20
- tagline "Login", :stroke => randcolor(:realdark)
- para "username:"
- @username_line = edit_line "#{ username }"
- para "password:"
- @password_line = edit_line "#{ password }", :secret => true
-
- button "login" do
- visit "/do_login/#{@username_line.text}/#{@password_line.text}"
+ stack :margin => 20 do
+ tagline "Login", :stroke => randcolor(:realdark)
+ para "username:"
+ @username_line = edit_line "#{ username }"
+ para "password:"
+ @password_line = edit_line "#{ password }", :secret => true
+
+ button "login" do
+ visit "/do_login/#{@username_line.text}/#{@password_line.text}"
+ end
+
+ para(link( 'license', :click => '/license' ))
end
- para(link( 'license', :click => '/license' ))
-
keypress do | key |
if key == "\n"
visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
end
end
def quit
exit()
end
def leave_forum(id)
info "leave forum #{id}"
record_last_read(id)
visit '/bbs'
end
def load_bbs
background black
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
def bbs
background black
@mainstack = stack :margin => 20 do
background aliceblue, :curve => 20
para "loading bbs..."
end
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
linklist, keypressproc = actions( action_list )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background randcolor(:light, 0.5), :curve => 20
- para *linklist
+ flow(:margin_left => 20, :margin_top => 20) { para *linklist }
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo, ivory],
["Subscribed", forums_joined, lightgrey],
["Zapped", forums_all, darkslateblue]].each do | group |
group_name, ordered_ids, coloring = *group
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
- caption group_name
+ caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
flow do
- coloring = randcolor(:light, 0.5)
+ coloring = rgb(1.0,1.0,1.0, 0.5)
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
background coloring, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
record_last_read(forum_id)
todo_list = @@bbs_cache[:todo].keys.sort
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
record_last_read(old_id)
visit "/enter_forum/#{new_id}"
end
def enter_forum(id)
info "enter_forum #{id}"
id = id.to_i
background black
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
info "first unread: #{first_unread.inspect}"
info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
if cache[:noteids].length == 0 # uh oh
noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
cache[:noteids] = forum.noteids(noterange).sort
end
info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
background black
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack :margin => 20 do
background blanchedalmond, :curve => 20
para "loading forum #{id}..."
end
@mainstack.clear do
background blanchedalmond, :curve => 20
- tagline cache[:name], :stroke => randcolor(:realdark)
- para *linklist
+ tagline cache[:name], :stroke => randcolor(:realdark), :margin => 20
+ flow(:margin_left => 20, :margin_top => 20) { para *linklist }
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
- caption group_name
- the_color = randcolor(:light)
+ caption group_name, :align => 'right', :stroke => randcolor(:realdark), :margin => 20
flow do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
stack :margin => 20, :width => 200 do
- background the_color, :curve => 10
+ background rgb(1.0,1.0,1.0, 0.5), :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
def foruminfo(id)
info "foruminfo #{id}"
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
stack :margin => 20 do
background blanchedalmond, :curve => 20
- para *linklist
+ flow(:margin_left => 20, :margin_top => 20) { para *linklist }
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
stack :margin => 20 do
background lightgrey, :curve => 10
caption "Forum moderator is #{@@forum_cache[:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
forum_id = forum_id.to_i
background black
cache = @@forum_cache[forum_id]
stack :margin => 20 do
background blanchedalmond, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack :margin => 20 do
- background randcolor(:light, 0.5), :curve => 20
- para *linklist
+ background randcolor, :curve => 20
+ flow(:margin_left => 20, :margin_top => 20) { para *linklist }
stack :margin => 20 do
- background randcolor(:light), :curve => 20
+ background rgb(1.0,1.0,1.0,0.8), :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
tagline "New Post", :stroke => randcolor(:realdark)
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
def new_post(forum_id)
background black
stack :margin => 20 do
background randcolor(:light, 0.5), :curve => 20
tagline "New Post", :stroke => randcolor(:realdark)
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
ccbe1dbd8c78d0cc322baff134f9cfd5357abb4c
|
smarter noteids, random colors
|
diff --git a/shoesca.rb b/shoesca.rb
index 814ea3e..6931c19 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,557 +1,546 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
+ url '/login_error/(.+)', :login_error
url '/bbs', :bbs
+ url '/do_login/([^\/]+)/(.+)', :do_login
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
+ def randcolor(bias=nil, alpha = 1.0)
+ if bias == :dark
+ rgb( (rand/2 + 0.2), (rand/2 + 0.2), (rand/2 + 0.2), alpha )
+ elsif bias == :light
+ rgb( (rand/2 + 0.5), (rand/2 + 0.5), (rand/2 + 0.5), alpha )
+ elsif bias == :realdark
+ rgb( rand/4, rand/4, rand/4, alpha)
+ else
+ rgb( rand * 0.8 + 0.2, rand * 0.8 + 0.2, rand * 0.8 + 0.2, alpha )
+ end
+ end
+
def license
info "license"
background black
stack :margin => 20 do
background aliceblue, :curve => 20
- border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
if cached
- info "got cache"
- info "seeing if #{ cached[:first_unread] } != #{ cached[:server_first_unread] }"
if cached[:first_unread] != cached[:server_first_unread]
- info "yep. must modify server's first_unread"
forum = @@bbs.jump(forum_id)
- info "setting first_unread to #{cached[:first_unread]}"
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
- info "after the change..."
if cached[:first_unread] > cached[:noteids].last
- info "first_unread is greater than last_note. deleting #{forum_id} from todo"
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
- info "first_unread is less than or equal to last_note. adding #{forum_id} to todo"
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
end
end
def quit_from_forum(id)
info "quit_from_forum"
record_last_read(id)
exit()
end
def quit
info "quit"
exit()
end
-
-
- def login
- background black
- @store = YAML::Store.new('bbsconfig.yaml')
- @username, @password = nil, nil
- @store.transaction(true) do
- @username, @password = @store['username'], @store['password']
+ def login_error(error)
+ stack do
+ para err.message
+ link("try again",:click => '/')
end
+ end
- def do_login
- @@username = @username_line.text
- @@password = @password_line.text
- @mainstack.append do
- para "logging in..."
+ def do_login(username, password)
+ begin
+ @@bbs = Raccdoc::Connection.new(:user => username, :password => password,
+ :host => HOST,
+ :port => PORT
+ )
+ YAML::Store.new('bbsconfig.yaml').transaction do |store|
+ store['username'], store['password'] = username, password
end
- Thread.new do
- begin
- @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
- :host => HOST,
- :port => PORT
- )
- rescue RuntimeError => err
- debug "error: #{err.message}"
- @@bbs = nil
- @mainstack.append do
- para err.message
- end
- end
- if @@bbs
- @store.transaction do
- @store['username'], @store['password'] = @username, @password
- end
- visit '/load_bbs'
- end
- end
+ visit '/load_bbs'
+ rescue RuntimeError => err
+ debug "error: #{err.message}"
+ @@bbs = nil
+ visit "/login_error/#{err.message}"
end
+ end
+ def login
+ background black
+ username, password = nil, nil
+ YAML::Store.new('bbsconfig.yaml').transaction(true) do |store|
+ username, password = store['username'], store['password']
+ end
- @mainstack = stack :margin => 20 do
- background salmon, :curve => 20
- border black, :curve => 20
- tagline "Login"
+ stack :margin => 20 do
+ background randcolor(:light), :curve => 20
+ tagline "Login", :stroke => randcolor(:realdark)
para "username:"
- @username_line = edit_line "#{ @username }"
+ @username_line = edit_line "#{ username }"
para "password:"
- @password_line = edit_line "#{ @password }", :secret => true
+ @password_line = edit_line "#{ password }", :secret => true
button "login" do
- do_login
+ visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
- do_login
+ visit "/do_login/#{@username_line.text}/#{@password_line.text}"
end
end
end
end
def quit
exit()
end
def leave_forum(id)
info "leave forum #{id}"
record_last_read(id)
visit '/bbs'
end
def load_bbs
background black
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
def bbs
background black
@mainstack = stack :margin => 20 do
background aliceblue, :curve => 20
- border black, :curve => 20
para "loading bbs..."
end
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
- action_list << [ ' ', '[ ]first forum with unread', "/forum/#{forums_todo.first}"]
+ action_list << [ ' ', '[ ]first forum with unread', "/enter_forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
linklist, keypressproc = actions( action_list )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
- background aliceblue, :curve => 20
- border black, :curve => 20
+ background randcolor(:light, 0.5), :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo, ivory],
["Subscribed", forums_joined, lightgrey],
["Zapped", forums_all, darkslateblue]].each do | group |
group_name, ordered_ids, coloring = *group
stack :margin => 20 do
- background white, :curve => 20
- border black, :curve => 20
+ background randcolor(:light, 0.5), :curve => 20
caption group_name
flow do
+ coloring = randcolor(:light, 0.5)
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
background coloring, :curve => 10
- border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
record_last_read(forum_id)
todo_list = @@bbs_cache[:todo].keys.sort
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
record_last_read(old_id)
visit "/enter_forum/#{new_id}"
end
def enter_forum(id)
info "enter_forum #{id}"
id = id.to_i
background black
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
+ info "first_unread: #{ first_unread.inspect }"
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
+ info "first unread: #{first_unread.inspect}"
+ info "forum_id info: #{ @@bbs_cache[:all][id].inspect }"
noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
cache[:noteids] = forum.noteids(noterange).sort
+ if cache[:noteids].length == 0 # uh oh
+ noterange = "#{ @@bbs_cache[:all][id][:lastnote].to_i - HORIZON }-#{ @@bbs_cache[:all][id][:lastnote] }"
+ cache[:noteids] = forum.noteids(noterange).sort
+ end
+ info "noterange: #{noterange}"
cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
cache[:post_ok] = forum.post?
cache[:admin] = forum.admin
cache[:anonymous] = forum.anonymous
cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
background black
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack :margin => 20 do
background blanchedalmond, :curve => 20
- border black, :curve => 20
para "loading forum #{id}..."
end
@mainstack.clear do
background blanchedalmond, :curve => 20
- border black, :curve => 20
- tagline cache[:name]
+ tagline cache[:name], :stroke => randcolor(:realdark)
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
stack :margin => 20 do
- background white, :curve => 20
- border black, :curve => 20
+ background randcolor(:light, 0.5), :curve => 20
caption group_name
+ the_color = randcolor(:light)
flow do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
stack :margin => 20, :width => 200 do
- background ivory, :curve => 10
- border black, :curve => 10
+ background the_color, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
def foruminfo(id)
info "foruminfo #{id}"
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
stack :margin => 20 do
background blanchedalmond, :curve => 20
- border black, :curve => 20
para *linklist
@@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
info = @@forum_cache[:forum_info]
the_body = info[:body]
body_urls = the_body.scan(URLRE)
stack :margin => 20 do
background lightgrey, :curve => 10
- border black, :curve => 10
caption "Forum moderator is #{@@forum_cache[:admin]}."
caption "Forum info last updated #{info[:date]} by #{info[:from]}"
para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
forum_id = forum_id.to_i
background black
cache = @@forum_cache[forum_id]
stack :margin => 20 do
background blanchedalmond, :curve => 20
- border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
- stack :margin => 20 do
- background gold, :curve => 20
- border black, :curve => 20
- @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
- end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
- @messagestack.clear do
+ stack :margin => 20 do
+ background randcolor(:light, 0.5), :curve => 20
para *linklist
stack :margin => 20 do
- background aliceblue, :curve => 20
- border black, :curve => 20
+ background randcolor(:light), :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack :margin => 20 do
- background lime, :curve => 20
- border black, :curve => 20
- tagline "New Post"
+ background randcolor(:light, 0.5), :curve => 20
+ tagline "New Post", :stroke => randcolor(:realdark)
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
def new_post(forum_id)
background black
stack :margin => 20 do
- background lime, :curve => 20
- border black, :curve => 20
- tagline "New Post"
+ background randcolor(:light, 0.5), :curve => 20
+ tagline "New Post", :stroke => randcolor(:realdark)
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
2c852e482da303fdbadcd2ee8d89acaf59a5d281
|
add "horizon" of 200 posts, cleanup unused methods
|
diff --git a/shoesca.rb b/shoesca.rb
index 555c73f..814ea3e 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,565 +1,557 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
+ HORIZON = 200 # the range of noteids retrieved before or after the first_unread
url '/', :login
url '/bbs', :bbs
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
def license
info "license"
background black
stack :margin => 20 do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
if cached
info "got cache"
info "seeing if #{ cached[:first_unread] } != #{ cached[:server_first_unread] }"
if cached[:first_unread] != cached[:server_first_unread]
info "yep. must modify server's first_unread"
forum = @@bbs.jump(forum_id)
info "setting first_unread to #{cached[:first_unread]}"
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
info "after the change..."
if cached[:first_unread] > cached[:noteids].last
info "first_unread is greater than last_note. deleting #{forum_id} from todo"
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
info "first_unread is less than or equal to last_note. adding #{forum_id} to todo"
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
end
end
def quit_from_forum(id)
info "quit_from_forum"
record_last_read(id)
exit()
end
def quit
info "quit"
exit()
end
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@@username = @username_line.text
@@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/load_bbs'
end
end
end
@mainstack = stack :margin => 20 do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def quit
exit()
end
def leave_forum(id)
info "leave forum #{id}"
record_last_read(id)
visit '/bbs'
end
def load_bbs
background black
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
def bbs
background black
@mainstack = stack :margin => 20 do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading bbs..."
end
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
action_list << [ ' ', '[ ]first forum with unread', "/forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
linklist, keypressproc = actions( action_list )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo, ivory],
["Subscribed", forums_joined, lightgrey],
["Zapped", forums_all, darkslateblue]].each do | group |
group_name, ordered_ids, coloring = *group
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
background coloring, :curve => 10
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
record_last_read(forum_id)
todo_list = @@bbs_cache[:todo].keys.sort
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
-
- def with_new_bbs_connection
- begin
- bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
- :host => HOST,
- :port => PORT
- )
- yield bbs
- rescue RuntimeError => err
- debug "error: #{err.message}"
- visit '/'
- end
- end
-
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
record_last_read(old_id)
visit "/enter_forum/#{new_id}"
end
def enter_forum(id)
info "enter_forum #{id}"
id = id.to_i
background black
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
- cache[:post_headers] = forum.post_headers
- cache[:noteids] = forum.noteids.sort
+ noterange = "#{ first_unread - HORIZON }-#{ first_unread + HORIZON }"
+ cache[:noteids] = forum.noteids(noterange).sort
+ cache[:post_headers] = forum.post_headers(noterange)
cache[:name] = forum.name
+ cache[:post_ok] = forum.post?
+ cache[:admin] = forum.admin
+ cache[:anonymous] = forum.anonymous
+ cache[:private] = forum.private
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
background black
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
@mainstack.clear do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline cache[:name]
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
-
+
def foruminfo(id)
info "foruminfo #{id}"
- @forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
- @info = @forum.forum_information
- the_body = @info[:body]
+ @@forum_cache[:forum_info] ||= @@bbs.jump(id).forum_information
+ info = @@forum_cache[:forum_info]
+ the_body = info[:body]
body_urls = the_body.scan(URLRE)
stack :margin => 20 do
background lightgrey, :curve => 10
border black, :curve => 10
- caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
- caption "Forum info last updated #{@info[:date]} by Mikemike"
- para "#{@info[:body]}"
+ caption "Forum moderator is #{@@forum_cache[:admin]}."
+ caption "Forum info last updated #{info[:date]} by #{info[:from]}"
+ para "#{info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
forum_id = forum_id.to_i
background black
cache = @@forum_cache[forum_id]
stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
stack :margin => 20 do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
authority = " (#{msg[:authority]})" if msg[:authority]
@whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
@messagestack.clear do
para *linklist
stack :margin => 20 do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack :margin => 20 do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
- visit("/forum/#{forum_id}");
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
def new_post(forum_id)
background black
stack :margin => 20 do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
- visit("/forum/#{forum_id}");
+ visit("/enter_forum/#{forum_id}") # refresh cache cause there's a new post!
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
33f014f883053fc52d21163e835295307468d7ca
|
remove first_todo which isn't needed anymore
|
diff --git a/shoesca.rb b/shoesca.rb
index 7dcc526..555c73f 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,586 +1,565 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :login
url '/bbs', :bbs
url '/load_bbs', :load_bbs
url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
- url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
def license
info "license"
background black
stack :margin => 20 do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
if cached
info "got cache"
info "seeing if #{ cached[:first_unread] } != #{ cached[:server_first_unread] }"
if cached[:first_unread] != cached[:server_first_unread]
info "yep. must modify server's first_unread"
forum = @@bbs.jump(forum_id)
info "setting first_unread to #{cached[:first_unread]}"
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
info "after the change..."
if cached[:first_unread] > cached[:noteids].last
info "first_unread is greater than last_note. deleting #{forum_id} from todo"
@@bbs_cache[:todo].delete(forum_id)
end
if cached[:first_unread] <= cached[:noteids].last
info "first_unread is less than or equal to last_note. adding #{forum_id} to todo"
@@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
end
end
end
end
def quit_from_forum(id)
info "quit_from_forum"
record_last_read(id)
exit()
end
def quit
info "quit"
exit()
end
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@@username = @username_line.text
@@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/load_bbs'
end
end
end
@mainstack = stack :margin => 20 do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def quit
exit()
end
def leave_forum(id)
info "leave forum #{id}"
record_last_read(id)
visit '/bbs'
end
def load_bbs
background black
@@bbs_cache[:all] = @@bbs.forums('all')
@@bbs_cache[:todo] = @@bbs.forums('todo')
@@bbs_cache[:joined] = @@bbs.forums('joined')
visit '/bbs'
end
def bbs
background black
@mainstack = stack :margin => 20 do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading bbs..."
end
forums = @@bbs_cache[:all]
forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
# delete mail
forums.delete(1)
action_list = []
if forums_todo.length > 0
- action_list << [ ' ', '[ ]first forum with unread', "/first_todo"]
+ action_list << [ ' ', '[ ]first forum with unread', "/forum/#{forums_todo.first}"]
else
action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
end
action_list << [ 'q', '[q]uit', '/quit' ]
linklist, keypressproc = actions( action_list )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo, ivory],
["Subscribed", forums_joined, lightgrey],
["Zapped", forums_all, darkslateblue]].each do | group |
group_name, ordered_ids, coloring = *group
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
background coloring, :curve => 10
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
def goto_next_from(forum_id)
forum_id = forum_id.to_i
# id is forum to jump *from*
cache = @@forum_cache[forum_id]
cache[:first_unread] = cache[:noteids].last + 1
record_last_read(forum_id)
todo_list = @@bbs_cache[:todo].keys.sort
if todo_list.length > 0
visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
else
visit "/bbs"
end
end
def with_new_bbs_connection
begin
bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
yield bbs
rescue RuntimeError => err
debug "error: #{err.message}"
visit '/'
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
record_last_read(old_id)
visit "/enter_forum/#{new_id}"
end
def enter_forum(id)
info "enter_forum #{id}"
id = id.to_i
background black
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
cache[:post_headers] = forum.post_headers
cache[:noteids] = forum.noteids.sort
cache[:name] = forum.name
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
background black
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto_next_from/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
@mainstack.clear do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline cache[:name]
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
def foruminfo(id)
info "foruminfo #{id}"
@forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack :margin => 20 do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
-
- def first_todo
- info "first_todo"
- background black
- stack :margin => 20 do
- background blanchedalmond, :curve => 20
- border black, :curve => 20
- para "finding first forum with unread messages..."
- end
- forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
- if forums_todo.length > 0
- forum_id = forums_todo[0]
- visit "/enter_forum/#{forum_id}"
- else
- visit "/bbs"
- end
- end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
forum_id = forum_id.to_i
background black
cache = @@forum_cache[forum_id]
stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
forum_id = forum_id.to_i; msgnum = msgnum.to_i
cache = @@forum_cache[forum_id]
if msgnum < cache[:first_unread]
cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
stack :margin => 20 do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
- keypressproc.call(key)
+ keypressproc.call(key)
}
-# Thread.new {
- msg = get_message(forum_id, msgnum)
-
- body_urls = msg[:body].scan(URLRE)
-
- @messagestack.clear do
- para *linklist
- @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
- "#{msg[:body]}" +
- "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
-
- stack :margin => 20 do
- background aliceblue, :curve => 20
- border black, :curve => 20
- para @whole_message
- body_urls.each do | a_url |
- para link(a_url, :click => a_url)
- end
+ msg = get_message(forum_id, msgnum)
+ body_urls = msg[:body].scan(URLRE)
+ authority = " (#{msg[:authority]})" if msg[:authority]
+ @whole_message = ( "#{msg[:date]} from #{msg[:author]}#{authority}\n" +
+ "#{msg[:body]}" +
+ "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
+
+ @messagestack.clear do
+ para *linklist
+ stack :margin => 20 do
+ background aliceblue, :curve => 20
+ border black, :curve => 20
+ para @whole_message
+ body_urls.each do | a_url |
+ para link(a_url, :click => a_url)
end
end
- if @@forum_cache[forum_id][:first_unread] <= msgnum
- @@forum_cache[forum_id][:first_unread] = msgnum + 1
- end
- # }
+ end
+ if @@forum_cache[forum_id][:first_unread] <= msgnum
+ @@forum_cache[forum_id][:first_unread] = msgnum + 1
+ end
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack :margin => 20 do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
def new_post(forum_id)
background black
stack :margin => 20 do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
f0ea047becbd699eafe7e75bc0984d376f664be0
|
caching forum_list, cleanup, fix quit_from_forum
|
diff --git a/shoesca.rb b/shoesca.rb
index eeab7ef..3dd4b6a 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,584 +1,602 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
- STACKSTYLE = { :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :login
url '/bbs', :bbs
+ url '/load_bbs', :load_bbs
+ url '/quit_from_forum/(\d+)', :quit_from_forum
url '/quit', :quit
- url '/quit_from_forum/(d+)', :quit_from_forum
- url '/goto/(\d+)', :goto
+ url '/goto_next_from/(\d+)', :goto_next_from
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
def license
info "license"
background black
- stack STACKSTYLE do
+ stack :margin => 20 do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
if cached
info "got cache"
- info "seeing if #{ cached[:first_unread] } > #{ cached[:server_first_unread] }"
- if cached[:first_unread] > cached[:server_first_unread]
- info "yep"
+ info "seeing if #{ cached[:first_unread] } != #{ cached[:server_first_unread] }"
+ if cached[:first_unread] != cached[:server_first_unread]
+ info "yep. must modify server's first_unread"
forum = @@bbs.jump(forum_id)
info "setting first_unread to #{cached[:first_unread]}"
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
+
+ info "after the change..."
+ if cached[:first_unread] > cached[:noteids].last
+ info "first_unread is greater than last_note. deleting #{forum_id} from todo"
+ @@bbs_cache[:todo].delete(forum_id)
+ end
+
+ if cached[:first_unread] <= cached[:noteids].last
+ info "first_unread is less than or equal to last_note. adding #{forum_id} to todo"
+ @@bbs_cache[:todo][forum_id] = @@bbs_cache[:all][forum_id]
+ end
end
end
end
def quit_from_forum(id)
info "quit_from_forum"
record_last_read(id)
exit()
end
def quit
info "quit"
exit()
end
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@@username = @username_line.text
@@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
- visit '/bbs'
+ visit '/load_bbs'
end
end
end
- @mainstack = stack STACKSTYLE do
+ @mainstack = stack :margin => 20 do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def quit
exit()
end
def leave_forum(id)
info "leave forum #{id}"
record_last_read(id)
visit '/bbs'
end
+ def load_bbs
+ background black
+ @@bbs_cache[:all] = @@bbs.forums('all')
+ @@bbs_cache[:todo] = @@bbs.forums('todo')
+ @@bbs_cache[:joined] = @@bbs.forums('joined')
+ visit '/bbs'
+ end
+
def bbs
background black
- @mainstack = stack STACKSTYLE do
+ @mainstack = stack :margin => 20 do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading bbs..."
end
- Thread.new do
- forums = @@bbs.forums('all')
- forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
- forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
- forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
- forums_todo.each { |n| forums[n][:todo] = true }
- forums_joined.each { |n| forums[n][:joined] = true }
- # delete mail
- forums.delete(1)
- linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
- [ 'q', '[q]uit', '/quit' ]
- ] )
- keypress { | key | keypressproc.call(key) }
- @mainstack.clear do
- background aliceblue, :curve => 20
- border black, :curve => 20
- para *linklist
- # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
- # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
- [ ["Unread", forums_todo],
- ["Subscribed", forums_joined],
- ["Zapped", forums_all]].each do | pair |
- group_name, ordered_ids = *pair
- stack STACKSTYLE do
- background white, :curve => 20
- border black, :curve => 20
- caption group_name
- flow do
- ordered_ids.each do | id |
- data = forums[id]
- stack :width => 200, :margin => 20 do
- if data[:todo]
- background ivory, :curve => 10
- elsif data[:joined]
- background lightgrey, :curve => 10
- else
- background darkslateblue, :curve => 10
- end
- border black, :curve => 10
- para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
- end
+ forums = @@bbs_cache[:all]
+ forums_todo = (@@bbs_cache[:todo].keys - [1]).sort
+ forums_joined = (@@bbs_cache[:joined].keys - forums_todo - [1]).sort
+ forums_all = (@@bbs_cache[:all].keys - forums_joined - forums_todo - [1]).sort
+ # delete mail
+ forums.delete(1)
+ action_list = []
+ if forums_todo.length > 0
+ action_list << [ ' ', '[ ]first forum with unread', "/first_todo"]
+ else
+ action_list << [ ' ', '[ ]refresh_forums', "/load_bbs"]
+ end
+ action_list << [ 'q', '[q]uit', '/quit' ]
+
+ linklist, keypressproc = actions( action_list )
+ keypress { | key | keypressproc.call(key) }
+ @mainstack.clear do
+ background aliceblue, :curve => 20
+ border black, :curve => 20
+ para *linklist
+ # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
+ # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
+ [ ["Unread", forums_todo, ivory],
+ ["Subscribed", forums_joined, lightgrey],
+ ["Zapped", forums_all, darkslateblue]].each do | group |
+ group_name, ordered_ids, coloring = *group
+ stack :margin => 20 do
+ background white, :curve => 20
+ border black, :curve => 20
+ caption group_name
+ flow do
+ ordered_ids.each do | id |
+ data = forums[id]
+ stack :width => 200, :margin => 20 do
+ background coloring, :curve => 10
+ border black, :curve => 10
+ para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
-
- def goto(id)
+ def goto_next_from(forum_id)
+ forum_id = forum_id.to_i
# id is forum to jump *from*
- id = id.to_i
- para "marking read, moving on..."
- Thread.new {
- @the_forum = @@bbs.jump(id)
- @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
- visit '/first_todo'
- }
+ cache = @@forum_cache[forum_id]
+ cache[:first_unread] = cache[:noteids].last + 1
+ record_last_read(forum_id)
+ todo_list = @@bbs_cache[:todo].keys.sort
+ if todo_list.length > 0
+ visit "/enter_forum/#{@@bbs_cache[:todo].keys.first}"
+ else
+ visit "/bbs"
+ end
end
def with_new_bbs_connection
begin
bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
yield bbs
rescue RuntimeError => err
debug "error: #{err.message}"
visit '/'
end
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
record_last_read(old_id)
visit "/enter_forum/#{new_id}"
end
def enter_forum(id)
info "enter_forum #{id}"
id = id.to_i
background black
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
cache[:post_headers] = forum.post_headers
cache[:noteids] = forum.noteids.sort
cache[:name] = forum.name
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
background black
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
- "/goto/#{id}"],
+ "/goto_next_from/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
- @mainstack = stack STACKSTYLE do
+ @mainstack = stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
@mainstack.clear do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline cache[:name]
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
def foruminfo(id)
info "foruminfo #{id}"
@forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
- stack STACKSTYLE do
+ stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
- stack STACKSTYLE do
+ stack :margin => 20 do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
info "first_todo"
background black
- stack STACKSTYLE do
+ stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
visit "/enter_forum/#{forum_id}"
else
visit "/bbs"
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
forum_id = forum_id.to_i
background black
cache = @@forum_cache[forum_id]
- stack STACKSTYLE do
+ stack :margin => 20 do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
- @forum = @@bbs.jump(forum_id)
- first_unread_msg = @forum.first_unread.to_i
- if msgnum.to_i < first_unread_msg
- @forum.first_unread = msgnum
+ forum_id = forum_id.to_i; msgnum = msgnum.to_i
+ cache = @@forum_cache[forum_id]
+ if msgnum < cache[:first_unread]
+ cache[:first_unread] = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
+ info "visiting <#{action}>"
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
def get_message_from_db(db, forum_id, msgnum)
sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;"
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
def get_message(forum_id, msgnum)
msg = {}
post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
- stack STACKSTYLE do
+ stack :margin => 20 do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
# Thread.new {
msg = get_message(forum_id, msgnum)
body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
- stack STACKSTYLE do
+ stack :margin => 20 do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
# }
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
- stack STACKSTYLE do
+ stack :margin => 20 do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
def new_post(forum_id)
background black
- stack STACKSTYLE do
+ stack :margin => 20 do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
e2b6b77fa4488aa9053beba78da0a85e66713219
|
remove traces of db caching change /forums to /bbs
|
diff --git a/shoesca.rb b/shoesca.rb
index eb2b564..eeab7ef 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,617 +1,584 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
-#require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
STACKSTYLE = { :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :login
- url '/forums', :forums
+ url '/bbs', :bbs
url '/quit', :quit
url '/quit_from_forum/(d+)', :quit_from_forum
url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
- @@bbs, @@msg_store = nil, nil
+ @@bbs = nil
@@forum_cache = {}
@@bbs_cache = {}
-# @@msg_store = SQLite3::Database.new('messages.db')
-# @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);");
def license
info "license"
background black
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
if cached
info "got cache"
info "seeing if #{ cached[:first_unread] } > #{ cached[:server_first_unread] }"
if cached[:first_unread] > cached[:server_first_unread]
info "yep"
forum = @@bbs.jump(forum_id)
info "setting first_unread to #{cached[:first_unread]}"
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
end
end
end
def quit_from_forum(id)
info "quit_from_forum"
record_last_read(id)
exit()
end
def quit
info "quit"
exit()
end
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@@username = @username_line.text
@@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
- visit '/forums'
+ visit '/bbs'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def quit
exit()
end
def leave_forum(id)
info "leave forum #{id}"
record_last_read(id)
- visit '/forums'
+ visit '/bbs'
end
- def forums
+ def bbs
background black
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
- para "loading forums..."
+ para "loading bbs..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', '/quit' ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
end
def goto(id)
# id is forum to jump *from*
id = id.to_i
para "marking read, moving on..."
Thread.new {
@the_forum = @@bbs.jump(id)
@the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
visit '/first_todo'
}
end
def with_new_bbs_connection
begin
bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
yield bbs
rescue RuntimeError => err
debug "error: #{err.message}"
visit '/'
end
end
- def sneakily_cache_forum(forum_id, note_ids)
- # if the main message db doesn't exist, don't bother making a new one
- return unless @@msg_store
- Thread.new {
- # this is a separate thread; we need our own bbs and db handle
- with_new_bbs_connection do | bbs |
- msg_store = SQLite3::Database.new('messages.db')
- sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' +
- Array.new(note_ids.length, '?').join(', ') +' ) ;'
- already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i}
- (note_ids - already_stored).each do | msgnum |
- get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
- end
- end
- }
- end
-
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
record_last_read(old_id)
visit "/enter_forum/#{new_id}"
end
def enter_forum(id)
info "enter_forum #{id}"
id = id.to_i
background black
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
cache[:post_headers] = forum.post_headers
cache[:noteids] = forum.noteids.sort
- sneakily_cache_forum(id, cache[:noteids])
cache[:name] = forum.name
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
background black
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
@mainstack.clear do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline cache[:name]
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
def foruminfo(id)
info "foruminfo #{id}"
@forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
info "first_todo"
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
visit "/enter_forum/#{forum_id}"
else
- visit "/forums"
+ visit "/bbs"
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
forum_id = forum_id.to_i
background black
cache = @@forum_cache[forum_id]
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
def get_message_from_db(db, forum_id, msgnum)
sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;"
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
- def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil)
- bbs ||=@@bbs
- msg_store ||=@@msg_store
+ def get_message(forum_id, msgnum)
msg = {}
- post = bbs.jump(forum_id).read(msgnum)
+ post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
- store_message(msg_store, msg) if msg_store
- msg
- end
-
- def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil)
- bbs ||=@@bbs
- msg_store ||=@@msg_store
- msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store
- unless msg
- msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
- end
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
- Thread.new {
- post_ids = @@forum_cache[forum_id][:noteids]
- post_index = post_ids.index(msgnum)
- remaining = post_ids.length - post_index - 1
- msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
- msg_prev = post_ids[post_index - 1] if post_index > 0
-
- msg = get_message_with_caching(forum_id, msgnum)
-
- action_list = []
+ post_ids = @@forum_cache[forum_id][:noteids]
+ post_index = post_ids.index(msgnum)
+ remaining = post_ids.length - post_index - 1
+ msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
+ msg_prev = post_ids[post_index - 1] if post_index > 0
+
+ action_list = []
+ if msg_prev
+ action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
+ end
+ if msg_next
+ action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
+ end
+ action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
+ action_list << [ "e" , "[e]nter message", "/new_post/#{forum_id}" ]
+ action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
+ action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
+ action_list << [ "c", "[c]opy to clipboard",
+ Proc.new { self.clipboard=@whole_message;
+ alert( "Copied to clipboard.") } ]
+ if direction == 'forward'
+ if msg_next
+ action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
+ else
+ action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
+ end
+ if msg_prev
+ action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
+ else
+ action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
+ end
+ elsif direction == 'backward'
if msg_prev
- action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
+ action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
+ else
+ action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
- action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
- end
- action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
- action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
- action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
- action_list << [ "c", "[c]opy to clipboard",
- Proc.new { self.clipboard=@whole_message;
- alert( "Copied to clipboard.") } ]
- if direction == 'forward'
- if msg_next
- action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
- else
- action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
- end
- if msg_prev
- action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
- else
- action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
- end
- elsif direction == 'backward'
- if msg_prev
- action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
- else
- action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
- end
- if msg_next
- action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
- else
- action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
- end
+ action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
+ else
+ action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
- action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
+ end
+ action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
- linklist, keypressproc = actions(action_list)
- keypress { | key |
+ linklist, keypressproc = actions(action_list)
+ keypress { | key |
keypressproc.call(key)
- }
+ }
+# Thread.new {
+ msg = get_message(forum_id, msgnum)
+
body_urls = msg[:body].scan(URLRE)
-
+
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
- }
+ # }
end
-
+
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
def new_post(forum_id)
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
5b3e0cbad29e1ecf9d2287e9e7ba76220a87d712
|
fix some spots where it wasn't saving first_unread
|
diff --git a/shoesca.rb b/shoesca.rb
index bd4fe62..eb2b564 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,615 +1,617 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
#require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
STACKSTYLE = { :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :login
url '/forums', :forums
url '/quit', :quit
url '/quit_from_forum/(d+)', :quit_from_forum
url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
url '/leave_forum/(\d+)', :leave_forum
url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs, @@msg_store = nil, nil
@@forum_cache = {}
+ @@bbs_cache = {}
# @@msg_store = SQLite3::Database.new('messages.db')
# @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);");
def license
info "license"
background black
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def record_last_read(forum_id)
forum_id = forum_id.to_i
info "record_last_read for #{forum_id}"
cached = @@forum_cache[forum_id]
if cached
info "got cache"
info "seeing if #{ cached[:first_unread] } > #{ cached[:server_first_unread] }"
if cached[:first_unread] > cached[:server_first_unread]
info "yep"
forum = @@bbs.jump(forum_id)
info "setting first_unread to #{cached[:first_unread]}"
forum.first_unread = cached[:first_unread]
cached[:server_first_unread] = cached[:first_unread]
end
end
end
def quit_from_forum(id)
+ info "quit_from_forum"
record_last_read(id)
exit()
end
def quit
+ info "quit"
exit()
end
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@@username = @username_line.text
@@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
-
def quit
exit()
end
def leave_forum(id)
info "leave forum #{id}"
record_last_read(id)
visit '/forums'
end
def forums
background black
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', '/quit' ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
end
def goto(id)
# id is forum to jump *from*
id = id.to_i
para "marking read, moving on..."
Thread.new {
@the_forum = @@bbs.jump(id)
@the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
visit '/first_todo'
}
end
def with_new_bbs_connection
begin
bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
yield bbs
rescue RuntimeError => err
debug "error: #{err.message}"
visit '/'
end
end
def sneakily_cache_forum(forum_id, note_ids)
# if the main message db doesn't exist, don't bother making a new one
return unless @@msg_store
Thread.new {
# this is a separate thread; we need our own bbs and db handle
with_new_bbs_connection do | bbs |
msg_store = SQLite3::Database.new('messages.db')
sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' +
Array.new(note_ids.length, '?').join(', ') +' ) ;'
already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i}
(note_ids - already_stored).each do | msgnum |
get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
end
end
}
end
def switch_forum(old_id, new_id)
old_id, new_id = old_id.to_i, new_id.to_i
record_last_read(old_id)
visit "/enter_forum/#{new_id}"
end
def enter_forum(id)
info "enter_forum #{id}"
id = id.to_i
background black
# we pull stuff into forum_cache only when we enter a new forum.
forum = @@bbs.jump(id)
cache = {}
first_unread = forum.first_unread.to_i
cache[:server_first_unread] = first_unread
cache[:first_unread] = first_unread
cache[:post_headers] = forum.post_headers
cache[:noteids] = forum.noteids.sort
sneakily_cache_forum(id, cache[:noteids])
cache[:name] = forum.name
@@forum_cache[id] = cache
visit "/forum/#{id}"
end
def forum(id)
info "forum #{id}"
id = id.to_i
background black
cache = @@forum_cache[id]
unless cache
visit "/enter_forum/#{id}"
end
first_unread = cache[:first_unread]
posts = cache[:post_headers]
noteids = cache[:noteids]
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
@mainstack.clear do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline cache[:name]
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.reverse.each do | post_id |
post = posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
end
def foruminfo(id)
info "foruminfo #{id}"
@forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
- info "first_todo #{id}"
+ info "first_todo"
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
-# visit "/first_unread/#{forum_id}"
- visit "/forum/#{forum_id}"
+ visit "/enter_forum/#{forum_id}"
else
visit "/forums"
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
+ forum_id = forum_id.to_i
background black
cache = @@forum_cache[forum_id]
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
noteids = cache[:noteids]
first_unread_msg = cache[:first_unread]
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
- visit "/first_todo"
+ visit "/leave_forum/#{forum_id}"
end
end
def mark_unread(forum_id,msgnum)
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
def get_message_from_db(db, forum_id, msgnum)
sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;"
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil)
bbs ||=@@bbs
msg_store ||=@@msg_store
msg = {}
post = bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
store_message(msg_store, msg) if msg_store
msg
end
def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil)
bbs ||=@@bbs
msg_store ||=@@msg_store
msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store
unless msg
msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
end
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
msg = get_message_with_caching(forum_id, msgnum)
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
if @@forum_cache[forum_id][:first_unread] <= msgnum
@@forum_cache[forum_id][:first_unread] = msgnum + 1
end
}
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
def new_post(forum_id)
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
8bc8bc97059e948008cc11c937b25f1fa496d401
|
get rid of message caching db, make first_unread updates infrequent
|
diff --git a/shoesca.rb b/shoesca.rb
index 261ac4c..bd4fe62 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,569 +1,615 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
-require 'sqlite3'
+#require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
STACKSTYLE = { :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :login
url '/forums', :forums
+ url '/quit', :quit
+ url '/quit_from_forum/(d+)', :quit_from_forum
url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
+ url '/enter_forum/(\d+)', :enter_forum
url '/forum/(\d+)', :forum
+ url '/leave_forum/(\d+)', :leave_forum
+ url '/switch_forum/(\d+)/(\d+)', :switch_forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
- @@bbs, @msg_store = nil, nil
+ @@bbs, @@msg_store = nil, nil
@@forum_cache = {}
- @@msg_store = SQLite3::Database.new('messages.db')
- @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);");
+# @@msg_store = SQLite3::Database.new('messages.db')
+# @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);");
def license
+ info "license"
background black
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
+
+ def record_last_read(forum_id)
+ forum_id = forum_id.to_i
+ info "record_last_read for #{forum_id}"
+ cached = @@forum_cache[forum_id]
+ if cached
+ info "got cache"
+ info "seeing if #{ cached[:first_unread] } > #{ cached[:server_first_unread] }"
+ if cached[:first_unread] > cached[:server_first_unread]
+ info "yep"
+ forum = @@bbs.jump(forum_id)
+ info "setting first_unread to #{cached[:first_unread]}"
+ forum.first_unread = cached[:first_unread]
+ cached[:server_first_unread] = cached[:first_unread]
+ end
+ end
+ end
+
+ def quit_from_forum(id)
+ record_last_read(id)
+ exit()
+ end
+
+ def quit
+ exit()
+ end
+
+
+
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@@username = @username_line.text
@@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
-
keypress do | key |
if key == "\n"
do_login
end
end
end
end
+
+ def quit
+ exit()
+ end
+
+ def leave_forum(id)
+ info "leave forum #{id}"
+ record_last_read(id)
+ visit '/forums'
+ end
+
def forums
background black
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
- [ 'q', '[q]uit', Proc.new { exit() } ]
+ [ 'q', '[q]uit', '/quit' ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
- para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
+ para link("#{id}> #{data[:name]}", :click => "/enter_forum/#{id}")
end
end
end
end
end
end
end
end
def goto(id)
# id is forum to jump *from*
id = id.to_i
para "marking read, moving on..."
Thread.new {
@the_forum = @@bbs.jump(id)
@the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
visit '/first_todo'
}
end
def with_new_bbs_connection
begin
bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
yield bbs
rescue RuntimeError => err
debug "error: #{err.message}"
visit '/'
end
end
def sneakily_cache_forum(forum_id, note_ids)
# if the main message db doesn't exist, don't bother making a new one
return unless @@msg_store
Thread.new {
# this is a separate thread; we need our own bbs and db handle
with_new_bbs_connection do | bbs |
msg_store = SQLite3::Database.new('messages.db')
sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' +
Array.new(note_ids.length, '?').join(', ') +' ) ;'
already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i}
(note_ids - already_stored).each do | msgnum |
get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
end
end
}
end
+ def switch_forum(old_id, new_id)
+ old_id, new_id = old_id.to_i, new_id.to_i
+ record_last_read(old_id)
+ visit "/enter_forum/#{new_id}"
+ end
+
+ def enter_forum(id)
+ info "enter_forum #{id}"
+ id = id.to_i
+ background black
+ # we pull stuff into forum_cache only when we enter a new forum.
+ forum = @@bbs.jump(id)
+ cache = {}
+ first_unread = forum.first_unread.to_i
+ cache[:server_first_unread] = first_unread
+ cache[:first_unread] = first_unread
+ cache[:post_headers] = forum.post_headers
+ cache[:noteids] = forum.noteids.sort
+ sneakily_cache_forum(id, cache[:noteids])
+ cache[:name] = forum.name
+ @@forum_cache[id] = cache
+ visit "/forum/#{id}"
+ end
+
def forum(id)
+ info "forum #{id}"
id = id.to_i
background black
-
- @mainstack = stack STACKSTYLE do
- background blanchedalmond, :curve => 20
- border black, :curve => 20
- para "loading forum #{id}..."
+ cache = @@forum_cache[id]
+ unless cache
+ visit "/enter_forum/#{id}"
end
-
-
- Thread.new {
- @@forum_cache[id] = {}
- @forum = @@bbs.jump(id)
- first_unread = @forum.first_unread.to_i
- @@forum_cache[id][:first_unread] = first_unread
- @posts = @forum.post_headers
- noteids = @forum.noteids.sort
- @@forum_cache[id][:noteids] = noteids
- sneakily_cache_forum(id, noteids)
- @@forum_cache[id][:name] = @forum.name
- msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
- msgs_read = noteids.select { |msg| msg.to_i < first_unread }
- info "got posts"
+
+ first_unread = cache[:first_unread]
+ posts = cache[:post_headers]
+ noteids = cache[:noteids]
+ msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
+ msgs_read = noteids.select { |msg| msg.to_i < first_unread }
+
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
- [ 'l', 'forum [l]ist', "/forums"],
- [ 'f', 'read [f]orward',
+ [ 'l', 'forum [l]ist', "/leave_forum/#{id}"],
+ [ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
- [ 'q', '[q]uit', Proc.new { exit() } ]
+ [ 'q', '[q]uit', "/quit_from_forum/#{id}" ]
] )
keypress { | key | keypressproc.call(key) }
+ @mainstack = stack STACKSTYLE do
+ background blanchedalmond, :curve => 20
+ border black, :curve => 20
+ para "loading forum #{id}..."
+ end
-
- @mainstack.clear do
- background blanchedalmond, :curve => 20
- border black, :curve => 20
-
- para *linklist
- [ [ "Unread", msgs_unread, ],
- [ "Read", msgs_read, ]].each do | pair |
- group_name, ordered_ids = *pair
- info "adding #{group_name} stack"
- stack :margin => 20 do
- background white, :curve => 20
- border black, :curve => 20
- caption group_name
- flow do
- ordered_ids.reverse.each do | post_id |
- post = @posts[post_id.to_s]
- stack :margin => 20, :width => 200 do
- background ivory, :curve => 10
- border black, :curve => 10
- para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
- para post[:subject]
- end
+ @mainstack.clear do
+ background blanchedalmond, :curve => 20
+ border black, :curve => 20
+ tagline cache[:name]
+ para *linklist
+ [ [ "Unread", msgs_unread, ],
+ [ "Read", msgs_read, ]].each do | pair |
+ group_name, ordered_ids = *pair
+ stack :margin => 20 do
+ background white, :curve => 20
+ border black, :curve => 20
+ caption group_name
+ flow do
+ ordered_ids.reverse.each do | post_id |
+ post = posts[post_id.to_s]
+ stack :margin => 20, :width => 200 do
+ background ivory, :curve => 10
+ border black, :curve => 10
+ para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
+ para post[:subject]
end
end
end
end
end
- }
+ end
end
def foruminfo(id)
+ info "foruminfo #{id}"
@forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
- [ "q", "[q]uit", Proc.new { exit()} ]
+ [ "q", "[q]uit", "/quit_from_forum/#{id}" ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
+ info "first_todo #{id}"
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
# visit "/first_unread/#{forum_id}"
visit "/forum/#{forum_id}"
else
visit "/forums"
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
background black
+ cache = @@forum_cache[forum_id]
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
- Thread.new {
- @forum = @@bbs.jump(forum_id)
- noteids = @forum.noteids.map { |n| n.to_i }.sort
- first_unread_msg = @forum.first_unread.to_i
- first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
- if first_unread_found
- visit "/message/#{forum_id}/#{first_unread_found}/forward"
- else
- visit "/first_todo"
- end
- }
- end
-
- def mark_read(forum_id, msgnum)
- first_unread_msg = @@forum_cache[forum_id][:first_unread]
- if msgnum.to_i >= first_unread_msg
- @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1
- Thread.new {
- with_new_bbs_connection { | bbs | bbs.jump(forum_id).first_unread = msgnum.to_i + 1 }
- }
- end
-
+ noteids = cache[:noteids]
+ first_unread_msg = cache[:first_unread]
+ first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
+ if first_unread_found
+ visit "/message/#{forum_id}/#{first_unread_found}/forward"
+ else
+ visit "/first_todo"
+ end
end
def mark_unread(forum_id,msgnum)
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
-
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
def get_message_from_db(db, forum_id, msgnum)
sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;"
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil)
bbs ||=@@bbs
msg_store ||=@@msg_store
msg = {}
post = bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
store_message(msg_store, msg) if msg_store
msg
end
def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil)
bbs ||=@@bbs
msg_store ||=@@msg_store
msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store
unless msg
msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
end
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
- mark_read(forum_id, msgnum)
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
-
msg = get_message_with_caching(forum_id, msgnum)
- while not msg
- info "waiting for message to show up in the cache..."
- sleep 1
- msg = get_message_from_db(@@msg_store, forum_id, msgnum)
- end
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward'
if msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_prev
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
elsif direction == 'backward'
if msg_prev
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
if msg_next
action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
else
action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
end
end
- action_list << [ "q", "[q]uit", Proc.new { exit()} ]
+ action_list << [ "q", "[q]uit", "/quit_from_forum/#{forum_id}" ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
+ if @@forum_cache[forum_id][:first_unread] <= msgnum
+ @@forum_cache[forum_id][:first_unread] = msgnum + 1
+ end
}
end
-
+
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
def new_post(forum_id)
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
47be147cf4f184ff3730cfa0633a78d535ad316e
|
more isca-like "b" and "s" behavior in fora
|
diff --git a/shoesca.rb b/shoesca.rb
index 96198a9..261ac4c 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,553 +1,569 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
STACKSTYLE = { :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :login
url '/forums', :forums
url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs, @msg_store = nil, nil
@@forum_cache = {}
@@msg_store = SQLite3::Database.new('messages.db')
@@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);");
def license
background black
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@@username = @username_line.text
@@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def forums
background black
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
end
def goto(id)
# id is forum to jump *from*
id = id.to_i
para "marking read, moving on..."
Thread.new {
@the_forum = @@bbs.jump(id)
@the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
visit '/first_todo'
}
end
def with_new_bbs_connection
begin
bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
yield bbs
rescue RuntimeError => err
debug "error: #{err.message}"
visit '/'
end
end
def sneakily_cache_forum(forum_id, note_ids)
# if the main message db doesn't exist, don't bother making a new one
return unless @@msg_store
Thread.new {
# this is a separate thread; we need our own bbs and db handle
with_new_bbs_connection do | bbs |
msg_store = SQLite3::Database.new('messages.db')
sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' +
Array.new(note_ids.length, '?').join(', ') +' ) ;'
already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i}
(note_ids - already_stored).each do | msgnum |
get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
end
end
}
end
def forum(id)
id = id.to_i
background black
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
Thread.new {
@@forum_cache[id] = {}
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
@@forum_cache[id][:first_unread] = first_unread
@posts = @forum.post_headers
noteids = @forum.noteids.sort
@@forum_cache[id][:noteids] = noteids
sneakily_cache_forum(id, noteids)
@@forum_cache[id][:name] = @forum.name
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/forums"],
[ 'f', 'read [f]orward',
"/message/#{id}/#{noteids.first}/forward"],
[ 'b', 'read [b]ackward',
"/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.reverse.each do | post_id |
post = @posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
}
end
def foruminfo(id)
@forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", Proc.new { exit()} ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
# visit "/first_unread/#{forum_id}"
visit "/forum/#{forum_id}"
else
visit "/forums"
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
Thread.new {
@forum = @@bbs.jump(forum_id)
noteids = @forum.noteids.map { |n| n.to_i }.sort
first_unread_msg = @forum.first_unread.to_i
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/first_todo"
end
}
end
def mark_read(forum_id, msgnum)
first_unread_msg = @@forum_cache[forum_id][:first_unread]
if msgnum.to_i >= first_unread_msg
@@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1
Thread.new {
with_new_bbs_connection { | bbs | bbs.jump(forum_id).first_unread = msgnum.to_i + 1 }
}
end
end
def mark_unread(forum_id,msgnum)
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
def get_message_from_db(db, forum_id, msgnum)
sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;"
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil)
bbs ||=@@bbs
msg_store ||=@@msg_store
msg = {}
post = bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
store_message(msg_store, msg) if msg_store
msg
end
def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil)
bbs ||=@@bbs
msg_store ||=@@msg_store
msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store
unless msg
msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
end
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
mark_read(forum_id, msgnum)
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
msg = get_message_with_caching(forum_id, msgnum)
while not msg
info "waiting for message to show up in the cache..."
sleep 1
msg = get_message_from_db(@@msg_store, forum_id, msgnum)
end
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
- if direction == 'forward' and msg_next
- action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
- elsif direction == 'backward' and msg_next
- action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
- else
- action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
+ if direction == 'forward'
+ if msg_next
+ action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
+ else
+ action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
+ end
+ if msg_prev
+ action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_prev}/backward" ]
+ else
+ action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
+ end
+ elsif direction == 'backward'
+ if msg_prev
+ action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
+ else
+ action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
+ end
+ if msg_next
+ action_list << [ "b", "[b]ack up", "/message/#{forum_id}/#{msg_next}/forward" ]
+ else
+ action_list << [ " ", "[b]ack up", "/forum/#{forum_id}" ]
+ end
end
action_list << [ "q", "[q]uit", Proc.new { exit()} ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
}
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
- @post_box = edit_box quote, :width => 500, :height => 300
+ @post_box = edit_box quote, :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
def new_post(forum_id)
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
- @post_box = edit_box :width => 500, :height => 300
+ @post_box = edit_box :width => 500, :height => 300, :margin => 20
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
733a12c36113892b824a83080f7e34e4934ceecc
|
smarter message pre-caching (less db calls)
|
diff --git a/shoesca.rb b/shoesca.rb
index 4d4e983..96198a9 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,542 +1,553 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
PORT = 6145
STACKSTYLE = { :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :login
url '/forums', :forums
url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs, @msg_store = nil, nil
@@forum_cache = {}
@@msg_store = SQLite3::Database.new('messages.db')
- @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);");
+ @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT, UNIQUE (forum_id, message_id) ON CONFLICT REPLACE);");
def license
background black
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@@username = @username_line.text
@@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def forums
background black
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
end
def goto(id)
# id is forum to jump *from*
id = id.to_i
para "marking read, moving on..."
Thread.new {
@the_forum = @@bbs.jump(id)
@the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
visit '/first_todo'
}
end
def with_new_bbs_connection
begin
bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
:host => HOST,
:port => PORT
)
yield bbs
rescue RuntimeError => err
debug "error: #{err.message}"
visit '/'
end
end
def sneakily_cache_forum(forum_id, note_ids)
# if the main message db doesn't exist, don't bother making a new one
return unless @@msg_store
- Thread.new do
+ Thread.new {
# this is a separate thread; we need our own bbs and db handle
with_new_bbs_connection do | bbs |
msg_store = SQLite3::Database.new('messages.db')
- note_ids.each do | msgnum |
- get_message_with_caching(forum_id, msgnum, bbs, msg_store)
+ sql = 'SELECT message_id FROM messages WHERE forum_id = ? AND message_id IN (' +
+ Array.new(note_ids.length, '?').join(', ') +' ) ;'
+ already_stored = msg_store.execute(sql, forum_id, *note_ids).flatten.map {|_|_.to_i}
+ (note_ids - already_stored).each do | msgnum |
+ get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
end
end
- end
+ }
end
def forum(id)
id = id.to_i
background black
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
Thread.new {
@@forum_cache[id] = {}
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
@@forum_cache[id][:first_unread] = first_unread
@posts = @forum.post_headers
noteids = @forum.noteids.sort
@@forum_cache[id][:noteids] = noteids
sneakily_cache_forum(id, noteids)
@@forum_cache[id][:name] = @forum.name
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
- linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
+ linklist, keypressproc = actions( [[ 'e', '[e]nter msg', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/forums"],
- [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"],
- [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"],
+ [ 'f', 'read [f]orward',
+ "/message/#{id}/#{noteids.first}/forward"],
+ [ 'b', 'read [b]ackward',
+ "/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
- info "adding background"
background blanchedalmond, :curve => 20
border black, :curve => 20
+
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.reverse.each do | post_id |
post = @posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
}
end
def foruminfo(id)
@forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
- [ 'p', '[p]ost', "/new_post/#{id}"],
+ [ 'p', '[e]nter msg', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", Proc.new { exit()} ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
# visit "/first_unread/#{forum_id}"
visit "/forum/#{forum_id}"
else
visit "/forums"
end
end
def first_unread(forum_id)
info "first_unread for forum_id #{forum_id}"
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
Thread.new {
@forum = @@bbs.jump(forum_id)
noteids = @forum.noteids.map { |n| n.to_i }.sort
first_unread_msg = @forum.first_unread.to_i
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/first_todo"
end
}
end
def mark_read(forum_id, msgnum)
first_unread_msg = @@forum_cache[forum_id][:first_unread]
if msgnum.to_i >= first_unread_msg
@@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1
Thread.new {
with_new_bbs_connection { | bbs | bbs.jump(forum_id).first_unread = msgnum.to_i + 1 }
}
end
end
def mark_unread(forum_id,msgnum)
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
- def get_message(db, forum_id, msgnum)
- sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?";
+ def get_message_from_db(db, forum_id, msgnum)
+ sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?;"
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
+ def get_message_from_bbs_and_store(forum_id, msgnum, bbs=nil, msg_store=nil)
+ bbs ||=@@bbs
+ msg_store ||=@@msg_store
+ msg = {}
+ post = bbs.jump(forum_id).read(msgnum)
+ [:date, :author, :body, :authority].each { |k| msg[k] = post.send(k) }
+ msg[:message_id] = msgnum
+ msg[:forum_id] = forum_id
+ store_message(msg_store, msg) if msg_store
+ msg
+ end
+
def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil)
bbs ||=@@bbs
msg_store ||=@@msg_store
- msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store
+ msg = get_message_from_db(@@msg_store, forum_id, msgnum) if @@msg_store
unless msg
- debug "getting message #{msgnum} in #{forum_id} from bbs"
- msg = {}
- @post = bbs.jump(forum_id).read(msgnum)
- [:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) }
- msg[:message_id] = msgnum
- msg[:forum_id] = forum_id
- store_message(msg_store, msg) if msg_store
+ msg = get_message_from_bbs_and_store(forum_id, msgnum, bbs, msg_store)
end
msg
end
def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
background black
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
mark_read(forum_id, msgnum)
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
msg = get_message_with_caching(forum_id, msgnum)
while not msg
info "waiting for message to show up in the cache..."
sleep 1
- msg = get_message(@@msg_store, forum_id, msgnum)
+ msg = get_message_from_db(@@msg_store, forum_id, msgnum)
end
action_list = []
if msg_prev
action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
end
if msg_next
action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
end
action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
action_list << [ "c", "[c]opy to clipboard",
Proc.new { self.clipboard=@whole_message;
alert( "Copied to clipboard.") } ]
if direction == 'forward' and msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
elsif direction == 'backward' and msg_next
action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
else
action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
end
action_list << [ "q", "[q]uit", Proc.new { exit()} ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
}
end
def new_reply(forum_id, msgnum)
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
def new_post(forum_id)
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
fb49415b39ec138ed401d1f973a68634e02ba4f7
|
Spawns little threads with their own DB and BBS connection for utility tasks
|
diff --git a/shoesca.rb b/shoesca.rb
index 2508974..4d4e983 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,506 +1,542 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
-# STACKSTYLE = { :width => 650, :margin => 20 }
+ HOST = '64.198.88.46' # bbs.iscabbs.com was not resolving
+ PORT = 6145
STACKSTYLE = { :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
- url '/', :main
+ url '/', :login
url '/forums', :forums
url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
- url '/message/(\d+)/(\d+)', :message
+ url '/message/(\d+)/(\d+)/(.*)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs, @msg_store = nil, nil
@@forum_cache = {}
@@msg_store = SQLite3::Database.new('messages.db')
@@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);");
def license
background black
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
- @username = @username_line.text
- @password = @password_line.text
+ @@username = @username_line.text
+ @@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
- @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
- :host => '64.198.88.46', # bbs.iscabbs.com was not resolving
- :port => 6145
+ @@bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
+ :host => HOST,
+ :port => PORT
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
- def main
- if @@bbs
- visit '/forums'
- else
- visit '/login'
- end
- end
-
def forums
- visit '/login' unless @@bbs
background black
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
end
def goto(id)
# id is forum to jump *from*
id = id.to_i
para "marking read, moving on..."
Thread.new {
@the_forum = @@bbs.jump(id)
@the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
visit '/first_todo'
}
end
+ def with_new_bbs_connection
+ begin
+ bbs = Raccdoc::Connection.new(:user => @@username, :password => @@password,
+ :host => HOST,
+ :port => PORT
+ )
+ yield bbs
+ rescue RuntimeError => err
+ debug "error: #{err.message}"
+ visit '/'
+ end
+ end
+
+
+ def sneakily_cache_forum(forum_id, note_ids)
+ # if the main message db doesn't exist, don't bother making a new one
+ return unless @@msg_store
+ Thread.new do
+ # this is a separate thread; we need our own bbs and db handle
+ with_new_bbs_connection do | bbs |
+ msg_store = SQLite3::Database.new('messages.db')
+ note_ids.each do | msgnum |
+ get_message_with_caching(forum_id, msgnum, bbs, msg_store)
+ end
+ end
+ end
+ end
+
def forum(id)
- visit '/login' unless @@bbs
id = id.to_i
background black
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
+
Thread.new {
@@forum_cache[id] = {}
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
@@forum_cache[id][:first_unread] = first_unread
@posts = @forum.post_headers
noteids = @forum.noteids.sort
@@forum_cache[id][:noteids] = noteids
+ sneakily_cache_forum(id, noteids)
@@forum_cache[id][:name] = @forum.name
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/forums"],
- [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}"],
- [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}"],
+ [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}/forward"],
+ [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}/backward"],
[ 'g', '[g]oto next forum with unread messages',
"/goto/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
info "adding background"
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
- ordered_ids.each do | post_id |
+ ordered_ids.reverse.each do | post_id |
post = @posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background ivory, :curve => 10
border black, :curve => 10
- para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
+ para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}/forward")
para post[:subject]
end
end
end
end
end
end
}
end
def foruminfo(id)
- visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", Proc.new { exit()} ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
# visit "/first_unread/#{forum_id}"
visit "/forum/#{forum_id}"
else
visit "/forums"
end
end
def first_unread(forum_id)
- visit '/login' unless @@bbs
info "first_unread for forum_id #{forum_id}"
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
Thread.new {
@forum = @@bbs.jump(forum_id)
noteids = @forum.noteids.map { |n| n.to_i }.sort
first_unread_msg = @forum.first_unread.to_i
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
- visit "/message/#{forum_id}/#{first_unread_found}"
+ visit "/message/#{forum_id}/#{first_unread_found}/forward"
else
visit "/first_todo"
end
}
end
+ def mark_read(forum_id, msgnum)
+ first_unread_msg = @@forum_cache[forum_id][:first_unread]
+ if msgnum.to_i >= first_unread_msg
+ @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1
+ Thread.new {
+ with_new_bbs_connection { | bbs | bbs.jump(forum_id).first_unread = msgnum.to_i + 1 }
+ }
+ end
+
+ end
+
def mark_unread(forum_id,msgnum)
- visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
def get_message(db, forum_id, msgnum)
sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?";
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
- def get_message_with_caching(forum_id, msgnum)
+ def get_message_with_caching(forum_id, msgnum, bbs=nil, msg_store=nil)
+ bbs ||=@@bbs
+ msg_store ||=@@msg_store
msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store
unless msg
+ debug "getting message #{msgnum} in #{forum_id} from bbs"
msg = {}
- @post = @@bbs.jump(forum_id).read(msgnum)
+ @post = bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
- store_message(@@msg_store, msg) if @@msg_store
+ store_message(msg_store, msg) if msg_store
end
msg
end
- def message(forum_id,msgnum)
+ def message(forum_id,msgnum, direction)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
- visit '/login' unless @@bbs
background black
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
- first_unread_msg = @@forum_cache[forum_id][:first_unread]
- if msgnum.to_i >= first_unread_msg
- @messagestack.append { para "marking it read..." }
- @forum = @@bbs.jump(forum_id)
- @forum.first_unread = msgnum.to_i + 1
- @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1
- end
+ mark_read(forum_id, msgnum)
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
+
msg = get_message_with_caching(forum_id, msgnum)
while not msg
info "waiting for message to show up in the cache..."
sleep 1
msg = get_message(@@msg_store, forum_id, msgnum)
end
-
- action_list =
- if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
- if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
- [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
- [ "s" , "[s]top reading", "/forum/#{forum_id}" ],
- [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
- [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
- [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
- [ "q", "[q]uit", Proc.new { exit()} ] ]
+
+ action_list = []
+ if msg_prev
+ action_list << [ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}/backward"]
+ end
+ if msg_next
+ action_list << [ "n", "[n]ext","/message/#{forum_id}/#{msg_next}/forward" ]
+ end
+ action_list << [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ]
+ action_list << [ "s" , "[s]top reading", "/forum/#{forum_id}" ]
+ action_list << [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ]
+ action_list << [ "c", "[c]opy to clipboard",
+ Proc.new { self.clipboard=@whole_message;
+ alert( "Copied to clipboard.") } ]
+ if direction == 'forward' and msg_next
+ action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_next}/forward" ]
+ elsif direction == 'backward' and msg_next
+ action_list << [ " ", "[ ]continue", "/message/#{forum_id}/#{msg_prev}/backward" ]
+ else
+ action_list << [ " ", "[ ]continue", "/forum/#{forum_id}" ]
+ end
+ action_list << [ "q", "[q]uit", Proc.new { exit()} ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
}
end
def new_reply(forum_id, msgnum)
- visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
- para link("back", :click => "/message/#{forum_id}/#{msgnum}")
+ para link("back", :click => "/message/#{forum_id}/#{msgnum}/forward")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
def new_post(forum_id)
- visit '/login' unless @@bbs
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/forum/#{forum_id}");
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
303ce0179a9ba6c036bf5aafe597ce7c9e560d1f
|
don't immediately visit the new post you just posted. that marks remaining messages read!
|
diff --git a/shoesca.rb b/shoesca.rb
index 5f2054e..2508974 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,506 +1,506 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
# STACKSTYLE = { :width => 650, :margin => 20 }
STACKSTYLE = { :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :main
url '/forums', :forums
url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs, @msg_store = nil, nil
@@forum_cache = {}
@@msg_store = SQLite3::Database.new('messages.db')
@@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);");
def license
background black
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
:host => '64.198.88.46', # bbs.iscabbs.com was not resolving
:port => 6145
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
background black
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | id |
data = forums[id]
stack :width => 200, :margin => 20 do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
end
def goto(id)
# id is forum to jump *from*
id = id.to_i
para "marking read, moving on..."
Thread.new {
@the_forum = @@bbs.jump(id)
@the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
visit '/first_todo'
}
end
def forum(id)
visit '/login' unless @@bbs
id = id.to_i
background black
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
Thread.new {
@@forum_cache[id] = {}
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
@@forum_cache[id][:first_unread] = first_unread
@posts = @forum.post_headers
noteids = @forum.noteids.sort
@@forum_cache[id][:noteids] = noteids
@@forum_cache[id][:name] = @forum.name
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/forums"],
[ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}"],
[ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}"],
[ 'g', '[g]oto next forum with unread messages',
"/goto/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
info "adding background"
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
flow do
ordered_ids.each do | post_id |
post = @posts[post_id.to_s]
stack :margin => 20, :width => 200 do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
para post[:subject]
end
end
end
end
end
end
}
end
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", Proc.new { exit()} ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
# visit "/first_unread/#{forum_id}"
visit "/forum/#{forum_id}"
else
visit "/forums"
end
end
def first_unread(forum_id)
visit '/login' unless @@bbs
info "first_unread for forum_id #{forum_id}"
background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
Thread.new {
@forum = @@bbs.jump(forum_id)
noteids = @forum.noteids.map { |n| n.to_i }.sort
first_unread_msg = @forum.first_unread.to_i
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}"
else
visit "/first_todo"
end
}
end
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
def get_message(db, forum_id, msgnum)
sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?";
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
def get_message_with_caching(forum_id, msgnum)
msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store
unless msg
msg = {}
@post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
store_message(@@msg_store, msg) if @@msg_store
end
msg
end
def message(forum_id,msgnum)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
visit '/login' unless @@bbs
background black
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
first_unread_msg = @@forum_cache[forum_id][:first_unread]
if msgnum.to_i >= first_unread_msg
@messagestack.append { para "marking it read..." }
@forum = @@bbs.jump(forum_id)
@forum.first_unread = msgnum.to_i + 1
@@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
msg = get_message_with_caching(forum_id, msgnum)
while not msg
info "waiting for message to show up in the cache..."
sleep 1
msg = get_message(@@msg_store, forum_id, msgnum)
end
action_list =
if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
[ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
[ "s" , "[s]top reading", "/forum/#{forum_id}" ],
[ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
[ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
[ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
[ "q", "[q]uit", Proc.new { exit()} ] ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
}
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
- visit("/message/#{forum_id}/#{new_post.id}")
+ visit("/forum/#{forum_id}");
end
end
end
def new_post(forum_id)
visit '/login' unless @@bbs
background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
- visit("/message/#{forum_id}/#{new_post.id}")
+ visit("/forum/#{forum_id}");
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
3471d7222415a421729e2461da8a2f60b1ab27de
|
black background, thin messages and forums to fit more on screen, fix 'remaining' off by one
|
diff --git a/shoesca.rb b/shoesca.rb
index e754e0a..5f2054e 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,490 +1,506 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
- STACKSTYLE = { :width => 650, :margin => 20 }
+# STACKSTYLE = { :width => 650, :margin => 20 }
+ STACKSTYLE = { :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :main
url '/forums', :forums
url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs, @msg_store = nil, nil
@@forum_cache = {}
@@msg_store = SQLite3::Database.new('messages.db')
@@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);");
def license
+ background black
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
+ background black
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
:host => '64.198.88.46', # bbs.iscabbs.com was not resolving
:port => 6145
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
+ background black
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
- ordered_ids.each do | id |
- data = forums[id]
- stack STACKSTYLE do
- if data[:todo]
- background ivory, :curve => 10
- elsif data[:joined]
- background lightgrey, :curve => 10
- else
- background darkslateblue, :curve => 10
+ flow do
+ ordered_ids.each do | id |
+ data = forums[id]
+ stack :width => 200, :margin => 20 do
+ if data[:todo]
+ background ivory, :curve => 10
+ elsif data[:joined]
+ background lightgrey, :curve => 10
+ else
+ background darkslateblue, :curve => 10
+ end
+ border black, :curve => 10
+ para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
- border black, :curve => 10
- para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
def goto(id)
# id is forum to jump *from*
id = id.to_i
para "marking read, moving on..."
Thread.new {
@the_forum = @@bbs.jump(id)
@the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
visit '/first_todo'
}
end
def forum(id)
visit '/login' unless @@bbs
id = id.to_i
+ background black
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
Thread.new {
@@forum_cache[id] = {}
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
@@forum_cache[id][:first_unread] = first_unread
@posts = @forum.post_headers
noteids = @forum.noteids.sort
@@forum_cache[id][:noteids] = noteids
@@forum_cache[id][:name] = @forum.name
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'l', 'forum [l]ist', "/forums"],
[ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}"],
[ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}"],
[ 'g', '[g]oto next forum with unread messages',
"/goto/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
info "adding background"
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
- stack STACKSTYLE do
+ stack :margin => 20 do
background white, :curve => 20
border black, :curve => 20
caption group_name
- ordered_ids.each do | post_id |
- post = @posts[post_id.to_s]
- stack STACKSTYLE do
- background ivory, :curve => 10
- border black, :curve => 10
- para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
- para post[:subject]
+ flow do
+ ordered_ids.each do | post_id |
+ post = @posts[post_id.to_s]
+ stack :margin => 20, :width => 200 do
+ background ivory, :curve => 10
+ border black, :curve => 10
+ para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
+ para post[:subject]
+ end
end
end
end
end
end
}
end
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
+ background black
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", Proc.new { exit()} ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
+ background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
# visit "/first_unread/#{forum_id}"
visit "/forum/#{forum_id}"
else
visit "/forums"
end
end
def first_unread(forum_id)
visit '/login' unless @@bbs
info "first_unread for forum_id #{forum_id}"
+ background black
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
Thread.new {
@forum = @@bbs.jump(forum_id)
noteids = @forum.noteids.map { |n| n.to_i }.sort
first_unread_msg = @forum.first_unread.to_i
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}"
else
visit "/first_todo"
end
}
end
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
def get_message(db, forum_id, msgnum)
sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?";
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
def get_message_with_caching(forum_id, msgnum)
msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store
unless msg
msg = {}
@post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
store_message(@@msg_store, msg) if @@msg_store
end
msg
end
def message(forum_id,msgnum)
forum_id=forum_id.to_i
msgnum=msgnum.to_i
visit '/login' unless @@bbs
+ background black
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
first_unread_msg = @@forum_cache[forum_id][:first_unread]
if msgnum.to_i >= first_unread_msg
@messagestack.append { para "marking it read..." }
@forum = @@bbs.jump(forum_id)
@forum.first_unread = msgnum.to_i + 1
+ @@forum_cache[forum_id][:first_unread] = msgnum.to_i + 1
end
post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
- remaining = post_ids.length - post_index
+ remaining = post_ids.length - post_index - 1
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
msg = get_message_with_caching(forum_id, msgnum)
while not msg
info "waiting for message to show up in the cache..."
sleep 1
msg = get_message(@@msg_store, forum_id, msgnum)
end
action_list =
if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
[ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
[ "s" , "[s]top reading", "/forum/#{forum_id}" ],
[ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
[ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
[ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
[ "q", "[q]uit", Proc.new { exit()} ] ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
"[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
}
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
+ background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
def new_post(forum_id)
visit '/login' unless @@bbs
+ background black
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
076fe24cde2d46d49a917a20d8460f56cf3f9a1a
|
remove reference to packaged versions
|
diff --git a/README.txt b/README.txt
index e35887b..b5ce5cf 100644
--- a/README.txt
+++ b/README.txt
@@ -1,26 +1,21 @@
Shoesca (until I think of a better name).
Shoesca is a client for the ancient telnet-based ISCA BBS
telnet://bbs.iscabbs.com/
It utilizes Wade Minter's library for accessing the bbs through the
newer, non-telnet-based 'raccdoc' interface.
http://github.com/minter/raccdoc/tree/master
To use it you need a copy of Shoes ( http://shoooes.net/ ).
Fire up Shoes, and choose "Open an app" and open the shoesca.rb
file. You'll be presented with a login screen. The app will save
your login credentials in a file called bbsconfig.yaml, in the same
directory as the shoesca.rb file.
The first time you run the app, it will download a copy of the
raccdoc library; subsequent runs, it will use the copy it
downloaded the first time.
-Packaged, executable versions (.exe, .dmg, and .run) are
-available in the packages directory; however, they may be
-buggy (the .exe in particular pops up a bogus error message
-about SSLEAY32.dll). Downloading shoes from http//shoooes.net
-is preferable, esp. on Windows.
|
edheil/shoesca
|
99e292680f5fb9469ebe3f30921481cf512d95f4
|
cache forum data for faster reading
|
diff --git a/shoesca.rb b/shoesca.rb
index 5807390..e754e0a 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,474 +1,490 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
STACKSTYLE = { :width => 650, :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :main
url '/forums', :forums
url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs, @msg_store = nil, nil
-
+ @@forum_cache = {}
@@msg_store = SQLite3::Database.new('messages.db')
@@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);");
def license
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
:host => '64.198.88.46', # bbs.iscabbs.com was not resolving
:port => 6145
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | id |
data = forums[id]
stack STACKSTYLE do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
def goto(id)
# id is forum to jump *from*
id = id.to_i
para "marking read, moving on..."
Thread.new {
@the_forum = @@bbs.jump(id)
@the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
visit '/first_todo'
}
end
def forum(id)
visit '/login' unless @@bbs
id = id.to_i
- linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
- [ 'i', '[i]nfo', "/foruminfo/#{id}"],
- [ 'b', '[b]ack to forum list', "/forums"],
- [ 'g', '[g]oto next forum with unread messages',
- "/goto/#{id}"],
- [ ' ', '[ ]first unread', "/first_unread/#{id}"],
- [ 'q', '[q]uit', Proc.new { exit() } ]
- ] )
-
- keypress { | key | keypressproc.call(key) }
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
Thread.new {
+ @@forum_cache[id] = {}
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
+ @@forum_cache[id][:first_unread] = first_unread
@posts = @forum.post_headers
noteids = @forum.noteids.sort
+ @@forum_cache[id][:noteids] = noteids
+ @@forum_cache[id][:name] = @forum.name
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
+ linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
+ [ 'i', '[i]nfo', "/foruminfo/#{id}"],
+ [ 'l', 'forum [l]ist', "/forums"],
+ [ 'f', 'read [f]orward', "/message/#{id}/#{noteids.first}"],
+ [ 'b', 'read [b]ackward', "/message/#{id}/#{noteids.last}"],
+ [ 'g', '[g]oto next forum with unread messages',
+ "/goto/#{id}"],
+ [ ' ', '[ ]first unread', "/first_unread/#{id}"],
+ [ 'q', '[q]uit', Proc.new { exit() } ]
+ ] )
+
+ keypress { | key | keypressproc.call(key) }
+
+
@mainstack.clear do
info "adding background"
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | post_id |
post = @posts[post_id.to_s]
stack STACKSTYLE do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
para post[:subject]
end
end
end
end
end
}
end
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", Proc.new { exit()} ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
- visit "/first_unread/#{forum_id}"
+# visit "/first_unread/#{forum_id}"
+ visit "/forum/#{forum_id}"
else
visit "/forums"
end
end
def first_unread(forum_id)
visit '/login' unless @@bbs
info "first_unread for forum_id #{forum_id}"
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
Thread.new {
@forum = @@bbs.jump(forum_id)
noteids = @forum.noteids.map { |n| n.to_i }.sort
first_unread_msg = @forum.first_unread.to_i
first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}"
else
visit "/first_todo"
end
- }
+ }
end
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def store_message(db, msghash)
sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
end
def get_message(db, forum_id, msgnum)
sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?";
result = db.get_first_row(sql, forum_id, msgnum)
return nil unless result
msg = {}
[:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
msg[k] = result[i]
end
return msg
end
def get_message_with_caching(forum_id, msgnum)
msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store
unless msg
msg = {}
@post = @@bbs.jump(forum_id).read(msgnum)
[:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) }
msg[:message_id] = msgnum
msg[:forum_id] = forum_id
store_message(@@msg_store, msg) if @@msg_store
end
msg
end
def message(forum_id,msgnum)
+ forum_id=forum_id.to_i
msgnum=msgnum.to_i
visit '/login' unless @@bbs
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
- @forum = @@bbs.jump(forum_id)
- first_unread_msg = @forum.first_unread.to_i
+ first_unread_msg = @@forum_cache[forum_id][:first_unread]
if msgnum.to_i >= first_unread_msg
+ @messagestack.append { para "marking it read..." }
+ @forum = @@bbs.jump(forum_id)
@forum.first_unread = msgnum.to_i + 1
end
- post_ids = @forum.noteids.map{ |n| n.to_i }.sort
+ post_ids = @@forum_cache[forum_id][:noteids]
post_index = post_ids.index(msgnum)
remaining = post_ids.length - post_index
msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_prev = post_ids[post_index - 1] if post_index > 0
msg = get_message_with_caching(forum_id, msgnum)
+ while not msg
+ info "waiting for message to show up in the cache..."
+ sleep 1
+ msg = get_message(@@msg_store, forum_id, msgnum)
+ end
action_list =
if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
[ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
[ "s" , "[s]top reading", "/forum/#{forum_id}" ],
[ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
[ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
[ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
[ "q", "[q]uit", Proc.new { exit()} ] ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
"#{msg[:body]}" +
- "[#{@forum.name}> msg #{msgnum} (#{ remaining } remaining)]")
+ "[#{@@forum_cache[forum_id][:name]}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
}
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
def new_post(forum_id)
visit '/login' unless @@bbs
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
701ec61721c2bb554fa6d4f55634aab1e43d40d9
|
message caching with sqlite
|
diff --git a/shoesca.rb b/shoesca.rb
index 5ccf125..5807390 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,432 +1,474 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
+require 'sqlite3'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
STACKSTYLE = { :width => 650, :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :main
url '/forums', :forums
+ url '/goto/(\d+)', :goto
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
- @@bbs = nil
-
+ @@bbs, @msg_store = nil, nil
+
+ @@msg_store = SQLite3::Database.new('messages.db')
+ @@msg_store.execute("CREATE TABLE IF NOT EXISTS messages(forum_id INTEGER, message_id INTEGER, date TEXT, body TEXT, author TEXT, authority TEXT);");
def license
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
:host => '64.198.88.46', # bbs.iscabbs.com was not resolving
:port => 6145
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
- end
+ end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
-
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | id |
data = forums[id]
stack STACKSTYLE do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
+
+ def goto(id)
+ # id is forum to jump *from*
+ id = id.to_i
+ para "marking read, moving on..."
+ Thread.new {
+ @the_forum = @@bbs.jump(id)
+ @the_forum.first_unread = @the_forum.noteids.sort.last.to_i + 1
+ visit '/first_todo'
+ }
+ end
+
def forum(id)
visit '/login' unless @@bbs
+ id = id.to_i
linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'b', '[b]ack to forum list', "/forums"],
+ [ 'g', '[g]oto next forum with unread messages',
+ "/goto/#{id}"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
Thread.new {
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
@posts = @forum.post_headers
noteids = @forum.noteids.sort
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
@mainstack.clear do
info "adding background"
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | post_id |
post = @posts[post_id.to_s]
stack STACKSTYLE do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
para post[:subject]
end
end
end
end
end
}
end
-
+
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", Proc.new { exit()} ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
- info "found todo forum: #{forum_id}"
visit "/first_unread/#{forum_id}"
else
- info "found no todo forums: visiting forums"
visit "/forums"
end
end
def first_unread(forum_id)
visit '/login' unless @@bbs
info "first_unread for forum_id #{forum_id}"
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
+
Thread.new {
- if forum_id.length == 0 # need to find it
- info "zero length forum id, looking for first unread forum"
- end
- info "jumping to #{forum_id}"
@forum = @@bbs.jump(forum_id)
- info "finding first unread"
+ noteids = @forum.noteids.map { |n| n.to_i }.sort
first_unread_msg = @forum.first_unread.to_i
- info "seeing if it exists"
- first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg }
+ first_unread_found = noteids.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
- info "visiting it"
visit "/message/#{forum_id}/#{first_unread_found}"
else
- info "visiting first todo"
visit "/first_todo"
end
}
end
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
+ def store_message(db, msghash)
+ sql = "INSERT INTO messages VALUES( ?, ?, ?, ?, ?, ?)"
+ db.execute(sql, msghash[:forum_id], msghash[:message_id], msghash[:date], msghash[:body], msghash[:author], msghash[:authority])
+ end
+
+ def get_message(db, forum_id, msgnum)
+ sql = "SELECT * FROM messages WHERE forum_id = ? AND message_id = ?";
+ result = db.get_first_row(sql, forum_id, msgnum)
+ return nil unless result
+ msg = {}
+ [:forum_id, :message_id, :date, :body, :author, :authorty].each_with_index do | k, i |
+ msg[k] = result[i]
+ end
+ return msg
+ end
+
+ def get_message_with_caching(forum_id, msgnum)
+ msg = get_message(@@msg_store, forum_id, msgnum) if @@msg_store
+ unless msg
+ msg = {}
+ @post = @@bbs.jump(forum_id).read(msgnum)
+ [:date, :author, :body, :authority].each { |k| msg[k] = @post.send(k) }
+ msg[:message_id] = msgnum
+ msg[:forum_id] = forum_id
+ store_message(@@msg_store, msg) if @@msg_store
+ end
+ msg
+ end
+
def message(forum_id,msgnum)
+ msgnum=msgnum.to_i
visit '/login' unless @@bbs
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i >= first_unread_msg
@forum.first_unread = msgnum.to_i + 1
end
- post_ids = @forum.post_headers.keys.sort.reverse
+ post_ids = @forum.noteids.map{ |n| n.to_i }.sort
post_index = post_ids.index(msgnum)
- msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
- msg_next = post_ids[post_index - 1] if post_index > 0
- @post = @forum.read(msgnum)
+ remaining = post_ids.length - post_index
+ msg_next = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
+ msg_prev = post_ids[post_index - 1] if post_index > 0
+
+ msg = get_message_with_caching(forum_id, msgnum)
action_list =
if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
[ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
- [ "b" , "[b]ack to forum", "/forum/#{forum_id}" ],
+ [ "s" , "[s]top reading", "/forum/#{forum_id}" ],
[ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
[ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
[ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
[ "q", "[q]uit", Proc.new { exit()} ] ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
- the_body = @post.body
- body_urls = the_body.scan(URLRE)
+ body_urls = msg[:body].scan(URLRE)
@messagestack.clear do
para *linklist
- @whole_message = "#{@post.date} from #{@post.author}\n#{the_body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]"
+ @whole_message = ( "#{msg[:date]} from #{msg[:author]}\n" +
+ "#{msg[:body]}" +
+ "[#{@forum.name}> msg #{msgnum} (#{ remaining } remaining)]")
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
}
-
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
def new_post(forum_id)
visit '/login' unless @@bbs
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
f53c9083c0d3250be753f75d1004c0874e3ef6a4
|
typo fix in keypress actions
|
diff --git a/shoesca.rb b/shoesca.rb
index 7b336b2..5ccf125 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,432 +1,432 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
STACKSTYLE = { :width => 650, :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :main
url '/forums', :forums
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
def license
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
:host => '64.198.88.46', # bbs.iscabbs.com was not resolving
:port => 6145
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | id |
data = forums[id]
stack STACKSTYLE do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
def forum(id)
visit '/login' unless @@bbs
linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
- [ 'i', '[b]ack to forum list', "/forums"],
+ [ 'b', '[b]ack to forum list', "/forums"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
Thread.new {
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
@posts = @forum.post_headers
noteids = @forum.noteids.sort
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
@mainstack.clear do
info "adding background"
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | post_id |
post = @posts[post_id.to_s]
stack STACKSTYLE do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
para post[:subject]
end
end
end
end
end
}
end
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
[ "q", "[q]uit", Proc.new { exit()} ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
@info = @forum.forum_information
the_body = @info[:body]
body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
end
def first_todo
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
info "found todo forum: #{forum_id}"
visit "/first_unread/#{forum_id}"
else
info "found no todo forums: visiting forums"
visit "/forums"
end
end
def first_unread(forum_id)
visit '/login' unless @@bbs
info "first_unread for forum_id #{forum_id}"
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
Thread.new {
if forum_id.length == 0 # need to find it
info "zero length forum id, looking for first unread forum"
end
info "jumping to #{forum_id}"
@forum = @@bbs.jump(forum_id)
info "finding first unread"
first_unread_msg = @forum.first_unread.to_i
info "seeing if it exists"
first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
info "visiting it"
visit "/message/#{forum_id}/#{first_unread_found}"
else
info "visiting first todo"
visit "/first_todo"
end
}
end
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def message(forum_id,msgnum)
visit '/login' unless @@bbs
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i >= first_unread_msg
@forum.first_unread = msgnum.to_i + 1
end
post_ids = @forum.post_headers.keys.sort.reverse
post_index = post_ids.index(msgnum)
msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_next = post_ids[post_index - 1] if post_index > 0
@post = @forum.read(msgnum)
action_list =
if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
[ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
[ "b" , "[b]ack to forum", "/forum/#{forum_id}" ],
[ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
[ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
[ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
[ "q", "[q]uit", Proc.new { exit()} ] ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
the_body = @post.body
body_urls = the_body.scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = "#{@post.date} from #{@post.author}\n#{the_body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]"
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
}
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
def new_post(forum_id)
visit '/login' unless @@bbs
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
7dbd5a5ad490891988a117174fb4c90cd9938241
|
remove top stuff from forum_info
|
diff --git a/shoesca.rb b/shoesca.rb
index c83447c..7b336b2 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,428 +1,432 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
STACKSTYLE = { :width => 650, :margin => 20 }
URLRE = Regexp.new('https?://[^ \n\)]+')
url '/', :main
url '/forums', :forums
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
def license
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
:host => '64.198.88.46', # bbs.iscabbs.com was not resolving
:port => 6145
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | id |
data = forums[id]
stack STACKSTYLE do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
def forum(id)
visit '/login' unless @@bbs
linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'i', '[b]ack to forum list', "/forums"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
Thread.new {
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
@posts = @forum.post_headers
noteids = @forum.noteids.sort
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
@mainstack.clear do
info "adding background"
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | post_id |
post = @posts[post_id.to_s]
stack STACKSTYLE do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
para post[:subject]
end
end
end
end
end
}
end
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
-
+
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
+ [ "q", "[q]uit", Proc.new { exit()} ]
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
- tagline( link(link("Forums", :click => "/forums")), " / ",
- link( "#{@forum.name}>", :click => "/forum/#{id}") )
para *linklist
@info = @forum.forum_information
+ the_body = @info[:body]
+ body_urls = the_body.scan(URLRE)
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
+ body_urls.each do | a_url |
+ para link(a_url, :click => a_url)
+ end
end
end
end
-
+
def first_todo
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
info "found todo forum: #{forum_id}"
visit "/first_unread/#{forum_id}"
else
info "found no todo forums: visiting forums"
visit "/forums"
end
end
def first_unread(forum_id)
visit '/login' unless @@bbs
info "first_unread for forum_id #{forum_id}"
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
Thread.new {
if forum_id.length == 0 # need to find it
info "zero length forum id, looking for first unread forum"
end
info "jumping to #{forum_id}"
@forum = @@bbs.jump(forum_id)
info "finding first unread"
first_unread_msg = @forum.first_unread.to_i
info "seeing if it exists"
first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
info "visiting it"
visit "/message/#{forum_id}/#{first_unread_found}"
else
info "visiting first todo"
visit "/first_todo"
end
}
end
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def message(forum_id,msgnum)
visit '/login' unless @@bbs
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i >= first_unread_msg
@forum.first_unread = msgnum.to_i + 1
end
post_ids = @forum.post_headers.keys.sort.reverse
post_index = post_ids.index(msgnum)
msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_next = post_ids[post_index - 1] if post_index > 0
@post = @forum.read(msgnum)
action_list =
if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
[ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
[ "b" , "[b]ack to forum", "/forum/#{forum_id}" ],
[ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
[ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
[ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
[ "q", "[q]uit", Proc.new { exit()} ] ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
the_body = @post.body
body_urls = the_body.scan(URLRE)
@messagestack.clear do
para *linklist
@whole_message = "#{@post.date} from #{@post.author}\n#{the_body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]"
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
body_urls.each do | a_url |
para link(a_url, :click => a_url)
end
end
end
}
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
def new_post(forum_id)
visit '/login' unless @@bbs
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
430fd13a2ed223b2a4d2b642807eaa1a4d74149b
|
detect urls in message body
|
diff --git a/shoesca.rb b/shoesca.rb
index 17dc8f9..c83447c 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,421 +1,428 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
STACKSTYLE = { :width => 650, :margin => 20 }
-
+ URLRE = Regexp.new('https?://[^ \n\)]+')
+
url '/', :main
url '/forums', :forums
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
def license
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
@mainstack.append do
para "logging in..."
end
Thread.new do
begin
@@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
:host => '64.198.88.46', # bbs.iscabbs.com was not resolving
:port => 6145
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
@mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para "loading forums..."
end
Thread.new do
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack.clear do
background aliceblue, :curve => 20
border black, :curve => 20
para *linklist
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | id |
data = forums[id]
stack STACKSTYLE do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
end
def forum(id)
visit '/login' unless @@bbs
linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
[ 'i', '[i]nfo', "/foruminfo/#{id}"],
[ 'i', '[b]ack to forum list', "/forums"],
[ ' ', '[ ]first unread', "/first_unread/#{id}"],
[ 'q', '[q]uit', Proc.new { exit() } ]
] )
keypress { | key | keypressproc.call(key) }
@mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "loading forum #{id}..."
end
Thread.new {
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
@posts = @forum.post_headers
noteids = @forum.noteids.sort
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
info "got posts"
@mainstack.clear do
info "adding background"
background blanchedalmond, :curve => 20
border black, :curve => 20
para *linklist
[ [ "Unread", msgs_unread, ],
[ "Read", msgs_read, ]].each do | pair |
group_name, ordered_ids = *pair
info "adding #{group_name} stack"
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | post_id |
post = @posts[post_id.to_s]
stack STACKSTYLE do
background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
para post[:subject]
end
end
end
end
end
}
end
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline( link(link("Forums", :click => "/forums")), " / ",
link( "#{@forum.name}>", :click => "/forum/#{id}") )
para *linklist
@info = @forum.forum_information
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
end
end
end
def first_todo
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first forum with unread messages..."
end
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
if forums_todo.length > 0
forum_id = forums_todo[0]
info "found todo forum: #{forum_id}"
visit "/first_unread/#{forum_id}"
else
info "found no todo forums: visiting forums"
visit "/forums"
end
end
def first_unread(forum_id)
visit '/login' unless @@bbs
info "first_unread for forum_id #{forum_id}"
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
para "finding first unread message in forum #{forum_id}..."
end
Thread.new {
if forum_id.length == 0 # need to find it
info "zero length forum id, looking for first unread forum"
end
info "jumping to #{forum_id}"
@forum = @@bbs.jump(forum_id)
info "finding first unread"
first_unread_msg = @forum.first_unread.to_i
info "seeing if it exists"
first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg }
if first_unread_found
info "visiting it"
visit "/message/#{forum_id}/#{first_unread_found}"
else
info "visiting first todo"
visit "/first_todo"
end
}
end
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
if action.respond_to? :call
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def message(forum_id,msgnum)
visit '/login' unless @@bbs
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
@messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
Thread.new {
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i >= first_unread_msg
@forum.first_unread = msgnum.to_i + 1
end
post_ids = @forum.post_headers.keys.sort.reverse
post_index = post_ids.index(msgnum)
msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_next = post_ids[post_index - 1] if post_index > 0
@post = @forum.read(msgnum)
action_list =
if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
[ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
[ "b" , "[b]ack to forum", "/forum/#{forum_id}" ],
[ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
[ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
[ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
[ "q", "[q]uit", Proc.new { exit()} ] ]
linklist, keypressproc = actions(action_list)
keypress { | key |
keypressproc.call(key)
}
+ the_body = @post.body
+ body_urls = the_body.scan(URLRE)
+
@messagestack.clear do
para *linklist
- @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]"
+ @whole_message = "#{@post.date} from #{@post.author}\n#{the_body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]"
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
- end
+ body_urls.each do | a_url |
+ para link(a_url, :click => a_url)
+ end
+ end
end
}
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
def new_post(forum_id)
visit '/login' unless @@bbs
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
57156c5404ddaf1299b39a3bd5a658f096e40d24
|
finish using threads to load data, so feedback can be provided immediately
|
diff --git a/shoesca.rb b/shoesca.rb
index 7bc74ef..17dc8f9 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,393 +1,421 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
STACKSTYLE = { :width => 650, :margin => 20 }
url '/', :main
url '/forums', :forums
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
+ url '/first_todo', :first_todo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
def license
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
- begin
- @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
- :host => '64.198.88.46', # bbs.iscabbs.com was not resolving
- :port => 6145
- )
- rescue RuntimeError => err
- debug "error: #{err.message}"
- @@bbs = nil
- @mainstack.append do
- para err.message
- end
+ @mainstack.append do
+ para "logging in..."
end
- if @@bbs
- @store.transaction do
- @store['username'], @store['password'] = @username, @password
+ Thread.new do
+ begin
+ @@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
+ :host => '64.198.88.46', # bbs.iscabbs.com was not resolving
+ :port => 6145
+ )
+ rescue RuntimeError => err
+ debug "error: #{err.message}"
+ @@bbs = nil
+ @mainstack.append do
+ para err.message
+ end
+ end
+ if @@bbs
+ @store.transaction do
+ @store['username'], @store['password'] = @username, @password
+ end
+ visit '/forums'
end
- visit '/forums'
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
-# if @username and @password
-# do_login
-# end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
- forums = @@bbs.forums('all')
- forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
- forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
- forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
- forums_todo.each { |n| forums[n][:todo] = true }
- forums_joined.each { |n| forums[n][:joined] = true }
-
- # delete mail
- forums.delete(1)
-
- stack STACKSTYLE do
+ @mainstack = stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
- tagline link(link("Forums", :click => "/forums"))
-
- # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
- # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
- [ ["Unread", forums_todo],
- ["Subscribed", forums_joined],
- ["Zapped", forums_all]].each do | pair |
- group_name, ordered_ids = *pair
- if ordered_ids.length > 0
+ para "loading forums..."
+ end
+
+ Thread.new do
+ forums = @@bbs.forums('all')
+ forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
+ forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
+ forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
+ forums_todo.each { |n| forums[n][:todo] = true }
+ forums_joined.each { |n| forums[n][:joined] = true }
+
+ # delete mail
+ forums.delete(1)
+ linklist, keypressproc = actions( [[ ' ', '[ ]first forum with unread', "/first_todo"],
+ [ 'q', '[q]uit', Proc.new { exit() } ]
+ ] )
+ keypress { | key | keypressproc.call(key) }
+ @mainstack.clear do
+ background aliceblue, :curve => 20
+ border black, :curve => 20
+ para *linklist
+ # 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
+ # :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
+ [ ["Unread", forums_todo],
+ ["Subscribed", forums_joined],
+ ["Zapped", forums_all]].each do | pair |
+ group_name, ordered_ids = *pair
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | id |
data = forums[id]
stack STACKSTYLE do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
-
- keypress do | key |
- if key == ' '
- if forums_todo.length > 0
- visit "/forum/#{forums_todo[0]}"
- else
- visit '/forums'
- end
- elsif key == 'q'
- exit()
- end
- end
end
def forum(id)
visit '/login' unless @@bbs
- @forum = @@bbs.jump(id)
- first_unread = @forum.first_unread.to_i
- info "first_unread: #{first_unread}"
- stack STACKSTYLE do
+ linklist, keypressproc = actions( [[ 'p', '[p]ost', "/new_post/#{id}"],
+ [ 'i', '[i]nfo', "/foruminfo/#{id}"],
+ [ 'i', '[b]ack to forum list', "/forums"],
+ [ ' ', '[ ]first unread', "/first_unread/#{id}"],
+ [ 'q', '[q]uit', Proc.new { exit() } ]
+ ] )
+
+ keypress { | key | keypressproc.call(key) }
+
+ @mainstack = stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
- tagline( link(link("Forums", :click => "/forums")), " / ",
- link( "#{@forum.name}>", :click => "/forum/#{id}") )
- para "Admin is #{@forum.admin}."
- para( link("post", :click => "/new_post/#{id}"), " ",
- link("info", :click => "/foruminfo/#{id}") , " ",
- link("first unread", :click => "/first_unread/#{id}")
- )
+ para "loading forum #{id}..."
+ end
+
+ Thread.new {
+ @forum = @@bbs.jump(id)
+ first_unread = @forum.first_unread.to_i
@posts = @forum.post_headers
noteids = @forum.noteids.sort
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
- [ [ "Unread", msgs_unread ],
- [ "Read", msgs_read ] ].each do | pair |
- group_name, ordered_ids = *pair
- if ordered_ids.length > 0
+ info "got posts"
+ @mainstack.clear do
+ info "adding background"
+ background blanchedalmond, :curve => 20
+ border black, :curve => 20
+ para *linklist
+ [ [ "Unread", msgs_unread, ],
+ [ "Read", msgs_read, ]].each do | pair |
+ group_name, ordered_ids = *pair
+ info "adding #{group_name} stack"
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | post_id |
post = @posts[post_id.to_s]
stack STACKSTYLE do
- if post_id >= first_unread
- background ivory, :curve => 10
- else
- background lightgrey, :curve => 10
- end
+ background ivory, :curve => 10
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
para post[:subject]
end
end
end
end
end
- end
- keypress do | key |
- if key == " "
- visit "/first_unread/#{id}"
- elsif key == 'q'
- exit()
- end
- end
+ }
end
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline( link(link("Forums", :click => "/forums")), " / ",
link( "#{@forum.name}>", :click => "/forum/#{id}") )
para *linklist
@info = @forum.forum_information
- info @info.inspect
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
end
end
end
- def first_unread(forum_id)
- visit '/login' unless @@bbs
- @forum = @@bbs.jump(forum_id)
- first_unread_msg = @forum.first_unread.to_i
- first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg }
- info "first_unread_found: #{first_unread_found.inspect}"
- if first_unread_found
- visit "/message/#{forum_id}/#{first_unread_found}"
+ def first_todo
+ stack STACKSTYLE do
+ background blanchedalmond, :curve => 20
+ border black, :curve => 20
+ para "finding first forum with unread messages..."
+ end
+ forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
+ if forums_todo.length > 0
+ forum_id = forums_todo[0]
+ info "found todo forum: #{forum_id}"
+ visit "/first_unread/#{forum_id}"
else
+ info "found no todo forums: visiting forums"
visit "/forums"
end
end
+ def first_unread(forum_id)
+ visit '/login' unless @@bbs
+ info "first_unread for forum_id #{forum_id}"
+
+ stack STACKSTYLE do
+ background blanchedalmond, :curve => 20
+ border black, :curve => 20
+ para "finding first unread message in forum #{forum_id}..."
+ end
+ Thread.new {
+ if forum_id.length == 0 # need to find it
+ info "zero length forum id, looking for first unread forum"
+ end
+ info "jumping to #{forum_id}"
+ @forum = @@bbs.jump(forum_id)
+ info "finding first unread"
+ first_unread_msg = @forum.first_unread.to_i
+ info "seeing if it exists"
+ first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg }
+ if first_unread_found
+ info "visiting it"
+ visit "/message/#{forum_id}/#{first_unread_found}"
+ else
+ info "visiting first todo"
+ visit "/first_todo"
+ end
+ }
+ end
+
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
- debug "checking respond to"
if action.respond_to? :call
- debug "calling #{action}"
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def message(forum_id,msgnum)
visit '/login' unless @@bbs
- @forum = @@bbs.jump(forum_id)
- first_unread_msg = @forum.first_unread.to_i
- if msgnum.to_i >= first_unread_msg
- @forum.first_unread = msgnum.to_i + 1
+ stack STACKSTYLE do
+ background gold, :curve => 20
+ border black, :curve => 20
+ @messagestack = stack { para "loading message #{msgnum} in forum #{forum_id}..." }
end
- post_ids = @forum.post_headers.keys.sort.reverse
- post_index = post_ids.index(msgnum)
- msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
- msg_next = post_ids[post_index - 1] if post_index > 0
- @post = @forum.read(msgnum)
+ Thread.new {
+ @forum = @@bbs.jump(forum_id)
+ first_unread_msg = @forum.first_unread.to_i
+ if msgnum.to_i >= first_unread_msg
+ @forum.first_unread = msgnum.to_i + 1
+ end
+ post_ids = @forum.post_headers.keys.sort.reverse
+ post_index = post_ids.index(msgnum)
+ msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
+ msg_next = post_ids[post_index - 1] if post_index > 0
+ @post = @forum.read(msgnum)
- action_list =
+ action_list =
if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
[ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
[ "b" , "[b]ack to forum", "/forum/#{forum_id}" ],
[ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
[ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
[ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
[ "q", "[q]uit", Proc.new { exit()} ] ]
-
- linklist, keypressproc = actions(action_list)
- keypress { | key | keypressproc.call(key) }
-
- stack STACKSTYLE do
- background gold, :curve => 20
- border black, :curve => 20
- tagline (link("Forums", :click => "/forums"),
- " / ",
- link("#{@forum.name}>", :click => "/forum/#{forum_id}"),
- " / ",
- link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}"))
- @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]"
-
+
+ linklist, keypressproc = actions(action_list)
+ keypress { | key |
+ keypressproc.call(key)
+ }
+
+ @messagestack.clear do
+ para *linklist
+ @whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]"
- stack STACKSTYLE do
- background aliceblue, :curve => 20
- border black, :curve => 20
- para @whole_message
- end
- para *linklist
-
- end
-
+ stack STACKSTYLE do
+ background aliceblue, :curve => 20
+ border black, :curve => 20
+ para @whole_message
+ end
+ end
+ }
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
def new_post(forum_id)
visit '/login' unless @@bbs
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
9b87956367da8d1413ad8a77fb436e4784888437
|
notes about packages and their issues
|
diff --git a/README.txt b/README.txt
index b5ce5cf..e35887b 100644
--- a/README.txt
+++ b/README.txt
@@ -1,21 +1,26 @@
Shoesca (until I think of a better name).
Shoesca is a client for the ancient telnet-based ISCA BBS
telnet://bbs.iscabbs.com/
It utilizes Wade Minter's library for accessing the bbs through the
newer, non-telnet-based 'raccdoc' interface.
http://github.com/minter/raccdoc/tree/master
To use it you need a copy of Shoes ( http://shoooes.net/ ).
Fire up Shoes, and choose "Open an app" and open the shoesca.rb
file. You'll be presented with a login screen. The app will save
your login credentials in a file called bbsconfig.yaml, in the same
directory as the shoesca.rb file.
The first time you run the app, it will download a copy of the
raccdoc library; subsequent runs, it will use the copy it
downloaded the first time.
+Packaged, executable versions (.exe, .dmg, and .run) are
+available in the packages directory; however, they may be
+buggy (the .exe in particular pops up a bogus error message
+about SSLEAY32.dll). Downloading shoes from http//shoooes.net
+is preferable, esp. on Windows.
|
edheil/shoesca
|
112ed2fb35ed6575693bafd5416e1add263ddc23
|
remove 'require openssl' hack that's supposed to fix windows packaging bug but doesn't
|
diff --git a/shoesca.rb b/shoesca.rb
index b1d3fcb..7bc74ef 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,398 +1,393 @@
-
-
-
-
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
-require 'openssl/ssl' # prevents a weird little error on packaged versions for Win
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
STACKSTYLE = { :width => 650, :margin => 20 }
url '/', :main
url '/forums', :forums
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
def license
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
begin
@@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
:host => '64.198.88.46', # bbs.iscabbs.com was not resolving
:port => 6145
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
# if @username and @password
# do_login
# end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
tagline link(link("Forums", :click => "/forums"))
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | id |
data = forums[id]
stack STACKSTYLE do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
keypress do | key |
if key == ' '
if forums_todo.length > 0
visit "/forum/#{forums_todo[0]}"
else
visit '/forums'
end
elsif key == 'q'
exit()
end
end
end
def forum(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
info "first_unread: #{first_unread}"
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline( link(link("Forums", :click => "/forums")), " / ",
link( "#{@forum.name}>", :click => "/forum/#{id}") )
para "Admin is #{@forum.admin}."
para( link("post", :click => "/new_post/#{id}"), " ",
link("info", :click => "/foruminfo/#{id}") , " ",
link("first unread", :click => "/first_unread/#{id}")
)
@posts = @forum.post_headers
noteids = @forum.noteids.sort
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
[ [ "Unread", msgs_unread ],
[ "Read", msgs_read ] ].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | post_id |
post = @posts[post_id.to_s]
stack STACKSTYLE do
if post_id >= first_unread
background ivory, :curve => 10
else
background lightgrey, :curve => 10
end
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
para post[:subject]
end
end
end
end
end
end
keypress do | key |
if key == " "
visit "/first_unread/#{id}"
elsif key == 'q'
exit()
end
end
end
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
[ 'p', '[p]ost', "/new_post/#{id}"],
[ " ", "[ ]first unread message", "/first_unread/#{id}" ],
]
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline( link(link("Forums", :click => "/forums")), " / ",
link( "#{@forum.name}>", :click => "/forum/#{id}") )
para *linklist
@info = @forum.forum_information
info @info.inspect
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
end
end
end
def first_unread(forum_id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg }
info "first_unread_found: #{first_unread_found.inspect}"
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}"
else
visit "/forums"
end
end
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
def actions(list)
linklist = []
list.each do | item |
linklist << link(item[1], :click => item[2] )
linklist << " " unless item == list.last
end
keypressproc = Proc.new do | key |
found = list.assoc(key)
if found
action = found[2]
debug "checking respond to"
if action.respond_to? :call
debug "calling #{action}"
action.call
else
visit action
end
end
end
return linklist, keypressproc
end
def message(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i >= first_unread_msg
@forum.first_unread = msgnum.to_i + 1
end
post_ids = @forum.post_headers.keys.sort.reverse
post_index = post_ids.index(msgnum)
msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_next = post_ids[post_index - 1] if post_index > 0
@post = @forum.read(msgnum)
action_list =
if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
[ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
[ "b" , "[b]ack to forum", "/forum/#{forum_id}" ],
[ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
[ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
[ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
[ "q", "[q]uit", Proc.new { exit()} ] ]
linklist, keypressproc = actions(action_list)
keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
tagline (link("Forums", :click => "/forums"),
" / ",
link("#{@forum.name}>", :click => "/forum/#{forum_id}"),
" / ",
link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}"))
@whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]"
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
end
para *linklist
end
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
def new_post(forum_id)
visit '/login' unless @@bbs
stack STACKSTYLE do
background lime, :curve => 20
border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
11650b7e040e7a3bb0d37cf5e275043e405ad799
|
More cosmetics
|
diff --git a/shoesca.rb b/shoesca.rb
index f52aedf..b1d3fcb 100644
--- a/shoesca.rb
+++ b/shoesca.rb
@@ -1,361 +1,398 @@
Shoes.setup do
Gem.sources = ['http://gems.github.com/', 'http://gems.rubyforge.org/']
gem 'minter-raccdoc'
end
require 'raccdoc'
require 'yaml/store'
+require 'openssl/ssl' # prevents a weird little error on packaged versions for Win
class RaccdocClient < Shoes
LICENSE = <<eof
Copyright 2009 Edward Heil ( edheil (at) fastmail (dot) fm )
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
eof
STACKSTYLE = { :width => 650, :margin => 20 }
url '/', :main
url '/forums', :forums
url '/login', :login
url '/license', :license
url '/forum/(\d+)', :forum
url '/foruminfo/(\d+)', :foruminfo
url '/first_unread/(\d+)', :first_unread
url '/message/(\d+)/(\d+)', :message
url '/mark_unread/(\d+)/(\d+)', :mark_unread
url '/new_post/(\d+)', :new_post
url '/new_reply/(\d+)/(\d+)', :new_reply
@@bbs = nil
def license
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para link('back', :click => '/login')
para LICENSE
end
end
def login
@store = YAML::Store.new('bbsconfig.yaml')
@username, @password = nil, nil
@store.transaction(true) do
@username, @password = @store['username'], @store['password']
end
def do_login
@username = @username_line.text
@password = @password_line.text
begin
@@bbs = Raccdoc::Connection.new(:user => @username, :password => @password,
:host => '64.198.88.46', # bbs.iscabbs.com was not resolving
:port => 6145
)
rescue RuntimeError => err
debug "error: #{err.message}"
@@bbs = nil
@mainstack.append do
para err.message
end
end
if @@bbs
@store.transaction do
@store['username'], @store['password'] = @username, @password
end
visit '/forums'
end
end
@mainstack = stack STACKSTYLE do
background salmon, :curve => 20
border black, :curve => 20
tagline "Login"
para "username:"
@username_line = edit_line "#{ @username }"
para "password:"
@password_line = edit_line "#{ @password }", :secret => true
button "login" do
do_login
end
para(link( 'license', :click => '/license' ))
keypress do | key |
if key == "\n"
do_login
end
end
# if @username and @password
# do_login
# end
end
end
def main
if @@bbs
visit '/forums'
else
visit '/login'
end
end
def forums
visit '/login' unless @@bbs
forums = @@bbs.forums('all')
forums_todo = (@@bbs.forums('todo').to_a.map{ |k| k[0] } - [1]).sort
forums_joined = (@@bbs.forums('joined').to_a.map{ |k| k[0]} - forums_todo - [1]).sort
forums_all = (forums.to_a.map{ |k| k[0]} - forums_joined - forums_todo - [1]).sort
forums_todo.each { |n| forums[n][:todo] = true }
forums_joined.each { |n| forums[n][:joined] = true }
# delete mail
forums.delete(1)
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
tagline link(link("Forums", :click => "/forums"))
# 100 => { :topic => "100", :flags => 'nosubject,sparse,cananonymous',
# :name => "Some Forum", :lastnote => "99999", :admin => "Some Dude" }
[ ["Unread", forums_todo],
["Subscribed", forums_joined],
["Zapped", forums_all]].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | id |
data = forums[id]
stack STACKSTYLE do
if data[:todo]
background ivory, :curve => 10
elsif data[:joined]
background lightgrey, :curve => 10
else
background darkslateblue, :curve => 10
end
border black, :curve => 10
para link("#{id}> #{data[:name]}", :click => "/forum/#{id}")
end
end
end
end
end
end
keypress do | key |
if key == ' '
if forums_todo.length > 0
visit "/forum/#{forums_todo[0]}"
else
visit '/forums'
end
+ elsif key == 'q'
+ exit()
end
end
end
def forum(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
first_unread = @forum.first_unread.to_i
info "first_unread: #{first_unread}"
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline( link(link("Forums", :click => "/forums")), " / ",
link( "#{@forum.name}>", :click => "/forum/#{id}") )
para "Admin is #{@forum.admin}."
para( link("post", :click => "/new_post/#{id}"), " ",
link("info", :click => "/foruminfo/#{id}") , " ",
link("first unread", :click => "/first_unread/#{id}")
)
@posts = @forum.post_headers
noteids = @forum.noteids.sort
msgs_unread = noteids.select { |msg| msg.to_i >= first_unread }
msgs_read = noteids.select { |msg| msg.to_i < first_unread }
[ [ "Unread", msgs_unread ],
[ "Read", msgs_read ] ].each do | pair |
group_name, ordered_ids = *pair
if ordered_ids.length > 0
stack STACKSTYLE do
background white, :curve => 20
border black, :curve => 20
caption group_name
ordered_ids.each do | post_id |
post = @posts[post_id.to_s]
stack STACKSTYLE do
if post_id >= first_unread
background ivory, :curve => 10
else
background lightgrey, :curve => 10
end
border black, :curve => 10
para link("#{ post_id }/#{post[:author]}/#{post[:date]}/#{post[:size]}", :click => "/message/#{id}/#{post_id}")
para post[:subject]
end
end
end
end
end
end
keypress do | key |
if key == " "
visit "/first_unread/#{id}"
+ elsif key == 'q'
+ exit()
end
end
end
def foruminfo(id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(id)
+
+ linklist, keypressproc = actions [[ 'b', '[b]ack', "/forum/#{id}"],
+ [ 'p', '[p]ost', "/new_post/#{id}"],
+ [ " ", "[ ]first unread message", "/first_unread/#{id}" ],
+ ]
+ keypress { | key | keypressproc.call(key) }
stack STACKSTYLE do
background blanchedalmond, :curve => 20
border black, :curve => 20
tagline( link(link("Forums", :click => "/forums")), " / ",
link( "#{@forum.name}>", :click => "/forum/#{id}") )
- para( link("post", :click => "/new_post/#{id}") )
+ para *linklist
@info = @forum.forum_information
info @info.inspect
stack STACKSTYLE do
background lightgrey, :curve => 10
border black, :curve => 10
caption "Forum moderator is #{@forum.admin}. Total messages: #{@forum.noteids.last}."
caption "Forum info last updated #{@info[:date]} by Mikemike"
para "#{@info[:body]}"
end
end
end
def first_unread(forum_id)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
first_unread_found = @forum.noteids.sort.detect { |noteid| noteid >= first_unread_msg }
info "first_unread_found: #{first_unread_found.inspect}"
if first_unread_found
visit "/message/#{forum_id}/#{first_unread_found}"
else
visit "/forums"
end
end
def mark_unread(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i < first_unread_msg
@forum.first_unread = msgnum
end
visit "/forum/#{forum_id}"
end
+
+ def actions(list)
+ linklist = []
+ list.each do | item |
+ linklist << link(item[1], :click => item[2] )
+ linklist << " " unless item == list.last
+ end
+
+ keypressproc = Proc.new do | key |
+ found = list.assoc(key)
+ if found
+ action = found[2]
+ debug "checking respond to"
+ if action.respond_to? :call
+ debug "calling #{action}"
+ action.call
+ else
+ visit action
+ end
+ end
+ end
+ return linklist, keypressproc
+ end
+
def message(forum_id,msgnum)
visit '/login' unless @@bbs
@forum = @@bbs.jump(forum_id)
first_unread_msg = @forum.first_unread.to_i
if msgnum.to_i >= first_unread_msg
@forum.first_unread = msgnum.to_i + 1
end
post_ids = @forum.post_headers.keys.sort.reverse
post_index = post_ids.index(msgnum)
msg_prev = post_ids[post_index + 1] if post_index < (post_ids.length - 1)
msg_next = post_ids[post_index - 1] if post_index > 0
@post = @forum.read(msgnum)
+
+
+ action_list =
+ if msg_prev;[[ "p", "[p]revious", "/message/#{forum_id}/#{msg_prev}"]]; else []; end +
+ if msg_next; [[ "n", "[n]ext","/message/#{forum_id}/#{msg_next}" ]]; else []; end +
+ [ [ "r" , "[r]eply", "/new_reply/#{forum_id}/#{msgnum}" ],
+ [ "b" , "[b]ack to forum", "/forum/#{forum_id}" ],
+ [ "u", "mark [u]nread", "/mark_unread/#{forum_id}/#{msgnum}" ],
+ [ "c", "[c]opy to clipboard", Proc.new { self.clipboard=@whole_message; alert( "Copied to clipboard.") } ],
+ [ " ", "[ ]first unread message", "/first_unread/#{forum_id}" ],
+ [ "q", "[q]uit", Proc.new { exit()} ] ]
+
+ linklist, keypressproc = actions(action_list)
+ keypress { | key | keypressproc.call(key) }
+
stack STACKSTYLE do
background gold, :curve => 20
border black, :curve => 20
tagline (link("Forums", :click => "/forums"),
" / ",
link("#{@forum.name}>", :click => "/forum/#{forum_id}"),
" / ",
link("#{msgnum}", :click => "/message/#{forum_id}/#{msgnum}"))
@whole_message = "#{@post.date} from #{@post.author}\n#{@post.body}[#{@forum.name}> msg #{msgnum} (#{ post_index } remaining)]"
- para( if msg_next; link("next", :click => "/message/#{forum_id}/#{msg_next}"); end,
- " ",
- if msg_prev; link("previous", :click => "/message/#{forum_id}/#{msg_prev}"); end,
- " ",
- link("reply", :click => "/new_reply/#{forum_id}/#{msgnum}"),
- " ",
- link("mark unread", :click => "/mark_unread/#{forum_id}/#{msgnum}"),
- " ",
- link("copy post to clipboard") { self.clipboard=@whole_message; info @whole_message }
- )
+
stack STACKSTYLE do
background aliceblue, :curve => 20
border black, :curve => 20
para @whole_message
end
-# para @post.inspect
- end
- keypress do | key |
- if key == " "
- visit "/first_unread/#{forum_id}"
- end
+ para *linklist
+
end
+
end
def new_reply(forum_id, msgnum)
visit '/login' unless @@bbs
@post = @@bbs.jump(forum_id).read(msgnum)
old_body = @post.body.split("\n").map{ |line| "> #{line}" }.join("\n")
quote = "#{@post.author} wrote:\n#{old_body}\n\n"
stack STACKSTYLE do
background lime, :curve => 20
- border black, :curve => 10
+ border black, :curve => 20
tagline "New Post"
- para link("back", :click => "/forum/#{forum_id}")
+ para link("back", :click => "/message/#{forum_id}/#{msgnum}")
@post_box = edit_box quote, :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
-
end
def new_post(forum_id)
visit '/login' unless @@bbs
stack STACKSTYLE do
background lime, :curve => 20
- border black, :curve => 10
+ border black, :curve => 20
tagline "New Post"
para link("back", :click => "/forum/#{forum_id}")
@post_box = edit_box :width => 500, :height => 300
button "post" do
text = @post_box.text
new_post = @@bbs.jump(forum_id).post(text)
visit("/message/#{forum_id}/#{new_post.id}")
end
end
end
end
Shoes.app :width => 800
|
edheil/shoesca
|
f969bb67c099407103c437ed76b18e0b07d831a1
|
add packages for mac, linux, windows
|
diff --git a/packages/shoesca.dmg b/packages/shoesca.dmg
new file mode 100644
index 0000000..fe5b668
Binary files /dev/null and b/packages/shoesca.dmg differ
diff --git a/packages/shoesca.exe b/packages/shoesca.exe
new file mode 100644
index 0000000..0e61758
Binary files /dev/null and b/packages/shoesca.exe differ
diff --git a/packages/shoesca.run b/packages/shoesca.run
new file mode 100755
index 0000000..05808bb
--- /dev/null
+++ b/packages/shoesca.run
@@ -0,0 +1,387 @@
+#!/bin/sh
+# This script was generated using Makeself 2.1.4
+FULLSIZE=12301
+CRCsum="0000000000"
+MD5="0aeae809d4eb1a8ca4d2a26c217d8c70"
+TMPROOT=${TMPDIR:=/tmp}
+
+label="Shoesca"
+script="./sh-install"
+scriptargs=""
+targetdir="dist"
+filesizes="3478"
+keep=n
+
+print_cmd_arg=""
+if type printf > /dev/null; then
+ print_cmd="printf"
+elif test -x /usr/ucb/echo; then
+ print_cmd="/usr/ucb/echo"
+else
+ print_cmd="echo"
+fi
+
+unset CDPATH
+
+MS_Printf()
+{
+ $print_cmd $print_cmd_arg "$1"
+}
+
+MS_Progress()
+{
+ while read a; do
+ MS_Printf .
+ done
+}
+
+MS_dd()
+{
+ blocks=`expr $3 / 1024`
+ bytes=`expr $3 % 1024`
+ dd if="$1" ibs=$2 skip=1 obs=1024 conv=sync 2> /dev/null | \
+ { test $blocks -gt 0 && dd ibs=1024 obs=1024 count=$blocks ; \
+ test $bytes -gt 0 && dd ibs=1 obs=1024 count=$bytes ; } 2> /dev/null
+}
+
+MS_Help()
+{
+ cat << EOH >&2
+Makeself version 2.1.4
+ 1) Getting help or info about $0 :
+ $0 --help Print this message
+ $0 --info Print embedded info : title, default target directory, embedded script ...
+ $0 --lsm Print embedded lsm entry (or no LSM)
+ $0 --list Print the list of files in the archive
+ $0 --check Checks integrity of the archive
+
+ 2) Running $0 :
+ $0 [options] [--] [additional arguments to embedded script]
+ with following options (in that order)
+ --confirm Ask before running embedded script
+ --noexec Do not run embedded script
+ --keep Do not erase target directory after running
+ the embedded script
+ --nox11 Do not spawn an xterm
+ --nochown Do not give the extracted files to the current user
+ --target NewDirectory Extract in NewDirectory
+ --tar arg1 [arg2 ...] Access the contents of the archive through the tar command
+ -- Following arguments will be passed to the embedded script
+EOH
+}
+
+MS_Check()
+{
+ OLD_PATH=$PATH
+ PATH=${GUESS_MD5_PATH:-"$OLD_PATH:/bin:/usr/bin:/sbin:/usr/local/ssl/bin:/usr/local/bin:/opt/openssl/bin"}
+ MD5_PATH=`exec 2>&-; which md5sum || type md5sum | cut -c 11-`
+ MD5_PATH=${MD5_PATH:-`exec 2>&-; which md5 || type md5 | cut -c 8-`}
+ PATH=$OLD_PATH
+ MS_Printf "Verifying archive integrity..."
+ offset=`head -n 375 "$1" | wc -c | tr -d " "`
+ verb=$2
+ i=1
+ for s in $filesizes
+ do
+ crc=`echo $CRCsum | cut -d" " -f$i`
+ if test -x "$MD5_PATH"; then
+ md5=`echo $MD5 | cut -d" " -f$i`
+ if test $md5 = "00000000000000000000000000000000"; then
+ test x$verb = xy && echo " $1 does not contain an embedded MD5 checksum." >&2
+ else
+ md5sum=`MS_dd "$1" $offset $s | "$MD5_PATH" | cut -b-32`;
+ if test "$md5sum" != "$md5"; then
+ echo "Error in MD5 checksums: $md5sum is different from $md5" >&2
+ exit 2
+ else
+ test x$verb = xy && MS_Printf " MD5 checksums are OK." >&2
+ fi
+ crc="0000000000"; verb=n
+ fi
+ fi
+ if test $crc = "0000000000"; then
+ test x$verb = xy && echo " $1 does not contain a CRC checksum." >&2
+ else
+ sum1=`MS_dd "$1" $offset $s | CMD_ENV=xpg4 cksum | awk '{print $1}'`
+ if test "$sum1" = "$crc"; then
+ test x$verb = xy && MS_Printf " CRC checksums are OK." >&2
+ else
+ echo "Error in checksums: $sum1 is different from $crc"
+ exit 2;
+ fi
+ fi
+ i=`expr $i + 1`
+ offset=`expr $offset + $s`
+ done
+ echo " All good."
+}
+
+UnTAR()
+{
+ tar $1vf - 2>&1 || { echo Extraction failed. > /dev/tty; kill -15 $$; }
+}
+
+finish=true
+xterm_loop=
+nox11=n
+copy=none
+ownership=y
+verbose=n
+
+initargs="$@"
+
+while true
+do
+ case "$1" in
+ -h | --help)
+ MS_Help
+ exit 0
+ ;;
+ --info)
+ echo Identification: "$label"
+ echo Target directory: "$targetdir"
+ echo Uncompressed size: 13 KB
+ echo Compression: gzip
+ echo Date of packaging: Sun Mar 15 16:32:22 -0400 2009
+ echo Built with Makeself version 2.1.4 on
+ echo Build command was: "/usr/bin/makeself \\
+ \"dist\" \\
+ \"pkg/shoesca.rb.run\" \\
+ \"Shoesca\" \\
+ \"./sh-install\""
+ if test x$script != x; then
+ echo Script run after extraction:
+ echo " " $script $scriptargs
+ fi
+ if test x"" = xcopy; then
+ echo "Archive will copy itself to a temporary location"
+ fi
+ if test x"n" = xy; then
+ echo "directory $targetdir is permanent"
+ else
+ echo "$targetdir will be removed after extraction"
+ fi
+ exit 0
+ ;;
+ --dumpconf)
+ echo LABEL=\"$label\"
+ echo SCRIPT=\"$script\"
+ echo SCRIPTARGS=\"$scriptargs\"
+ echo archdirname=\"dist\"
+ echo KEEP=n
+ echo COMPRESS=gzip
+ echo filesizes=\"$filesizes\"
+ echo CRCsum=\"$CRCsum\"
+ echo MD5sum=\"$MD5\"
+ echo OLDUSIZE=13
+ echo OLDSKIP=376
+ exit 0
+ ;;
+ --lsm)
+cat << EOLSM
+No LSM.
+EOLSM
+ exit 0
+ ;;
+ --list)
+ echo Target directory: $targetdir
+ offset=`head -n 375 "$0" | wc -c | tr -d " "`
+ for s in $filesizes
+ do
+ MS_dd "$0" $offset $s | eval "gzip -cd" | UnTAR t
+ offset=`expr $offset + $s`
+ done
+ exit 0
+ ;;
+ --tar)
+ offset=`head -n 375 "$0" | wc -c | tr -d " "`
+ arg1="$2"
+ shift 2
+ for s in $filesizes
+ do
+ MS_dd "$0" $offset $s | eval "gzip -cd" | tar "$arg1" - $*
+ offset=`expr $offset + $s`
+ done
+ exit 0
+ ;;
+ --check)
+ MS_Check "$0" y
+ exit 0
+ ;;
+ --confirm)
+ verbose=y
+ shift
+ ;;
+ --noexec)
+ script=""
+ shift
+ ;;
+ --keep)
+ keep=y
+ shift
+ ;;
+ --target)
+ keep=y
+ targetdir=${2:-.}
+ shift 2
+ ;;
+ --nox11)
+ nox11=y
+ shift
+ ;;
+ --nochown)
+ ownership=n
+ shift
+ ;;
+ --xwin)
+ finish="echo Press Return to close this window...; read junk"
+ xterm_loop=1
+ shift
+ ;;
+ --phase2)
+ copy=phase2
+ shift
+ ;;
+ --)
+ shift
+ break ;;
+ -*)
+ echo Unrecognized flag : "$1" >&2
+ MS_Help
+ exit 1
+ ;;
+ *)
+ break ;;
+ esac
+done
+
+case "$copy" in
+copy)
+ tmpdir=$TMPROOT/makeself.$RANDOM.`date +"%y%m%d%H%M%S"`.$$
+ mkdir "$tmpdir" || {
+ echo "Could not create temporary directory $tmpdir" >&2
+ exit 1
+ }
+ SCRIPT_COPY="$tmpdir/makeself"
+ echo "Copying to a temporary location..." >&2
+ cp "$0" "$SCRIPT_COPY"
+ chmod +x "$SCRIPT_COPY"
+ cd "$TMPROOT"
+ exec "$SCRIPT_COPY" --phase2
+ ;;
+phase2)
+ finish="$finish ; rm -rf `dirname $0`"
+ ;;
+esac
+
+if test "$nox11" = "n"; then
+ if tty -s; then # Do we have a terminal?
+ :
+ else
+ if test x"$DISPLAY" != x -a x"$xterm_loop" = x; then # No, but do we have X?
+ if xset q > /dev/null 2>&1; then # Check for valid DISPLAY variable
+ GUESS_XTERMS="xterm rxvt dtterm eterm Eterm kvt konsole aterm"
+ for a in $GUESS_XTERMS; do
+ if type $a >/dev/null 2>&1; then
+ XTERM=$a
+ break
+ fi
+ done
+ chmod a+x $0 || echo Please add execution rights on $0
+ if test `echo "$0" | cut -c1` = "/"; then # Spawn a terminal!
+ exec $XTERM -title "$label" -e "$0" --xwin "$initargs"
+ else
+ exec $XTERM -title "$label" -e "./$0" --xwin "$initargs"
+ fi
+ fi
+ fi
+ fi
+fi
+
+if test "$targetdir" = "."; then
+ tmpdir="."
+else
+ if test "$keep" = y; then
+ echo "Creating directory $targetdir" >&2
+ tmpdir="$targetdir"
+ dashp="-p"
+ else
+ tmpdir="$TMPROOT/selfgz$$$RANDOM"
+ dashp=""
+ fi
+ mkdir $dashp $tmpdir || {
+ echo 'Cannot create target directory' $tmpdir >&2
+ echo 'You should try option --target OtherDirectory' >&2
+ eval $finish
+ exit 1
+ }
+fi
+
+location="`pwd`"
+if test x$SETUP_NOCHECK != x1; then
+ MS_Check "$0"
+fi
+offset=`head -n 375 "$0" | wc -c | tr -d " "`
+
+if test x"$verbose" = xy; then
+ MS_Printf "About to extract 13 KB in $tmpdir ... Proceed ? [Y/n] "
+ read yn
+ if test x"$yn" = xn; then
+ eval $finish; exit 1
+ fi
+fi
+
+MS_Printf "Uncompressing $label"
+res=3
+if test "$keep" = n; then
+ trap 'echo Signal caught, cleaning up >&2; cd $TMPROOT; /bin/rm -rf $tmpdir; eval $finish; exit 15' 1 2 3 15
+fi
+
+for s in $filesizes
+do
+ if MS_dd "$0" $offset $s | eval "gzip -cd" | ( cd "$tmpdir"; UnTAR x ) | MS_Progress; then
+ if test x"$ownership" = xy; then
+ (PATH=/usr/xpg4/bin:$PATH; cd "$tmpdir"; chown -R `id -u` .; chgrp -R `id -g` .)
+ fi
+ else
+ echo
+ echo "Unable to decompress $0" >&2
+ eval $finish; exit 1
+ fi
+ offset=`expr $offset + $s`
+done
+echo
+
+cd "$tmpdir"
+res=0
+if test x"$script" != x; then
+ if test x"$verbose" = xy; then
+ MS_Printf "OK to execute: $script $scriptargs $* ? [Y/n] "
+ read yn
+ if test x"$yn" = x -o x"$yn" = xy -o x"$yn" = xY; then
+ eval $script $scriptargs $*; res=$?;
+ fi
+ else
+ eval $script $scriptargs $*; res=$?
+ fi
+ if test $res -ne 0; then
+ test x"$verbose" = xy && echo "The program '$script' returned an error code ($res)" >&2
+ fi
+fi
+if test "$keep" = n; then
+ cd $TMPROOT
+ /bin/rm -rf $tmpdir
+fi
+eval $finish; exit $res
+ Öe½I íZ{sÛ6Ïßü[:3®6%¹¶*±'nê4sc;Óɹ!5I°|XQc}÷ÛÅ%ÊQ4éõÂ[Äb±X`¿IçÎ_u:{{ûûøÛéÜ;¨þªëN·ÛÝ¿·{°{oèݽÝ;°ÿt»§àc®¿áNwü· þº9½×Û·6¯Ø¿ðÝø,6ù?·ÿÖ7í¡µÓ©N9KSfö4Ëâ^»=uGW,Ó±ÌV<yÚwKþv|5i~¿m¢meS?x~røk<ó~µä8ÓMýÑD³e[þ.aç-Øwõ % úð ²), =vÅûjü ©öôåó¶#Zr¤ä-#XÀFSö|Üõühçb¸ãmaÿ<ñ4Û,ÃlÂ2ô{hÓØùv^ÂMT/(¶Öm»F[rWtèýĽµa÷¨í±ëvAK̵´PZÑ´¹À[©Ì
8*ա6줶$.
+Jâ+´J¤Ô©fÁ\ª5L=³l4uT·ÔNÄnq¹[
ºGÿé©ò$AeG<¼¨ÁØ<¡%ðDîª]xëgÐ} ÚèNŹV}*
=¡eÝ-Æ Qx
þ;1^Lã®Ý ª@N
GJ²¦!÷ ³®&VrhÃÎvë$CÛúÒIéëõÙ®ÒìÝÏ÷öÖàÿîþ½{üß;øÿã²ð¸²,Áã<~b¡ò<a8Ë*&,LMó¡3âa»±
®$ÎÇ<0ÿµ}th~±d'qG#<ËJØï¹0hä2wà f<a
ËnÂdzø,Êà¡búìñÉóÔòáCÆÇÖcÏ2Í`·ÓùN¼xðù4ySqãf-#0
.µ<NÍZuéâO7¼'AÊÇJa=óFn óü4Küa1@p#¯ ×Ï-$äÇÀu)ð±hüôâ5nmÄ̯òaààÔ±(eàâ¼DI§ÌáÜ"ö'4û¹pêf>Gghà%)¶á;=¶peá*IáxLZ¨å7+Ç9«.×å Sã2¦(
6ó òó`ÛBNøùÙÅÓ¯/àøÅøùøììøÅÅÈM9ö²k&åøaÆC8uIJ9êl=?9{üùxvúìâ
¡ìg/NÎÏáÉË38WÇgÏ¿>=>W¯Ï^½<?q Î)Ĭ[¶s,Ì»æ±âRß ñ0Ù!²ÃÔ½fhÄó¯Q!ñ>¿ßFpiZdƾ¡FÏÆq¬SÔì¡ÙlæL¢\B %¤í#Ç"/EÇ=¿8~üïó7§ä»ï 7ó={xûmè
n2A`{·@[Bûü¨ àJó0%²¼+:.nJ²TEt¨uUDµ¿xß¶
+yÕN?ó%"LTò(a®gðÔ5diêNä*y¹ds«@µì*Ø#6Ät")¸4¥Â°8/Ë+:õÑ£áR_äm¾ÇÆPnwL´I×;& Å*¸4bä=,Ñç95#O(IPË»FWÍ %G(ñ´y[&¯Ê
D)Vþ×Ú+/ÀµÌ{süü´×;§îf8Í0ñhìOÊÀJø#õ$rC\Å£Sñõ;³-¶§édØ©;¢tÓ̵ÊmY#E¼lèÞF» i6#ÅZäj<>(dH'ú~{:±·æ2'Ö÷+\CVÊ-AáO¯÷GK{Ö£ÙÈ"Æ{å<GåDÛ
Ì÷]=:(+ì9Ýïï;÷ï;{hÿ-@eË5úEÆdRæÁdòàÏOóDLrÐÝÛßxö7o38Ë£ÌÙIp± ,I
+Qæ°õõ`ëÞ8*ºöÊþjO4Jp"Â7Ñî¥Ñ%|ÝVÈÏWïðô'¦(
¯¸jUúfiúáÑ5ª \û)"g©TnmUÒ7J0©Tüì¹ò|°O)´AÄÞÚze={9¾D´ zX eòÞÞzgߢ*HïK)¨v«ÈYبuÊF NJÙDè±æÈÐj¶H ¶i½¥¬Pd©NSäRhhæSE
VËÒ£®Ø<FODzÃ
µà¦`ÿÙ-)±ì[¥_»õ£áC[+¶V]¦ÛUA°âíuÇ-uK(©]ËìXã´5r>ùðCðRhÍÍfÃ
4HÊ ã¸Ð¬²µÑr2>pÐßÁÍîùe§ØËn¿
G$3ýÆÑq¼UQ^+dj¬:XÙº]Rb#±Ôç0w4Åï&ºQä˨٣.J+äéXð¬rÍ0ÙiT=0<Ð ÇåHr³Û²>[£,eÄ?ûÐÆ6#ÐV^j·Z:üÐí»uRñkqâD"
î$Áñ4þ¨¼b ãùinÄ£yÈs*KyåÕå;ç!®pr§ÍUv}OQ]/Õ¸äþ1÷¬p ökQ"«aé~ ùöyÅÁ¤g²ýÏ`AGì÷¥íE]?1²(H`ÞÀ÷(ÿEf¶2ºE<mA§à¸ÍV\b6õ³zwØÐ)ä5rÅÑÔXE¥ÛÔ¸Üß3Ö//<»¸d¾×_êßÊÔ5±|ÿÓcâr]ÝÎÊ Ì³
HeçÛ
ôÔb°
³Û%yx0J餿´uÒB¥µÆz5ÃË3
+·ï-°Ðk&köu!ÞvkIز&Õ¶ÙZó
+¤_Ø%^7 aÆ
kãBâ^©¼1Àx#PµL}Ý·N}ýßÄݦïµÞ½ÔÿH°Èû[ÆÅXóôMÕ1©oòõæÁ6û¨r7Ûj¹:P42OT©ÞG¡GssôØÚ`Y_]²øC/U@þ¹8ºÍ?¡r¸¶ø)"(,³äUzÚôÄaIvñhB'=íê¡P%#Ôé%¾hÝÖÆ\ÃQEùt¦.uëéÎBÍÁG±Dhô~JBYò é$-¯`ÀdQ%ý7Ä$ü«®º0¥l(ãa½h(ÚTËÄ^°ÏÙ
_±×Ä^á5 Êo.$ýP¬'ZrOËïAÏqø"g±ÞÆ%Ý_öÜ<ò¤_VÑLý?VñU?TÁXu`«æW¢dñ¼lªdúÝ1
+¬]MUk1ÓDLÊ5ÿGQî£qî ¬Q6¥ý- Åû*mqâ¼¥1zê¸-'|@`n|:éÉÍ¥v,q3ÔÁ:ÀÏÜ TL¥½CÃÆ'!KâÅò¢×# DÔÁÃ9<÷¯X¥Yn¬CîÍû¸¿1Me3ª"LéÄÇ÷þ±0_m¥àx,SH.É7
+ã3¿t±¦H3ô`©VdíljýqrV5ûiTï%ÓÕaJäÊ#µ"NëMe¼¸*¶y×åá3nÔ ®":ÖW
h9´ùkOMÈÍÍ{ýwÝ7Ü`'äØo¡[Ù
Æk
+káPEÂè
=3E{ôGæVáý ¡öÚàº4Æ¢.ý²°¤Ð,ä©¢tº¥´½ÍÖHÛY¦ëÙGº+Nn깦NxðqH
+è2x®?7n§¥¯]/ZnÏúZÎLB·UïlÊ6Pܸñ¤+ÙÀ!YÀ8á!h,*¿D@ಸ\ZY© YÔ§ÂÐH½pð£I«oW^°¨àó@-î7]k{@!SݬӮ\^OE÷>Ïͽ~:°átrñy@MY$¿'Xc©$&ÔÚÍ/ 6¡~
+ñÎN¹xXǽ<OtXõ©ªr«:Ú¢2öÆ
K¹Û_)ltURU§²D7ú½dþnøR8S¾;ó
+)Q>öt½Õ¹t@q®è"è4ü¬Iï.[êÕåͰé.Ý.lX8ôäZ2 Q¿çâÍHcTBY=Ê+z6L2ú½èF)?ðÃ{ÁÔ]yýÍà[¤|&zÒÖ)Ud»!«ßOÓXú¶ñÖ~¾Ó2ñ±!¶¿ë«ÔâeF@&µo~v ÏWëK}MѪºbs]Ósq5^Y<tÖ>ðüð°ï?ʰò¿0±ü¶×cc
÷qE_ú»ã¯××ëëõå¯ÿ~W < |