3 * StatusNet, the distributed open-source microblogging tool
5 * Superclass for plugins that do "real time" updates of timelines using Ajax
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Evan Prodromou <evan@status.net>
25 * @author Mikael Nordfeldth <mmn@hethane.se>
26 * @copyright 2009 StatusNet, Inc.
27 * @copyright 2014 Free Software Foundation, Inc.
28 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
29 * @link http://status.net/
32 if (!defined('GNUSOCIAL')) { exit(1); }
35 * Superclass for plugin to do realtime updates
37 * Based on experience with the Comet and Meteor plugins,
38 * this superclass extracts out some of the common functionality
42 * @author Evan Prodromou <evan@status.net>
43 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
44 * @link http://status.net/
46 class RealtimePlugin extends Plugin
48 protected $showurl = null;
51 * When it's time to initialize the plugin, calculate and
52 * pass the URLs we need.
54 function onInitializePlugin()
56 // FIXME: need to find a better way to pass this pattern in
57 $this->showurl = common_local_url('shownotice',
58 array('notice' => '0000000000'));
62 function onCheckSchema()
64 $schema = Schema::get();
65 $schema->ensureTable('realtime_channel', Realtime_channel::schemaDef());
70 * Hook for RouterInitialized event.
72 * @param Net_URL_Mapper $m path-to-action mapper
73 * @return boolean hook return
75 function onRouterInitialized($m)
77 $m->connect('main/channel/:channelkey/keepalive',
78 array('action' => 'keepalivechannel'),
79 array('channelkey' => '[a-z0-9]{32}'));
80 $m->connect('main/channel/:channelkey/close',
81 array('action' => 'closechannel'),
82 array('channelkey' => '[a-z0-9]{32}'));
86 function onEndShowScripts($action)
88 $channel = $this->_getChannel($action);
90 if (empty($channel)) {
94 $timeline = $this->_pathToChannel(array($channel->channel_key));
96 // If there's not a timeline on this page,
99 if (empty($timeline)) {
103 $base = $action->selfUrl();
104 if (mb_strstr($base, '?')) {
105 $url = $base . '&realtime=1';
107 $url = $base . '?realtime=1';
110 $scripts = $this->_getScripts();
112 foreach ($scripts as $script) {
113 $action->script($script);
116 $user = common_current_user();
118 if (!empty($user->id)) {
119 $user_id = $user->id;
124 if ($action->boolean('realtime')) {
125 $realtimeUI = ' RealtimeUpdate.initPopupWindow();';
128 $pluginPath = common_path('plugins/Realtime/');
129 $keepalive = common_local_url('keepalivechannel', array('channelkey' => $channel->channel_key));
130 $close = common_local_url('closechannel', array('channelkey' => $channel->channel_key));
131 $realtimeUI = ' RealtimeUpdate.initActions('.json_encode($url).', '.json_encode($timeline).', '.json_encode($pluginPath).', '.json_encode($keepalive).', '.json_encode($close).'); ';
134 $script = ' $(document).ready(function() { '.
136 $this->_updateInitialize($timeline, $user_id).
138 $action->inlineScript($script);
143 public function onEndShowStylesheets(Action $action)
145 $urlpath = self::staticPath(str_replace('Plugin','',__CLASS__),
146 'css/realtimeupdate.css');
147 $action->cssLink($urlpath, null, 'screen, projection, tv');
151 public function onHandleQueuedNotice(Notice $notice)
155 // Add to the author's timeline
158 $profile = $notice->getProfile();
159 } catch (Exception $e) {
160 $this->log(LOG_ERR, $e->getMessage());
165 $user = $profile->getUser();
166 $paths[] = array('showstream', $user->nickname, null);
167 } catch (NoSuchUserException $e) {
168 // We really should handle the remote profile views too
172 // Add to the public timeline
174 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
175 ($notice->is_local == Notice::REMOTE && !common_config('public', 'localonly'))) {
176 $paths[] = array('public', null, null);
179 // Add to the tags timeline
181 $tags = $this->getNoticeTags($notice);
184 foreach ($tags as $tag) {
185 $paths[] = array('tag', $tag, null);
189 // Add to inbox timelines
192 $ni = $notice->whoGets();
194 foreach (array_keys($ni) as $user_id) {
195 $user = User::getKV('id', $user_id);
196 $paths[] = array('all', $user->nickname, null);
199 // Add to the replies timeline
201 $reply = new Reply();
202 $reply->notice_id = $notice->id;
204 if ($reply->find()) {
205 while ($reply->fetch()) {
206 $user = User::getKV('id', $reply->profile_id);
208 $paths[] = array('replies', $user->nickname, null);
213 // Add to the group timeline
216 $gi = new Group_inbox();
217 $gi->notice_id = $notice->id;
220 while ($gi->fetch()) {
221 $ug = User_group::getKV('id', $gi->group_id);
222 $paths[] = array('showgroup', $ug->nickname, null);
226 if (count($paths) > 0) {
228 $json = $this->noticeAsJson($notice);
232 // XXX: We should probably fan-out here and do a
233 // new queue item for each path
235 foreach ($paths as $path) {
237 list($action, $arg1, $arg2) = $path;
239 $channels = Realtime_channel::getAllChannels($action, $arg1, $arg2);
240 $this->log(LOG_INFO, sprintf(_("%d candidate channels for notice %d"),
244 foreach ($channels as $channel) {
246 // XXX: We should probably fan-out here and do a
247 // new queue item for each user/path combo
249 if (is_null($channel->user_id)) {
252 $profile = Profile::getKV('id', $channel->user_id);
254 if ($notice->inScope($profile)) {
256 sprintf(_("Delivering notice %d to channel (%s, %s, %s) for user '%s'"),
261 ($profile) ? ($profile->nickname) : "<public>"));
262 $timeline = $this->_pathToChannel(array($channel->channel_key));
263 $this->_publish($timeline, $json);
268 $this->_disconnect();
274 function onStartShowBody($action)
276 $realtime = $action->boolean('realtime');
281 $action->elementStart('body',
282 (common_current_user()) ? array('id' => $action->trimmed('action'),
283 'class' => 'user_in realtime-popup')
284 : array('id' => $action->trimmed('action'),
285 'class'=> 'realtime-popup'));
287 // XXX hack to deal with JS that tries to get the
288 // root url from page output
290 $action->elementStart('address');
292 if (common_config('singleuser', 'enabled')) {
293 $user = User::singleUser();
294 $url = common_local_url('showstream', array('nickname' => $user->nickname));
296 $url = common_local_url('public');
299 $action->element('a', array('class' => 'url',
303 $action->elementEnd('address');
305 $action->showContentBlock();
306 $action->showScripts();
307 $action->elementEnd('body');
308 return false; // No default processing
311 function noticeAsJson($notice)
313 // FIXME: this code should be abstracted to a neutral third
314 // party, like Notice::asJson(). I'm not sure of the ethics
315 // of refactoring from within a plugin, so I'm just abusing
316 // the ApiAction method. Don't do this unless you're me!
318 $act = new ApiAction('/dev/null');
320 $arr = $act->twitterStatusArray($notice, true);
321 $arr['url'] = $notice->getUrl();
322 $arr['html'] = htmlspecialchars($notice->rendered);
323 $arr['source'] = htmlspecialchars($arr['source']);
324 $arr['conversation_url'] = $notice->getConversationUrl();
326 $profile = $notice->getProfile();
327 $arr['user']['profile_url'] = $profile->profileurl;
329 // Add needed repeat data
331 if (!empty($notice->repeat_of)) {
332 $original = Notice::getKV('id', $notice->repeat_of);
333 if ($original instanceof Notice) {
334 $arr['retweeted_status']['url'] = $original->getUrl();
335 $arr['retweeted_status']['html'] = htmlspecialchars($original->rendered);
336 $arr['retweeted_status']['source'] = htmlspecialchars($original->source);
337 $originalProfile = $original->getProfile();
338 $arr['retweeted_status']['user']['profile_url'] = $originalProfile->profileurl;
339 $arr['retweeted_status']['conversation_url'] = $original->getConversationUrl();
347 function getNoticeTags($notice)
351 $nt = new Notice_tag();
352 $nt->notice_id = $notice->id;
356 while ($nt->fetch()) {
367 function _getScripts()
369 $urlpath = self::staticPath(str_replace('Plugin','',__CLASS__),
370 'js/realtimeupdate.js');
371 return array($urlpath);
375 * Export any i18n messages that need to be loaded at runtime...
377 * @param Action $action
378 * @param array $messages
380 * @return boolean hook return value
382 function onEndScriptMessages($action, &$messages)
384 // TRANS: Text label for realtime view "play" button, usually replaced by an icon.
385 $messages['realtime_play'] = _m('BUTTON', 'Play');
386 // TRANS: Tooltip for realtime view "play" button.
387 $messages['realtime_play_tooltip'] = _m('TOOLTIP', 'Play');
388 // TRANS: Text label for realtime view "pause" button
389 $messages['realtime_pause'] = _m('BUTTON', 'Pause');
390 // TRANS: Tooltip for realtime view "pause" button
391 $messages['realtime_pause_tooltip'] = _m('TOOLTIP', 'Pause');
392 // TRANS: Text label for realtime view "popup" button, usually replaced by an icon.
393 $messages['realtime_popup'] = _m('BUTTON', 'Pop up');
394 // TRANS: Tooltip for realtime view "popup" button.
395 $messages['realtime_popup_tooltip'] = _m('TOOLTIP', 'Pop up in a window');
400 function _updateInitialize($timeline, $user_id)
402 return "RealtimeUpdate.init($user_id, \"$this->showurl\"); ";
409 function _publish($timeline, $json)
413 function _disconnect()
417 function _pathToChannel($path)
423 function _getTimeline($action)
425 $channel = $this->_getChannel($action);
426 if (empty($channel)) {
430 return $this->_pathToChannel(array($channel->channel_key));
433 function _getChannel($action)
439 $action_name = $action->trimmed('action');
443 // FIXME: profile + tag
445 switch ($action_name) {
450 $tag = $action->trimmed('tag');
454 $this->log(LOG_NOTICE, "Unexpected 'tag' action without tag argument");
462 $nickname = common_canonical_nickname($action->trimmed('nickname'));
463 if (!empty($nickname)) {
466 $this->log(LOG_NOTICE, "Unexpected $action_name action without nickname argument.");
474 $user = common_current_user();
476 $user_id = (!empty($user)) ? $user->id : null;
478 $channel = Realtime_channel::getChannel($user_id,
486 function onStartReadWriteTables(&$alwaysRW, &$rwdb)
488 $alwaysRW[] = 'realtime_channel';