synctwitterfriends.php 8.9 KB

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