Finish subscription functionality, start cleaning up the pager
[blerg.git] / www / js / blerg.js
1 /* Blerg is (C) 2011 The Dominion of Awesome, and is distributed under a
2  * BSD-style license.  Please see the COPYING file for details.
3  */
4
5 // Config
6 var baseURL = '';
7 var recordTemplate = new Template(
8     '<div class="record">#{data}<div class="info">Posted #{date}</div></div>'
9 );
10 var tagRecordTemplate = new Template(
11     '<div class="record">#{data}<div class="info">Posted by <a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> on #{date}</div></div>'
12 );
13 var latestRecordsTemplate = new Template(
14     '<div class="record"><a class="author ref" href="/\##{author}" onclick="return qlink()">@#{author}</a> #{data}</div>'
15 );
16
17 // Page elements
18 var items;
19
20 // Other globals
21 var currentPager;
22 var loginStatus;
23
24 // Object to keep track of login status
25 function LoginStatus() {
26     var cookies = {};
27     document.cookie.split(/;\s+/).each(function(v) {
28         kv = v.split('=');
29         cookies[kv[0]] = kv[1];
30     });
31     if (cookies.auth && cookies.username) {
32         this.loggedIn = true;
33         this.username = cookies.username;
34     } else {
35         this.loggedIn = false;
36         this.username = null;
37     }
38     this.update();
39 }
40
41 LoginStatus.prototype.login = function(username, password) {
42     new Ajax.Request(baseURL + '/login', {
43         parameters: {
44             username: username,
45             password: password
46         },
47         onSuccess: function(r) {
48             var j = r.responseText.evalJSON();
49             if (j && j.status == 'success') {
50                 this.loggedIn = true;
51                 this.username = username;
52                 document.cookie = "username=" + username;
53                 $('login.password').value = '';
54                 this.update();
55             } else {
56                 alert("Could not log in");
57                 $('login.username').focus();
58             }
59         }.bind(this),
60         onFailure: function(r) {
61             alert("Could not log in");
62             $('login.username').focus();
63         }
64     });
65 }
66
67 LoginStatus.prototype.logout = function() {
68     new Ajax.Request(baseURL + '/logout', {
69         parameters: {
70             username: this.username
71         },
72         onSuccess: function(r) {
73             this.loggedIn = false;
74             document.cookie = "auth=; expires=1-Jan-1970 00:00:00 GMT";
75             this.update();
76         }.bind(this)
77     });
78     document.cookie = "username=; expires=1-Jan-1970 00:00:00 GMT";
79 }
80
81 LoginStatus.prototype.update = function() {
82     if (this.loggedIn) {
83         $('userlink').href = '/#' + this.username;
84         $('userlink').update('@' + this.username);
85         $('reflink').href = '/#/ref/' + this.username;
86         $('login').hide();
87         $('logout').show();
88     } else {
89         $('post').hide();
90         $('login').show();
91         $('logout').hide();
92     }
93 }
94
95 LoginStatus.prototype.post = function(msg) {
96     if (!this.loggedIn) {
97         alert("You are not logged in!");
98         return;
99     }
100
101     new Ajax.Request(baseURL + '/put', {
102         parameters: {
103             username: this.username,
104             data: msg
105         },
106         onSuccess: function(r) {
107             var j = r.responseText.evalJSON();
108             if (j && j.status == 'success') {
109                 $('post.content').value = '';
110                 if (location.hash != '#' + this.username) {
111                     qlink(this.username);
112                 } else {
113                     currentPager.itemCount++;
114                     currentPager.pageStart = null;
115                     currentPager.loadItems();
116                 }
117             } else {
118                 alert('Post failed!');
119             }
120         }.bind(this),
121         onFailure: function(r) {
122             alert('Post failed!');
123         }
124     });
125 }
126
127
128 // Base object for paged data
129 function Pager() {
130     this.itemsPerPage = 10;
131 }
132
133 Pager.prototype.initPager = function() {
134     this.itemCache = new Hash();
135     this.pageStart = null;
136 }
137
138 Pager.prototype.olderPage = function() {
139     if (this.pageStart >= this.itemsPerPage) {
140         qlink(this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage));
141     }
142 }
143
144 Pager.prototype.newerPage = function() {
145     if (this.pageStart + this.itemsPerPage < this.itemCount) {
146         qlink(this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage));
147     }
148 }
149
150 Pager.prototype.addItems = function(items) {
151     items.each(function(v) {
152         if (!this.itemCache[v.id])
153             this.itemCache[v.id] = v;
154     }.bind(this));
155 }
156
157 Pager.prototype.displayItems = function() {
158     if (this.pageStart == undefined)
159         this.pageStart == this.itemCount - 1;
160     items.update();
161
162     if (this.pageStart != undefined && this.itemCache[this.pageStart]) {
163         var end = (this.pageStart >= this.itemsPerPage ? this.pageStart - this.itemsPerPage + 1 : 0);
164         for (var i = this.pageStart; i >= end; i--) {
165             items.insert(this.itemCache[i].html);
166         }
167     } else {
168         items.insert("There doesn't seem to be anything here!");
169     }
170
171     if (this.pageStart < this.itemCount - 1) {
172         $('newer_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart + this.itemsPerPage);
173         $('newer_link').show();
174     } else {
175         $('newer_link').hide();
176     }
177
178     if (this.pageStart >= 10) {
179         $('older_link').href = '/#' + this.baseFrag + '/p' + (this.pageStart - this.itemsPerPage);
180         $('older_link').show();
181     } else {
182         $('older_link').hide();
183     }
184 }
185
186 Pager.prototype.showPageAt = function(r) {
187     if (this.itemCache[r] && this.itemCache[r - 9]) {
188         this.pageStart = r;
189         this.displayItems();
190     } else {
191         this.loadItems((r >= 49 ? r - 49 : 0), r);
192     }
193 }
194
195 Pager.prototype.showRecord = function(r) {
196     this.showPageAt(r);
197 }
198
199
200 // Object to render user pages
201 function User(username) {
202     this.initPager();
203     this.username = username;
204     this.baseFrag = username;
205
206     $$('[name=user.subscribelink]').each(Element.hide);
207     $$('[name=user.unsubscribelink]').each(Element.hide);
208
209     if (loginStatus.loggedIn) {
210         new Ajax.Request(baseURL + '/feedinfo/' + username, {
211             method: 'post',
212             parameters: {
213                 username: loginStatus.username
214             },
215             onSuccess: function(r) {
216                 var json = r.responseText.evalJSON();
217                 if (json.subscribed) {
218                     $$('[name=user.subscribelink]').each(Element.hide);
219                     $$('[name=user.unsubscribelink]').each(Element.show);
220                 } else {
221                     $$('[name=user.subscribelink]').each(Element.show);
222                     $$('[name=user.unsubscribelink]').each(Element.hide);
223                 }
224             }
225         });
226     }
227
228     new Ajax.Request(baseURL + '/info/' + username, {
229         method: 'get',
230         onSuccess: function(r) {
231             var j = r.responseText.evalJSON();
232             if (j) {
233                 this.itemCount = parseInt(j.record_count);
234                 this.displayItems();
235             }
236         }.bind(this)
237     });
238 }
239 User.prototype = new Pager();
240 User.prototype.constructor = User;
241
242 User.prototype.show = function() {
243     $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
244     $('welcome').hide();
245     items.show();
246     $('rss').show();
247     $('rsslink').href = '/rss/' + this.username;
248     $$('[name=user.reflink]').each(function(e) {
249         e.href = '/#/ref/' + this.username;
250     }.bind(this));
251     $('usercontrols').show();
252 }
253
254 User.prototype.loadItems = function(from, to) {
255     var url;
256     if (from != undefined && to != undefined) {
257         url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
258         this.pageStart = to;
259     } else {
260         url = baseURL + '/get/' + this.username;
261     }
262
263     new Ajax.Request(url, {
264         method: 'get',
265         onSuccess: function(r) {
266             var records = r.responseText.evalJSON();
267             if (records && records.length > 0) {
268                 records.each(function(v) {
269                     v.id = v.record;
270                     mangleRecord(v, recordTemplate);
271                 });
272                 this.addItems(records);
273                 if (!this.pageStart)
274                     this.pageStart = records[0].recInt;
275             }
276             this.displayItems();
277         }.bind(this),
278         onFailure: function(r) {
279             this.displayItems();
280         }.bind(this),
281         on404: function(r) {
282             displayError('User not found');
283         }
284     });
285 }
286
287 function mangleRecord(record, template) {
288     record.recInt = parseInt(record.record);
289
290     var lines = record.data.split(/\r?\n/);
291     if (lines[lines.length - 1] == '')
292         lines.pop();
293
294     var out = ['<p>'];
295     var endpush = null;
296     var listMode = false;
297     lines.each(function(l) {
298         if (l == '') {
299             if (out[out.length - 1] == '<br>') {
300                 out[out.length - 1] = '<p>';
301             }
302             if (out[out.length - 1] == '</li>') {
303                 out.push('</ul>');
304                 out.push('<p>');
305                 listMode = false;
306             }
307             return;
308         }
309
310         if (l[0] == '>') {
311             var pi = out.lastIndexOf('<p>');
312             if (pi != -1) {
313                 out[pi] = '<p class="quote">';
314                 l = l.replace(/^>\s*/, '');
315             }
316         }
317         if (l[0] == '*') {
318             if (!listMode) {
319                 var pi = out.lastIndexOf('<p>');
320                 out[pi] = '<ul>';
321                 listMode = true;
322             }
323             l = l.replace(/^\*\s*/, '');
324             out.push('<li>');
325             endpush = '</li>';
326         }
327         if (l[0] == '=') {
328             var m = l.match(/^(=+)/);
329             var depth = m[1].length;
330             if (depth <= 5) {
331                 l = l.replace(/^=+\s*/, '').replace(/\s*=+$/, '');
332                 out.push('<h' + depth + '>');
333                 endpush = '</h' + depth + '>';
334             }
335         }
336
337         // Sanitize HTML input
338         l = l.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
339
340         // Turn HTTP URLs into links
341         l = l.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
342
343         // Turn markdown links into links
344         l = l.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
345
346         // Turn *foo* into italics and **foo** into bold
347         l = l.replace(/(\s)\*\*([^*]+)\*\*(\s)/g, '$1<b>$2</b>$3');
348         l = l.replace(/(\s)\*([^*]+)\*(\s)/g, '$1<i>$2</i>$3');
349
350         // Turn refs and tags into links
351         l = l.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#/tag/$2" class="ref" onclick="return qlink()">#$2</a>');
352         l = l.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref" onclick="return qlink()">@$2</a>');
353
354         out.push(l);
355         if (endpush) {
356             out.push(endpush);
357             endpush = null;
358         } else {
359             out.push('<br>');
360         }
361     });
362     while (out[out.length - 1] == '<br>' || out[out.length - 1] == '<p>')
363         out.pop();
364
365     record.data = out.join('');
366     record.date = (new Date(record.timestamp * 1000)).toString();
367     record.html = template.evaluate(record);
368 }
369
370 function displayError(msg) {
371     items.innerText = msg;
372 }
373
374
375 // Object for browsing tags
376 function Tag(type, tag) {
377     this.initPager();
378     this.type = type;
379     this.tag = tag;
380
381     var url = baseURL + "/tag/";
382     switch(type) {
383     case 'tag':
384         //url += '%23';
385         url += 'H';  // apache is eating the hash, even encoded.  Probably a security feature.
386         this.baseFrag = '/tag/' + tag;
387         break;
388     case 'ref':
389         url += '%40';
390         this.baseFrag = '/ref/' + tag;
391         break;
392     default:
393         alert('Invalid tag type: ' + type);
394         return;
395     }
396     url += tag;
397
398     new Ajax.Request(url, {
399         method: 'get',
400         onSuccess: function(r) {
401             var j = r.responseText.evalJSON();
402             if (j) {
403                 var maxid = j.length - 1;
404                 j.each(function(v, i) {
405                     v.id = maxid - i;
406                     mangleRecord(v, tagRecordTemplate)
407                 });
408                 this.addItems(j);
409                 this.pageStart = j.length - 1;
410             }
411             this.displayItems();
412         }.bind(this),
413         onFailure: function(r) {
414             this.displayItems();
415         }.bind(this)
416     });
417
418 }
419 Tag.prototype = new Pager();
420 Tag.prototype.constructor = Tag;
421
422 Tag.prototype.show = function() {
423     var ctype = {ref: '@', tag: '#'}[this.type];
424
425     $$('[name=section]').each(function(v) {
426         v.update(' about ' + ctype + this.tag);
427     }.bind(this));
428     $('welcome').hide();
429     $('post').hide();
430     $('older_link').hide();
431     $('newer_link').hide();
432     $('rss').hide();
433     items.show();
434     $('usercontrols').hide();
435 }
436
437
438 // Pager for browsing subscription feeds
439 function Feed() {
440     this.initPager();
441     this.baseFrag = '/feed';
442
443     new Ajax.Request(baseURL + '/feed', {
444         method: 'post',
445         parameters: {
446             username: loginStatus.username
447         },
448         onSuccess: function(r) {
449             var response = r.responseText.evalJSON();
450             if (response) {
451                 var maxid = response.length - 1;
452                 response.each(function(v, i) {
453                     v.id = maxid - i;
454                     mangleRecord(v, tagRecordTemplate)
455                 });
456                 this.addItems(response);
457                 this.pageStart = response.length - 1;
458             }
459             this.displayItems();
460         }.bind(this),
461         onFailure: function(r) {
462             this.displayItems();
463         }.bind(this)
464     });
465 }
466 Feed.prototype = new Pager();
467 Feed.prototype.constructor = Feed;
468
469 Feed.prototype.show = function() {
470     $$('[name=section]').each(function(v) {
471         v.update(' ' + loginStatus.username + "'s spycam");
472     }.bind(this));
473     $('welcome').hide();
474     $('post').hide();
475     $('older_link').hide();
476     $('newer_link').hide();
477     $('rss').hide();
478     items.show();
479     $('usercontrols').hide();
480 }
481
482
483 function postPopup() {
484     if (loginStatus.loggedIn) {
485         var post = $('post');
486         if (post.visible()) {
487             post.hide();
488         } else {
489             post.show();
490             if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
491                 $('post.content').value = '@' + currentPager.username + ': ';
492             }
493             $('post.content').focus();
494         }
495     }
496 }
497
498 function signup() {
499     var username = $('signup.username').value;
500     var password = $('signup.password').value;
501
502     new Ajax.Request(baseURL + '/create', {
503         parameters: {
504             username: username,
505             password: password
506         },
507         onSuccess: function(r) {
508             $('signup').hide();
509             qlink(username);
510
511             loginStatus.login(username, password);
512         },
513         onFailure: function(r) {
514             alert("Failed to create user");
515         }
516     });
517 }
518
519 function signup_cancel() {
520     $('signup').hide();
521     hashSwitch();
522 }
523
524 function subscribe() {
525     new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
526         method: 'post',
527         parameters: {
528             username: loginStatus.username
529         },
530         onSuccess: function(r) {
531             var response = r.responseText.evalJSON();
532             if (response.status == 'success') {
533                 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
534                 $$('[name=user.subscribelink]').each(Element.hide);
535                 $$('[name=user.unsubscribelink]').each(Element.show);
536             } else {
537                 alert('Failed to subscribe. This is probably for the best');
538             }
539         },
540         onFailure: function(r) {
541             alert('Failed to subscribe. This is probably for the best');
542         }
543     });
544 }
545
546 function unsubscribe() {
547     new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
548         method: 'post',
549         parameters: {
550             username: loginStatus.username
551         },
552         onSuccess: function(r) {
553             var response = r.responseText.evalJSON();
554             if (response.status == 'success') {
555                 alert("You come to your senses.");
556                 $$('[name=user.subscribelink]').each(Element.show);
557                 $$('[name=user.unsubscribelink]').each(Element.hide);
558             } else {
559                 alert('You are unable to tear yourself away (because something failed on the server)');
560             }
561         },
562         onFailure: function(r) {
563             alert('You are unable to tear yourself away (because something failed on the server)');
564         }
565     });
566 }
567
568 var resizePostContentTimeout = null;
569 function resizePostContent() {
570     if (resizePostContentTimeout)
571         clearTimeout(resizePostContentTimeout);
572     resizePostContentTimeout = setTimeout(function() {
573         var c = $('post.content');
574         var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
575         var m = c.value.match(/\r?\n/g);
576         if (m)
577             lines += m.length;
578         if (lines <= 3) {
579             c.style.height = "";
580         } else {
581             c.style.height = (lines * 17) + "pt";
582         }
583         resizePostContentTimeout = null;
584     }, 150);
585 }
586
587 var tickerTimer = null;
588 var tickerHead, tickerTail;
589
590 function tickerFader(a, b, p) {
591     var p2 = 1 - p;
592
593     a.style.opacity = p;
594     a.style.lineHeight = (100 * p) + '%';
595
596     b.style.opacity = p2;
597     b.style.lineHeight = (100 * p2) + '%';
598     if (p == 1.0)
599         b.hide();
600 }
601
602 function ticker() {
603     tickerHead.show();
604     Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
605     tickerHead = tickerHead.nextSibling;
606     tickerTail = tickerTail.nextSibling;
607     if (tickerHead == null) {
608         stopTicker();
609         loadLatest.delay(10);
610     }
611 }
612
613 function startTicker() {
614     stopTicker();
615     for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
616         elem.hide();
617     }
618
619     // Show the first five
620     tickerHead = $('latest-posts').firstChild;
621     for (var i = 0; i < 10 && tickerHead; i++) {
622         tickerHead.show();
623         tickerHead = tickerHead.nextSibling;
624     }
625     tickerTail = $('latest-posts').firstChild;
626     tickerTimer = setInterval(ticker, 5000);
627 }
628
629 function stopTicker() {
630     if (tickerTimer)
631         clearInterval(tickerTimer);
632     tickerTimer = null;
633 }
634
635 function loadLatest() {
636     new Ajax.Request(baseURL + '/latest.json', {
637         onSuccess: function(r) {
638             var j = r.responseText.evalJSON();
639
640             $('latest-tags').update();
641             j.tags.each(function(v) {
642                 var a = new Element('a', {href: '/#/tag/' + v});
643                 a.insert('#' + v);
644                 a.onclick = qlink;
645                 a.className = 'ref';
646                 $('latest-tags').insert(a);
647                 $('latest-tags').appendChild(document.createTextNode(' '));
648             });
649
650             $('latest-posts').update();
651             j.records.each(function(v) {
652                 v.data = v.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
653                 v.date = (new Date(v.timestamp * 1000)).toString();
654                 var html = latestRecordsTemplate.evaluate(v);
655                 $('latest-posts').insert(html);
656             });
657             startTicker();
658         }
659     });
660 }
661
662 function qlink(loc) {
663     if (loc) {
664         location.hash = loc;
665     } else if (this.href) {
666         location.hash = this.href;
667     } else {
668         // Bogus qlink
669         return;
670     }
671     hashSwitch();
672     return false;
673 }
674
675 function hashSwitch() {
676     var m;
677     stopTicker();
678     if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
679         $('post').show();
680         $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
681     } else if (m = location.hash.match(/^#\/(ref|tag)\/([A-Za-z0-9_-]+)$/)) {
682         currentPager = new Tag(m[1], m[2]);
683         currentPager.show();
684     } else if (m = location.hash.match(/^#\/feed/)) {
685         if (loginStatus.loggedIn) {
686             currentPager = new Feed();
687             currentPager.show();
688         } else {
689             location.href = baseURL;
690         }
691     } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(?:\/(p)?(\d+))?$/)) {
692         if (!currentPager || currentPager.username != m[1])
693             currentPager = new User(m[1]);
694         currentPager.show();
695         loginStatus.update();
696
697         if (m[3]) {
698             var r = parseInt(m[3]);
699             if (m[2] == 'p') {
700                 currentPager.showPageAt(r);
701             } else {
702                 currentPager.showRecord(r);
703             }
704         } else {
705             currentPager.pageStart = currentPager.itemCount - 1;
706             currentPager.loadItems();
707         }
708     } else {
709         $$('[name=section]').each(function(v) { v.update('Welcome') });
710         $('signup').hide();
711         items.update();
712         items.hide();
713         $('newer_link').hide();
714         $('older_link').hide();
715         $('welcome').show();
716         $('rss').hide();
717         $('usercontrols').hide();
718         loadLatest();
719     }
720 }
721
722 var lastHash;
723 function hashCheck() {
724     if (location.hash != lastHash) {
725         lastHash = location.hash;
726         hashSwitch();
727     }
728 }
729
730 function init() {
731     items = $('items');
732     loginStatus = new LoginStatus();
733
734     lastHash = location.hash;
735     hashSwitch();
736
737     setInterval(hashCheck, 250);
738
739     document.body.observe('keyup', function(event) {
740         if (event.shiftKey && event.keyCode == '32') {
741             postPopup();
742             event.stop();
743         }
744     });
745     $('post.content').addEventListener('keyup', function(event) {
746         event.stopPropagation();
747     }, true);
748 }