4 * StatusNet - the distributed open-source microblogging tool
5 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));
23 $shortoptions = 'di::';
24 $longoptions = array('id::', 'debug');
26 $helptext = <<<END_OF_TRIM_HELP
27 Batch script for synching local friends with Twitter friends.
28 -i --id Identity (default 'generic')
29 -d --debug Debug (lots of log output)
33 require_once INSTALLDIR . '/scripts/commandline.inc';
34 require_once dirname(__DIR__) . '/twitter.php';
37 * Daemon to sync local friends with Twitter friends
41 * @author Zach Copley <zach@status.net>
42 * @author Evan Prodromou <evan@status.net>
43 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
44 * @link http://status.net/
46 class SyncTwitterFriendsDaemon extends ParallelizingDaemon
51 * @param string $id the name/id of this daemon
52 * @param int $interval sleep this long before doing everything again
53 * @param int $max_children maximum number of child processes at a time
54 * @param boolean $debug debug output flag
59 function __construct($id = null, $interval = 60,
60 $max_children = 2, $debug = null)
62 parent::__construct($id, $interval, $max_children, $debug);
68 * @return string Name of the daemon.
72 return ('synctwitterfriends.' . $this->_id);
76 * Find all the Twitter foreign links for users who have requested
77 * automatically subscribing to their Twitter friends locally.
79 * @return array flinks an array of Foreign_link objects
84 $flink = new Foreign_link();
86 $conn = &$flink->getDatabaseConnection();
88 $flink->service = TWITTER_SERVICE;
89 $flink->orderBy('last_friendsync');
90 $flink->limit(25); // sync this many users during this run
93 while ($flink->fetch()) {
94 if (($flink->friendsync & FOREIGN_FRIEND_RECV) == FOREIGN_FRIEND_RECV) {
95 $flinks[] = clone($flink);
101 global $_DB_DATAOBJECT;
102 unset($_DB_DATAOBJECT['CONNECTIONS']);
107 // FIXME: make it so we can force a Foreign_link here without colliding with parent
108 function childTask($flink) {
109 // Each child ps needs its own DB connection
111 // Note: DataObject::getDatabaseConnection() creates
112 // a new connection if there isn't one already
113 $conn = &$flink->getDatabaseConnection();
115 $this->subscribeTwitterFriends($flink);
117 $flink->last_friendsync = common_sql_now();
122 // XXX: Couldn't find a less brutal way to blow
123 // away a cached connection
124 global $_DB_DATAOBJECT;
125 unset($_DB_DATAOBJECT['CONNECTIONS']);
128 function fetchTwitterFriends(Foreign_link $flink)
134 if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
135 $token = TwitterOAuthClient::unpackToken($flink->credentials);
136 $client = new TwitterOAuthClient($token->key, $token->secret);
137 common_debug($this->name() . '- Grabbing friends IDs with OAuth.');
139 common_debug("Skipping Twitter friends for {$flink->user_id} since not OAuth.");
144 $friends_ids = $client->friendsIds();
145 } catch (Exception $e) {
146 common_log(LOG_WARNING, $this->name() .
147 ' - error getting friend ids: ' .
152 if (empty($friends_ids)) {
153 common_debug($this->name() .
154 " - Twitter user $flink->foreign_id " .
155 'doesn\'t have any friends!');
159 common_debug($this->name() . ' - Twitter\'s API says Twitter user id ' .
160 "$flink->foreign_id has " .
161 count($friends_ids) . ' friends.');
163 // Calculate how many pages to get...
164 $pages = ceil(count($friends_ids) / 100);
167 common_debug($this->name() . " - $user seems to have no friends.");
170 for ($i = 1; $i <= $pages; $i++) {
173 $more_friends = $client->statusesFriends(null, null, null, $i);
174 } catch (Exception $e) {
175 common_log(LOG_WARNING, $this->name() .
176 ' - cURL error getting Twitter statuses/friends ' .
177 "page $i - " . $e->getCode() . ' - ' .
181 if (empty($more_friends)) {
182 common_log(LOG_WARNING, $this->name() .
183 " - Couldn't retrieve page $i " .
184 "of Twitter user $flink->foreign_id friends.");
187 if (is_array($more_friends)) {
188 $friends = array_merge($friends, $more_friends);
196 function subscribeTwitterFriends(Foreign_link $flink)
199 $profile = $flink->getProfile();
200 } catch (NoResultException $e) {
201 common_log(LOG_WARNING, 'Foreign_link has no matching local profile for local ID: '.$flink->user_id);
204 $friends = $this->fetchTwitterFriends($flink);
206 if (empty($friends)) {
207 common_debug($this->name() .
208 ' - Couldn\'t get friends from Twitter for ' .
209 "Twitter user $flink->foreign_id.");
213 foreach ($friends as $friend) {
215 $friend_name = $friend->screen_name;
216 $friend_id = (int) $friend->id;
218 // Update or create the Foreign_user record for each
221 if (!save_twitter_user($friend_id, $friend_name)) {
222 common_log(LOG_WARNING, $this->name() .
223 " - Couldn't save $screen_name's friend, $friend_name.");
227 // Check to see if there's a related local user and try to subscribe
229 $friend_flink = Foreign_link::getByForeignID($friend_id, TWITTER_SERVICE);
231 // Get associated user and subscribe her
232 $friend_profile = $friend_flink->getProfile();
234 Subscription::start($profile, $friend_profile);
236 $this->name() . ' - Subscribed ' .
237 "{$friend_profile->nickname} to {$profile->nickname}.");
238 } catch (NoResultException $e) {
239 // either no foreign link for this friend's foreign ID or no profile found on local ID.
240 } catch (Exception $e) {
241 common_debug($this->name() .
242 ' - Tried and failed subscribing ' .
243 "{$friend_profile->nickname} to {$profile->nickname} - " .
256 if (have_option('i')) {
257 $id = get_option_value('i');
258 } else if (have_option('--id')) {
259 $id = get_option_value('--id');
260 } else if (count($args) > 0) {
266 if (have_option('d') || have_option('debug')) {
270 $syncer = new SyncTwitterFriendsDaemon($id, 60, 2, $debug);