]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Realtime/realtimeupdate.js
Went through realtimeupdate.js and added documentation comments -- does not alter...
[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(){ RealtimeUpdate._windowhasfocus = true; });
88
89         $(window).bind('blur', function() {
90           $('#notices_primary .notice').removeClass('mark-top');
91
92           $('#notices_primary .notice:first').addClass('mark-top');
93
94           RealtimeUpdate._updatecounter = 0;
95           document.title = RealtimeUpdate._documenttitle;
96           RealtimeUpdate._windowhasfocus = false;
97
98           return false;
99         });
100      },
101
102      /**
103       * Accept a notice in a Twitter-API JSON style and either show it
104       * or queue it up, depending on whether the realtime display is
105       * active.
106       *
107       * The meat of a Realtime plugin subclass is to provide a substrate
108       * transport to receive data and shove it into this function. :)
109       *
110       * Note that the JSON data is extended from the standard API return
111       * with additional fields added by RealtimePlugin's PHP code.
112       *
113       * @param {Object} data: extended JSON API-formatted notice
114       *
115       * @fixme Ticket #2914: already-visible sent notices are still queued up
116       *        when paused, inflating the queue count
117       *
118       * @access public
119       */
120      receive: function(data)
121      {
122           if (RealtimeUpdate._paused === false) {
123               RealtimeUpdate.purgeLastNoticeItem();
124
125               RealtimeUpdate.insertNoticeItem(data);
126           }
127           else {
128               RealtimeUpdate._queuedNotices.push(data);
129
130               RealtimeUpdate.updateQueuedCounter();
131           }
132
133           RealtimeUpdate.updateWindowCounter();
134      },
135
136      /**
137       * Add a visible representation of the given notice at the top of
138       * the current timeline.
139       *
140       * If the notice is already in the timeline, nothing will be added.
141       *
142       * @param {Object} data: extended JSON API-formatted notice
143       *
144       * @fixme while core UI JS code is used to activate the AJAX UI controls,
145       *        the actual production of HTML (in makeNoticeItem and its subs)
146       *        duplicates core code without plugin hook points or i18n support.
147       *
148       * @access private
149       */
150      insertNoticeItem: function(data) {
151         // Don't add it if it already exists
152         if ($("#notice-"+data.id).length > 0) {
153             return;
154         }
155
156         var noticeItem = RealtimeUpdate.makeNoticeItem(data);
157         var noticeItemID = $(noticeItem).attr('id');
158
159         $("#notices_primary .notices").prepend(noticeItem);
160         $("#notices_primary .notice:first").css({display:"none"});
161         $("#notices_primary .notice:first").fadeIn(1000);
162
163         SN.U.NoticeReplyTo($('#'+noticeItemID));
164         SN.U.NoticeWithAttachment($('#'+noticeItemID));
165      },
166
167      /**
168       * Trims a notice off the end of the timeline if we have more than the
169       * maximum number of notices visible.
170       *
171       * @access private
172       */
173      purgeLastNoticeItem: function() {
174         if ($('#notices_primary .notice').length > RealtimeUpdate._maxnotices) {
175             $("#notices_primary .notice:last").remove();
176         }
177      },
178
179      /**
180       * If the window/tab is in background, increment the counter of newly
181       * received notices and append it onto the window title.
182       *
183       * Has no effect if the window is in foreground.
184       *
185       * @access private
186       */
187      updateWindowCounter: function() {
188           if (RealtimeUpdate._windowhasfocus === false) {
189               RealtimeUpdate._updatecounter += 1;
190               document.title = '('+RealtimeUpdate._updatecounter+') ' + RealtimeUpdate._documenttitle;
191           }
192      },
193
194      /**
195       * Builds a notice HTML block from JSON API-style data.
196       *
197       * @param {Object} data: extended JSON API-formatted notice
198       * @return {String} HTML fragment
199       *
200       * @fixme this replicates core StatusNet code, making maintenance harder
201       * @fixme sloppy HTML building (raw concat without escaping)
202       * @fixme no i18n support
203       * @fixme local variables pollute global namespace
204       *
205       * @access private
206       */
207      makeNoticeItem: function(data)
208      {
209           if (data.hasOwnProperty('retweeted_status')) {
210                original = data['retweeted_status'];
211                repeat   = data;
212                data     = original;
213                unique   = repeat['id'];
214                responsible = repeat['user'];
215           } else {
216                original = null;
217                repeat = null;
218                unique = data['id'];
219                responsible = data['user'];
220           }
221
222           user = data['user'];
223           html = data['html'].replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/g,'"').replace(/&amp;/g,'&');
224           source = data['source'].replace(/&lt;/g,'<').replace(/&gt;/g,'>').replace(/&quot;/g,'"').replace(/&amp;/g,'&');
225
226           ni = "<li class=\"hentry notice\" id=\"notice-"+unique+"\">"+
227                "<div class=\"entry-title\">"+
228                "<span class=\"vcard author\">"+
229                "<a href=\""+user['profile_url']+"\" class=\"url\" title=\""+user['name']+"\">"+
230                "<img src=\""+user['profile_image_url']+"\" class=\"avatar photo\" width=\"48\" height=\"48\" alt=\""+user['screen_name']+"\"/>"+
231                "<span class=\"nickname fn\">"+user['screen_name']+"</span>"+
232                "</a>"+
233                "</span>"+
234                "<p class=\"entry-content\">"+html+"</p>"+
235                "</div>"+
236                "<div class=\"entry-content\">"+
237                "<a class=\"timestamp\" rel=\"bookmark\" href=\""+data['url']+"\" >"+
238                "<abbr class=\"published\" title=\""+data['created_at']+"\">a few seconds ago</abbr>"+
239                "</a> "+
240                "<span class=\"source\">"+
241                "from "+
242                 "<span class=\"device\">"+source+"</span>"+ // may have a link
243                "</span>";
244           if (data['conversation_url']) {
245                ni = ni+" <a class=\"response\" href=\""+data['conversation_url']+"\">in context</a>";
246           }
247
248           if (repeat) {
249                ru = repeat['user'];
250                ni = ni + "<span class=\"repeat vcard\">Repeated by " +
251                     "<a href=\"" + ru['profile_url'] + "\" class=\"url\">" +
252                     "<span class=\"nickname\">"+ ru['screen_name'] + "</span></a></span>";
253           }
254
255           ni = ni+"</div>";
256
257           ni = ni + "<div class=\"notice-options\">";
258
259           if (RealtimeUpdate._userid != 0) {
260                var input = $("form#form_notice fieldset input#token");
261                var session_key = input.val();
262                ni = ni+RealtimeUpdate.makeFavoriteForm(data['id'], session_key);
263                ni = ni+RealtimeUpdate.makeReplyLink(data['id'], data['user']['screen_name']);
264                if (RealtimeUpdate._userid == responsible['id']) {
265                     ni = ni+RealtimeUpdate.makeDeleteLink(data['id']);
266                } else if (RealtimeUpdate._userid != user['id']) {
267                     ni = ni+RealtimeUpdate.makeRepeatForm(data['id'],  session_key);
268                }
269           }
270
271           ni = ni+"</div>";
272
273           ni = ni+"</li>";
274           return ni;
275      },
276
277      /**
278       * Creates a favorite button.
279       *
280       * @param {number} id: notice ID to work with
281       * @param {String} session_key: session token for form CSRF protection
282       * @return {String} HTML fragment
283       *
284       * @fixme this replicates core StatusNet code, making maintenance harder
285       * @fixme sloppy HTML building (raw concat without escaping)
286       * @fixme no i18n support
287       *
288       * @access private
289       */
290      makeFavoriteForm: function(id, session_key)
291      {
292           var ff;
293
294           ff = "<form id=\"favor-"+id+"\" class=\"form_favor\" method=\"post\" action=\""+RealtimeUpdate._favorurl+"\">"+
295                 "<fieldset>"+
296                "<legend>Favor this notice</legend>"+
297                "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
298                "<input name=\"notice\" type=\"hidden\" id=\"notice-n"+id+"\" value=\""+id+"\"/>"+
299                "<input type=\"submit\" id=\"favor-submit-"+id+"\" name=\"favor-submit-"+id+"\" class=\"submit\" value=\"Favor\" title=\"Favor this notice\"/>"+
300                 "</fieldset>"+
301                "</form>";
302           return ff;
303      },
304
305      /**
306       * Creates a reply button.
307       *
308       * @param {number} id: notice ID to work with
309       * @param {String} nickname: nick of the user to whom we are replying
310       * @return {String} HTML fragment
311       *
312       * @fixme this replicates core StatusNet code, making maintenance harder
313       * @fixme sloppy HTML building (raw concat without escaping)
314       * @fixme no i18n support
315       *
316       * @access private
317       */
318      makeReplyLink: function(id, nickname)
319      {
320           var rl;
321           rl = "<a class=\"notice_reply\" href=\""+RealtimeUpdate._replyurl+"?replyto="+nickname+"\" title=\"Reply to this notice\">Reply <span class=\"notice_id\">"+id+"</span></a>";
322           return rl;
323      },
324
325      /**
326       * Creates a repeat button.
327       *
328       * @param {number} id: notice ID to work with
329       * @param {String} session_key: session token for form CSRF protection
330       * @return {String} HTML fragment
331       *
332       * @fixme this replicates core StatusNet code, making maintenance harder
333       * @fixme sloppy HTML building (raw concat without escaping)
334       * @fixme no i18n support
335       *
336       * @access private
337       */
338      makeRepeatForm: function(id, session_key)
339      {
340           var rf;
341           rf = "<form id=\"repeat-"+id+"\" class=\"form_repeat\" method=\"post\" action=\""+RealtimeUpdate._repeaturl+"\">"+
342                "<fieldset>"+
343                "<legend>Repeat this notice?</legend>"+
344                "<input name=\"token-"+id+"\" type=\"hidden\" id=\"token-"+id+"\" value=\""+session_key+"\"/>"+
345                "<input name=\"notice\" type=\"hidden\" id=\"notice-"+id+"\" value=\""+id+"\"/>"+
346                "<input type=\"submit\" id=\"repeat-submit-"+id+"\" name=\"repeat-submit-"+id+"\" class=\"submit\" value=\"Yes\" title=\"Repeat this notice\"/>"+
347                "</fieldset>"+
348                "</form>";
349
350           return rf;
351      },
352
353      /**
354       * Creates a delete button.
355       *
356       * @param {number} id: notice ID to create a delete link for
357       * @return {String} HTML fragment
358       *
359       * @fixme this replicates core StatusNet code, making maintenance harder
360       * @fixme sloppy HTML building (raw concat without escaping)
361       * @fixme no i18n support
362       *
363       * @access private
364       */
365      makeDeleteLink: function(id)
366      {
367           var dl, delurl;
368           delurl = RealtimeUpdate._deleteurl.replace("0000000000", id);
369
370           dl = "<a class=\"notice_delete\" href=\""+delurl+"\" title=\"Delete this notice\">Delete</a>";
371
372           return dl;
373      },
374
375      /**
376       * Adds a control widget at the top of the timeline view, containing
377       * pause/play and popup buttons.
378       *
379       * @param {String} url: full URL to the popup window variant of this timeline page
380       * @param {String} timeline: string key for the timeline (eg 'public' or 'evan-all')
381       * @param {String} path: URL to the base directory containing the Realtime plugin,
382       *                       used to fetch resources if needed.
383       *
384       * @todo timeline and path parameters are unused and probably should be removed.
385       *
386       * @access private
387       */
388      initActions: function(url, timeline, path)
389      {
390         $('#notices_primary').prepend('<ul id="realtime_actions"><li id="realtime_playpause"></li><li id="realtime_timeline"></li></ul>');
391
392         RealtimeUpdate._pluginPath = path;
393
394         RealtimeUpdate.initPlayPause();
395         RealtimeUpdate.initAddPopup(url, timeline, RealtimeUpdate._pluginPath);
396      },
397
398      /**
399       * Initialize the state of the play/pause controls.
400       *
401       * If the browser supports the localStorage interface, we'll attempt
402       * to retrieve a pause state from there; otherwise we default to paused.
403       *
404       * @access private
405       */
406      initPlayPause: function()
407      {
408         if (typeof(localStorage) == 'undefined') {
409             RealtimeUpdate.showPause();
410         }
411         else {
412             if (localStorage.getItem('RealtimeUpdate_paused') === 'true') {
413                 RealtimeUpdate.showPlay();
414             }
415             else {
416                 RealtimeUpdate.showPause();
417             }
418         }
419      },
420
421      /**
422       * Switch the realtime UI into paused state.
423       * Uses SN.msg i18n system for the button label and tooltip.
424       *
425       * State will be saved and re-used next time if the browser supports
426       * the localStorage interface (via setPause).
427       *
428       * @access private
429       */
430      showPause: function()
431      {
432         RealtimeUpdate.setPause(false);
433         RealtimeUpdate.showQueuedNotices();
434         RealtimeUpdate.addNoticesHover();
435
436         $('#realtime_playpause').remove();
437         $('#realtime_actions').prepend('<li id="realtime_playpause"><button id="realtime_pause" class="pause"></button></li>');
438         $('#realtime_pause').text(SN.msg('realtime_pause'))
439                             .attr('title', SN.msg('realtime_pause_tooltip'))
440                             .bind('click', function() {
441             RealtimeUpdate.removeNoticesHover();
442             RealtimeUpdate.showPlay();
443             return false;
444         });
445      },
446
447      /**
448       * Switch the realtime UI into play state.
449       * Uses SN.msg i18n system for the button label and tooltip.
450       *
451       * State will be saved and re-used next time if the browser supports
452       * the localStorage interface (via setPause).
453       *
454       * @access private
455       */
456      showPlay: function()
457      {
458         RealtimeUpdate.setPause(true);
459         $('#realtime_playpause').remove();
460         $('#realtime_actions').prepend('<li id="realtime_playpause"><span id="queued_counter"></span> <button id="realtime_play" class="play"></button></li>');
461         $('#realtime_play').text(SN.msg('realtime_play'))
462                            .attr('title', SN.msg('realtime_play_tooltip'))
463                            .bind('click', function() {
464             RealtimeUpdate.showPause();
465             return false;
466         });
467      },
468
469      /**
470       * Update the internal pause/play state.
471       * Do not call directly; use showPause() and showPlay().
472       *
473       * State will be saved and re-used next time if the browser supports
474       * the localStorage interface.
475       *
476       * @param {boolean} state: true = paused, false = not paused
477       *
478       * @access private
479       */
480      setPause: function(state)
481      {
482         RealtimeUpdate._paused = state;
483         if (typeof(localStorage) != 'undefined') {
484             localStorage.setItem('RealtimeUpdate_paused', RealtimeUpdate._paused);
485         }
486      },
487
488      /**
489       * Go through notices we have previously received while paused,
490       * dumping them into the timeline view.
491       *
492       * @fixme long timelines are not trimmed here as they are for things received while not paused
493       * @fixme Ticket #2913: the queued counter on the window title does not get cleared
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