twitterstreamreader.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * PHP version 5
  6. *
  7. * LICENCE: This program is free software: you can redistribute it and/or modify
  8. * it under the terms of the GNU Affero General Public License as published by
  9. * the Free Software Foundation, either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU Affero General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Affero General Public License
  18. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  19. *
  20. * @category Plugin
  21. * @package StatusNet
  22. * @author Brion Vibber <brion@status.net>
  23. * @copyright 2010 StatusNet, Inc.
  24. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  25. * @link http://status.net/
  26. */
  27. /**
  28. * Base class for reading Twitter's User Streams and Site Streams
  29. * real-time streaming APIs.
  30. *
  31. * Caller can hook event callbacks for various types of messages;
  32. * the data from the stream and some context info will be passed
  33. * on to the callbacks.
  34. */
  35. abstract class TwitterStreamReader extends JsonStreamReader
  36. {
  37. protected $callbacks = array();
  38. function __construct(TwitterOAuthClient $auth, $baseUrl)
  39. {
  40. $this->baseUrl = $baseUrl;
  41. $this->oauth = $auth;
  42. }
  43. public function connect($method, $params=array())
  44. {
  45. $url = $this->oAuthUrl($this->baseUrl . '/' . $method, $params);
  46. return parent::connect($url);
  47. }
  48. /**
  49. * Sign our target URL with OAuth auth stuff.
  50. *
  51. * @param string $url
  52. * @param array $params
  53. * @return string
  54. */
  55. protected function oAuthUrl($url, $params=array())
  56. {
  57. // In an ideal world this would be better encapsulated. :)
  58. $request = OAuthRequest::from_consumer_and_token($this->oauth->consumer,
  59. $this->oauth->token, 'GET', $url, $params);
  60. $request->sign_request($this->oauth->sha1_method,
  61. $this->oauth->consumer, $this->oauth->token);
  62. return $request->to_url();
  63. }
  64. /**
  65. * Add an event callback to receive notifications when things come in
  66. * over the wire.
  67. *
  68. * Callbacks should be in the form: function(object $data, array $context)
  69. * where $context may list additional data on some streams, such as the
  70. * user to whom the message should be routed.
  71. *
  72. * Available events:
  73. *
  74. * Messaging:
  75. *
  76. * 'status': $data contains a status update in standard Twitter JSON format.
  77. * $data->user: sending user in standard Twitter JSON format.
  78. * $data->text... etc
  79. *
  80. * 'direct_message': $data contains a direct message in standard Twitter JSON format.
  81. * $data->sender: sending user in standard Twitter JSON format.
  82. * $data->recipient: receiving user in standard Twitter JSON format.
  83. * $data->text... etc
  84. *
  85. *
  86. * Out of band events:
  87. *
  88. * 'follow': User has either started following someone, or is being followed.
  89. * $data->source: following user in standard Twitter JSON format.
  90. * $data->target: followed user in standard Twitter JSON format.
  91. *
  92. * 'favorite': Someone has favorited a status update.
  93. * $data->source: user doing the favoriting, in standard Twitter JSON format.
  94. * $data->target: user whose status was favorited, in standard Twitter JSON format.
  95. * $data->target_object: the favorited status update in standard Twitter JSON format.
  96. *
  97. * 'unfavorite': Someone has unfavorited a status update.
  98. * $data->source: user doing the unfavoriting, in standard Twitter JSON format.
  99. * $data->target: user whose status was unfavorited, in standard Twitter JSON format.
  100. * $data->target_object: the unfavorited status update in standard Twitter JSON format.
  101. *
  102. *
  103. * Meta information:
  104. *
  105. * 'friends':
  106. * $data->friends: array of user IDs of the current user's friends.
  107. *
  108. * 'delete': Advisory that a Twitter status has been deleted; nice clients
  109. * should follow suit.
  110. * $data->id: ID of status being deleted
  111. * $data->user_id: ID of its owning user
  112. *
  113. * 'scrub_geo': Advisory that a user is clearing geo data from their status
  114. * stream; nice clients should follow suit.
  115. * $data->user_id: ID of user
  116. * $data->up_to_status_id: any notice older than this should be scrubbed.
  117. *
  118. * 'limit': Advisory that tracking has hit a resource limit.
  119. * $data->track
  120. *
  121. * 'raw': receives the full JSON data for all message types.
  122. *
  123. * @param string $event
  124. * @param callable $callback
  125. */
  126. public function hookEvent($event, $callback)
  127. {
  128. $this->callbacks[$event][] = $callback;
  129. }
  130. /**
  131. * Call event handler callbacks for the given event.
  132. *
  133. * @param string $event
  134. * @param mixed $arg1 ... one or more params to pass on
  135. */
  136. protected function fireEvent($event, $arg1)
  137. {
  138. if (array_key_exists($event, $this->callbacks)) {
  139. $args = array_slice(func_get_args(), 1);
  140. foreach ($this->callbacks[$event] as $callback) {
  141. call_user_func_array($callback, $args);
  142. }
  143. }
  144. }
  145. protected function handleJson(stdClass $data)
  146. {
  147. $this->routeMessage($data);
  148. }
  149. abstract protected function routeMessage(stdClass $data);
  150. /**
  151. * Send the decoded JSON object out to any event listeners.
  152. *
  153. * @param array $data
  154. * @param array $context optional additional context data to pass on
  155. */
  156. protected function handleMessage(stdClass $data, array $context=array())
  157. {
  158. $this->fireEvent('raw', $data, $context);
  159. if (isset($data->text)) {
  160. $this->fireEvent('status', $data, $context);
  161. return;
  162. }
  163. if (isset($data->event)) {
  164. $this->fireEvent($data->event, $data, $context);
  165. return;
  166. }
  167. if (isset($data->friends)) {
  168. $this->fireEvent('friends', $data, $context);
  169. }
  170. $knownMeta = array('delete', 'scrub_geo', 'limit', 'direct_message');
  171. foreach ($knownMeta as $key) {
  172. if (isset($data->$key)) {
  173. $this->fireEvent($key, $data->$key, $context);
  174. return;
  175. }
  176. }
  177. }
  178. }
  179. /**
  180. * Multiuser stream listener for Twitter Site Streams API
  181. * http://dev.twitter.com/pages/site_streams
  182. *
  183. * The site streams API allows listening to updates for multiple users.
  184. * Pass in the user IDs to listen to in via followUser() -- note they
  185. * must each have a valid OAuth token for the application ID we're
  186. * connecting as.
  187. *
  188. * You'll need to be connecting with the auth keys for the user who
  189. * owns the application registration.
  190. *
  191. * The user each message is destined for will be passed to event handlers
  192. * in $context['for_user_id'].
  193. */
  194. class TwitterSiteStream extends TwitterStreamReader
  195. {
  196. protected $userIds;
  197. public function __construct(TwitterOAuthClient $auth, $baseUrl='https://sitestream.twitter.com')
  198. {
  199. parent::__construct($auth, $baseUrl);
  200. }
  201. public function connect($method='2b/site.json')
  202. {
  203. $params = array();
  204. if ($this->userIds) {
  205. $params['follow'] = implode(',', $this->userIds);
  206. }
  207. return parent::connect($method, $params);
  208. }
  209. /**
  210. * Set the users whose home streams should be pulled.
  211. * They all must have valid oauth tokens for this application.
  212. *
  213. * Must be called before connect().
  214. *
  215. * @param array $userIds
  216. */
  217. function followUsers($userIds)
  218. {
  219. $this->userIds = $userIds;
  220. }
  221. /**
  222. * Each message in the site stream tells us which user ID it should be
  223. * routed to; we'll need that to let the caller know what to do.
  224. *
  225. * @param array $data
  226. */
  227. function routeMessage(stdClass $data)
  228. {
  229. $context = array(
  230. 'source' => 'sitestream',
  231. 'for_user' => $data->for_user
  232. );
  233. parent::handleMessage($data->message, $context);
  234. }
  235. }
  236. /**
  237. * Stream listener for Twitter User Streams API
  238. * http://dev.twitter.com/pages/user_streams
  239. *
  240. * This will pull the home stream and additional events just for the user
  241. * we've authenticated as.
  242. */
  243. class TwitterUserStream extends TwitterStreamReader
  244. {
  245. public function __construct(TwitterOAuthClient $auth, $baseUrl='https://userstream.twitter.com')
  246. {
  247. parent::__construct($auth, $baseUrl);
  248. }
  249. public function connect($method='2/user.json')
  250. {
  251. return parent::connect($method);
  252. }
  253. /**
  254. * Each message in the user stream is just ready to go.
  255. *
  256. * @param array $data
  257. */
  258. function routeMessage(stdClass $data)
  259. {
  260. $context = array(
  261. 'source' => 'userstream'
  262. );
  263. parent::handleMessage($data, $context);
  264. }
  265. }