ostatusqueuehandler.php 11 KB

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