ostatusqueuehandler.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  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 WebSub 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 WebSub 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 WebSub 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 WebSub 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 WebSub 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. // NOTE: external hub pings will not be fixed by
  169. // our legacy_http thing!
  170. $hub = common_config('ostatus', 'hub');
  171. if ($hub) {
  172. $this->pushFeedExternal($feed, $hub);
  173. }
  174. // If we used to be http but now are https, see if we find an http entry for this feed URL
  175. // and then upgrade it. This self-healing feature needs to be enabled manually in config.
  176. // This code is based on a patch by @hannes2peer@quitter.se
  177. if (common_config('fix', 'legacy_http') && parse_url($feed, PHP_URL_SCHEME) === 'https') {
  178. common_log(LOG_DEBUG, "OSTATUS [{$this->notice->getID()}]: Searching for http scheme instead for HubSub feed topic: "._ve($feed));
  179. $http_feed = str_replace('https://', 'http://', $feed);
  180. $sub = new HubSub();
  181. $sub->topic = $http_feed;
  182. // If we find it we upgrade the rows in the hubsub table.
  183. if ($sub->find()) {
  184. common_log(LOG_INFO, "OSTATUS [{$this->notice->getID()}]: Found topic with http scheme for "._ve($feed).", will update the rows to use https instead!");
  185. // we found an http:// URL but we use https:// now
  186. // so let's update the rows to reflect on this!
  187. while ($sub->fetch()) {
  188. common_debug("OSTATUS [{$this->notice->getID()}]: Changing topic URL to https for feed callback "._ve($sub->callback));
  189. $orig = clone($sub);
  190. $sub->topic = $feed;
  191. // hashkey column will be set automagically in HubSub->onUpdateKeys through updateWithKeys
  192. $sub->updateWithKeys($orig);
  193. unset($orig);
  194. }
  195. }
  196. }
  197. $sub = new HubSub();
  198. $sub->topic = $feed;
  199. if ($sub->find()) {
  200. $args = array_slice(func_get_args(), 2);
  201. $atom = call_user_func_array($callback, $args);
  202. $this->pushFeedInternal($atom, $sub);
  203. } else {
  204. common_log(LOG_INFO, "OSTATUS [{$this->notice->getID()}]: No WebSub subscribers for $feed");
  205. }
  206. }
  207. /**
  208. * Ping external hub about this update.
  209. * The hub will pull the feed and check for new items later.
  210. * Not guaranteed safe in an environment with database replication.
  211. *
  212. * @param string $feed feed topic URI
  213. * @param string $hub WebSub hub URI
  214. * @fixme can consolidate pings for user & group posts
  215. */
  216. function pushFeedExternal($feed, $hub)
  217. {
  218. $client = new HTTPClient();
  219. try {
  220. $data = array('hub.mode' => 'publish',
  221. 'hub.url' => $feed);
  222. $response = $client->post($hub, array(), $data);
  223. if ($response->getStatus() == 204) {
  224. common_log(LOG_INFO, "WebSub ping to hub $hub for $feed ok");
  225. return true;
  226. } else {
  227. common_log(LOG_ERR, "WebSub ping to hub $hub for $feed failed with HTTP " .
  228. $response->getStatus() . ': ' .
  229. $response->getBody());
  230. }
  231. } catch (Exception $e) {
  232. common_log(LOG_ERR, "WebSub ping to hub $hub for $feed failed: " . $e->getMessage());
  233. return false;
  234. }
  235. }
  236. /**
  237. * Queue up direct feed update pushes to subscribers on our internal hub.
  238. * If there are a large number of subscriber sites, intermediate bulk
  239. * distribution triggers may be queued.
  240. *
  241. * @param string $atom update feed, containing only new/changed items
  242. * @param HubSub $sub open query of subscribers
  243. */
  244. function pushFeedInternal($atom, $sub)
  245. {
  246. common_log(LOG_INFO, "Preparing $sub->N WebSub distribution(s) for $sub->topic");
  247. $n = 0;
  248. $batch = array();
  249. while ($sub->fetch()) {
  250. $n++;
  251. if ($n < self::MAX_UNBATCHED) {
  252. $sub->distribute($atom);
  253. } else {
  254. $batch[] = $sub->callback;
  255. if (count($batch) >= self::BATCH_SIZE) {
  256. $sub->bulkDistribute($atom, $batch);
  257. $batch = array();
  258. }
  259. }
  260. }
  261. if (count($batch) > 0) {
  262. $sub->bulkDistribute($atom, $batch);
  263. }
  264. }
  265. /**
  266. * Build a single-item version of the sending user's Atom feed.
  267. * @return string
  268. */
  269. function userFeedForNotice()
  270. {
  271. $atom = new AtomUserNoticeFeed($this->user);
  272. $atom->addEntryFromNotice($this->notice);
  273. $feed = $atom->getString();
  274. return $feed;
  275. }
  276. function groupFeedForNotice($group_id)
  277. {
  278. $group = User_group::getKV('id', $group_id);
  279. $atom = new AtomGroupNoticeFeed($group);
  280. $atom->addEntryFromNotice($this->notice);
  281. $feed = $atom->getString();
  282. return $feed;
  283. }
  284. function peopletagFeedForNotice($ptag)
  285. {
  286. $atom = new AtomListNoticeFeed($ptag);
  287. $atom->addEntryFromNotice($this->notice);
  288. $feed = $atom->getString();
  289. return $feed;
  290. }
  291. }