]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Realtime/realtimeupdate.js
better output for registration confirmation
[quix0rs-gnu-social.git] / plugins / Realtime / realtimeupdate.js
1 /*
2  * StatusNet - a distributed open-source microblogging tool
3  * Copyright (C) 2008, StatusNet, Inc.
4  *
5  * Add a notice encoded as JSON into the current timeline
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
19  *
20  * @category  Plugin
21  * @package   StatusNet
22  * @author    Evan Prodromou <evan@status.net>
23  * @author    Sarven Capadisli <csarven@status.net>
24  * @copyright 2009 StatusNet, Inc.
25  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
26  * @link      http://status.net/
27  */
28
29 /**
30  * This is the UI portion of the Realtime plugin base class, handling
31  * queueing up and displaying of notices that have been received through
32  * other code in one of the subclassed plugin implementations such as
33  * Meteor or Orbited.
34  *
35  * Notices are passed in as JSON objects formatted per the Twitter-compatible
36  * API.
37  *
38  * @todo Currently we duplicate a lot of formatting and layout code from
39  *       the PHP side of StatusNet, which makes it very difficult to maintain
40  *       this package. Internationalization as well as newer features such
41  *       as location data, customized source links for OStatus profiles,
42  *       and image thumbnails are not yet supported in Realtime yet because
43  *       they have not been implemented here.
44  */
45 RealtimeUpdate = {
46      _userid: 0,
47      _showurl: '',
48      _updatecounter: 0,
49      _maxnotices: 50,
50      _windowhasfocus: true,
51      _documenttitle: '',
52      _paused:false,
53      _queuedNotices:[],
54
55      /**
56       * Initialize the Realtime plugin UI on a page with a timeline view.
57       *
58       * This function is called from a JS fragment inserted by the PHP side
59       * of the Realtime plugin, and provides us with base information
60       * needed to build a near-replica of StatusNet's NoticeListItem output.
61       *
62       * Once the UI is initialized, a plugin subclass will need to actually
63       * feed data into the RealtimeUpdate object!
64       *
65       * @param {int} userid: local profile ID of the currently logged-in user
66       * @param {String} showurl: URL for shownotice action, used when fetching formatting notices.
67       *                            This URL contains a stub value of 0000000000 which will be replaced with the notice ID.
68       *
69       * @access public
70       */
71      init: function(userid, showurl)
72      {
73         RealtimeUpdate._userid = userid;
74         RealtimeUpdate._showurl = showurl;
75
76         RealtimeUpdate._documenttitle = document.title;
77
78         $(window).bind('focus', function() {
79           RealtimeUpdate._windowhasfocus = true;
80
81           // Clear the counter on the window title when we focus in.
82           RealtimeUpdate._updatecounter = 0;
83           RealtimeUpdate.removeWindowCounter();
84         });
85
86         $(window).bind('blur', function() {
87           $('#notices_primary .notice').removeClass('mark-top');
88
89           $('#notices_primary .notice:first').addClass('mark-top');
90
91           // While we're in the background, received messages will increment
92           // a counter that we put on the window title. This will cause some
93           // browsers to also flash or mark the tab or window title bar until
94           // you seek attention (eg Firefox 4 pinned app tabs).
95           RealtimeUpdate._windowhasfocus = false;
96
97           return false;
98         });
99      },
100
101      /**
102       * Accept a notice in a Twitter-API JSON style and either show it
103       * or queue it up, depending on whether the realtime display is
104       * active.
105       *
106       * The meat of a Realtime plugin subclass is to provide a substrate
107       * transport to receive data and shove it into this function. :)
108       *
109       * Note that the JSON data is extended from the standard API return
110       * with additional fields added by RealtimePlugin's PHP code.
111       *
112       * @param {Object} data: extended JSON API-formatted notice
113       *
114       * @access public
115       */
116      receive: function(data)
117      {
118           if (RealtimeUpdate.isNoticeVisible(data.id)) {
119               // Probably posted by the user in this window, and so already
120               // shown by the AJAX form handler. Ignore it.
121               return;
122           }
123           if (RealtimeUpdate._paused === false) {
124               RealtimeUpdate.purgeLastNoticeItem();
125
126               RealtimeUpdate.insertNoticeItem(data);
127           }
128           else {
129               RealtimeUpdate._queuedNotices.push(data);
130
131               RealtimeUpdate.updateQueuedCounter();
132           }
133
134           RealtimeUpdate.updateWindowCounter();
135      },
136
137      /**
138       * Add a visible representation of the given notice at the top of
139       * the current timeline.
140       *
141       * If the notice is already in the timeline, nothing will be added.
142       *
143       * @param {Object} data: extended JSON API-formatted notice
144       *
145       * @fixme while core UI JS code is used to activate the AJAX UI controls,
146       *        the actual production of HTML (in makeNoticeItem and its subs)
147       *        duplicates core code without plugin hook points or i18n support.
148       *
149       * @access private
150       */
151      insertNoticeItem: function(data) {
152         // Don't add it if it already exists
153         if (RealtimeUpdate.isNoticeVisible(data.id)) {
154             return;
155         }
156
157         RealtimeUpdate.makeNoticeItem(data, function(noticeItem) {
158             // Check again in case it got shown while we were waiting for data...
159             if (RealtimeUpdate.isNoticeVisible(data.id)) {
160                 return;
161             }
162             var noticeItemID = $(noticeItem).attr('id');
163
164             var list = $("#notices_primary .notices:first")
165             var prepend = true;
166
167             var threaded = list.hasClass('threaded-notices');
168             if (threaded && data.in_reply_to_status_id) {
169                 // aho!
170                 var parent = $('#notice-' + data.in_reply_to_status_id);
171                 if (parent.length == 0) {
172                     // @todo fetch the original, insert it, and finish the rest
173                 } else {
174                     // Check the parent notice to make sure it's not a reply itself.
175                     // If so, use it's parent as the parent.
176                     var parentList = parent.closest('.notices');
177                     if (parentList.hasClass('threaded-replies')) {
178                         parent = parentList.closest('.notice');
179                     }
180                     list = parent.find('.threaded-replies');
181                     if (list.length == 0) {
182                         list = $('<ul class="notices threaded-replies xoxo"></ul>');
183                         parent.append(list);
184                         SN.U.NoticeInlineReplyPlaceholder(parent);
185                     }
186                     prepend = false;
187                 }
188             }
189
190             var newNotice = $(noticeItem);
191             if (prepend) {
192                 list.prepend(newNotice);
193             } else {
194                 var placeholder = list.find('li.notice-reply-placeholder')
195                 if (placeholder.length > 0) {
196                     newNotice.insertBefore(placeholder)
197                 } else {
198                     newNotice.appendTo(list);
199                 }
200             }
201             newNotice.css({display:"none"}).fadeIn(1000);
202
203             SN.U.NoticeReplyTo($('#'+noticeItemID));
204             SN.U.NoticeWithAttachment($('#'+noticeItemID));
205         });
206      },
207
208      /**
209       * Check if the given notice is visible in the timeline currently.
210       * Used to avoid duplicate processing of notices that have been
211       * displayed by other means.
212       *
213       * @param {number} id: notice ID to check
214       *
215       * @return boolean
216       *
217       * @access private
218       */
219      isNoticeVisible: function(id) {
220         return ($("#notice-"+id).length > 0);
221      },
222
223      /**
224       * Trims a notice off the end of the timeline if we have more than the
225       * maximum number of notices visible.
226       *
227       * @access private
228       */
229      purgeLastNoticeItem: function() {
230         if ($('#notices_primary .notice').length > RealtimeUpdate._maxnotices) {
231             $("#notices_primary .notice:last").remove();
232         }
233      },
234
235      /**
236       * If the window/tab is in background, increment the counter of newly
237       * received notices and append it onto the window title.
238       *
239       * Has no effect if the window is in foreground.
240       *
241       * @access private
242       */
243      updateWindowCounter: function() {
244           if (RealtimeUpdate._windowhasfocus === false) {
245               RealtimeUpdate._updatecounter += 1;
246               document.title = '('+RealtimeUpdate._updatecounter+') ' + RealtimeUpdate._documenttitle;
247           }
248      },
249
250      /**
251       * Clear the background update counter from the window title.
252       *
253       * @access private
254       *
255       * @fixme could interfere with anything else trying similar tricks
256       */
257      removeWindowCounter: function() {
258           document.title = RealtimeUpdate._documenttitle;
259      },
260
261      /**
262       * Builds a notice HTML block from JSON API-style data;
263       * loads data from server, so runs async.
264       *
265       * @param {Object} data: extended JSON API-formatted notice
266       * @param {function} callback: function(DOMNode) to receive new code
267       *
268       * @access private
269       */
270      makeNoticeItem: function(data, callback)
271      {
272          var url = RealtimeUpdate._showurl.replace('0000000000', data.id);
273          $.get(url, {ajax: 1}, function(data, textStatus, xhr) {
274              var notice = $('li.notice:first', data);
275              if (notice.length) {
276                  var node = document._importNode(notice[0], true);
277                  callback(node);
278              }
279          });
280      },
281
282      /**
283       * Creates a favorite button.
284       *
285       * @param {number} id: notice ID to work with
286       * @param {String} session_key: session token for form CSRF protection
287       * @return {String} HTML fragment
288       *
289       * @fixme this replicates core StatusNet code, making maintenance harder
290       * @fixme sloppy HTML building (raw concat without escaping)
291       * @fixme no i18n support
292       *
293       * @access private
294       */
295      makeFavoriteForm: function(id, session_key)
296      {
297           var ff;
298
299           ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
300                 "<fieldset>"+
301                "<legend>Favor this notice</legend>"+
302                "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
303                "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
304                "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
305                 "</fieldset>"+
306                "</form>";
307           return ff;
308      },
309
310      /**
311       * Creates a reply button.
312       *
313       * @param {number} id: notice ID to work with
314       * @param {String} nickname: nick of the user to whom we are replying
315       * @return {String} HTML fragment
316       *
317       * @fixme this replicates core StatusNet code, making maintenance harder
318       * @fixme sloppy HTML building (raw concat without escaping)
319       * @fixme no i18n support
320       *
321       * @access private
322       */
323      makeReplyLink: function(id, nickname)
324      {
325           var rl;
326           rl = "<a class=\"notice_reply\" href=\""+RealtimeUpdate._replyurl+"?replyto="+nickname+"\" title=\"Reply to this notice\">Reply <span class=\"notice_id\">"+id+"</span></a>";
327           return rl;
328      },
329
330      /**
331       * Creates a repeat button.
332       *
333       * @param {number} id: notice ID to work with
334       * @param {String} session_key: session token for form CSRF protection
335       * @return {String} HTML fragment
336       *
337       * @fixme this replicates core StatusNet code, making maintenance harder
338       * @fixme sloppy HTML building (raw concat without escaping)
339       * @fixme no i18n support
340       *
341       * @access private
342       */
343      makeRepeatForm: function(id, session_key)
344      {
345           var rf;
346           rf = "<form id=\"repeat-"+id+"\" class=\"form_repeat\" method=\"post\" action=\""+RealtimeUpdate._repeaturl+"\">"+
347                "<fieldset>"+
348                "<legend>Repeat this notice?</legend>"+
349                "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
350                "<input name=\"notice\" type=\"hidden\" id=\"notice-"+id+"\" value=\""+id+"\"/>"+
351                "<input type=\"submit\" id=\"repeat-submit-"+id+"\" name=\"repeat-submit-"+id+"\" class=\"submit\" value=\"Yes\" title=\"Repeat this notice\"/>"+
352                "</fieldset>"+
353                "</form>";
354
355           return rf;
356      },
357
358      /**
359       * Creates a delete button.
360       *
361       * @param {number} id: notice ID to create a delete link for
362       * @return {String} HTML fragment
363       *
364       * @fixme this replicates core StatusNet code, making maintenance harder
365       * @fixme sloppy HTML building (raw concat without escaping)
366       * @fixme no i18n support
367       *
368       * @access private
369       */
370      makeDeleteLink: function(id)
371      {
372           var dl, delurl;
373           delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);
374
375           dl = "<a class=\"notice_delete\" href=\""+delurl+"\" title=\"Delete this notice\">Delete</a>";
376
377           return dl;
378      },
379
380      /**
381       * Adds a control widget at the top of the timeline view, containing
382       * pause/play and popup buttons.
383       *
384       * @param {String} url: full URL to the popup window variant of this timeline page
385       * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
386       * @param {String} path: URL to the base directory containing the Realtime plugin,
387       *                       used to fetch resources if needed.
388       *
389       * @todo timeline and path parameters are unused and probably should be removed.
390       *
391       * @access private
392       */
393      initActions: function(url, timeline, path)
394      {
395         $('#notices_primary').prepend('<ul id="realtime_actions"><li id="realtime_playpause"></li><li id="realtime_timeline"></li></ul>');
396
397         RealtimeUpdate._pluginPath = path;
398
399         RealtimeUpdate.initPlayPause();
400         RealtimeUpdate.initAddPopup(url, timeline, RealtimeUpdate._pluginPath);
401      },
402
403      /**
404       * Initialize the state of the play/pause controls.
405       *
406       * If the browser supports the localStorage interface, we'll attempt
407       * to retrieve a pause state from there; otherwise we default to paused.
408       *
409       * @access private
410       */
411      initPlayPause: function()
412      {
413         if (typeof(localStorage) == 'undefined') {
414             RealtimeUpdate.showPause();
415         }
416         else {
417             if (localStorage.getItem('RealtimeUpdate_paused') === 'true') {
418                 RealtimeUpdate.showPlay();
419             }
420             else {
421                 RealtimeUpdate.showPause();
422             }
423         }
424      },
425
426      /**
427       * Switch the realtime UI into paused state.
428       * Uses SN.msg i18n system for the button label and tooltip.
429       *
430       * State will be saved and re-used next time if the browser supports
431       * the localStorage interface (via setPause).
432       *
433       * @access private
434       */
435      showPause: function()
436      {
437         RealtimeUpdate.setPause(false);
438         RealtimeUpdate.showQueuedNotices();
439         RealtimeUpdate.addNoticesHover();
440
441         $('#realtime_playpause').remove();
442         $('#realtime_actions').prepend('<li id="realtime_playpause"><button id="realtime_pause" class="pause"></button></li>');
443         $('#realtime_pause').text(SN.msg('realtime_pause'))
444                             .attr('title', SN.msg('realtime_pause_tooltip'))
445                             .bind('click', function() {
446             RealtimeUpdate.removeNoticesHover();
447             RealtimeUpdate.showPlay();
448             return false;
449         });
450      },
451
452      /**
453       * Switch the realtime UI into play state.
454       * Uses SN.msg i18n system for the button label and tooltip.
455       *
456       * State will be saved and re-used next time if the browser supports
457       * the localStorage interface (via setPause).
458       *
459       * @access private
460       */
461      showPlay: function()
462      {
463         RealtimeUpdate.setPause(true);
464         $('#realtime_playpause').remove();
465         $('#realtime_actions').prepend('<li id="realtime_playpause"><span id="queued_counter"></span> <button id="realtime_play" class="play"></button></li>');
466         $('#realtime_play').text(SN.msg('realtime_play'))
467                            .attr('title', SN.msg('realtime_play_tooltip'))
468                            .bind('click', function() {
469             RealtimeUpdate.showPause();
470             return false;
471         });
472      },
473
474      /**
475       * Update the internal pause/play state.
476       * Do not call directly; use showPause() and showPlay().
477       *
478       * State will be saved and re-used next time if the browser supports
479       * the localStorage interface.
480       *
481       * @param {boolean} state: true = paused, false = not paused
482       *
483       * @access private
484       */
485      setPause: function(state)
486      {
487         RealtimeUpdate._paused = state;
488         if (typeof(localStorage) != 'undefined') {
489             localStorage.setItem('RealtimeUpdate_paused', RealtimeUpdate._paused);
490         }
491      },
492
493      /**
494       * Go through notices we have previously received while paused,
495       * dumping them into the timeline view.
496       *
497       * @fixme long timelines are not trimmed here as they are for things received while not paused
498       *
499       * @access private
500       */
501      showQueuedNotices: function()
502      {
503         $.each(RealtimeUpdate._queuedNotices, function(i, n) {
504             RealtimeUpdate.insertNoticeItem(n);
505         });
506
507         RealtimeUpdate._queuedNotices = [];
508
509         RealtimeUpdate.removeQueuedCounter();
510      },
511
512      /**
513       * Update the Realtime widget control's counter of queued notices to show
514       * the current count. This will be called after receiving and queueing
515       * a notice while paused.
516       *
517       * @access private
518       */
519      updateQueuedCounter: function()
520      {
521         $('#realtime_playpause #queued_counter').html('('+RealtimeUpdate._queuedNotices.length+')');
522      },
523
524      /**
525       * Clear the Realtime widget control's counter of queued notices.
526       *
527       * @access private
528       */
529      removeQueuedCounter: function()
530      {
531         $('#realtime_playpause #queued_counter').empty();
532      },
533
534      /**
535       * Set up event handlers on the timeline view to automatically pause
536       * when the mouse is over the timeline, as this indicates the user's
537       * desire to interact with the UI. (Which is hard to do when it's moving!)
538       *
539       * @access private
540       */
541      addNoticesHover: function()
542      {
543         $('#notices_primary .notices').hover(
544             function() {
545                 if (RealtimeUpdate._paused === false) {
546                     RealtimeUpdate.showPlay();
547                 }
548             },
549             function() {
550                 if (RealtimeUpdate._paused === true) {
551                     RealtimeUpdate.showPause();
552                 }
553             }
554         );
555      },
556
557      /**
558       * Tear down event handlers on the timeline view to automatically pause
559       * when the mouse is over the timeline.
560       *
561       * @fixme this appears to remove *ALL* event handlers from the timeline,
562       *        which assumes that nobody else is adding any event handlers.
563       *        Sloppy -- we should only remove the ones we add.
564       *
565       * @access private
566       */
567      removeNoticesHover: function()
568      {
569         $('#notices_primary .notices').unbind();
570      },
571
572      /**
573       * UI initialization, to be called from Realtime plugin code on regular
574       * timeline pages.
575       *
576       * Adds a button to the control widget at the top of the timeline view,
577       * allowing creation of a popup window with a more compact real-time
578       * view of the current timeline.
579       *
580       * @param {String} url: full URL to the popup window variant of this timeline page
581       * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
582       * @param {String} path: URL to the base directory containing the Realtime plugin,
583       *                       used to fetch resources if needed.
584       *
585       * @todo timeline and path parameters are unused and probably should be removed.
586       *
587       * @access public
588       */
589      initAddPopup: function(url, timeline, path)
590      {
591          $('#realtime_timeline').append('<button id="realtime_popup"></button>');
592          $('#realtime_popup').text(SN.msg('realtime_popup'))
593                              .attr('title', SN.msg('realtime_popup_tooltip'))
594                              .bind('click', function() {
595                 window.open(url,
596                          '',
597                          'toolbar=no,resizable=yes,scrollbars=yes,status=no,menubar=no,personalbar=no,location=no,width=500,height=550');
598
599              return false;
600          });
601      },
602
603      /**
604       * UI initialization, to be called from Realtime plugin code on popup
605       * compact timeline pages.
606       *
607       * Sets up links in notices to open in a new window.
608       *
609       * @fixme fails to do the same for UI links like context view which will
610       *        look bad in the tiny chromeless window.
611       *
612       * @access public
613       */
614      initPopupWindow: function()
615      {
616          $('.notices .entry-title a, .notices .entry-content a').bind('click', function() {
617             window.open(this.href, '');
618
619             return false;
620          });
621
622          $('#showstream .entity_profile').css({'width':'69%'});
623      }
624 }
625