]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/ostatusqueuehandler.php
Merge remote-tracking branch 'upstream/master' into social-master
[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 if (!defined('STATUSNET')) {
21     exit(1);
22 }
23
24 /**
25  * Prepare PuSH and Salmon distributions for an outgoing message.
26  *
27  * @package OStatusPlugin
28  * @author Brion Vibber <brion@status.net>
29  */
30 class OStatusQueueHandler extends QueueHandler
31 {
32     // If we have more than this many subscribing sites on a single feed,
33     // break up the PuSH distribution into smaller batches which will be
34     // rolled into the queue progressively. This reduces disruption to
35     // other, shorter activities being enqueued while we work.
36     const MAX_UNBATCHED = 50;
37
38     // Each batch (a 'hubprep' entry) will have this many items.
39     // Selected to provide a balance between queue packet size
40     // and number of batches that will end up getting processed.
41     // For 20,000 target sites, 1000 should work acceptably.
42     const BATCH_SIZE = 1000;
43
44     function transport()
45     {
46         return 'ostatus';
47     }
48
49     function handle($notice)
50     {
51         assert($notice instanceof Notice);
52
53         $this->notice = $notice;
54         $this->user = User::getKV('id', $notice->profile_id);
55
56         try {
57             $profile = $this->notice->getProfile();
58         } catch (Exception $e) {
59             common_log(LOG_ERR, "Can't get profile for notice; skipping: " . $e->getMessage());
60             return true;
61         }
62
63         if ($notice->isLocal()) {
64             // Notices generated on remote sites will have already
65             // been pushed to user's subscribers by their origin sites.
66             $this->pushUser();
67         }
68
69         foreach ($notice->getGroups() as $group) {
70             $oprofile = Ostatus_profile::getKV('group_id', $group->id);
71             if ($oprofile) {
72                 // remote group
73                 if ($notice->isLocal()) {
74                     $this->pingReply($oprofile);
75                 }
76             } else {
77                 // local group
78                 $this->pushGroup($group->id);
79             }
80         }
81
82         if ($notice->isLocal()) {
83             // Notices generated on other sites will have already
84             // pinged their reply-targets.
85
86             foreach ($notice->getReplies() as $profile_id) {
87                 $oprofile = Ostatus_profile::getKV('profile_id', $profile_id);
88                 if ($oprofile) {
89                     $this->pingReply($oprofile);
90                 }
91             }
92
93             if (!empty($this->notice->reply_to)) {
94                 $replyTo = Notice::getKV('id', $this->notice->reply_to);
95                 if (!empty($replyTo)) {
96                     foreach($replyTo->getReplies() as $profile_id) {
97                         $oprofile = Ostatus_profile::getKV('profile_id', $profile_id);
98                         if ($oprofile) {
99                             $this->pingReply($oprofile);
100                         }
101                     }
102                 }
103             }
104
105             foreach ($notice->getProfileTags() as $ptag) {
106                 $oprofile = Ostatus_profile::getKV('peopletag_id', $ptag->id);
107                 if (!$oprofile) {
108                     $this->pushPeopletag($ptag);
109                 }
110             }
111         }
112
113         return true;
114     }
115
116     function pushUser()
117     {
118         if ($this->user) {
119             // For local posts, ping the PuSH hub to update their feed.
120             // http://identi.ca/api/statuses/user_timeline/1.atom
121             $feed = common_local_url('ApiTimelineUser',
122                                      array('id' => $this->user->id,
123                                            'format' => 'atom'));
124             $this->pushFeed($feed, array($this, 'userFeedForNotice'));
125         }
126     }
127
128     function pushGroup($group_id)
129     {
130         // For a local group, ping the PuSH hub to update its feed.
131         // Updates may come from either a local or a remote user.
132         $feed = common_local_url('ApiTimelineGroup',
133                                  array('id' => $group_id,
134                                        'format' => 'atom'));
135         $this->pushFeed($feed, array($this, 'groupFeedForNotice'), $group_id);
136     }
137
138     function pushPeopletag($ptag)
139     {
140         // For a local people tag, ping the PuSH hub to update its feed.
141         // Updates may come from either a local or a remote user.
142         $feed = common_local_url('ApiTimelineList',
143                                  array('id' => $ptag->id,
144                                        'user' => $ptag->tagger,
145                                        'format' => 'atom'));
146         $this->pushFeed($feed, array($this, 'peopletagFeedForNotice'), $ptag);
147     }
148
149     function pingReply(OStatus_profile $oprofile)
150     {
151         if ($this->user) {
152             // For local posts, send a Salmon ping to the mentioned
153             // remote user or group.
154             // @fixme as an optimization we can skip this if the
155             // remote profile is subscribed to the author.
156             $oprofile->notifyDeferred($this->notice, $this->user->getProfile());
157         }
158     }
159
160     /**
161      * @param string $feed URI to the feed
162      * @param callable $callback function to generate Atom feed update if needed
163      *        any additional params are passed to the callback.
164      */
165     function pushFeed($feed, $callback)
166     {
167         $hub = common_config('ostatus', 'hub');
168         if ($hub) {
169             $this->pushFeedExternal($feed, $hub);
170         }
171
172         $sub = new HubSub();
173         $sub->topic = $feed;
174         if ($sub->find()) {
175             $args = array_slice(func_get_args(), 2);
176             $atom = call_user_func_array($callback, $args);
177             $this->pushFeedInternal($atom, $sub);
178         } else {
179             common_log(LOG_INFO, "No PuSH subscribers for $feed");
180         }
181         return true;
182     }
183
184     /**
185      * Ping external hub about this update.
186      * The hub will pull the feed and check for new items later.
187      * Not guaranteed safe in an environment with database replication.
188      *
189      * @param string $feed feed topic URI
190      * @param string $hub PuSH hub URI
191      * @fixme can consolidate pings for user & group posts
192      */
193     function pushFeedExternal($feed, $hub)
194     {
195         $client = new HTTPClient();
196         try {
197             $data = array('hub.mode' => 'publish',
198                           'hub.url' => $feed);
199             $response = $client->post($hub, array(), $data);
200             if ($response->getStatus() == 204) {
201                 common_log(LOG_INFO, "PuSH ping to hub $hub for $feed ok");
202                 return true;
203             } else {
204                 common_log(LOG_ERR, "PuSH ping to hub $hub for $feed failed with HTTP " .
205                                     $response->getStatus() . ': ' .
206                                     $response->getBody());
207             }
208         } catch (Exception $e) {
209             common_log(LOG_ERR, "PuSH ping to hub $hub for $feed failed: " . $e->getMessage());
210             return false;
211         }
212     }
213
214     /**
215      * Queue up direct feed update pushes to subscribers on our internal hub.
216      * If there are a large number of subscriber sites, intermediate bulk
217      * distribution triggers may be queued.
218      *
219      * @param string $atom update feed, containing only new/changed items
220      * @param HubSub $sub open query of subscribers
221      */
222     function pushFeedInternal($atom, $sub)
223     {
224         common_log(LOG_INFO, "Preparing $sub->N PuSH distribution(s) for $sub->topic");
225         $n = 0;
226         $batch = array();
227         while ($sub->fetch()) {
228             $n++;
229             if ($n < self::MAX_UNBATCHED) {
230                 $sub->distribute($atom);
231             } else {
232                 $batch[] = $sub->callback;
233                 if (count($batch) >= self::BATCH_SIZE) {
234                     $sub->bulkDistribute($atom, $batch);
235                     $batch = array();
236                 }
237             }
238         }
239         if (count($batch) >= 0) {
240             $sub->bulkDistribute($atom, $batch);
241         }
242     }
243
244     /**
245      * Build a single-item version of the sending user's Atom feed.
246      * @return string
247      */
248     function userFeedForNotice()
249     {
250         $atom = new AtomUserNoticeFeed($this->user);
251         $atom->addEntryFromNotice($this->notice);
252         $feed = $atom->getString();
253
254         return $feed;
255     }
256
257     function groupFeedForNotice($group_id)
258     {
259         $group = User_group::getKV('id', $group_id);
260
261         $atom = new AtomGroupNoticeFeed($group);
262         $atom->addEntryFromNotice($this->notice);
263         $feed = $atom->getString();
264
265         return $feed;
266     }
267
268     function peopletagFeedForNotice($ptag)
269     {
270         $atom = new AtomListNoticeFeed($ptag);
271         $atom->addEntryFromNotice($this->notice);
272         $feed = $atom->getString();
273
274         return $feed;
275     }
276 }