diff options
Diffstat (limited to 'plugins/Comet')
-rw-r--r-- | plugins/Comet/CometPlugin.php | 138 | ||||
-rw-r--r-- | plugins/Comet/bayeux.class.inc.php | 129 | ||||
-rw-r--r-- | plugins/Comet/bayeux.class.inc.phps | 123 | ||||
-rw-r--r-- | plugins/Comet/jquery.comet.js | 363 | ||||
-rw-r--r-- | plugins/Comet/updatetimeline.js | 3 |
5 files changed, 756 insertions, 0 deletions
diff --git a/plugins/Comet/CometPlugin.php b/plugins/Comet/CometPlugin.php new file mode 100644 index 000000000..10f8c198c --- /dev/null +++ b/plugins/Comet/CometPlugin.php @@ -0,0 +1,138 @@ +<?php +/** + * Laconica, the distributed open-source microblogging tool + * + * Plugin to do "real time" updates using Comet/Bayeux + * + * PHP version 5 + * + * LICENCE: This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see <http://www.gnu.org/licenses/>. + * + * @category Plugin + * @package Laconica + * @author Evan Prodromou <evan@controlyourself.ca> + * @copyright 2009 Control Yourself, Inc. + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + */ + +if (!defined('LACONICA')) { + exit(1); +} + +/** + * Plugin to do realtime updates using Comet + * + * @category Plugin + * @package Laconica + * @author Evan Prodromou <evan@controlyourself.ca> + * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0 + * @link http://laconi.ca/ + */ + +class CometPlugin extends Plugin +{ + var $server = null; + + function __construct($server=null) + { + $this->server = $server; + + parent::__construct(); + } + + function onEndShowScripts($action) + { + $timeline = null; + + switch ($action->trimmed('action')) { + case 'public': + $timeline = '/timelines/public'; + break; + default: + return true; + } + + $action->element('script', array('type' => 'text/javascript', + 'src' => common_path('plugins/Comet/jquery.comet.js')), + ' '); + $action->elementStart('script', array('type' => 'text/javascript')); + $action->raw("var _timelineServer = \"$this->server\"; ". + "var _timeline = \"$timeline\";"); + $action->elementEnd('script'); + $action->element('script', array('type' => 'text/javascript', + 'src' => common_path('plugins/Comet/updatetimeline.js')), + ' '); + return true; + } + + function onEndNoticeSave($notice) + { + $this->log(LOG_INFO, "Called for save notice."); + + $timelines = array(); + + // XXX: Add other timelines; this is just for the public one + + if ($notice->is_local || + ($notice->is_local == 0 && !common_config('public', 'localonly'))) { + $timelines[] = '/timelines/public'; + } + + if (count($timelines) > 0) { + // Require this, since we need it + require_once(INSTALLDIR.'/plugins/Comet/bayeux.class.inc.php'); + + $json = $this->noticeAsJson($notice); + + $this->log(LOG_DEBUG, "JSON = '$json'"); + + // Bayeux? Comet? Huh? These terms confuse me + $bay = new Bayeux($this->server); + + foreach ($timelines as $timeline) { + $this->log(LOG_INFO, "Posting notice $notice->id to '$timeline'."); + $bay->publish($timeline, $json); + $this->log(LOG_DEBUG, "Done posting notice $notice->id to '$timeline'."); + } + + $bay = NULL; + } + + $this->log(LOG_DEBUG, "All done."); + return true; + } + + function noticeAsJson($notice) + { + // FIXME: this code should be abstracted to a neutral third + // party, like Notice::asJson(). I'm not sure of the ethics + // of refactoring from within a plugin, so I'm just abusing + // the TwitterApiAction method. Don't do this unless you're me! + + require_once(INSTALLDIR.'/lib/twitterapi.php'); + + $act = new TwitterApiAction('/dev/null'); + + $arr = $act->twitter_status_array($notice, true); + return $arr; + } + + // Push this up to Plugin + + function log($level, $msg) + { + common_log($level, get_class($this) . ': '.$msg); + } +} diff --git a/plugins/Comet/bayeux.class.inc.php b/plugins/Comet/bayeux.class.inc.php new file mode 100644 index 000000000..602a7b644 --- /dev/null +++ b/plugins/Comet/bayeux.class.inc.php @@ -0,0 +1,129 @@ +<?php +/* + * + * Phomet: a php comet client + * + * Copyright (C) 2008 Morgan 'ARR!' Allen <morganrallen@gmail.com> http://morglog.alleycatracing.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +class Bayeux +{ + private $oCurl = ''; + private $nNextId = 0; + + public $sUrl = ''; + + function __construct($sUrl) + { + $this->sUrl = $sUrl; + + $this->oCurl = curl_init(); + + $aHeaders = array(); + $aHeaders[] = 'Connection: Keep-Alive'; + + curl_setopt($this->oCurl, CURLOPT_URL, $sUrl); + curl_setopt($this->oCurl, CURLOPT_HTTPHEADER, $aHeaders); + curl_setopt($this->oCurl, CURLOPT_HEADER, 0); + curl_setopt($this->oCurl, CURLOPT_POST, 1); + curl_setopt($this->oCurl, CURLOPT_RETURNTRANSFER,1); + + $this->handShake(); + } + + function __destruct() + { + $this->disconnect(); + } + + function handShake() + { + $msgHandshake = array(); + $msgHandshake['channel'] = '/meta/handshake'; + $msgHandshake['version'] = "1.0"; + $msgHandshake['minimumVersion'] = "0.9"; + $msgHandshake['supportedConnectionTypes'] = array('long-polling'); + $msgHandshake['id'] = $this->nNextId++; + + curl_setopt($this->oCurl, CURLOPT_POSTFIELDS, "message=".urlencode(str_replace('\\', '', json_encode(array($msgHandshake))))); + + $data = curl_exec($this->oCurl); + + if(curl_errno($this->oCurl)) + die("Error: " . curl_error($this->oCurl)); + + $oReturn = json_decode($data); + + common_debug(print_r($oReturn, true)); + + if (is_array($oReturn)) { + $oReturn = $oReturn[0]; + } + + $bSuccessful = ($oReturn->successful) ? true : false; + + if($bSuccessful) + { + $this->clientId = $oReturn->clientId; + + $this->connect(); + } + } + + public function connect() + { + $aMsg['channel'] = '/meta/connect'; + $aMsg['id'] = $this->nNextId++; + $aMsg['clientId'] = $this->clientId; + $aMsg['connectionType'] = 'long-polling'; + + curl_setopt($this->oCurl, CURLOPT_POSTFIELDS, "message=".urlencode(str_replace('\\', '', json_encode(array($aMsg))))); + + $data = curl_exec($this->oCurl); + } + + function disconnect() + { + $msgHandshake = array(); + $msgHandshake['channel'] = '/meta/disconnect'; + $msgHandshake['id'] = $this->nNextId++; + $msgHandshake['clientId'] = $this->clientId; + + curl_setopt($this->oCurl, CURLOPT_POSTFIELDS, "message=".urlencode(str_replace('\\', '', json_encode(array($msgHandshake))))); + + curl_exec($this->oCurl); + } + + public function publish($sChannel, $oData) + { + if(!$sChannel || !$oData) + return; + + $aMsg = array(); + + $aMsg['channel'] = $sChannel; + $aMsg['id'] = $this->nNextId++; + $aMsg['data'] = $oData; + $aMsg['clientId'] = $this->clientId; + + curl_setopt($this->oCurl, CURLOPT_POSTFIELDS, "message=".urlencode(str_replace('\\', '', json_encode(array($aMsg))))); + + $data = curl_exec($this->oCurl); +// var_dump($data); + } +} diff --git a/plugins/Comet/bayeux.class.inc.phps b/plugins/Comet/bayeux.class.inc.phps new file mode 100644 index 000000000..ea004a453 --- /dev/null +++ b/plugins/Comet/bayeux.class.inc.phps @@ -0,0 +1,123 @@ +<?php +/* + * + * Phomet: a php comet client + * + * Copyright (C) 2008 Morgan 'ARR!' Allen <morganrallen@gmail.com> http://morglog.alleycatracing.com + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + * + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + * + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA + * + */ + +class Bayeux + { + private $oCurl = ''; + private $nNextId = 0; + + public $sUrl = ''; + + function __construct($sUrl) + { + $this->sUrl = $sUrl; + + $this->oCurl = curl_init(); + + $aHeaders = array(); + $aHeaders[] = 'Connection: Keep-Alive'; + + curl_setopt($this->oCurl, CURLOPT_URL, $sUrl); + curl_setopt($this->oCurl, CURLOPT_HTTPHEADER, $aHeaders); + curl_setopt($this->oCurl, CURLOPT_HEADER, 0); + curl_setopt($this->oCurl, CURLOPT_POST, 1); + curl_setopt($this->oCurl, CURLOPT_RETURNTRANSFER,1); + + $this->handShake(); + } + + function __destruct() + { + $this->disconnect(); + } + + function handShake() + { + $msgHandshake = array(); + $msgHandshake['channel'] = '/meta/handshake'; + $msgHandshake['version'] = "1.0"; + $msgHandshake['minimumVersion'] = "0.9"; + $msgHandshake['id'] = $this->nNextId++; + + curl_setopt($this->oCurl, CURLOPT_POSTFIELDS, "message=".urlencode(str_replace('\\', '', json_encode(array($msgHandshake))))); + + $data = curl_exec($this->oCurl); + + if(curl_errno($this->oCurl)) + die("Error: " . curl_error($this->oCurl)); + + $oReturn = json_decode($data); + $oReturn = $oReturn[0]; + + $bSuccessful = ($oReturn->successful) ? true : false; + + if($bSuccessful) + { + $this->clientId = $oReturn->clientId; + + $this->connect(); + } + } + + public function connect() + { + $aMsg['channel'] = '/meta/connect'; + $aMsg['id'] = $this->nNextId++; + $aMsg['clientId'] = $this->clientId; + $aMsg['connectionType'] = 'long-polling'; + + curl_setopt($this->oCurl, CURLOPT_POSTFIELDS, "message=".urlencode(str_replace('\\', '', json_encode(array($aMsg))))); + + $data = curl_exec($this->oCurl); + } + + function disconnect() + { + $msgHandshake = array(); + $msgHandshake['channel'] = '/meta/disconnect'; + $msgHandshake['id'] = $this->nNextId++; + $msgHandshake['clientId'] = $this->clientId; + + curl_setopt($this->oCurl, CURLOPT_POSTFIELDS, "message=".urlencode(str_replace('\\', '', json_encode(array($msgHandshake))))); + + curl_exec($this->oCurl); + } + + public function publish($sChannel, $oData) + { + if(!$sChannel || !$oData) + return; + + $aMsg = array(); + + $aMsg['channel'] = $sChannel; + $aMsg['id'] = $this->nNextId++; + $aMsg['data'] = $oData; + $aMsg['clientId'] = $this->clientId; + + curl_setopt($this->oCurl, CURLOPT_POSTFIELDS, "message=".urlencode(str_replace('\\', '', json_encode(array($aMsg))))); + + $data = curl_exec($this->oCurl); +// var_dump($data); + } + } diff --git a/plugins/Comet/jquery.comet.js b/plugins/Comet/jquery.comet.js new file mode 100644 index 000000000..2124e882c --- /dev/null +++ b/plugins/Comet/jquery.comet.js @@ -0,0 +1,363 @@ +(function($)
+{
+ var msgHandshake =
+ {
+ version: '1.0',
+ minimumVersion: '0.9',
+ channel: '/meta/handshake'
+ };
+
+ var oTransport = function()
+ {
+ this._bXD =
+ (($.comet._sUrl.substring(0,4) == 'http') && ($.comet._sUrl.substr(7,location.href.length).replace(/\/.*/, '') != location.host))
+ ?
+ true
+ :false;
+
+ this.connectionType = (this._bXD) ? 'callback-polling' : 'long-polling';
+
+ this.startup = function(oReturn)
+ {
+ if(this._comet._bConnected) return;
+ this.tunnelInit();
+ };
+
+ this.tunnelInit = function()
+ {
+ var msgConnect =
+ {
+ channel: '/meta/connect',
+ clientId: $.comet.clientId,
+ id: String($.comet._nNextId++),
+ connectionType: $.comet._oTransport.connectionType
+ };
+
+ this.openTunnel(msgConnect);
+ };
+
+ this.openTunnel = function(oMsg)
+ {
+ $.comet._bPolling = true;
+
+ this._send($.comet._sUrl, oMsg, function(sReturn)
+ {
+ var oReturn = (typeof sReturn != "object") ? (eval('(' + sReturn + ')')) : sReturn;
+ $.comet._bPolling = false;
+ $.comet.deliver(oReturn);
+ $.comet._oTransport.closeTunnel();
+ });
+ };
+
+ this.closeTunnel = function()
+ {
+ if(!$.comet._bInitialized) return;
+
+ if($.comet._advice)
+ {
+ if($.comet._advice.reconnect == 'none') return;
+
+ if($.comet._advice.interval > 0)
+ {
+ setTimeout($.comet._oTransport._connect, $.comet._advice.interval);
+ }
+ else
+ {
+ $.comet._oTransport._connect();
+ }
+ }
+ else
+ {
+ $.comet._oTransport._connect();
+ }
+ };
+
+ this._connect = function()
+ {
+ if(!$.comet._bInitialized) return;
+
+ if($.comet._bPolling) return;
+
+ if($.comet._advice && $.comet._advice.reconnect == 'handshake')
+ {
+ $.comet._bConnected = false;
+ $.comet.init($.comet._sUrl);
+ }
+ else if($.comet._bConnected)
+ {
+ var msgConnect =
+ {
+ //jsonp: 'test',
+ clientId: $.comet.clientId,
+ id: String($.comet._nNextId++),
+ channel: '/meta/connect',
+ connectionType: $.comet._oTransport.connectionType
+ };
+ $.comet._oTransport.openTunnel(msgConnect);
+ }
+ };
+
+ this._send = function(sUrl, oMsg, fCallback) {
+ //default callback will check advice, deliver messages, and reconnect
+ var fCallback = (fCallback) ? fCallback : function(sReturn)
+ {
+ var oReturn = (typeof sReturn != "object") ? (eval('(' + sReturn + ')')) : sReturn;
+
+ $.comet.deliver(oReturn);
+
+ if($.comet._advice)
+ {
+ if($.comet._advice.reconnect == 'none')
+ return;
+
+ if($.comet._advice.interval > 0)
+ {
+ setTimeout($.comet._oTransport._connect, $.comet._advice.interval);
+ }
+ else
+ {
+ $.comet._oTransport._connect();
+ }
+ }
+ else
+ {
+ $.comet._oTransport._connect();
+ }
+ };
+
+ //regular AJAX for same domain calls
+ if((!this._bXD) && (this.connectionType == 'long-polling'))
+ {
+ this._pollRequest = $.ajax({
+ url: sUrl,
+ type: 'post',
+ beforeSend: function(oXhr) { oXhr.setRequestHeader('Connection', 'Keep-Alive'); },
+ data: { message: JSON.stringify(oMsg) },
+ success: fCallback
+ });
+ }
+ else // JSONP callback for cross domain
+ {
+ this._pollRequest = $.ajax({
+ url: sUrl,
+ dataType: 'jsonp',
+ jsonp: 'jsonp',
+ beforeSend: function(oXhr) { oXhr.setRequestHeader('Connection', 'Keep-Alive'); },
+ data:
+ {
+ message: JSON.stringify($.extend(oMsg,{connectionType: 'callback-polling' }))
+ },
+ success: fCallback
+ });
+ }
+ }
+ };
+
+ $.comet = new function()
+ {
+ this.CONNECTED = 'CONNECTED';
+ this.CONNECTING = 'CONNECTING';
+ this.DISCONNECTED = 'DISCONNECTED';
+ this.DISCONNECTING = 'DISCONNECTING';
+
+ this._aMessageQueue = [];
+ this._aSubscriptions = [];
+ this._aSubscriptionCallbacks = [];
+ this._bInitialized = false;
+ this._bConnected = false;
+ this._nBatch = 0;
+ this._nNextId = 0;
+ // just define the transport, do not assign it yet.
+ this._oTransport = ''; //oTransport;
+ this._sUrl = '';
+
+ this.supportedConectionTypes = [ 'long-polling', 'callback-polling' ];
+
+ this.clientId = '';
+
+ this._bTrigger = true; // this sends $.event.trigger(channel, data)
+
+ this.init = function(sUrl)
+ {
+ this._sUrl = (sUrl) ? sUrl : '/cometd';
+
+ this._oTransport = new oTransport();
+
+ this._aMessageQueue = [];
+ this._aSubscriptions = [];
+ this._bInitialized = true;
+ this.startBatch();
+
+ var oMsg = $.extend(msgHandshake, {id: String(this._nNextId++)});
+
+ this._oTransport._send(this._sUrl, oMsg, $.comet._finishInit);
+ };
+
+ this._finishInit = function(sReturn)
+ {
+ var oReturn = (typeof sReturn != "object") ? (eval('(' + sReturn + ')')[0]) : sReturn[0];
+
+ if(oReturn.advice)
+ $.comet._advice = oReturn.advice;
+
+ var bSuccess = (oReturn.successful) ? oReturn.successful : false;
+ // do version check
+
+ if(bSuccess)
+ {
+ // pick transport ?
+ // ......
+
+ $.comet._oTransport._comet = $.comet;
+ $.comet._oTransport.version = $.comet.version;
+
+ $.comet.clientId = oReturn.clientId;
+ $.comet._oTransport.startup(oReturn);
+ $.comet.endBatch();
+ }
+ };
+
+ this._sendMessage = function(oMsg)
+ {
+ if($.comet._nBatch <= 0)
+ {
+ if(oMsg.length > 0)
+ for(var i in oMsg)
+ {
+ oMsg[i].clientId = String($.comet.clientId);
+ oMsg[i].id = String($.comet._nNextId++);
+ }
+ else
+ {
+ oMsg.clientId = String($.comet.clientId);
+ oMsg.id = String($.comet._nNextId++);
+ }
+
+ $.comet._oTransport._send($.comet._sUrl, oMsg);
+ }
+ else
+ {
+ $.comet._aMessageQueue.push(oMsg);
+ }
+ };
+
+
+ this.startBatch = function() { this._nBatch++ };
+ this.endBatch = function() {
+ if(--this._nBatch <= 0)
+ {
+ this._nBatch = 0;
+ if(this._aMessageQueue.length > 0)
+ {
+ this._sendMessage(this._aMessageQueue);
+ this._aMessageQueue = [];
+ }
+ }
+ };
+
+ this.subscribe = function(sSubscription, fCallback)
+ {
+ // if this topic has not been subscribed to yet, send the message now
+ if(!this._aSubscriptions[sSubscription])
+ {
+ this._aSubscriptions.push(sSubscription)
+
+ if (fCallback) {
+ this._aSubscriptionCallbacks[sSubscription] = fCallback;
+ }
+
+ this._sendMessage({ channel: '/meta/subscribe', subscription: sSubscription });
+ }
+
+ //$.event.add(window, sSubscription, fCallback);
+ };
+
+ this.unsubscribe = function(sSubscription) {
+ $.comet._sendMessage({ channel: '/meta/unsubscribe', subscription: sSubscription });
+ };
+
+ this.publish = function(sChannel, oData)
+ {
+ $.comet._sendMessage({channel: sChannel, data: oData});
+ };
+
+ this.deliver = function(sReturn)
+ {
+ var oReturn = sReturn;//eval(sReturn);
+
+ $(oReturn).each(function()
+ {
+ $.comet._deliver(this);
+ });
+ };
+
+ this.disconnect = function()
+ {
+ $($.comet._aSubscriptions).each(function(i)
+ {
+ $.comet.unsubscribe($.comet._aSubscriptions[i]);
+ });
+
+ $.comet._sendMessage({channel:'/meta/disconnect'});
+
+ $.comet._bInitialized = false;
+ }
+
+ this._deliver = function(oMsg,oData)
+ {
+ if(oMsg.advice)
+ {
+ $.comet._advice = oMsg.advice;
+ }
+
+ switch(oMsg.channel)
+ {
+ case '/meta/connect':
+ if(oMsg.successful && !$.comet._bConnected)
+ {
+ $.comet._bConnected = $.comet._bInitialized;
+ $.comet.endBatch();
+ /*
+ $.comet._sendMessage(msgConnect);
+ */
+ }
+ else
+ {}
+ //$.comet._bConnected = false;
+ break;
+
+ // add in subscription handling stuff
+ case '/meta/subscribe':
+ if(!oMsg.successful)
+ {
+ $.comet._oTransport._cancelConnect();
+ return;
+ }
+ break;
+
+ case '/meta/unsubscribe':
+ if(!oMsg.successful)
+ {
+ $.comet._oTransport._cancelConnect();
+ return;
+ }
+ break;
+
+ }
+
+ if(oMsg.data)
+ {
+ if($.comet._bTrigger)
+ {
+ $.event.trigger(oMsg.channel, [oMsg]);
+ }
+
+ var cb = $.comet._aSubscriptionCallbacks[oMsg.channel];
+ if (cb) {
+ cb(oMsg);
+ }
+ }
+ };
+};
+
+})(jQuery);
diff --git a/plugins/Comet/updatetimeline.js b/plugins/Comet/updatetimeline.js new file mode 100644 index 000000000..f4da1f47c --- /dev/null +++ b/plugins/Comet/updatetimeline.js @@ -0,0 +1,3 @@ +// update the local timeline from a Comet server +// + |