synctwitterfriends.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  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. function childTask($flink) {
  93. // Each child ps needs its own DB connection
  94. // Note: DataObject::getDatabaseConnection() creates
  95. // a new connection if there isn't one already
  96. $conn = &$flink->getDatabaseConnection();
  97. $this->subscribeTwitterFriends($flink);
  98. $flink->last_friendsync = common_sql_now();
  99. $flink->update();
  100. $conn->disconnect();
  101. // XXX: Couldn't find a less brutal way to blow
  102. // away a cached connection
  103. global $_DB_DATAOBJECT;
  104. unset($_DB_DATAOBJECT['CONNECTIONS']);
  105. }
  106. function fetchTwitterFriends($flink)
  107. {
  108. $friends = array();
  109. $client = null;
  110. if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
  111. $token = TwitterOAuthClient::unpackToken($flink->credentials);
  112. $client = new TwitterOAuthClient($token->key, $token->secret);
  113. common_debug($this->name() . '- Grabbing friends IDs with OAuth.');
  114. } else {
  115. common_debug("Skipping Twitter friends for {$flink->user_id} since not OAuth.");
  116. return $friends;
  117. }
  118. try {
  119. $friends_ids = $client->friendsIds();
  120. } catch (Exception $e) {
  121. common_log(LOG_WARNING, $this->name() .
  122. ' - error getting friend ids: ' .
  123. $e->getMessage());
  124. return $friends;
  125. }
  126. if (empty($friends_ids)) {
  127. common_debug($this->name() .
  128. " - Twitter user $flink->foreign_id " .
  129. 'doesn\'t have any friends!');
  130. return $friends;
  131. }
  132. common_debug($this->name() . ' - Twitter\'s API says Twitter user id ' .
  133. "$flink->foreign_id has " .
  134. count($friends_ids) . ' friends.');
  135. // Calculate how many pages to get...
  136. $pages = ceil(count($friends_ids) / 100);
  137. if ($pages == 0) {
  138. common_debug($this->name() . " - $user seems to have no friends.");
  139. }
  140. for ($i = 1; $i <= $pages; $i++) {
  141. try {
  142. $more_friends = $client->statusesFriends(null, null, null, $i);
  143. } catch (Exception $e) {
  144. common_log(LOG_WARNING, $this->name() .
  145. ' - cURL error getting Twitter statuses/friends ' .
  146. "page $i - " . $e->getCode() . ' - ' .
  147. $e->getMessage());
  148. }
  149. if (empty($more_friends)) {
  150. common_log(LOG_WARNING, $this->name() .
  151. " - Couldn't retrieve page $i " .
  152. "of Twitter user $flink->foreign_id friends.");
  153. continue;
  154. } else {
  155. if (is_array($more_friends)) {
  156. $friends = array_merge($friends, $more_friends);
  157. }
  158. }
  159. }
  160. return $friends;
  161. }
  162. function subscribeTwitterFriends($flink)
  163. {
  164. $friends = $this->fetchTwitterFriends($flink);
  165. if (empty($friends)) {
  166. common_debug($this->name() .
  167. ' - Couldn\'t get friends from Twitter for ' .
  168. "Twitter user $flink->foreign_id.");
  169. return false;
  170. }
  171. $profile = $flink->getProfile();
  172. foreach ($friends as $friend) {
  173. $friend_name = $friend->screen_name;
  174. $friend_id = (int) $friend->id;
  175. // Update or create the Foreign_user record for each
  176. // Twitter friend
  177. if (!save_twitter_user($friend_id, $friend_name)) {
  178. common_log(LOG_WARNING, $this->name() .
  179. " - Couldn't save $screen_name's friend, $friend_name.");
  180. continue;
  181. }
  182. // Check to see if there's a related local user
  183. $friend_flink = Foreign_link::getByForeignID($friend_id,
  184. TWITTER_SERVICE);
  185. if (!empty($friend_flink)) {
  186. // Get associated user and subscribe her
  187. $friend_profile = Profile::getKV('id', $friend_flink->user_id);
  188. if ($friend_profile instanceof Profile) {
  189. try {
  190. $other = Profile::getKV('id', $invites->user_id);
  191. Subscription::start($profile, $friend_profile);
  192. common_log(LOG_INFO,
  193. $this->name() . ' - Subscribed ' .
  194. "{$friend_profile->nickname} to {$profile->nickname}.");
  195. } catch (Exception $e) {
  196. common_debug($this->name() .
  197. ' - Tried and failed subscribing ' .
  198. "{$friend_profile->nickname} to {$profile->nickname} - " .
  199. $e->getMessage());
  200. }
  201. }
  202. }
  203. }
  204. return true;
  205. }
  206. }
  207. $id = null;
  208. $debug = null;
  209. if (have_option('i')) {
  210. $id = get_option_value('i');
  211. } else if (have_option('--id')) {
  212. $id = get_option_value('--id');
  213. } else if (count($args) > 0) {
  214. $id = $args[0];
  215. } else {
  216. $id = null;
  217. }
  218. if (have_option('d') || have_option('debug')) {
  219. $debug = true;
  220. }
  221. $syncer = new SyncTwitterFriendsDaemon($id, 60, 2, $debug);
  222. $syncer->runOnce();