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') && !defined('LACONICA')) {
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.
55 function onInitializePlugin()
57 // FIXME: need to find a better way to pass this pattern in
58 $this->showurl = common_local_url('shownotice',
59 array('notice' => '0000000000'));
63 function onCheckSchema()
65 $schema = Schema::get();
66 $schema->ensureTable('realtime_channel', Realtime_channel::schemaDef());
70 function onAutoload($cls)
72 $dir = dirname(__FILE__);
76 case 'KeepalivechannelAction':
77 case 'ClosechannelAction':
78 include_once $dir . '/' . strtolower(mb_substr($cls, 0, -6)) . '.php';
80 case 'Realtime_channel':
81 include_once $dir.'/'.$cls.'.php';
89 * Hook for RouterInitialized event.
91 * @param Net_URL_Mapper $m path-to-action mapper
92 * @return boolean hook return
94 function onRouterInitialized($m)
96 $m->connect('main/channel/:channelkey/keepalive',
97 array('action' => 'keepalivechannel'),
98 array('channelkey' => '[a-z0-9]{32}'));
99 $m->connect('main/channel/:channelkey/close',
100 array('action' => 'closechannel'),
101 array('channelkey' => '[a-z0-9]{32}'));
105 function onEndShowScripts($action)
107 $channel = $this->_getChannel($action);
109 if (empty($channel)) {
113 $timeline = $this->_pathToChannel(array($channel->channel_key));
115 // If there's not a timeline on this page,
118 if (empty($timeline)) {
122 $base = $action->selfUrl();
123 if (mb_strstr($base, '?')) {
124 $url = $base . '&realtime=1';
126 $url = $base . '?realtime=1';
129 $scripts = $this->_getScripts();
131 foreach ($scripts as $script) {
132 $action->script($script);
135 $user = common_current_user();
137 if (!empty($user->id)) {
138 $user_id = $user->id;
143 if ($action->boolean('realtime')) {
144 $realtimeUI = ' RealtimeUpdate.initPopupWindow();';
147 $pluginPath = common_path('plugins/Realtime/');
148 $keepalive = common_local_url('keepalivechannel', array('channelkey' => $channel->channel_key));
149 $close = common_local_url('closechannel', array('channelkey' => $channel->channel_key));
150 $realtimeUI = ' RealtimeUpdate.initActions("'.$url.'", "'.$timeline.'", "'. $pluginPath .'", "'.$keepalive.'", "'.$close.'"); ';
153 $script = ' $(document).ready(function() { '.
155 $this->_updateInitialize($timeline, $user_id).
157 $action->inlineScript($script);
162 function onEndShowStatusNetStyles($action)
164 $action->cssLink(Plugin::staticPath('Realtime', 'realtimeupdate.css'),
166 'screen, projection, tv');
170 function onHandleQueuedNotice($notice)
174 // Add to the author's timeline
176 $user = User::staticGet('id', $notice->profile_id);
179 $paths[] = array('showstream', $user->nickname, null);
182 // Add to the public timeline
184 if ($notice->is_local == Notice::LOCAL_PUBLIC ||
185 ($notice->is_local == Notice::REMOTE_OMB && !common_config('public', 'localonly'))) {
186 $paths[] = array('public', null, null);
189 // Add to the tags timeline
191 $tags = $this->getNoticeTags($notice);
194 foreach ($tags as $tag) {
195 $paths[] = array('tag', $tag, null);
199 // Add to inbox timelines
202 $ni = $notice->whoGets();
204 foreach (array_keys($ni) as $user_id) {
205 $user = User::staticGet('id', $user_id);
206 $paths[] = array('all', $user->nickname, null);
209 // Add to the replies timeline
211 $reply = new Reply();
212 $reply->notice_id = $notice->id;
214 if ($reply->find()) {
215 while ($reply->fetch()) {
216 $user = User::staticGet('id', $reply->profile_id);
218 $paths[] = array('replies', $user->nickname, null);
223 // Add to the group timeline
226 $gi = new Group_inbox();
227 $gi->notice_id = $notice->id;
230 while ($gi->fetch()) {
231 $ug = User_group::staticGet('id', $gi->group_id);
232 $paths[] = array('showgroup', $ug->nickname, null);
236 if (count($paths) > 0) {
238 $json = $this->noticeAsJson($notice);
242 // XXX: We should probably fan-out here and do a
243 // new queue item for each path
245 foreach ($paths as $path) {
247 list($action, $arg1, $arg2) = $path;
249 $channels = Realtime_channel::getAllChannels($action, $arg1, $arg2);
251 foreach ($channels as $channel) {
253 // XXX: We should probably fan-out here and do a
254 // new queue item for each user/path combo
256 if (is_null($channel->user_id)) {
259 $profile = Profile::staticGet('id', $channel->user_id);
261 if ($notice->inScope($profile)) {
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');
291 $action->element('a', array('class' => 'url',
292 'href' => common_local_url('public')),
294 $action->elementEnd('address');
296 $action->showContentBlock();
297 $action->showScripts();
298 $action->elementEnd('body');
299 return false; // No default processing
302 function noticeAsJson($notice)
304 // FIXME: this code should be abstracted to a neutral third
305 // party, like Notice::asJson(). I'm not sure of the ethics
306 // of refactoring from within a plugin, so I'm just abusing
307 // the ApiAction method. Don't do this unless you're me!
309 $act = new ApiAction('/dev/null');
311 $arr = $act->twitterStatusArray($notice, true);
312 $arr['url'] = $notice->bestUrl();
313 $arr['html'] = htmlspecialchars($notice->rendered);
314 $arr['source'] = htmlspecialchars($arr['source']);
315 $arr['conversation_url'] = $this->getConversationUrl($notice);
317 $profile = $notice->getProfile();
318 $arr['user']['profile_url'] = $profile->profileurl;
320 // Add needed repeat data
322 if (!empty($notice->repeat_of)) {
323 $original = Notice::staticGet('id', $notice->repeat_of);
324 if (!empty($original)) {
325 $arr['retweeted_status']['url'] = $original->bestUrl();
326 $arr['retweeted_status']['html'] = htmlspecialchars($original->rendered);
327 $arr['retweeted_status']['source'] = htmlspecialchars($original->source);
328 $originalProfile = $original->getProfile();
329 $arr['retweeted_status']['user']['profile_url'] = $originalProfile->profileurl;
330 $arr['retweeted_status']['conversation_url'] = $this->getConversationUrl($original);
338 function getNoticeTags($notice)
342 $nt = new Notice_tag();
343 $nt->notice_id = $notice->id;
347 while ($nt->fetch()) {
358 function getConversationUrl($notice)
362 if ($notice->hasConversation()) {
363 $conv = Conversation::staticGet(
365 $notice->conversation
367 $convurl = $conv->uri;
369 if(empty($convurl)) {
371 "Couldn't find Conversation ID %d to make 'in context'"
372 . "link for Notice ID %d",
373 $notice->conversation,
377 common_log(LOG_WARNING, $msg);
379 $convurl .= '#notice-' . $notice->id;
386 function _getScripts()
388 if (common_config('site', 'minify')) {
389 $js = 'realtimeupdate.min.js';
391 $js = 'realtimeupdate.js';
393 return array(Plugin::staticPath('Realtime', $js));
397 * Export any i18n messages that need to be loaded at runtime...
399 * @param Action $action
400 * @param array $messages
402 * @return boolean hook return value
404 function onEndScriptMessages($action, &$messages)
406 // TRANS: Text label for realtime view "play" button, usually replaced by an icon.
407 $messages['realtime_play'] = _m('BUTTON', 'Play');
408 // TRANS: Tooltip for realtime view "play" button.
409 $messages['realtime_play_tooltip'] = _m('TOOLTIP', 'Play');
410 // TRANS: Text label for realtime view "pause" button
411 $messages['realtime_pause'] = _m('BUTTON', 'Pause');
412 // TRANS: Tooltip for realtime view "pause" button
413 $messages['realtime_pause_tooltip'] = _m('TOOLTIP', 'Pause');
414 // TRANS: Text label for realtime view "popup" button, usually replaced by an icon.
415 $messages['realtime_popup'] = _m('BUTTON', 'Pop up');
416 // TRANS: Tooltip for realtime view "popup" button.
417 $messages['realtime_popup_tooltip'] = _m('TOOLTIP', 'Pop up in a window');
422 function _updateInitialize($timeline, $user_id)
424 return "RealtimeUpdate.init($user_id, \"$this->showurl\"); ";
431 function _publish($timeline, $json)
435 function _disconnect()
439 function _pathToChannel($path)
445 function _getTimeline($action)
447 $channel = $this->_getChannel($action);
448 if (empty($channel)) {
452 return $this->_pathToChannel(array($channel->channel_key));
455 function _getChannel($action)
461 $action_name = $action->trimmed('action');
465 // FIXME: profile + tag
467 switch ($action_name) {
472 $tag = $action->trimmed('tag');
476 $this->log(LOG_NOTICE, "Unexpected 'tag' action without tag argument");
484 $nickname = common_canonical_nickname($action->trimmed('nickname'));
485 if (!empty($nickname)) {
488 $this->log(LOG_NOTICE, "Unexpected $action_name action without nickname argument.");
496 $user = common_current_user();
498 $user_id = (!empty($user)) ? $user->id : null;
500 $channel = Realtime_channel::getChannel($user_id,
508 function onStartReadWriteTables(&$alwaysRW, &$rwdb)
510 $alwaysRW[] = 'realtime_channel';