]> git.mxchange.org Git - quix0rs-gnu-social.git/commitdiff
Changes to make plugin use database instead of polling session readiness
authorLuke Fitzgerald <lw.fitzgerald@googlemail.com>
Sat, 31 Jul 2010 00:12:35 +0000 (17:12 -0700)
committerLuke Fitzgerald <lw.fitzgerald@googlemail.com>
Sat, 31 Jul 2010 00:12:35 +0000 (17:12 -0700)
plugins/Msn/MsnPlugin.php
plugins/Msn/extlib/phpmsnclass/msn.class.php
plugins/Msn/msn_waiting_message.php [new file with mode: 0644]
plugins/Msn/msnmanager.php

index 2d31f997589327a2b235bf82164aca80919b48d6..3d9f19c0a5d7441ec62ab4fc4c175d6ce5e150d7 100644 (file)
@@ -106,6 +106,7 @@ class MsnPlugin extends ImPlugin {
                 require_once(INSTALLDIR.'/plugins/Msn/extlib/phpmsnclass/msn.class.php');\r
                 return false;\r
             case 'MsnManager':\r
+            case 'Msn_waiting_message':\r
                 include_once $dir . '/'.strtolower($cls).'.php';\r
                 return false;\r
             default:\r
@@ -124,6 +125,25 @@ class MsnPlugin extends ImPlugin {
         return true;\r
     }\r
 \r
+    /**\r
+    * Ensure the database table is present\r
+    *\r
+    */\r
+    public function onCheckSchema() {\r
+        $schema = Schema::get();\r
+\r
+        // For storing messages while sessions become ready\r
+        $schema->ensureTable('msn_waiting_message',\r
+                             array(new ColumnDef('id', 'integer', null,\r
+                                                 false, 'PRI', null, null, true),\r
+                                   new ColumnDef('screenname', 'integer', null, false),\r
+                                   new ColumnDef('message', 'text', null, false),\r
+                                   new ColumnDef('created', 'datetime', null, false),\r
+                                   new ColumnDef('claimed', 'datetime')));\r
+\r
+        return true;\r
+    }\r
+\r
     /**\r
     * Get a microid URI for the given screenname\r
     *\r
index 9766a363768737cca2f927dd043285c862b8f75d..9abdce1b618a26a3a77814ff2737241cb3a859af 100644 (file)
@@ -949,7 +949,10 @@ class MSN {
                 // SB: <<< IRO {id} {rooster} {roostercount} {email} {alias} {clientid}\r
                 @list(/* IRO */, /* id */, $cur_num, $total, $email, $alias, $clientid) = @explode(' ', $data);\r
                 $this->debug_message("*** $email joined session");\r
-                $session['joined'] = true;\r
+                if ($email == $session['to']) {\r
+                    $session['joined'] = true;\r
+                    $this->callHandler('SessionReady', array('to' => $email));\r
+                }\r
                 break;\r
             case 'BYE':\r
                 $this->debug_message("*** Quit for BYE");\r
@@ -970,9 +973,11 @@ class MSN {
             case 'JOI':\r
                 // SB: <<< JOI {user} {alias} {clientid?}\r
                 // someone join us\r
-                // we don't need the data, just ignore it\r
-                // no more user here\r
-                $session['joined'] = true;\r
+                @list(/* JOI */, $email) = @explode(' ', $data);\r
+                if ($email == $session['to']) {\r
+                    $session['joined'] = true;\r
+                    $this->callHandler('SessionReady', array('to' => $email));\r
+                }\r
                 break;\r
             case 'MSG':\r
                 // SB: <<< MSG {email} {alias} {len}\r
@@ -1478,6 +1483,7 @@ class MSN {
 \r
             if ($this->sb_writeln($socket, $id, "MSG $id N $len") === false ||\r
                 $this->sb_writedata($socket, $SendString) === false) {\r
+                    $this->endSBSession($socket);\r
                     return false;\r
                 }\r
         }\r
@@ -1485,6 +1491,7 @@ class MSN {
 \r
         if ($this->sb_writeln($socket, $id, "MSG $id N $len") === false ||\r
             $this->sb_writedata($socket, $aMessage) === false) {\r
+                $this->endSBSession($socket);\r
                 return false;\r
             }\r
 \r
@@ -1518,8 +1525,14 @@ class MSN {
      *                   where network is 1 for MSN, 32 for Yahoo\r
      *                   and 'Offline' for offline messages\r
      * @param string $message Message\r
+     * @param boolean &$waitForSession Boolean passed by reference,\r
+     *                                 if set to true on return, message\r
+     *                                 did not fail to send but is\r
+     *                                 waiting for a valid session\r
+     *\r
+     * @return boolean true on success\r
      */\r
-    public function sendMessage($to, $message) {\r
+    public function sendMessage($to, $message, &$waitForSession) {\r
         if ($message != '') {\r
             $toParts = explode('@', $to);\r
             if(count($toParts) < 3) {\r
@@ -1537,6 +1550,8 @@ class MSN {
                         $this->debug_message("*** No existing SB session or request has timed out");\r
                         $this->reqSBSession($recipient);\r
                     }\r
+\r
+                    $waitForSession = true;\r
                     return false;\r
                 } else {\r
                     $socket = $this->switchBoardSessionLookup[$recipient];\r
@@ -1544,10 +1559,12 @@ class MSN {
                     if ($this->switchBoardSessions[$intsocket]['offline']) {\r
                         $this->debug_message("*** Contact ($recipient) offline, sending OIM");\r
                         $this->endSBSession($socket);\r
+                        $waitForSession = false;\r
                         return $this->sendMessage($recipient.'@Offline', $message);\r
                     } else {\r
                         if ($this->switchBoardSessions[$intsocket]['joined'] !== true) {\r
                             $this->debug_message("*** Recipient has not joined session, returning false");\r
+                            $waitForSession = true;\r
                             return false;\r
                         }\r
 \r
@@ -1558,6 +1575,7 @@ class MSN {
                             return true;\r
                         }\r
 \r
+                        $waitForSession = false;\r
                         return false;\r
                     }\r
                 }\r
@@ -3100,7 +3118,7 @@ X-OIM-Sequence-Num: 1
      * Registers a user handler\r
      *\r
      * Handler List\r
-     * IMIn, Pong, ConnectFailed, Reconnect,\r
+     * IMIn, SessionReady, Pong, ConnectFailed, Reconnect,\r
      * AddedToList, RemovedFromList, StatusChange\r
      *\r
      * @param string $event Event name\r
diff --git a/plugins/Msn/msn_waiting_message.php b/plugins/Msn/msn_waiting_message.php
new file mode 100644 (file)
index 0000000..0efd8b0
--- /dev/null
@@ -0,0 +1,73 @@
+<?php\r
+/**\r
+ * Table Definition for msn_plugin_message\r
+ */\r
+require_once INSTALLDIR.'/classes/Memcached_DataObject.php';\r
+\r
+class Msn_waiting_message extends Memcached_DataObject {\r
+\r
+    public $__table = 'msn_waiting_message'; // table name\r
+    public $id;                              // int primary_key not_null auto_increment\r
+    public $screenname;                      // varchar(255) not_null\r
+    public $message;                         // text not_null\r
+    public $created;                         // datetime() not_null\r
+    public $claimed;                         // datetime()\r
+\r
+    /* Static get */\r
+    public function staticGet($k, $v = null) {\r
+        return Memcached_DataObject::staticGet('Msn_waiting_message', $k, $v);\r
+    }\r
+\r
+    /**\r
+     * @param mixed $screenname screenname or array of screennames to pull from\r
+     *                          If not specified, checks all queues in the system.\r
+     */\r
+    public static function top($screenname = null) {\r
+        $wm = new Msn_waiting_message();\r
+        if ($screenname) {\r
+            if (is_array($screenname)) {\r
+                // @fixme use safer escaping\r
+                $list = implode("','", array_map('addslashes', $transports));\r
+                $wm->whereAdd("screename in ('$list')");\r
+            } else {\r
+                $wm->screenname = $screenname;\r
+            }\r
+        }\r
+        $wm->orderBy('created');\r
+        $wm->whereAdd('claimed is null');\r
+\r
+        $wm->limit(1);\r
+\r
+        $cnt = $wm->find(true);\r
+\r
+        if ($cnt) {\r
+            # XXX: potential race condition\r
+            # can we force it to only update if claimed is still null\r
+            # (or old)?\r
+            common_log(LOG_INFO, 'claiming msn waiting message id = ' . $wm->id);\r
+            $orig = clone($wm);\r
+            $wm->claimed = common_sql_now();\r
+            $result = $wm->update($orig);\r
+            if ($result) {\r
+                common_log(LOG_INFO, 'claim succeeded.');\r
+                return $wm;\r
+            } else {\r
+                common_log(LOG_INFO, 'claim failed.');\r
+            }\r
+        }\r
+        $wm = null;\r
+        return null;\r
+    }\r
+\r
+    /**\r
+     * Release a claimed item.\r
+     */\r
+    public function releaseClaim() {\r
+        // DB_DataObject doesn't let us save nulls right now\r
+        $sql = sprintf("UPDATE msn_waiting_message SET claimed=NULL WHERE id=%d", $this->id);\r
+        $this->query($sql);\r
+\r
+        $this->claimed = null;\r
+        $this->encache();\r
+    }\r
+}\r
index b62bbd7ad8bb73bfdb95ac03a21087b4c8593f23..9014501e7ee72438b935e36524e0aa86100c76c1 100644 (file)
@@ -113,6 +113,7 @@ class MsnManager extends ImManager {
                 )\r
             );\r
             $this->conn->registerHandler('IMin', array($this, 'handle_msn_message'));\r
+            $this->conn->registerHandler('SessionReady', array($this, 'handle_session_ready'));\r
             $this->conn->registerHandler('Pong', array($this, 'update_ping_time'));\r
             $this->conn->registerHandler('ConnectFailed', array($this, 'handle_connect_failed'));\r
             $this->conn->registerHandler('Reconnect', array($this, 'handle_reconnect'));\r
@@ -142,7 +143,7 @@ class MsnManager extends ImManager {
 \r
     /**\r
      * Update the time till the next ping\r
-     * \r
+     *\r
      * @param $data Time till next ping\r
      * @return void\r
      */\r
@@ -163,6 +164,22 @@ class MsnManager extends ImManager {
         return true;\r
     }\r
 \r
+    /**\r
+    * Called via a callback when a session becomes ready\r
+    *\r
+    * @param array $data Data\r
+    */\r
+    public function handle_session_ready($data) {\r
+        while (($wm = Msn_waiting_message::top($data['to']) != NULL)) {\r
+            if ($this->conn->sendMessage($wm->screenname, $wm->message, $ignore)) {\r
+                $wm->delete();\r
+            } else {\r
+                // Requeue the message in the regular queue\r
+                $this->plugin->send_message($wm->screenname, $wm->message);\r
+            }\r
+        }\r
+    }\r
+\r
     /**\r
     * Called by callback to log failure during connect\r
     *\r
@@ -182,11 +199,34 @@ class MsnManager extends ImManager {
     public function handle_reconnect($data) {\r
         common_log(LOG_NOTICE, 'MSN reconnecting');\r
     }\r
-    \r
+\r
+    /**\r
+    * Enters a message into the database for sending via a callback\r
+    * when the session is established\r
+    *\r
+    * @param string $to Intended recipient\r
+    * @param string $message Message\r
+    */\r
+    private function enqueue_waiting_message($to, $message) {\r
+        $wm = new Msn_waiting_message();\r
+\r
+        $wm->screenname = $to;\r
+        $wm->message    = $message;\r
+        $wm->created    = common_sql_now();\r
+        $result         = $wm->insert();\r
+\r
+        if (!$result) {\r
+            common_log_db_error($wm, 'INSERT', __FILE__);\r
+            throw new ServerException('DB error inserting queue item');\r
+        }\r
+\r
+        return true;\r
+    }\r
+\r
     /**\r
      * Send a message using the daemon\r
-     * \r
-     * @param $data Message\r
+     *\r
+     * @param $data Message data\r
      * @return boolean true on success\r
      */\r
     public function send_raw_message($data) {\r
@@ -195,10 +235,15 @@ class MsnManager extends ImManager {
             return false;\r
         }\r
 \r
-        if (!$this->conn->sendMessage($data['to'], $data['message'])) {\r
-            return false;\r
+        $waitForSession = false;\r
+        if (!$this->conn->sendMessage($data['to'], $data['message'], $waitForSession)) {\r
+            if ($waitForSession) {\r
+                $this->enqueue_waiting_message($data['to'], $data['message']);\r
+            } else {\r
+                return false;\r
+            }\r
         }\r
-        \r
+\r
         // Sending a command updates the time till next ping\r
         $this->lastping = time();\r
         $this->pingInterval = 50;\r