twitterstatusfetcher.php 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. #!/usr/bin/env php
  2. <?php
  3. /**
  4. * StatusNet - the distributed open-source microblogging tool
  5. * Copyright (C) 2008-2010, StatusNet, Inc.
  6. *
  7. * 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. define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));
  21. // Tune number of processes and how often to poll Twitter
  22. // XXX: Should these things be in config.php?
  23. define('MAXCHILDREN', 2);
  24. define('POLL_INTERVAL', 70); // in seconds, Twitter API v1.1 says 15 calls every 15 mins
  25. $shortoptions = 'di::';
  26. $longoptions = array('id::', 'debug');
  27. $helptext = <<<END_OF_TRIM_HELP
  28. Batch script for retrieving Twitter messages from foreign service.
  29. -i --id Identity (default 'generic')
  30. -d --debug Debug (lots of log output)
  31. END_OF_TRIM_HELP;
  32. require_once INSTALLDIR . '/scripts/commandline.inc';
  33. require_once INSTALLDIR . '/lib/common.php';
  34. require_once INSTALLDIR . '/lib/daemon.php';
  35. require_once dirname(__DIR__) . '/twitter.php';
  36. /**
  37. * Fetch statuses from Twitter
  38. *
  39. * Fetches statuses from Twitter and inserts them as notices
  40. *
  41. * NOTE: an Avatar path MUST be set in config.php for this
  42. * script to work, e.g.:
  43. * $config['avatar']['path'] = $config['site']['path'] . '/avatar/';
  44. *
  45. * @todo @fixme @gar Fix the above. For some reason $_path is always empty when
  46. * this script is run, so the default avatar path is always set wrong in
  47. * default.php. Therefore it must be set explicitly in config.php. --Z
  48. *
  49. * @category Twitter
  50. * @package StatusNet
  51. * @author Zach Copley <zach@status.net>
  52. * @author Evan Prodromou <evan@status.net>
  53. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  54. * @link http://status.net/
  55. */
  56. class TwitterStatusFetcher extends ParallelizingDaemon
  57. {
  58. /**
  59. * Constructor
  60. *
  61. * @param string $id the name/id of this daemon
  62. * @param int $interval sleep this long before doing everything again
  63. * @param int $max_children maximum number of child processes at a time
  64. * @param boolean $debug debug output flag
  65. *
  66. * @return void
  67. *
  68. **/
  69. function __construct($id = null, $interval = 60,
  70. $max_children = 2, $debug = null)
  71. {
  72. parent::__construct($id, $interval, $max_children, $debug);
  73. }
  74. /**
  75. * Name of this daemon
  76. *
  77. * @return string Name of the daemon.
  78. */
  79. function name()
  80. {
  81. return ('twitterstatusfetcher.'.$this->_id);
  82. }
  83. /**
  84. * Find all the Twitter foreign links for users who have requested
  85. * importing of their friends' timelines
  86. *
  87. * @return array flinks an array of Foreign_link objects
  88. */
  89. function getObjects()
  90. {
  91. global $_DB_DATAOBJECT;
  92. $flink = new Foreign_link();
  93. $conn = &$flink->getDatabaseConnection();
  94. $flink->service = TWITTER_SERVICE;
  95. $flink->orderBy('last_noticesync');
  96. $flink->find();
  97. $flinks = array();
  98. while ($flink->fetch()) {
  99. if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
  100. FOREIGN_NOTICE_RECV) {
  101. $flinks[] = clone($flink);
  102. common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
  103. } else {
  104. common_log(LOG_INFO, "nothing to sync");
  105. }
  106. }
  107. $flink->free();
  108. unset($flink);
  109. $conn->disconnect();
  110. unset($_DB_DATAOBJECT['CONNECTIONS']);
  111. return $flinks;
  112. }
  113. // FIXME: make it so we can force a Foreign_link here without colliding with parent
  114. function childTask($flink) {
  115. // Each child ps needs its own DB connection
  116. // Note: DataObject::getDatabaseConnection() creates
  117. // a new connection if there isn't one already
  118. $conn = &$flink->getDatabaseConnection();
  119. $this->getTimeline($flink, 'home_timeline');
  120. $this->getTimeline($flink, 'mentions_timeline');
  121. $flink->last_friendsync = common_sql_now();
  122. $flink->update();
  123. $conn->disconnect();
  124. // XXX: Couldn't find a less brutal way to blow
  125. // away a cached connection
  126. global $_DB_DATAOBJECT;
  127. unset($_DB_DATAOBJECT['CONNECTIONS']);
  128. }
  129. function getTimeline(Foreign_link $flink, $timelineUri = 'home_timeline')
  130. {
  131. common_log(LOG_DEBUG, $this->name() . ' - Trying to get ' . $timelineUri .
  132. ' timeline for Twitter user ' . $flink->foreign_id);
  133. $client = null;
  134. if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
  135. $token = TwitterOAuthClient::unpackToken($flink->credentials);
  136. $client = new TwitterOAuthClient($token->key, $token->secret);
  137. common_log(LOG_DEBUG, $this->name() . ' - Grabbing ' . $timelineUri . ' timeline with OAuth.');
  138. } else {
  139. common_log(LOG_ERR, "Skipping " . $timelineUri . " timeline for " .
  140. $flink->foreign_id . " since not OAuth.");
  141. }
  142. $timeline = null;
  143. $lastId = Twitter_synch_status::getLastId($flink->foreign_id, $timelineUri);
  144. common_log(LOG_DEBUG, "Got lastId value '" . $lastId . "' for foreign id '" .
  145. $flink->foreign_id . "' and timeline '" . $timelineUri. "'");
  146. try {
  147. $timeline = $client->statusesTimeline($lastId, $timelineUri);
  148. } catch (Exception $e) {
  149. common_log(LOG_ERR, $this->name() .
  150. ' - Unable to get ' . $timelineUri . ' timeline for user ' . $flink->user_id .
  151. ' - code: ' . $e->getCode() . 'msg: ' . $e->getMessage());
  152. }
  153. if (empty($timeline)) {
  154. common_log(LOG_DEBUG, $this->name() . " - Empty '" . $timelineUri . "' timeline.");
  155. return;
  156. }
  157. common_log(LOG_INFO, $this->name() .
  158. ' - Retrieved ' . sizeof($timeline) . ' statuses from ' . $timelineUri . ' timeline' .
  159. ' - for user ' . $flink->user_id);
  160. if (!empty($timeline)) {
  161. $qm = QueueManager::get();
  162. // Reverse to preserve order
  163. foreach (array_reverse($timeline) as $status) {
  164. $data = array(
  165. 'status' => $status,
  166. 'for_user' => $flink->foreign_id,
  167. );
  168. $qm->enqueue($data, 'tweetin');
  169. }
  170. $lastId = twitter_id($timeline[0]);
  171. Twitter_synch_status::setLastId($flink->foreign_id, $timelineUri, $lastId);
  172. common_debug("Set lastId value '$lastId' for foreign id '{$flink->foreign_id}' and timeline '" .
  173. $timelineUri . "'");
  174. }
  175. // Okay, record the time we synced with Twitter for posterity
  176. $flink->last_noticesync = common_sql_now();
  177. $flink->update();
  178. }
  179. }
  180. $id = null;
  181. $debug = null;
  182. if (have_option('i')) {
  183. $id = get_option_value('i');
  184. } else if (have_option('--id')) {
  185. $id = get_option_value('--id');
  186. } else if (count($args) > 0) {
  187. $id = $args[0];
  188. } else {
  189. $id = null;
  190. }
  191. if (have_option('d') || have_option('debug')) {
  192. $debug = true;
  193. }
  194. $fetcher = new TwitterStatusFetcher($id, POLL_INTERVAL, MAXCHILDREN, $debug);
  195. $fetcher->runOnce();