]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/ostatusqueuehandler.php
Merge branch '0.9.x' into activityexport
[quix0rs-gnu-social.git] / plugins / OStatus / lib / ostatusqueuehandler.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 /**
21  * Prepare PuSH and Salmon distributions for an outgoing message.
22  *
23  * @package OStatusPlugin
24  * @author Brion Vibber <brion@status.net>
25  */
26 class OStatusQueueHandler extends QueueHandler
27 {
28     // If we have more than this many subscribing sites on a single feed,
29     // break up the PuSH distribution into smaller batches which will be
30     // rolled into the queue progressively. This reduces disruption to
31     // other, shorter activities being enqueued while we work.
32     const MAX_UNBATCHED = 50;
33
34     // Each batch (a 'hubprep' entry) will have this many items.
35     // Selected to provide a balance between queue packet size
36     // and number of batches that will end up getting processed.
37     // For 20,000 target sites, 1000 should work acceptably.
38     const BATCH_SIZE = 1000;
39
40     function transport()
41     {
42         return 'ostatus';
43     }
44
45     function handle($notice)
46     {
47         assert($notice instanceof Notice);
48
49         $this->notice = $notice;
50         $this->user = User::staticGet($notice->profile_id);
51
52         $this->pushUser();
53
54         foreach ($notice->getGroups() as $group) {
55             $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
56             if ($oprofile) {
57                 $this->pingReply($oprofile);
58             } else {
59                 $this->pushGroup($group->id);
60             }
61         }
62
63         foreach ($notice->getReplies() as $profile_id) {
64             $oprofile = Ostatus_profile::staticGet('profile_id', $profile_id);
65             if ($oprofile) {
66                 $this->pingReply($oprofile);
67             }
68         }
69
70         if (!empty($this->notice->reply_to)) {
71             $replyTo = Notice::staticGet('id', $this->notice->reply_to);
72             if (!empty($replyTo)) {
73                 foreach($replyTo->getReplies() as $profile_id) {
74                     $oprofile = Ostatus_profile::staticGet('profile_id', $profile_id);
75                     if ($oprofile) {
76                         $this->pingReply($oprofile);
77                     }
78                 }
79             }
80         }
81         return true;
82     }
83
84     function pushUser()
85     {
86         if ($this->user) {
87             // For local posts, ping the PuSH hub to update their feed.
88             // http://identi.ca/api/statuses/user_timeline/1.atom
89             $feed = common_local_url('ApiTimelineUser',
90                                      array('id' => $this->user->id,
91                                            'format' => 'atom'));
92             $this->pushFeed($feed, array($this, 'userFeedForNotice'));
93         }
94     }
95
96     function pushGroup($group_id)
97     {
98         // For a local group, ping the PuSH hub to update its feed.
99         // Updates may come from either a local or a remote user.
100         $feed = common_local_url('ApiTimelineGroup',
101                                  array('id' => $group_id,
102                                        'format' => 'atom'));
103         $this->pushFeed($feed, array($this, 'groupFeedForNotice'), $group_id);
104     }
105
106     function pingReply($oprofile)
107     {
108         if ($this->user) {
109             // For local posts, send a Salmon ping to the mentioned
110             // remote user or group.
111             // @fixme as an optimization we can skip this if the
112             // remote profile is subscribed to the author.
113             $oprofile->notifyDeferred($this->notice, $this->user);
114         }
115     }
116
117     /**
118      * @param string $feed URI to the feed
119      * @param callable $callback function to generate Atom feed update if needed
120      *        any additional params are passed to the callback.
121      */
122     function pushFeed($feed, $callback)
123     {
124         $hub = common_config('ostatus', 'hub');
125         if ($hub) {
126             $this->pushFeedExternal($feed, $hub);
127         }
128
129         $sub = new HubSub();
130         $sub->topic = $feed;
131         if ($sub->find()) {
132             $args = array_slice(func_get_args(), 2);
133             $atom = call_user_func_array($callback, $args);
134             $this->pushFeedInternal($atom, $sub);
135         } else {
136             common_log(LOG_INFO, "No PuSH subscribers for $feed");
137         }
138         return true;
139     }
140
141     /**
142      * Ping external hub about this update.
143      * The hub will pull the feed and check for new items later.
144      * Not guaranteed safe in an environment with database replication.
145      *
146      * @param string $feed feed topic URI
147      * @param string $hub PuSH hub URI
148      * @fixme can consolidate pings for user & group posts
149      */
150     function pushFeedExternal($feed, $hub)
151     {
152         $client = new HTTPClient();
153         try {
154             $data = array('hub.mode' => 'publish',
155                           'hub.url' => $feed);
156             $response = $client->post($hub, array(), $data);
157             if ($response->getStatus() == 204) {
158                 common_log(LOG_INFO, "PuSH ping to hub $hub for $feed ok");
159                 return true;
160             } else {
161                 common_log(LOG_ERR, "PuSH ping to hub $hub for $feed failed with HTTP " .
162                                     $response->getStatus() . ': ' .
163                                     $response->getBody());
164             }
165         } catch (Exception $e) {
166             common_log(LOG_ERR, "PuSH ping to hub $hub for $feed failed: " . $e->getMessage());
167             return false;
168         }
169     }
170
171     /**
172      * Queue up direct feed update pushes to subscribers on our internal hub.
173      * If there are a large number of subscriber sites, intermediate bulk
174      * distribution triggers may be queued.
175      *
176      * @param string $atom update feed, containing only new/changed items
177      * @param HubSub $sub open query of subscribers
178      */
179     function pushFeedInternal($atom, $sub)
180     {
181         common_log(LOG_INFO, "Preparing $sub->N PuSH distribution(s) for $sub->topic");
182         $n = 0;
183         $batch = array();
184         while ($sub->fetch()) {
185             $n++;
186             if ($n < self::MAX_UNBATCHED) {
187                 $sub->distribute($atom);
188             } else {
189                 $batch[] = $sub->callback;
190                 if (count($batch) >= self::BATCH_SIZE) {
191                     $sub->bulkDistribute($atom, $batch);
192                     $batch = array();
193                 }
194             }
195         }
196         if (count($batch) >= 0) {
197             $sub->bulkDistribute($atom, $batch);
198         }
199     }
200
201     /**
202      * Build a single-item version of the sending user's Atom feed.
203      * @return string
204      */
205     function userFeedForNotice()
206     {
207         $atom = new AtomUserNoticeFeed($this->user);
208         $atom->addEntryFromNotice($this->notice);
209         $feed = $atom->getString();
210
211         return $feed;
212     }
213
214     function groupFeedForNotice($group_id)
215     {
216         $group = User_group::staticGet('id', $group_id);
217
218         $atom = new AtomGroupNoticeFeed($group);
219         $atom->addEntryFromNotice($this->notice);
220         $feed = $atom->getString();
221
222         return $feed;
223     }
224 }