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