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