synctwitterfriends.php 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #!/usr/bin/env php
  2. <?php
  3. /*
  4. * StatusNet - the distributed open-source microblogging tool
  5. * Copyright (C) 2008, 2009, 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. $shortoptions = 'di::';
  22. $longoptions = array('id::', 'debug');
  23. $helptext = <<<END_OF_TRIM_HELP
  24. Batch script for synching local friends with Twitter friends.
  25. -i --id Identity (default 'generic')
  26. -d --debug Debug (lots of log output)
  27. END_OF_TRIM_HELP;
  28. require_once INSTALLDIR . '/scripts/commandline.inc';
  29. require_once dirname(__DIR__) . '/twitter.php';
  30. /**
  31. * Daemon to sync local friends with Twitter friends
  32. *
  33. * @category Twitter
  34. * @package StatusNet
  35. * @author Zach Copley <zach@status.net>
  36. * @author Evan Prodromou <evan@status.net>
  37. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  38. * @link http://status.net/
  39. */
  40. class SyncTwitterFriendsDaemon extends ParallelizingDaemon
  41. {
  42. /**
  43. * Constructor
  44. *
  45. * @param string $id the name/id of this daemon
  46. * @param int $interval sleep this long before doing everything again
  47. * @param int $max_children maximum number of child processes at a time
  48. * @param boolean $debug debug output flag
  49. *
  50. * @return void
  51. *
  52. **/
  53. function __construct($id = null, $interval = 60,
  54. $max_children = 2, $debug = null)
  55. {
  56. parent::__construct($id, $interval, $max_children, $debug);
  57. }
  58. /**
  59. * Name of this daemon
  60. *
  61. * @return string Name of the daemon.
  62. */
  63. function name()
  64. {
  65. return ('synctwitterfriends.' . $this->_id);
  66. }
  67. /**
  68. * Find all the Twitter foreign links for users who have requested
  69. * automatically subscribing to their Twitter friends locally.
  70. *
  71. * @return array flinks an array of Foreign_link objects
  72. */
  73. function getObjects()
  74. {
  75. $flinks = array();
  76. $flink = new Foreign_link();
  77. $conn = &$flink->getDatabaseConnection();
  78. $flink->service = TWITTER_SERVICE;
  79. $flink->orderBy('last_friendsync');
  80. $flink->limit(25); // sync this many users during this run
  81. $flink->find();
  82. while ($flink->fetch()) {
  83. if (($flink->friendsync & FOREIGN_FRIEND_RECV) == FOREIGN_FRIEND_RECV) {
  84. $flinks[] = clone($flink);
  85. }
  86. }
  87. $conn->disconnect();
  88. global $_DB_DATAOBJECT;
  89. unset($_DB_DATAOBJECT['CONNECTIONS']);
  90. return $flinks;
  91. }
  92. // FIXME: make it so we can force a Foreign_link here without colliding with parent
  93. function childTask($flink) {
  94. // Each child ps needs its own DB connection
  95. // Note: DataObject::getDatabaseConnection() creates
  96. // a new connection if there isn't one already
  97. $conn = &$flink->getDatabaseConnection();
  98. $this->subscribeTwitterFriends($flink);
  99. $flink->last_friendsync = common_sql_now();
  100. $flink->update();
  101. $conn->disconnect();
  102. // XXX: Couldn't find a less brutal way to blow
  103. // away a cached connection
  104. global $_DB_DATAOBJECT;
  105. unset($_DB_DATAOBJECT['CONNECTIONS']);
  106. }
  107. function fetchTwitterFriends(Foreign_link $flink)
  108. {
  109. $friends = array();
  110. $client = null;
  111. if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
  112. $token = TwitterOAuthClient::unpackToken($flink->credentials);
  113. $client = new TwitterOAuthClient($token->key, $token->secret);
  114. common_debug($this->name() . '- Grabbing friends IDs with OAuth.');
  115. } else {
  116. common_debug("Skipping Twitter friends for {$flink->user_id} since not OAuth.");
  117. return $friends;
  118. }
  119. try {
  120. $friends_ids = $client->friendsIds();
  121. } catch (Exception $e) {
  122. common_log(LOG_WARNING, $this->name() .
  123. ' - error getting friend ids: ' .
  124. $e->getMessage());
  125. return $friends;
  126. }
  127. if (empty($friends_ids)) {
  128. common_debug($this->name() .
  129. " - Twitter user $flink->foreign_id " .
  130. 'doesn\'t have any friends!');
  131. return $friends;
  132. }
  133. common_debug($this->name() . ' - Twitter\'s API says Twitter user id ' .
  134. "$flink->foreign_id has " .
  135. count($friends_ids) . ' friends.');
  136. // Calculate how many pages to get...
  137. $pages = ceil(count($friends_ids) / 100);
  138. if ($pages == 0) {
  139. common_debug($this->name() . " - $user seems to have no friends.");
  140. }
  141. for ($i = 1; $i <= $pages; $i++) {
  142. try {
  143. $more_friends = $client->statusesFriends(null, null, null, $i);
  144. } catch (Exception $e) {
  145. common_log(LOG_WARNING, $this->name() .
  146. ' - cURL error getting Twitter statuses/friends ' .
  147. "page $i - " . $e->getCode() . ' - ' .
  148. $e->getMessage());
  149. }
  150. if (empty($more_friends)) {
  151. common_log(LOG_WARNING, $this->name() .
  152. " - Couldn't retrieve page $i " .
  153. "of Twitter user $flink->foreign_id friends.");
  154. continue;
  155. } else {
  156. if (is_array($more_friends)) {
  157. $friends = array_merge($friends, $more_friends);
  158. }
  159. }
  160. }
  161. return $friends;
  162. }
  163. function subscribeTwitterFriends(Foreign_link $flink)
  164. {
  165. try {
  166. $profile = $flink->getProfile();
  167. } catch (NoResultException $e) {
  168. common_log(LOG_WARNING, 'Foreign_link has no matching local profile for local ID: '.$flink->user_id);
  169. }
  170. $friends = $this->fetchTwitterFriends($flink);
  171. if (empty($friends)) {
  172. common_debug($this->name() .
  173. ' - Couldn\'t get friends from Twitter for ' .
  174. "Twitter user $flink->foreign_id.");
  175. return false;
  176. }
  177. foreach ($friends as $friend) {
  178. $friend_name = $friend->screen_name;
  179. $friend_id = (int) $friend->id;
  180. // Update or create the Foreign_user record for each
  181. // Twitter friend
  182. if (!save_twitter_user($friend_id, $friend_name)) {
  183. common_log(LOG_WARNING, $this->name() .
  184. " - Couldn't save $screen_name's friend, $friend_name.");
  185. continue;
  186. }
  187. // Check to see if there's a related local user and try to subscribe
  188. try {
  189. $friend_flink = Foreign_link::getByForeignID($friend_id, TWITTER_SERVICE);
  190. // Get associated user and subscribe her
  191. $friend_profile = $friend_flink->getProfile();
  192. Subscription::start($profile, $friend_profile);
  193. common_log(LOG_INFO,
  194. $this->name() . ' - Subscribed ' .
  195. "{$friend_profile->nickname} to {$profile->nickname}.");
  196. } catch (NoResultException $e) {
  197. // either no foreign link for this friend's foreign ID or no profile found on local ID.
  198. } catch (Exception $e) {
  199. common_debug($this->name() .
  200. ' - Tried and failed subscribing ' .
  201. "{$friend_profile->nickname} to {$profile->nickname} - " .
  202. $e->getMessage());
  203. }
  204. }
  205. return true;
  206. }
  207. }
  208. $id = null;
  209. $debug = null;
  210. if (have_option('i')) {
  211. $id = get_option_value('i');
  212. } else if (have_option('--id')) {
  213. $id = get_option_value('--id');
  214. } else if (count($args) > 0) {
  215. $id = $args[0];
  216. } else {
  217. $id = null;
  218. }
  219. if (have_option('d') || have_option('debug')) {
  220. $debug = true;
  221. }
  222. $syncer = new SyncTwitterFriendsDaemon($id, 60, 2, $debug);
  223. $syncer->runOnce();