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 * @copyright 2009 StatusNet, Inc.
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://status.net/
30 if (!defined('STATUSNET')) {
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 $action->cssLink(Plugin::staticPath('Realtime', 'realtimeupdate.css'),
147 'screen, projection, tv');
151 function onHandleQueuedNotice($notice)
155 // Add to the author's timeline
158 $profile = $notice->getProfile();
159 } catch (Exception $e) {
160 $this->log(LOG_ERR, $e->getMessage());
164 $user = User::getKV('id', $notice->profile_id);
167 $paths[] = array('showstream', $user->nickname, null);
170 // Add to the public timeline
172 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
173 ($notice->is_local == Notice::REMOTE && !common_config('public', 'localonly'))) {
174 $paths[] = array('public', null, null);
177 // Add to the tags timeline
179 $tags = $this->getNoticeTags($notice);
182 foreach ($tags as $tag) {
183 $paths[] = array('tag', $tag, null);
187 // Add to inbox timelines
190 $ni = $notice->whoGets();
192 foreach (array_keys($ni) as $user_id) {
193 $user = User::getKV('id', $user_id);
194 $paths[] = array('all', $user->nickname, null);
197 // Add to the replies timeline
199 $reply = new Reply();
200 $reply->notice_id = $notice->id;
202 if ($reply->find()) {
203 while ($reply->fetch()) {
204 $user = User::getKV('id', $reply->profile_id);
206 $paths[] = array('replies', $user->nickname, null);
211 // Add to the group timeline
214 $gi = new Group_inbox();
215 $gi->notice_id = $notice->id;
218 while ($gi->fetch()) {
219 $ug = User_group::getKV('id', $gi->group_id);
220 $paths[] = array('showgroup', $ug->nickname, null);
224 if (count($paths) > 0) {
226 $json = $this->noticeAsJson($notice);
230 // XXX: We should probably fan-out here and do a
231 // new queue item for each path
233 foreach ($paths as $path) {
235 list($action, $arg1, $arg2) = $path;
237 $channels = Realtime_channel::getAllChannels($action, $arg1, $arg2);
238 $this->log(LOG_INFO, sprintf(_("%d candidate channels for notice %d"),
242 foreach ($channels as $channel) {
244 // XXX: We should probably fan-out here and do a
245 // new queue item for each user/path combo
247 if (is_null($channel->user_id)) {
250 $profile = Profile::getKV('id', $channel->user_id);
252 if ($notice->inScope($profile)) {
254 sprintf(_("Delivering notice %d to channel (%s, %s, %s) for user '%s'"),
259 ($profile) ? ($profile->nickname) : "<public>"));
260 $timeline = $this->_pathToChannel(array($channel->channel_key));
261 $this->_publish($timeline, $json);
266 $this->_disconnect();
272 function onStartShowBody($action)
274 $realtime = $action->boolean('realtime');
279 $action->elementStart('body',
280 (common_current_user()) ? array('id' => $action->trimmed('action'),
281 'class' => 'user_in realtime-popup')
282 : array('id' => $action->trimmed('action'),
283 'class'=> 'realtime-popup'));
285 // XXX hack to deal with JS that tries to get the
286 // root url from page output
288 $action->elementStart('address');
290 if (common_config('singleuser', 'enabled')) {
291 $user = User::singleUser();
292 $url = common_local_url('showstream', array('nickname' => $user->nickname));
294 $url = common_local_url('public');
297 $action->element('a', array('class' => 'url',
301 $action->elementEnd('address');
303 $action->showContentBlock();
304 $action->showScripts();
305 $action->elementEnd('body');
306 return false; // No default processing
309 function noticeAsJson($notice)
311 // FIXME: this code should be abstracted to a neutral third
312 // party, like Notice::asJson(). I'm not sure of the ethics
313 // of refactoring from within a plugin, so I'm just abusing
314 // the ApiAction method. Don't do this unless you're me!
316 $act = new ApiAction('/dev/null');
318 $arr = $act->twitterStatusArray($notice, true);
319 $arr['url'] = $notice->bestUrl();
320 $arr['html'] = htmlspecialchars($notice->rendered);
321 $arr['source'] = htmlspecialchars($arr['source']);
322 $arr['conversation_url'] = $this->getConversationUrl($notice);
324 $profile = $notice->getProfile();
325 $arr['user']['profile_url'] = $profile->profileurl;
327 // Add needed repeat data
329 if (!empty($notice->repeat_of)) {
330 $original = Notice::getKV('id', $notice->repeat_of);
331 if (!empty($original)) {
332 $arr['retweeted_status']['url'] = $original->bestUrl();
333 $arr['retweeted_status']['html'] = htmlspecialchars($original->rendered);
334 $arr['retweeted_status']['source'] = htmlspecialchars($original->source);
335 $originalProfile = $original->getProfile();
336 $arr['retweeted_status']['user']['profile_url'] = $originalProfile->profileurl;
337 $arr['retweeted_status']['conversation_url'] = $this->getConversationUrl($original);
345 function getNoticeTags($notice)
349 $nt = new Notice_tag();
350 $nt->notice_id = $notice->id;
354 while ($nt->fetch()) {
365 function getConversationUrl($notice)
369 if ($notice->hasConversation()) {
370 $conv = Conversation::getKV(
372 $notice->conversation
374 $convurl = $conv->uri;
376 if(empty($convurl)) {
377 $msg = sprintf( "Could not find Conversation ID %d to make 'in context'"
378 . "link for Notice ID %d.",
379 $notice->conversation,
383 common_log(LOG_WARNING, $msg);
385 $convurl .= '#notice-' . $notice->id;
392 function _getScripts()
394 if (common_config('site', 'minify')) {
395 $js = 'realtimeupdate.min.js';
397 $js = 'realtimeupdate.js';
399 return array(Plugin::staticPath('Realtime', $js));
403 * Export any i18n messages that need to be loaded at runtime...
405 * @param Action $action
406 * @param array $messages
408 * @return boolean hook return value
410 function onEndScriptMessages($action, &$messages)
412 // TRANS: Text label for realtime view "play" button, usually replaced by an icon.
413 $messages['realtime_play'] = _m('BUTTON', 'Play');
414 // TRANS: Tooltip for realtime view "play" button.
415 $messages['realtime_play_tooltip'] = _m('TOOLTIP', 'Play');
416 // TRANS: Text label for realtime view "pause" button
417 $messages['realtime_pause'] = _m('BUTTON', 'Pause');
418 // TRANS: Tooltip for realtime view "pause" button
419 $messages['realtime_pause_tooltip'] = _m('TOOLTIP', 'Pause');
420 // TRANS: Text label for realtime view "popup" button, usually replaced by an icon.
421 $messages['realtime_popup'] = _m('BUTTON', 'Pop up');
422 // TRANS: Tooltip for realtime view "popup" button.
423 $messages['realtime_popup_tooltip'] = _m('TOOLTIP', 'Pop up in a window');
428 function _updateInitialize($timeline, $user_id)
430 return "RealtimeUpdate.init($user_id, \"$this->showurl\"); ";
437 function _publish($timeline, $json)
441 function _disconnect()
445 function _pathToChannel($path)
451 function _getTimeline($action)
453 $channel = $this->_getChannel($action);
454 if (empty($channel)) {
458 return $this->_pathToChannel(array($channel->channel_key));
461 function _getChannel($action)
467 $action_name = $action->trimmed('action');
471 // FIXME: profile + tag
473 switch ($action_name) {
478 $tag = $action->trimmed('tag');
482 $this->log(LOG_NOTICE, "Unexpected 'tag' action without tag argument");
490 $nickname = common_canonical_nickname($action->trimmed('nickname'));
491 if (!empty($nickname)) {
494 $this->log(LOG_NOTICE, "Unexpected $action_name action without nickname argument.");
502 $user = common_current_user();
504 $user_id = (!empty($user)) ? $user->id : null;
506 $channel = Realtime_channel::getChannel($user_id,
514 function onStartReadWriteTables(&$alwaysRW, &$rwdb)
516 $alwaysRW[] = 'realtime_channel';