synctwitterfriends.php 9.2 KB

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