ostatusqueuehandler.php 13 KB

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