]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Realtime/realtimeupdate.js
Realtime plugin: fix i18n, thumbnails, location display, OStatus server display,...
[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             var noticeItemID = $(noticeItem).attr('id');
159
160             var list = $("#notices_primary .notices:first")
161             var prepend = true;
162
163             var threaded = list.hasClass('threaded-notices');
164             if (threaded && data.in_reply_to_status_id) {
165                 // aho!
166                 var parent = $('#notice-' + data.in_reply_to_status_id);
167                 if (parent.length == 0) {
168                     // @todo fetch the original, insert it, and finish the rest
169                 } else {
170                     // Check the parent notice to make sure it's not a reply itself.
171                     // If so, use it's parent as the parent.
172                     var parentList = parent.closest('.notices');
173                     if (parentList.hasClass('threaded-replies')) {
174                         parent = parentList.closest('.notice');
175                     }
176                     list = parent.find('.threaded-replies');
177                     if (list.length == 0) {
178                         list = $('<ul class="notices threaded-replies xoxo"></ul>');
179                         parent.append(list);
180                     }
181                     prepend = false;
182                 }
183             }
184
185             var newNotice = $(noticeItem);
186             if (prepend) {
187                 list.prepend(newNotice);
188             } else {
189                 var placeholder = list.find('li.notice-reply-placeholder')
190                 if (placeholder.length > 0) {
191                     newNotice.insertBefore(placeholder)
192                 } else {
193                     newNotice.appendTo(list);
194                     SN.U.NoticeInlineReplyPlaceholder(parent);
195                 }
196             }
197             newNotice.css({display:"none"}).fadeIn(1000);
198
199             SN.U.NoticeReplyTo($('#'+noticeItemID));
200             SN.U.NoticeWithAttachment($('#'+noticeItemID));
201         });
202      },
203
204      /**
205       * Check if the given notice is visible in the timeline currently.
206       * Used to avoid duplicate processing of notices that have been
207       * displayed by other means.
208       *
209       * @param {number} id: notice ID to check
210       *
211       * @return boolean
212       *
213       * @access private
214       */
215      isNoticeVisible: function(id) {
216         return ($("#notice-"+id).length > 0);
217      },
218
219      /**
220       * Trims a notice off the end of the timeline if we have more than the
221       * maximum number of notices visible.
222       *
223       * @access private
224       */
225      purgeLastNoticeItem: function() {
226         if ($('#notices_primary .notice').length > RealtimeUpdate._maxnotices) {
227             $("#notices_primary .notice:last").remove();
228         }
229      },
230
231      /**
232       * If the window/tab is in background, increment the counter of newly
233       * received notices and append it onto the window title.
234       *
235       * Has no effect if the window is in foreground.
236       *
237       * @access private
238       */
239      updateWindowCounter: function() {
240           if (RealtimeUpdate._windowhasfocus === false) {
241               RealtimeUpdate._updatecounter += 1;
242               document.title = '('+RealtimeUpdate._updatecounter+') ' + RealtimeUpdate._documenttitle;
243           }
244      },
245
246      /**
247       * Clear the background update counter from the window title.
248       *
249       * @access private
250       *
251       * @fixme could interfere with anything else trying similar tricks
252       */
253      removeWindowCounter: function() {
254           document.title = RealtimeUpdate._documenttitle;
255      },
256
257      /**
258       * Builds a notice HTML block from JSON API-style data;
259       * loads data from server, so runs async.
260       *
261       * @param {Object} data: extended JSON API-formatted notice
262       * @param {function} callback: function(DOMNode) to receive new code
263       *
264       * @access private
265       */
266      makeNoticeItem: function(data, callback)
267      {
268          var url = RealtimeUpdate._showurl.replace('0000000000', data.id);
269          $.get(url, {ajax: 1}, function(data, textStatus, xhr) {
270              var notice = $('li.notice:first', data);
271              if (notice.length) {
272                  var node = document._importNode(notice[0], true);
273                  callback(node);
274              }
275          });
276      },
277
278      /**
279       * Creates a favorite button.
280       *
281       * @param {number} id: notice ID to work with
282       * @param {String} session_key: session token for form CSRF protection
283       * @return {String} HTML fragment
284       *
285       * @fixme this replicates core StatusNet code, making maintenance harder
286       * @fixme sloppy HTML building (raw concat without escaping)
287       * @fixme no i18n support
288       *
289       * @access private
290       */
291      makeFavoriteForm: function(id, session_key)
292      {
293           var ff;
294
295           ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
296                 "<fieldset>"+
297                "<legend>Favor this notice</legend>"+
298                "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
299                "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
300                "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
301                 "</fieldset>"+
302                "</form>";
303           return ff;
304      },
305
306      /**
307       * Creates a reply button.
308       *
309       * @param {number} id: notice ID to work with
310       * @param {String} nickname: nick of the user to whom we are replying
311       * @return {String} HTML fragment
312       *
313       * @fixme this replicates core StatusNet code, making maintenance harder
314       * @fixme sloppy HTML building (raw concat without escaping)
315       * @fixme no i18n support
316       *
317       * @access private
318       */
319      makeReplyLink: function(id, nickname)
320      {
321           var rl;
322           rl = "<a class=\"notice_reply\" href=\""+RealtimeUpdate._replyurl+"?replyto="+nickname+"\" title=\"Reply to this notice\">Reply <span class=\"notice_id\">"+id+"</span></a>";
323           return rl;
324      },
325
326      /**
327       * Creates a repeat button.
328       *
329       * @param {number} id: notice ID to work with
330       * @param {String} session_key: session token for form CSRF protection
331       * @return {String} HTML fragment
332       *
333       * @fixme this replicates core StatusNet code, making maintenance harder
334       * @fixme sloppy HTML building (raw concat without escaping)
335       * @fixme no i18n support
336       *
337       * @access private
338       */
339      makeRepeatForm: function(id, session_key)
340      {
341           var rf;
342           rf = "<form id=\"repeat-"+id+"\" class=\"form_repeat\" method=\"post\" action=\""+RealtimeUpdate._repeaturl+"\">"+
343                "<fieldset>"+
344                "<legend>Repeat this notice?</legend>"+
345                "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
346                "<input name=\"notice\" type=\"hidden\" id=\"notice-"+id+"\" value=\""+id+"\"/>"+
347                "<input type=\"submit\" id=\"repeat-submit-"+id+"\" name=\"repeat-submit-"+id+"\" class=\"submit\" value=\"Yes\" title=\"Repeat this notice\"/>"+
348                "</fieldset>"+
349                "</form>";
350
351           return rf;
352      },
353
354      /**
355       * Creates a delete button.
356       *
357       * @param {number} id: notice ID to create a delete link for
358       * @return {String} HTML fragment
359       *
360       * @fixme this replicates core StatusNet code, making maintenance harder
361       * @fixme sloppy HTML building (raw concat without escaping)
362       * @fixme no i18n support
363       *
364       * @access private
365       */
366      makeDeleteLink: function(id)
367      {
368           var dl, delurl;
369           delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);
370
371           dl = "<a class=\"notice_delete\" href=\""+delurl+"\" title=\"Delete this notice\">Delete</a>";
372
373           return dl;
374      },
375
376      /**
377       * Adds a control widget at the top of the timeline view, containing
378       * pause/play and popup buttons.
379       *
380       * @param {String} url: full URL to the popup window variant of this timeline page
381       * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
382       * @param {String} path: URL to the base directory containing the Realtime plugin,
383       *                       used to fetch resources if needed.
384       *
385       * @todo timeline and path parameters are unused and probably should be removed.
386       *
387       * @access private
388       */
389      initActions: function(url, timeline, path)
390      {
391         $('#notices_primary').prepend('<ul id="realtime_actions"><li id="realtime_playpause"></li><li id="realtime_timeline"></li></ul>');
392
393         RealtimeUpdate._pluginPath = path;
394
395         RealtimeUpdate.initPlayPause();
396         RealtimeUpdate.initAddPopup(url, timeline, RealtimeUpdate._pluginPath);
397      },
398
399      /**
400       * Initialize the state of the play/pause controls.
401       *
402       * If the browser supports the localStorage interface, we'll attempt
403       * to retrieve a pause state from there; otherwise we default to paused.
404       *
405       * @access private
406       */
407      initPlayPause: function()
408      {
409         if (typeof(localStorage) == 'undefined') {
410             RealtimeUpdate.showPause();
411         }
412         else {
413             if (localStorage.getItem('RealtimeUpdate_paused') === 'true') {
414                 RealtimeUpdate.showPlay();
415             }
416             else {
417                 RealtimeUpdate.showPause();
418             }
419         }
420      },
421
422      /**
423       * Switch the realtime UI into paused state.
424       * Uses SN.msg i18n system for the button label and tooltip.
425       *
426       * State will be saved and re-used next time if the browser supports
427       * the localStorage interface (via setPause).
428       *
429       * @access private
430       */
431      showPause: function()
432      {
433         RealtimeUpdate.setPause(false);
434         RealtimeUpdate.showQueuedNotices();
435         RealtimeUpdate.addNoticesHover();
436
437         $('#realtime_playpause').remove();
438         $('#realtime_actions').prepend('<li id="realtime_playpause"><button id="realtime_pause" class="pause"></button></li>');
439         $('#realtime_pause').text(SN.msg('realtime_pause'))
440                             .attr('title', SN.msg('realtime_pause_tooltip'))
441                             .bind('click', function() {
442             RealtimeUpdate.removeNoticesHover();
443             RealtimeUpdate.showPlay();
444             return false;
445         });
446      },
447
448      /**
449       * Switch the realtime UI into play state.
450       * Uses SN.msg i18n system for the button label and tooltip.
451       *
452       * State will be saved and re-used next time if the browser supports
453       * the localStorage interface (via setPause).
454       *
455       * @access private
456       */
457      showPlay: function()
458      {
459         RealtimeUpdate.setPause(true);
460         $('#realtime_playpause').remove();
461         $('#realtime_actions').prepend('<li id="realtime_playpause"><span id="queued_counter"></span> <button id="realtime_play" class="play"></button></li>');
462         $('#realtime_play').text(SN.msg('realtime_play'))
463                            .attr('title', SN.msg('realtime_play_tooltip'))
464                            .bind('click', function() {
465             RealtimeUpdate.showPause();
466             return false;
467         });
468      },
469
470      /**
471       * Update the internal pause/play state.
472       * Do not call directly; use showPause() and showPlay().
473       *
474       * State will be saved and re-used next time if the browser supports
475       * the localStorage interface.
476       *
477       * @param {boolean} state: true = paused, false = not paused
478       *
479       * @access private
480       */
481      setPause: function(state)
482      {
483         RealtimeUpdate._paused = state;
484         if (typeof(localStorage) != 'undefined') {
485             localStorage.setItem('RealtimeUpdate_paused', RealtimeUpdate._paused);
486         }
487      },
488
489      /**
490       * Go through notices we have previously received while paused,
491       * dumping them into the timeline view.
492       *
493       * @fixme long timelines are not trimmed here as they are for things received while not paused
494       *
495       * @access private
496       */
497      showQueuedNotices: function()
498      {
499         $.each(RealtimeUpdate._queuedNotices, function(i, n) {
500             RealtimeUpdate.insertNoticeItem(n);
501         });
502
503         RealtimeUpdate._queuedNotices = [];
504
505         RealtimeUpdate.removeQueuedCounter();
506      },
507
508      /**
509       * Update the Realtime widget control's counter of queued notices to show
510       * the current count. This will be called after receiving and queueing
511       * a notice while paused.
512       *
513       * @access private
514       */
515      updateQueuedCounter: function()
516      {
517         $('#realtime_playpause #queued_counter').html('('+RealtimeUpdate._queuedNotices.length+')');
518      },
519
520      /**
521       * Clear the Realtime widget control's counter of queued notices.
522       *
523       * @access private
524       */
525      removeQueuedCounter: function()
526      {
527         $('#realtime_playpause #queued_counter').empty();
528      },
529
530      /**
531       * Set up event handlers on the timeline view to automatically pause
532       * when the mouse is over the timeline, as this indicates the user's
533       * desire to interact with the UI. (Which is hard to do when it's moving!)
534       *
535       * @access private
536       */
537      addNoticesHover: function()
538      {
539         $('#notices_primary .notices').hover(
540             function() {
541                 if (RealtimeUpdate._paused === false) {
542                     RealtimeUpdate.showPlay();
543                 }
544             },
545             function() {
546                 if (RealtimeUpdate._paused === true) {
547                     RealtimeUpdate.showPause();
548                 }
549             }
550         );
551      },
552
553      /**
554       * Tear down event handlers on the timeline view to automatically pause
555       * when the mouse is over the timeline.
556       *
557       * @fixme this appears to remove *ALL* event handlers from the timeline,
558       *        which assumes that nobody else is adding any event handlers.
559       *        Sloppy -- we should only remove the ones we add.
560       *
561       * @access private
562       */
563      removeNoticesHover: function()
564      {
565         $('#notices_primary .notices').unbind();
566      },
567
568      /**
569       * UI initialization, to be called from Realtime plugin code on regular
570       * timeline pages.
571       *
572       * Adds a button to the control widget at the top of the timeline view,
573       * allowing creation of a popup window with a more compact real-time
574       * view of the current timeline.
575       *
576       * @param {String} url: full URL to the popup window variant of this timeline page
577       * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
578       * @param {String} path: URL to the base directory containing the Realtime plugin,
579       *                       used to fetch resources if needed.
580       *
581       * @todo timeline and path parameters are unused and probably should be removed.
582       *
583       * @access public
584       */
585      initAddPopup: function(url, timeline, path)
586      {
587          $('#realtime_timeline').append('<button id="realtime_popup"></button>');
588          $('#realtime_popup').text(SN.msg('realtime_popup'))
589                              .attr('title', SN.msg('realtime_popup_tooltip'))
590                              .bind('click', function() {
591                 window.open(url,
592                          '',
593                          'toolbar=no,resizable=yes,scrollbars=yes,status=no,menubar=no,personalbar=no,location=no,width=500,height=550');
594
595              return false;
596          });
597      },
598
599      /**
600       * UI initialization, to be called from Realtime plugin code on popup
601       * compact timeline pages.
602       *
603       * Sets up links in notices to open in a new window.
604       *
605       * @fixme fails to do the same for UI links like context view which will
606       *        look bad in the tiny chromeless window.
607       *
608       * @access public
609       */
610      initPopupWindow: function()
611      {
612          $('.notices .entry-title a, .notices .entry-content a').bind('click', function() {
613             window.open(this.href, '');
614
615             return false;
616          });
617
618          $('#showstream .entity_profile').css({'width':'69%'});
619      }
620 }
621