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
40 * Currently depends on Favorite plugin.
44 * @author Evan Prodromou <evan@status.net>
45 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
46 * @link http://status.net/
48 class RealtimePlugin extends Plugin
50 protected $showurl = null;
53 * When it's time to initialize the plugin, calculate and
54 * pass the URLs we need.
56 function onInitializePlugin()
58 // FIXME: need to find a better way to pass this pattern in
59 $this->showurl = common_local_url('shownotice',
60 array('notice' => '0000000000'));
64 function onCheckSchema()
66 $schema = Schema::get();
67 $schema->ensureTable('realtime_channel', Realtime_channel::schemaDef());
72 * Hook for RouterInitialized event.
74 * @param URLMapper $m path-to-action mapper
75 * @return boolean hook return
77 public function onRouterInitialized(URLMapper $m)
79 $m->connect('main/channel/:channelkey/keepalive',
80 array('action' => 'keepalivechannel'),
81 array('channelkey' => '[a-z0-9]{32}'));
82 $m->connect('main/channel/:channelkey/close',
83 array('action' => 'closechannel'),
84 array('channelkey' => '[a-z0-9]{32}'));
88 function onEndShowScripts($action)
90 $channel = $this->_getChannel($action);
92 if (empty($channel)) {
96 $timeline = $this->_pathToChannel(array($channel->channel_key));
98 // If there's not a timeline on this page,
101 if (empty($timeline)) {
105 $base = $action->selfUrl();
106 if (mb_strstr($base, '?')) {
107 $url = $base . '&realtime=1';
109 $url = $base . '?realtime=1';
112 $scripts = $this->_getScripts();
114 foreach ($scripts as $script) {
115 $action->script($script);
118 $user = common_current_user();
120 if (!empty($user->id)) {
121 $user_id = $user->id;
126 if ($action->boolean('realtime')) {
127 $realtimeUI = ' RealtimeUpdate.initPopupWindow();';
130 $pluginPath = common_path('plugins/Realtime/');
131 $keepalive = common_local_url('keepalivechannel', array('channelkey' => $channel->channel_key));
132 $close = common_local_url('closechannel', array('channelkey' => $channel->channel_key));
133 $realtimeUI = ' RealtimeUpdate.initActions('.json_encode($url).', '.json_encode($timeline).', '.json_encode($pluginPath).', '.json_encode($keepalive).', '.json_encode($close).'); ';
136 $script = ' $(document).ready(function() { '.
138 $this->_updateInitialize($timeline, $user_id).
140 $action->inlineScript($script);
145 public function onEndShowStylesheets(Action $action)
147 $urlpath = self::staticPath(str_replace('Plugin','',__CLASS__),
148 'css/realtimeupdate.css');
149 $action->cssLink($urlpath, null, 'screen, projection, tv');
153 public function onHandleQueuedNotice(Notice $notice)
157 // Add to the author's timeline
160 $profile = $notice->getProfile();
161 } catch (Exception $e) {
162 $this->log(LOG_ERR, $e->getMessage());
167 $user = $profile->getUser();
168 $paths[] = array('showstream', $user->nickname, null);
169 } catch (NoSuchUserException $e) {
170 // We really should handle the remote profile views too
174 // Add to the public timeline
176 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
177 ($notice->is_local == Notice::REMOTE && !common_config('public', 'localonly'))) {
178 $paths[] = array('public', null, null);
181 // Add to the tags timeline
183 $tags = $this->getNoticeTags($notice);
186 foreach ($tags as $tag) {
187 $paths[] = array('tag', $tag, null);
191 // Add to inbox timelines
194 $ni = $notice->whoGets();
196 foreach (array_keys($ni) as $user_id) {
197 $user = User::getKV('id', $user_id);
198 $paths[] = array('all', $user->nickname, null);
201 // Add to the replies timeline
203 $reply = new Reply();
204 $reply->notice_id = $notice->id;
206 if ($reply->find()) {
207 while ($reply->fetch()) {
208 $user = User::getKV('id', $reply->profile_id);
210 $paths[] = array('replies', $user->nickname, null);
215 // Add to the group timeline
218 $gi = new Group_inbox();
219 $gi->notice_id = $notice->id;
222 while ($gi->fetch()) {
223 $ug = User_group::getKV('id', $gi->group_id);
224 $paths[] = array('showgroup', $ug->nickname, null);
228 if (count($paths) > 0) {
230 $json = $this->noticeAsJson($notice);
234 // XXX: We should probably fan-out here and do a
235 // new queue item for each path
237 foreach ($paths as $path) {
239 list($action, $arg1, $arg2) = $path;
241 $channels = Realtime_channel::getAllChannels($action, $arg1, $arg2);
242 $this->log(LOG_INFO, sprintf(_("%d candidate channels for notice %d"),
246 foreach ($channels as $channel) {
248 // XXX: We should probably fan-out here and do a
249 // new queue item for each user/path combo
251 if (is_null($channel->user_id)) {
254 $profile = Profile::getKV('id', $channel->user_id);
256 if ($notice->inScope($profile)) {
258 sprintf(_("Delivering notice %d to channel (%s, %s, %s) for user '%s'"),
263 ($profile) ? ($profile->nickname) : "<public>"));
264 $timeline = $this->_pathToChannel(array($channel->channel_key));
265 $this->_publish($timeline, $json);
270 $this->_disconnect();
276 function onStartShowBody($action)
278 $realtime = $action->boolean('realtime');
283 $action->elementStart('body',
284 (common_current_user()) ? array('id' => $action->trimmed('action'),
285 'class' => 'user_in realtime-popup')
286 : array('id' => $action->trimmed('action'),
287 'class'=> 'realtime-popup'));
289 // XXX hack to deal with JS that tries to get the
290 // root url from page output
292 $action->elementStart('address');
294 if (common_config('singleuser', 'enabled')) {
295 $user = User::singleUser();
296 $url = common_local_url('showstream', array('nickname' => $user->nickname));
298 $url = common_local_url('public');
301 $action->element('a', array('class' => 'url',
305 $action->elementEnd('address');
307 $action->showContentBlock();
308 $action->showScripts();
309 $action->elementEnd('body');
310 return false; // No default processing
313 function noticeAsJson($notice)
315 // FIXME: this code should be abstracted to a neutral third
316 // party, like Notice::asJson(). I'm not sure of the ethics
317 // of refactoring from within a plugin, so I'm just abusing
318 // the ApiAction method. Don't do this unless you're me!
320 $act = new ApiAction('/dev/null');
322 $arr = $act->twitterStatusArray($notice, true);
323 $arr['url'] = $notice->getUrl(true);
324 $arr['html'] = htmlspecialchars($notice->rendered);
325 $arr['source'] = htmlspecialchars($arr['source']);
326 $arr['conversation_url'] = $notice->getConversationUrl();
328 $profile = $notice->getProfile();
329 $arr['user']['profile_url'] = $profile->profileurl;
331 // Add needed repeat data
333 if (!empty($notice->repeat_of)) {
334 $original = Notice::getKV('id', $notice->repeat_of);
335 if ($original instanceof Notice) {
336 $arr['retweeted_status']['url'] = $original->getUrl(true);
337 $arr['retweeted_status']['html'] = htmlspecialchars($original->rendered);
338 $arr['retweeted_status']['source'] = htmlspecialchars($original->source);
339 $originalProfile = $original->getProfile();
340 $arr['retweeted_status']['user']['profile_url'] = $originalProfile->profileurl;
341 $arr['retweeted_status']['conversation_url'] = $original->getConversationUrl();
349 function getNoticeTags($notice)
353 $nt = new Notice_tag();
354 $nt->notice_id = $notice->id;
358 while ($nt->fetch()) {
369 function _getScripts()
371 $urlpath = self::staticPath(str_replace('Plugin','',__CLASS__),
372 'js/realtimeupdate.js');
373 return array($urlpath);
377 * Export any i18n messages that need to be loaded at runtime...
379 * @param Action $action
380 * @param array $messages
382 * @return boolean hook return value
384 function onEndScriptMessages($action, &$messages)
386 // TRANS: Text label for realtime view "play" button, usually replaced by an icon.
387 $messages['realtime_play'] = _m('BUTTON', 'Play');
388 // TRANS: Tooltip for realtime view "play" button.
389 $messages['realtime_play_tooltip'] = _m('TOOLTIP', 'Play');
390 // TRANS: Text label for realtime view "pause" button
391 $messages['realtime_pause'] = _m('BUTTON', 'Pause');
392 // TRANS: Tooltip for realtime view "pause" button
393 $messages['realtime_pause_tooltip'] = _m('TOOLTIP', 'Pause');
394 // TRANS: Text label for realtime view "popup" button, usually replaced by an icon.
395 $messages['realtime_popup'] = _m('BUTTON', 'Pop up');
396 // TRANS: Tooltip for realtime view "popup" button.
397 $messages['realtime_popup_tooltip'] = _m('TOOLTIP', 'Pop up in a window');
402 function _updateInitialize($timeline, $user_id)
404 return "RealtimeUpdate.init($user_id, \"$this->showurl\"); ";
411 function _publish($timeline, $json)
415 function _disconnect()
419 function _pathToChannel($path)
425 function _getTimeline($action)
427 $channel = $this->_getChannel($action);
428 if (empty($channel)) {
432 return $this->_pathToChannel(array($channel->channel_key));
435 function _getChannel($action)
441 $action_name = $action->trimmed('action');
445 // FIXME: profile + tag
447 switch ($action_name) {
452 $tag = $action->trimmed('tag');
456 $this->log(LOG_NOTICE, "Unexpected 'tag' action without tag argument");
464 $nickname = common_canonical_nickname($action->trimmed('nickname'));
465 if (!empty($nickname)) {
468 $this->log(LOG_NOTICE, "Unexpected $action_name action without nickname argument.");
476 $user = common_current_user();
478 $user_id = (!empty($user)) ? $user->id : null;
480 $channel = Realtime_channel::getChannel($user_id,
488 function onStartReadWriteTables(&$alwaysRW, &$rwdb)
490 $alwaysRW[] = 'realtime_channel';