Add obsess/unobsess functionality
[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}">@#{author}</a> on #{date}</div></div>'
12 );
13 var latestRecordsTemplate = new Template(
14     '<div class="record"><a class="author ref" href="/\##{author}">@#{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                     location.href = '/#' + this.username;
112                     hashSwitch();
113                 } else {
114                     currentPager.itemCount++;
115                     currentPager.pageStart = null;
116                     currentPager.loadItems();
117                 }
118             } else {
119                 alert('Post failed!');
120             }
121         }.bind(this),
122         onFailure: function(r) {
123             alert('Post failed!');
124         }
125     });
126 }
127
128
129 // Base object for paged data
130 function Pager() {
131     this.itemsPerPage = 10;
132 }
133
134 Pager.prototype.initPager = function() {
135     this.itemCache = new Hash();
136     this.pageStart = null;
137 }
138
139 Pager.prototype.olderPage = function() {
140     if (this.pageStart >= this.itemsPerPage) {
141         this.pageStart -= this.itemsPerPage;
142         this.displayItems();
143     }
144 }
145
146 Pager.prototype.newerPage = function() {
147     if (this.pageStart + this.itemsPerPage < this.itemCount) {
148         this.pageStart += this.itemsPerPage;
149         this.displayItems();
150     }
151 }
152
153 Pager.prototype.addItems = function(items) {
154     items.each(function(v) {
155         if (!this.itemCache[v.id])
156             this.itemCache[v.id] = v;
157     }.bind(this));
158 }
159
160 Pager.prototype.displayItems = function() {
161     if (this.pageStart == undefined)
162         this.pageStart == this.itemCount - 1;
163     items.update();
164
165     if (this.pageStart != undefined && this.itemCache[this.pageStart]) {
166         var end = (this.pageStart >= this.itemsPerPage ? this.pageStart - this.itemsPerPage + 1 : 0);
167         for (var i = this.pageStart; i >= end; i--) {
168             items.insert(this.itemCache[i].html);
169         }
170     } else {
171         items.insert("There doesn't seem to be anything here!");
172     }
173
174     if (this.pageStart < this.itemCount - 1)
175         $('newer_link').show();
176     else
177         $('newer_link').hide();
178
179     if (this.pageStart >= 10)
180         $('older_link').show();
181     else
182         $('older_link').hide();
183 }
184
185
186 // Object to render user pages
187 function User(username) {
188     this.initPager();
189     this.username = username;
190
191     $$('[name=user.obsesslink]').each(Element.hide);
192     $$('[name=user.unobsesslink]').each(Element.hide);
193
194     if (loginStatus.loggedIn) {
195         new Ajax.Request(baseURL + '/feedinfo/' + username, {
196             method: 'post',
197             parameters: {
198                 username: loginStatus.username
199             },
200             onSuccess: function(r) {
201                 var json = r.responseText.evalJSON();
202                 if (json.subscribed) {
203                     $$('[name=user.obsesslink]').each(Element.hide);
204                     $$('[name=user.unobsesslink]').each(Element.show);
205                 } else {
206                     $$('[name=user.obsesslink]').each(Element.show);
207                     $$('[name=user.unobsesslink]').each(Element.hide);
208                 }
209             }
210         });
211     }
212
213     new Ajax.Request(baseURL + '/info/' + username, {
214         method: 'get',
215         onSuccess: function(r) {
216             var j = r.responseText.evalJSON();
217             if (j) {
218                 this.itemCount = parseInt(j.record_count);
219                 this.displayItems();
220             }
221         }.bind(this)
222     });
223 }
224 User.prototype = new Pager();
225 User.prototype.constructor = User;
226
227 User.prototype.show = function() {
228     $$('[name=section]').each(function(v) { v.update(' @' + this.username) }.bind(this));
229     $('welcome').hide();
230     items.show();
231     $('rss').show();
232     $('rsslink').href = '/rss/' + this.username;
233     $$('[name=user.reflink]').each(function(e) {
234         e.href = '/#ref/' + this.username;
235     }.bind(this));
236     $('usercontrols').show();
237 }
238
239 User.prototype.loadItems = function(from, to) {
240     var url;
241     if (from != undefined && to != undefined) {
242         url = baseURL + '/get/' + this.username + '/' + from + '-' + to;
243         this.pageStart = to;
244     } else {
245         url = baseURL + '/get/' + this.username;
246     }
247
248     new Ajax.Request(url, {
249         method: 'get',
250         onSuccess: function(r) {
251             var records = r.responseText.evalJSON();
252             if (records && records.length > 0) {
253                 records.each(function(v) {
254                     v.id = v.record;
255                     mangleRecord(v, recordTemplate);
256                 });
257                 this.addItems(records);
258                 if (!this.pageStart)
259                     this.pageStart = records[0].recInt;
260             }
261             this.displayItems();
262         }.bind(this),
263         onFailure: function(r) {
264             this.displayItems();
265         }.bind(this),
266         on404: function(r) {
267             displayError('User not found');
268         }
269     });
270 }
271
272 function mangleRecord(record, template) {
273     record.recInt = parseInt(record.record);
274
275     // Sanitize HTML input
276     record.data = record.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
277
278     // Turn HTTP URLs into links
279     record.data = record.data.replace(/(\s|^)(https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/([^\s"]*[^.!,;?()\s])?)?)/g, '$1<a href="$2">$2</a>');
280
281     // Turn markdown links into links
282     record.data = record.data.replace(/(\s|^)\[([^\]]+)\]\((https?:\/\/[a-zA-Z0-9.-]*[a-zA-Z0-9](\/[^)"]*?)?)\)/g, '$1<a href="$3">$2</a>');
283
284     // Turn *foo* into italics and **foo** into bold
285     record.data = record.data.replace(/(\s)\*\*([^*]+)\*\*(\s)/g, '$1<b>$2</b>$3');
286     record.data = record.data.replace(/(\s)\*([^*]+)\*(\s)/g, '$1<i>$2</i>$3');
287
288     // Turn refs and tags into links
289     record.data = record.data.replace(/(\s|^)#([A-Za-z0-9_-]+)/g, '$1<a href="#tag/$2" class="ref">#$2</a>');
290     record.data = record.data.replace(/(\s|^)@([A-Za-z0-9_-]+)/g, '$1<a href="#$2" class="ref">@$2</a>');
291
292     // Turn newlines into linebreaks and paragraphs
293     record.data = record.data.replace(/\r?\n\r?\n/g, "<p>").replace(/\r?\n/g, "<br>");
294
295     record.date = (new Date(record.timestamp * 1000)).toString();
296     record.html = template.evaluate(record);
297 }
298
299 function displayError(msg) {
300     items.innerText = msg;
301 }
302
303
304 // Object for browsing tags
305 function Tag(type, tag) {
306     this.initPager();
307     this.type = type;
308     this.tag = tag;
309
310     var url = baseURL + "/tag/";
311     switch(type) {
312     case 'tag':
313         //url += '%23';
314         url += 'H';  // apache is eating the hash, even encoded.  Probably a security feature.
315         break;
316     case 'ref':
317         url += '%40';
318         break;
319     default:
320         alert('Invalid tag type: ' + type);
321         return;
322     }
323     url += tag;
324
325     new Ajax.Request(url, {
326         method: 'get',
327         onSuccess: function(r) {
328             var j = r.responseText.evalJSON();
329             if (j) {
330                 var maxid = j.length - 1;
331                 j.each(function(v, i) {
332                     v.id = maxid - i;
333                     mangleRecord(v, tagRecordTemplate)
334                 });
335                 this.addItems(j);
336                 this.pageStart = j.length - 1;
337             }
338             this.displayItems();
339         }.bind(this),
340         onFailure: function(r) {
341             this.displayItems();
342         }.bind(this)
343     });
344
345 }
346 Tag.prototype = new Pager();
347 Tag.prototype.constructor = Tag;
348
349 Tag.prototype.show = function() {
350     var ctype = {ref: '@', tag: '#'}[this.type];
351
352     $$('[name=section]').each(function(v) {
353         v.update(' about ' + ctype + this.tag);
354     }.bind(this));
355     $('welcome').hide();
356     $('post').hide();
357     $('older_link').hide();
358     $('newer_link').hide();
359     $('rss').hide();
360     items.show();
361     $('usercontrols').hide();
362 }
363
364 function postPopup() {
365     if (loginStatus.loggedIn) {
366         var post = $('post');
367         if (post.visible()) {
368             post.hide();
369         } else {
370             post.show();
371             if (currentPager.username && currentPager.username != loginStatus.username && !$('post.content').value) {
372                 $('post.content').value = '@' + currentPager.username + ': ';
373             }
374             $('post.content').focus();
375         }
376     }
377 }
378
379 function signup() {
380     var username = $('signup.username').value;
381     var password = $('signup.password').value;
382
383     new Ajax.Request(baseURL + '/create', {
384         parameters: {
385             username: username,
386             password: password
387         },
388         onSuccess: function(r) {
389             $('signup').hide();
390             location.href = '/#' + username;
391             hashSwitch();
392
393             loginStatus.login(username, password);
394         },
395         onFailure: function(r) {
396             alert("Failed to create user");
397         }
398     });
399 }
400
401 function signup_cancel() {
402     $('signup').hide();
403     hashSwitch();
404 }
405
406 function newer_page() {
407     if (currentPager)
408         currentPager.newerPage();
409 }
410
411 function older_page() {
412     if (currentPager)
413         currentPager.olderPage();
414 }
415
416 function obsess() {
417     new Ajax.Request(baseURL + '/subscribe/' + currentPager.username, {
418         method: 'post',
419         parameters: {
420             username: loginStatus.username
421         },
422         onSuccess: function(r) {
423             var response = r.responseText.evalJSON();
424             if (response.status == 'success') {
425                 alert("You call " + currentPager.username + " and begin breathing heavily into the handset.");
426                 $$('[name=user.obsesslink]').each(Element.hide);
427                 $$('[name=user.unobsesslink]').each(Element.show);
428             } else {
429                 alert('Failed to obsess. This is probably for the best');
430             }
431         },
432         onFailure: function(r) {
433             alert('Failed to obsess. This is probably for the best');
434         }
435     });
436 }
437
438 function unobsess() {
439     new Ajax.Request(baseURL + '/unsubscribe/' + currentPager.username, {
440         method: 'post',
441         parameters: {
442             username: loginStatus.username
443         },
444         onSuccess: function(r) {
445             var response = r.responseText.evalJSON();
446             if (response.status == 'success') {
447                 alert("You come to your senses.");
448                 $$('[name=user.obsesslink]').each(Element.show);
449                 $$('[name=user.unobsesslink]').each(Element.hide);
450             } else {
451                 alert('You are unable to tear yourself away (because something failed on the server)');
452             }
453         },
454         onFailure: function(r) {
455             alert('You are unable to tear yourself away (because something failed on the server)');
456         }
457     });
458 }
459
460 var resizePostContentTimeout = null;
461 function resizePostContent() {
462     if (resizePostContentTimeout)
463         clearTimeout(resizePostContentTimeout);
464     resizePostContentTimeout = setTimeout(function() {
465         var c = $('post.content');
466         var lines = Math.floor(c.value.length / (100 * (c.clientWidth / 1000))) + 1;
467         var m = c.value.match(/\r?\n/g);
468         if (m)
469             lines += m.length;
470         if (lines <= 3) {
471             c.style.height = "";
472         } else {
473             c.style.height = (lines * 17) + "pt";
474         }
475         resizePostContentTimeout = null;
476     }, 150);
477 }
478
479 var tickerTimer = null;
480 var tickerHead, tickerTail;
481
482 function tickerFader(a, b, p) {
483     var p2 = 1 - p;
484
485     a.style.opacity = p;
486     a.style.lineHeight = (100 * p) + '%';
487
488     b.style.opacity = p2;
489     b.style.lineHeight = (100 * p2) + '%';
490     if (p == 1.0)
491         b.hide();
492 }
493
494 function ticker() {
495     tickerHead.show();
496     Bytex64.FX.run(tickerFader.curry(tickerHead, tickerTail), 0.5);
497     tickerHead = tickerHead.nextSibling;
498     tickerTail = tickerTail.nextSibling;
499     if (tickerHead == null) {
500         stopTicker();
501         loadLatest.delay(10);
502     }
503 }
504
505 function startTicker() {
506     stopTicker();
507     for (var elem = $('latest-posts').firstChild; elem != null; elem = elem.nextSibling) {
508         elem.hide();
509     }
510
511     // Show the first five
512     tickerHead = $('latest-posts').firstChild;
513     for (var i = 0; i < 10 && tickerHead; i++) {
514         tickerHead.show();
515         tickerHead = tickerHead.nextSibling;
516     }
517     tickerTail = $('latest-posts').firstChild;
518     tickerTimer = setInterval(ticker, 5000);
519 }
520
521 function stopTicker() {
522     if (tickerTimer)
523         clearInterval(tickerTimer);
524     tickerTimer = null;
525 }
526
527 function loadLatest() {
528     new Ajax.Request(baseURL + '/latest.json', {
529         onSuccess: function(r) {
530             var j = r.responseText.evalJSON();
531
532             $('latest-tags').update();
533             j.tags.each(function(v) {
534                 var a = new Element('a', {href: '/#tag/' + v});
535                 a.insert('#' + v);
536                 a.className = 'ref';
537                 $('latest-tags').insert(a);
538                 $('latest-tags').appendChild(document.createTextNode(' '));
539             });
540
541             $('latest-posts').update();
542             j.records.each(function(v) {
543                 v.data = v.data.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
544                 v.date = (new Date(v.timestamp * 1000)).toString();
545                 var html = latestRecordsTemplate.evaluate(v);
546                 $('latest-posts').insert(html);
547             });
548             startTicker();
549         }
550     });
551 }
552
553 function hashSwitch() {
554     var m;
555     stopTicker();
556     if (m = location.search.match(/^\?post\/([^/]+)\/(.+)/)) {
557         $('post').show();
558         $('post.content').value = '[' + decodeURIComponent(m[1]).replace(']','').replace('[','') + '](' + decodeURIComponent(m[2]) + ')';
559     } else if (m = location.hash.match(/^#(ref|tag)\/([A-Za-z0-9_-]+)$/)) {
560         currentPager = new Tag(m[1], m[2]);
561         currentPager.show();
562     } else if (m = location.hash.match(/^#([A-Za-z0-9_-]+)(:(\d+))?$/)) {
563         if (!currentPager || currentPager.username != m[1])
564             currentPager = new User(m[1]);
565         currentPager.show();
566         loginStatus.update();
567
568         if (m[3]) {
569             var r = parseInt(m[3]);
570             currentPager.showRecord = r;
571             if (currentPager.recordCache[r]) {
572                 currentPager.displayItems();
573             } else {
574                 currentPager.loadItems((r >= 49 ? r - 49 : 0), r);
575             }
576         } else {
577             currentPager.pageStart = currentPager.itemCount - 1;
578             currentPager.loadItems();
579         }
580     } else {
581         $$('[name=section]').each(function(v) { v.update('Welcome') });
582         $('signup').hide();
583         items.update();
584         items.hide();
585         $('newer_link').hide();
586         $('older_link').hide();
587         $('welcome').show();
588         $('rss').hide();
589         $('usercontrols').hide();
590         loadLatest();
591     }
592 }
593
594 var lastHash;
595 function hashCheck() {
596     if (location.hash != lastHash) {
597         lastHash = location.hash;
598         hashSwitch();
599     }
600 }
601
602 function init() {
603     items = $('items');
604     loginStatus = new LoginStatus();
605
606     lastHash = location.hash;
607     hashSwitch();
608
609     setInterval(hashCheck, 250);
610
611     document.body.observe('keyup', function(event) {
612         if (event.shiftKey && event.keyCode == '32') {
613             postPopup();
614             event.stop();
615         }
616     });
617     $('post.content').addEventListener('keyup', function(event) {
618         event.stopPropagation();
619     }, true);
620 }