]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/OStatus/lib/ostatusqueuehandler.php
Merge commit 'refs/merge-requests/164' of git://gitorious.org/statusnet/mainline...
[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::staticGet('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         $this->pushUser();
64
65         foreach ($notice->getGroups() as $group) {
66             $oprofile = Ostatus_profile::staticGet('group_id', $group->id);
67             if ($oprofile) {
68                 $this->pingReply($oprofile);
69             } else {
70                 $this->pushGroup($group->id);
71             }
72         }
73         
74         foreach ($notice->getReplies() as $profile_id) {
75             $oprofile = Ostatus_profile::staticGet('profile_id', $profile_id);
76             if ($oprofile) {
77                 $this->pingReply($oprofile);
78             }
79         }
80
81         if (!empty($this->notice->reply_to)) {
82             $replyTo = Notice::staticGet('id', $this->notice->reply_to);
83             if (!empty($replyTo)) {
84                 foreach($replyTo->getReplies() as $profile_id) {
85                     $oprofile = Ostatus_profile::staticGet('profile_id', $profile_id);
86                     if ($oprofile) {
87                         $this->pingReply($oprofile);
88                     }
89                 }
90             }
91         }
92
93         foreach ($notice->getProfileTags() as $ptag) {
94             $oprofile = Ostatus_profile::staticGet('peopletag_id', $ptag->id);
95             if (!$oprofile) {
96                 $this->pushPeopletag($ptag);
97             }
98         }
99
100         return true;
101     }
102
103     function pushUser()
104     {
105         if ($this->user) {
106             // For local posts, ping the PuSH hub to update their feed.
107             // http://identi.ca/api/statuses/user_timeline/1.atom
108             $feed = common_local_url('ApiTimelineUser',
109                                      array('id' => $this->user->id,
110                                            'format' => 'atom'));
111             $this->pushFeed($feed, array($this, 'userFeedForNotice'));
112         }
113     }
114
115     function pushGroup($group_id)
116     {
117         // For a local group, ping the PuSH hub to update its feed.
118         // Updates may come from either a local or a remote user.
119         $feed = common_local_url('ApiTimelineGroup',
120                                  array('id' => $group_id,
121                                        'format' => 'atom'));
122         $this->pushFeed($feed, array($this, 'groupFeedForNotice'), $group_id);
123     }
124
125     function pushPeopletag($ptag)
126     {
127         // For a local people tag, ping the PuSH hub to update its feed.
128         // Updates may come from either a local or a remote user.
129         $feed = common_local_url('ApiTimelineList',
130                                  array('id' => $ptag->id,
131                                        'user' => $ptag->tagger,
132                                        'format' => 'atom'));
133         $this->pushFeed($feed, array($this, 'peopletagFeedForNotice'), $ptag);
134     }
135
136     function pingReply($oprofile)
137     {
138         if ($this->user) {
139             // For local posts, send a Salmon ping to the mentioned
140             // remote user or group.
141             // @fixme as an optimization we can skip this if the
142             // remote profile is subscribed to the author.
143             $oprofile->notifyDeferred($this->notice, $this->user);
144         }
145     }
146
147     /**
148      * @param string $feed URI to the feed
149      * @param callable $callback function to generate Atom feed update if needed
150      *        any additional params are passed to the callback.
151      */
152     function pushFeed($feed, $callback)
153     {
154         $hub = common_config('ostatus', 'hub');
155         if ($hub) {
156             $this->pushFeedExternal($feed, $hub);
157         }
158
159         $sub = new HubSub();
160         $sub->topic = $feed;
161         if ($sub->find()) {
162             $args = array_slice(func_get_args(), 2);
163             $atom = call_user_func_array($callback, $args);
164             $this->pushFeedInternal($atom, $sub);
165         } else {
166             common_log(LOG_INFO, "No PuSH subscribers for $feed");
167         }
168         return true;
169     }
170
171     /**
172      * Ping external hub about this update.
173      * The hub will pull the feed and check for new items later.
174      * Not guaranteed safe in an environment with database replication.
175      *
176      * @param string $feed feed topic URI
177      * @param string $hub PuSH hub URI
178      * @fixme can consolidate pings for user & group posts
179      */
180     function pushFeedExternal($feed, $hub)
181     {
182         $client = new HTTPClient();
183         try {
184             $data = array('hub.mode' => 'publish',
185                           'hub.url' => $feed);
186             $response = $client->post($hub, array(), $data);
187             if ($response->getStatus() == 204) {
188                 common_log(LOG_INFO, "PuSH ping to hub $hub for $feed ok");
189                 return true;
190             } else {
191                 common_log(LOG_ERR, "PuSH ping to hub $hub for $feed failed with HTTP " .
192                                     $response->getStatus() . ': ' .
193                                     $response->getBody());
194             }
195         } catch (Exception $e) {
196             common_log(LOG_ERR, "PuSH ping to hub $hub for $feed failed: " . $e->getMessage());
197             return false;
198         }
199     }
200
201     /**
202      * Queue up direct feed update pushes to subscribers on our internal hub.
203      * If there are a large number of subscriber sites, intermediate bulk
204      * distribution triggers may be queued.
205      *
206      * @param string $atom update feed, containing only new/changed items
207      * @param HubSub $sub open query of subscribers
208      */
209     function pushFeedInternal($atom, $sub)
210     {
211         common_log(LOG_INFO, "Preparing $sub->N PuSH distribution(s) for $sub->topic");
212         $n = 0;
213         $batch = array();
214         while ($sub->fetch()) {
215             $n++;
216             if ($n < self::MAX_UNBATCHED) {
217                 $sub->distribute($atom);
218             } else {
219                 $batch[] = $sub->callback;
220                 if (count($batch) >= self::BATCH_SIZE) {
221                     $sub->bulkDistribute($atom, $batch);
222                     $batch = array();
223                 }
224             }
225         }
226         if (count($batch) >= 0) {
227             $sub->bulkDistribute($atom, $batch);
228         }
229     }
230
231     /**
232      * Build a single-item version of the sending user's Atom feed.
233      * @return string
234      */
235     function userFeedForNotice()
236     {
237         $atom = new AtomUserNoticeFeed($this->user);
238         $atom->addEntryFromNotice($this->notice);
239         $feed = $atom->getString();
240
241         return $feed;
242     }
243
244     function groupFeedForNotice($group_id)
245     {
246         $group = User_group::staticGet('id', $group_id);
247
248         $atom = new AtomGroupNoticeFeed($group);
249         $atom->addEntryFromNotice($this->notice);
250         $feed = $atom->getString();
251
252         return $feed;
253     }
254
255     function peopletagFeedForNotice($ptag)
256     {
257         $atom = new AtomListNoticeFeed($ptag);
258         $atom->addEntryFromNotice($this->notice);
259         $feed = $atom->getString();
260
261         return $feed;
262     }
263 }