]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Realtime/realtimeupdate.js
Ticket #2913: Realtime background update marker no longer triggers false positives...
[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      _replyurl: '',
48      _favorurl: '',
49      _repeaturl: '',
50      _deleteurl: '',
51      _updatecounter: 0,
52      _maxnotices: 50,
53      _windowhasfocus: true,
54      _documenttitle: '',
55      _paused:false,
56      _queuedNotices:[],
57
58      /**
59       * Initialize the Realtime plugin UI on a page with a timeline view.
60       *
61       * This function is called from a JS fragment inserted by the PHP side
62       * of the Realtime plugin, and provides us with base information
63       * needed to build a near-replica of StatusNet's NoticeListItem output.
64       *
65       * Once the UI is initialized, a plugin subclass will need to actually
66       * feed data into the RealtimeUpdate object!
67       *
68       * @param {int} userid: local profile ID of the currently logged-in user
69       * @param {String} replyurl: URL for newnotice action, used when generating reply buttons
70       * @param {String} favorurl: URL for favor action, used when generating fave buttons
71       * @param {String} repeaturl: URL for repeat action, used when generating repeat buttons
72       * @param {String} deleteurl: URL template for deletenotice action, used when generating delete buttons.
73       *                            This URL contains a stub value of 0000000000 which will be replaced with the notice ID.
74       *
75       * @access public
76       */
77      init: function(userid, replyurl, favorurl, repeaturl, deleteurl)
78      {
79         RealtimeUpdate._userid = userid;
80         RealtimeUpdate._replyurl = replyurl;
81         RealtimeUpdate._favorurl = favorurl;
82         RealtimeUpdate._repeaturl = repeaturl;
83         RealtimeUpdate._deleteurl = deleteurl;
84
85         RealtimeUpdate._documenttitle = document.title;
86
87         $(window).bind('focus', function() {
88           RealtimeUpdate._windowhasfocus = true;
89
90           // Clear the counter on the window title when we focus in.
91           RealtimeUpdate._updatecounter = 0;
92           RealtimeUpdate.removeWindowCounter();
93         });
94
95         $(window).bind('blur', function() {
96           $('#notices_primary .notice').removeClass('mark-top');
97
98           $('#notices_primary .notice:first').addClass('mark-top');
99
100           // While we're in the background, received messages will increment
101           // a counter that we put on the window title. This will cause some
102           // browsers to also flash or mark the tab or window title bar until
103           // you seek attention (eg Firefox 4 pinned app tabs).
104           RealtimeUpdate._windowhasfocus = false;
105
106           return false;
107         });
108      },
109
110      /**
111       * Accept a notice in a Twitter-API JSON style and either show it
112       * or queue it up, depending on whether the realtime display is
113       * active.
114       *
115       * The meat of a Realtime plugin subclass is to provide a substrate
116       * transport to receive data and shove it into this function. :)
117       *
118       * Note that the JSON data is extended from the standard API return
119       * with additional fields added by RealtimePlugin's PHP code.
120       *
121       * @param {Object} data: extended JSON API-formatted notice
122       *
123       * @access public
124       */
125      receive: function(data)
126      {
127           if (RealtimeUpdate.isNoticeVisible(data.id)) {
128               // Probably posted by the user in this window, and so already
129               // shown by the AJAX form handler. Ignore it.
130               return;
131           }
132           if (RealtimeUpdate._paused === false) {
133               RealtimeUpdate.purgeLastNoticeItem();
134
135               RealtimeUpdate.insertNoticeItem(data);
136           }
137           else {
138               RealtimeUpdate._queuedNotices.push(data);
139
140               RealtimeUpdate.updateQueuedCounter();
141           }
142
143           RealtimeUpdate.updateWindowCounter();
144      },
145
146      /**
147       * Add a visible representation of the given notice at the top of
148       * the current timeline.
149       *
150       * If the notice is already in the timeline, nothing will be added.
151       *
152       * @param {Object} data: extended JSON API-formatted notice
153       *
154       * @fixme while core UI JS code is used to activate the AJAX UI controls,
155       *        the actual production of HTML (in makeNoticeItem and its subs)
156       *        duplicates core code without plugin hook points or i18n support.
157       *
158       * @access private
159       */
160      insertNoticeItem: function(data) {
161         // Don't add it if it already exists
162         if (RealtimeUpdate.isNoticeVisible(data.id)) {
163             return;
164         }
165
166         var noticeItem = RealtimeUpdate.makeNoticeItem(data);
167         var noticeItemID = $(noticeItem).attr('id');
168
169         $("#notices_primary .notices").prepend(noticeItem);
170         $("#notices_primary .notice:first").css({display:"none"});
171         $("#notices_primary .notice:first").fadeIn(1000);
172
173         SN.U.NoticeReplyTo($('#'+noticeItemID));
174         SN.U.NoticeWithAttachment($('#'+noticeItemID));
175      },
176
177      /**
178       * Check if the given notice is visible in the timeline currently.
179       * Used to avoid duplicate processing of notices that have been
180       * displayed by other means.
181       *
182       * @param {number} id: notice ID to check
183       *
184       * @return boolean
185       *
186       * @access private
187       */
188      isNoticeVisible: function(id) {
189         return ($("#notice-"+id).length > 0);
190      },
191
192      /**
193       * Trims a notice off the end of the timeline if we have more than the
194       * maximum number of notices visible.
195       *
196       * @access private
197       */
198      purgeLastNoticeItem: function() {
199         if ($('#notices_primary .notice').length > RealtimeUpdate._maxnotices) {
200             $("#notices_primary .notice:last").remove();
201         }
202      },
203
204      /**
205       * If the window/tab is in background, increment the counter of newly
206       * received notices and append it onto the window title.
207       *
208       * Has no effect if the window is in foreground.
209       *
210       * @access private
211       */
212      updateWindowCounter: function() {
213           if (RealtimeUpdate._windowhasfocus === false) {
214               RealtimeUpdate._updatecounter += 1;
215               document.title = '('+RealtimeUpdate._updatecounter+') ' + RealtimeUpdate._documenttitle;
216           }
217      },
218
219      /**
220       * Clear the background update counter from the window title.
221       *
222       * @access private
223       *
224       * @fixme could interfere with anything else trying similar tricks
225       */
226      removeWindowCounter: function() {
227           document.title = RealtimeUpdate._documenttitle;
228      },
229
230      /**
231       * Builds a notice HTML block from JSON API-style data.
232       *
233       * @param {Object} data: extended JSON API-formatted notice
234       * @return {String} HTML fragment
235       *
236       * @fixme this replicates core StatusNet code, making maintenance harder
237       * @fixme sloppy HTML building (raw concat without escaping)
238       * @fixme no i18n support
239       * @fixme local variables pollute global namespace
240       *
241       * @access private
242       */
243      makeNoticeItem: function(data)
244      {
245           if (data.hasOwnProperty('retweeted_status')) {
246                original = data['retweeted_status'];
247                repeat   = data;
248                data     = original;
249                unique   = repeat['id'];
250                responsible = repeat['user'];
251           } else {
252                original = null;
253                repeat = null;
254                unique = data['id'];
255                responsible = data['user'];
256           }
257
258           user = data['user'];
259           html = data['html'].replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/g,'"').replace(/&amp;/g,'&');
260           source = data['source'].replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/g,'"').replace(/&amp;/g,'&');
261
262           ni = "<li class=\"hentry notice\" id=\"notice-"+unique+"\">"+
263                "<div class=\"entry-title\">"+
264                "<span class=\"vcard author\">"+
265                "<a href=\""+user['profile_url']+"\" class=\"url\" title=\""+user['name']+"\">"+
266                "<img src=\""+user['profile_image_url']+"\" class=\"avatar photo\" width=\"48\" height=\"48\" alt=\""+user['screen_name']+"\"/>"+
267                "<span class=\"nickname fn\">"+user['screen_name']+"</span>"+
268                "</a>"+
269                "</span>"+
270                "<p class=\"entry-content\">"+html+"</p>"+
271                "</div>"+
272                "<div class=\"entry-content\">"+
273                "<a class=\"timestamp\" rel=\"bookmark\" href=\""+data['url']+"\" >"+
274                "<abbr class=\"published\" title=\""+data['created_at']+"\">a few seconds ago</abbr>"+
275                "</a> "+
276                "<span class=\"source\">"+
277                "from "+
278                 "<span class=\"device\">"+source+"</span>"+ // may have a link
279                "</span>";
280           if (data['conversation_url']) {
281                ni = ni+" <a class=\"response\" href=\""+data['conversation_url']+"\">in context</a>";
282           }
283
284           if (repeat) {
285                ru = repeat['user'];
286                ni = ni + "<span class=\"repeat vcard\">Repeated by " +
287                     "<a href=\"" + ru['profile_url'] + "\" class=\"url\">" +
288                     "<span class=\"nickname\">"+ ru['screen_name'] + "</span></a></span>";
289           }
290
291           ni = ni+"</div>";
292
293           ni = ni + "<div class=\"notice-options\">";
294
295           if (RealtimeUpdate._userid != 0) {
296                var input = $("form#form_notice fieldset input#token");
297                var session_key = input.val();
298                ni = ni+RealtimeUpdate.makeFavoriteForm(data['id'], session_key);
299                ni = ni+RealtimeUpdate.makeReplyLink(data['id'], data['user']['screen_name']);
300                if (RealtimeUpdate._userid == responsible['id']) {
301                     ni = ni+RealtimeUpdate.makeDeleteLink(data['id']);
302                } else if (RealtimeUpdate._userid != user['id']) {
303                     ni = ni+RealtimeUpdate.makeRepeatForm(data['id'],  session_key);
304                }
305           }
306
307           ni = ni+"</div>";
308
309           ni = ni+"</li>";
310           return ni;
311      },
312
313      /**
314       * Creates a favorite button.
315       *
316       * @param {number} id: notice ID to work with
317       * @param {String} session_key: session token for form CSRF protection
318       * @return {String} HTML fragment
319       *
320       * @fixme this replicates core StatusNet code, making maintenance harder
321       * @fixme sloppy HTML building (raw concat without escaping)
322       * @fixme no i18n support
323       *
324       * @access private
325       */
326      makeFavoriteForm: function(id, session_key)
327      {
328           var ff;
329
330           ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
331                 "<fieldset>"+
332                "<legend>Favor this notice</legend>"+
333                "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
334                "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
335                "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
336                 "</fieldset>"+
337                "</form>";
338           return ff;
339      },
340
341      /**
342       * Creates a reply button.
343       *
344       * @param {number} id: notice ID to work with
345       * @param {String} nickname: nick of the user to whom we are replying
346       * @return {String} HTML fragment
347       *
348       * @fixme this replicates core StatusNet code, making maintenance harder
349       * @fixme sloppy HTML building (raw concat without escaping)
350       * @fixme no i18n support
351       *
352       * @access private
353       */
354      makeReplyLink: function(id, nickname)
355      {
356           var rl;
357           rl = "<a class=\"notice_reply\" href=\""+RealtimeUpdate._replyurl+"?replyto="+nickname+"\" title=\"Reply to this notice\">Reply <span class=\"notice_id\">"+id+"</span></a>";
358           return rl;
359      },
360
361      /**
362       * Creates a repeat button.
363       *
364       * @param {number} id: notice ID to work with
365       * @param {String} session_key: session token for form CSRF protection
366       * @return {String} HTML fragment
367       *
368       * @fixme this replicates core StatusNet code, making maintenance harder
369       * @fixme sloppy HTML building (raw concat without escaping)
370       * @fixme no i18n support
371       *
372       * @access private
373       */
374      makeRepeatForm: function(id, session_key)
375      {
376           var rf;
377           rf = "<form id=\"repeat-"+id+"\" class=\"form_repeat\" method=\"post\" action=\""+RealtimeUpdate._repeaturl+"\">"+
378                "<fieldset>"+
379                "<legend>Repeat this notice?</legend>"+
380                "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
381                "<input name=\"notice\" type=\"hidden\" id=\"notice-"+id+"\" value=\""+id+"\"/>"+
382                "<input type=\"submit\" id=\"repeat-submit-"+id+"\" name=\"repeat-submit-"+id+"\" class=\"submit\" value=\"Yes\" title=\"Repeat this notice\"/>"+
383                "</fieldset>"+
384                "</form>";
385
386           return rf;
387      },
388
389      /**
390       * Creates a delete button.
391       *
392       * @param {number} id: notice ID to create a delete link for
393       * @return {String} HTML fragment
394       *
395       * @fixme this replicates core StatusNet code, making maintenance harder
396       * @fixme sloppy HTML building (raw concat without escaping)
397       * @fixme no i18n support
398       *
399       * @access private
400       */
401      makeDeleteLink: function(id)
402      {
403           var dl, delurl;
404           delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);
405
406           dl = "<a class=\"notice_delete\" href=\""+delurl+"\" title=\"Delete this notice\">Delete</a>";
407
408           return dl;
409      },
410
411      /**
412       * Adds a control widget at the top of the timeline view, containing
413       * pause/play and popup buttons.
414       *
415       * @param {String} url: full URL to the popup window variant of this timeline page
416       * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
417       * @param {String} path: URL to the base directory containing the Realtime plugin,
418       *                       used to fetch resources if needed.
419       *
420       * @todo timeline and path parameters are unused and probably should be removed.
421       *
422       * @access private
423       */
424      initActions: function(url, timeline, path)
425      {
426         $('#notices_primary').prepend('<ul id="realtime_actions"><li id="realtime_playpause"></li><li id="realtime_timeline"></li></ul>');
427
428         RealtimeUpdate._pluginPath = path;
429
430         RealtimeUpdate.initPlayPause();
431         RealtimeUpdate.initAddPopup(url, timeline, RealtimeUpdate._pluginPath);
432      },
433
434      /**
435       * Initialize the state of the play/pause controls.
436       *
437       * If the browser supports the localStorage interface, we'll attempt
438       * to retrieve a pause state from there; otherwise we default to paused.
439       *
440       * @access private
441       */
442      initPlayPause: function()
443      {
444         if (typeof(localStorage) == 'undefined') {
445             RealtimeUpdate.showPause();
446         }
447         else {
448             if (localStorage.getItem('RealtimeUpdate_paused') === 'true') {
449                 RealtimeUpdate.showPlay();
450             }
451             else {
452                 RealtimeUpdate.showPause();
453             }
454         }
455      },
456
457      /**
458       * Switch the realtime UI into paused state.
459       * Uses SN.msg i18n system for the button label and tooltip.
460       *
461       * State will be saved and re-used next time if the browser supports
462       * the localStorage interface (via setPause).
463       *
464       * @access private
465       */
466      showPause: function()
467      {
468         RealtimeUpdate.setPause(false);
469         RealtimeUpdate.showQueuedNotices();
470         RealtimeUpdate.addNoticesHover();
471
472         $('#realtime_playpause').remove();
473         $('#realtime_actions').prepend('<li id="realtime_playpause"><button id="realtime_pause" class="pause"></button></li>');
474         $('#realtime_pause').text(SN.msg('realtime_pause'))
475                             .attr('title', SN.msg('realtime_pause_tooltip'))
476                             .bind('click', function() {
477             RealtimeUpdate.removeNoticesHover();
478             RealtimeUpdate.showPlay();
479             return false;
480         });
481      },
482
483      /**
484       * Switch the realtime UI into play state.
485       * Uses SN.msg i18n system for the button label and tooltip.
486       *
487       * State will be saved and re-used next time if the browser supports
488       * the localStorage interface (via setPause).
489       *
490       * @access private
491       */
492      showPlay: function()
493      {
494         RealtimeUpdate.setPause(true);
495         $('#realtime_playpause').remove();
496         $('#realtime_actions').prepend('<li id="realtime_playpause"><span id="queued_counter"></span> <button id="realtime_play" class="play"></button></li>');
497         $('#realtime_play').text(SN.msg('realtime_play'))
498                            .attr('title', SN.msg('realtime_play_tooltip'))
499                            .bind('click', function() {
500             RealtimeUpdate.showPause();
501             return false;
502         });
503      },
504
505      /**
506       * Update the internal pause/play state.
507       * Do not call directly; use showPause() and showPlay().
508       *
509       * State will be saved and re-used next time if the browser supports
510       * the localStorage interface.
511       *
512       * @param {boolean} state: true = paused, false = not paused
513       *
514       * @access private
515       */
516      setPause: function(state)
517      {
518         RealtimeUpdate._paused = state;
519         if (typeof(localStorage) != 'undefined') {
520             localStorage.setItem('RealtimeUpdate_paused', RealtimeUpdate._paused);
521         }
522      },
523
524      /**
525       * Go through notices we have previously received while paused,
526       * dumping them into the timeline view.
527       *
528       * @fixme long timelines are not trimmed here as they are for things received while not paused
529       *
530       * @access private
531       */
532      showQueuedNotices: function()
533      {
534         $.each(RealtimeUpdate._queuedNotices, function(i, n) {
535             RealtimeUpdate.insertNoticeItem(n);
536         });
537
538         RealtimeUpdate._queuedNotices = [];
539
540         RealtimeUpdate.removeQueuedCounter();
541      },
542
543      /**
544       * Update the Realtime widget control's counter of queued notices to show
545       * the current count. This will be called after receiving and queueing
546       * a notice while paused.
547       *
548       * @access private
549       */
550      updateQueuedCounter: function()
551      {
552         $('#realtime_playpause #queued_counter').html('('+RealtimeUpdate._queuedNotices.length+')');
553      },
554
555      /**
556       * Clear the Realtime widget control's counter of queued notices.
557       *
558       * @access private
559       */
560      removeQueuedCounter: function()
561      {
562         $('#realtime_playpause #queued_counter').empty();
563      },
564
565      /**
566       * Set up event handlers on the timeline view to automatically pause
567       * when the mouse is over the timeline, as this indicates the user's
568       * desire to interact with the UI. (Which is hard to do when it's moving!)
569       *
570       * @access private
571       */
572      addNoticesHover: function()
573      {
574         $('#notices_primary .notices').hover(
575             function() {
576                 if (RealtimeUpdate._paused === false) {
577                     RealtimeUpdate.showPlay();
578                 }
579             },
580             function() {
581                 if (RealtimeUpdate._paused === true) {
582                     RealtimeUpdate.showPause();
583                 }
584             }
585         );
586      },
587
588      /**
589       * Tear down event handlers on the timeline view to automatically pause
590       * when the mouse is over the timeline.
591       *
592       * @fixme this appears to remove *ALL* event handlers from the timeline,
593       *        which assumes that nobody else is adding any event handlers.
594       *        Sloppy -- we should only remove the ones we add.
595       *
596       * @access private
597       */
598      removeNoticesHover: function()
599      {
600         $('#notices_primary .notices').unbind();
601      },
602
603      /**
604       * UI initialization, to be called from Realtime plugin code on regular
605       * timeline pages.
606       *
607       * Adds a button to the control widget at the top of the timeline view,
608       * allowing creation of a popup window with a more compact real-time
609       * view of the current timeline.
610       *
611       * @param {String} url: full URL to the popup window variant of this timeline page
612       * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
613       * @param {String} path: URL to the base directory containing the Realtime plugin,
614       *                       used to fetch resources if needed.
615       *
616       * @todo timeline and path parameters are unused and probably should be removed.
617       *
618       * @access public
619       */
620      initAddPopup: function(url, timeline, path)
621      {
622          $('#realtime_timeline').append('<button id="realtime_popup"></button>');
623          $('#realtime_popup').text(SN.msg('realtime_popup'))
624                              .attr('title', SN.msg('realtime_popup_tooltip'))
625                              .bind('click', function() {
626                 window.open(url,
627                          '',
628                          'toolbar=no,resizable=yes,scrollbars=yes,status=no,menubar=no,personalbar=no,location=no,width=500,height=550');
629
630              return false;
631          });
632      },
633
634      /**
635       * UI initialization, to be called from Realtime plugin code on popup
636       * compact timeline pages.
637       *
638       * Sets up links in notices to open in a new window.
639       *
640       * @fixme fails to do the same for UI links like context view which will
641       *        look bad in the tiny chromeless window.
642       *
643       * @access public
644       */
645      initPopupWindow: function()
646      {
647          $('.notices .entry-title a, .notices .entry-content a').bind('click', function() {
648             window.open(this.href, '');
649
650             return false;
651          });
652
653          $('#showstream .entity_profile').css({'width':'69%'});
654      }
655 }
656