]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/synctwitterfriends.php
Make statuses/home_timeline return the same thing as statuses/friends_timeline to...
[quix0rs-gnu-social.git] / scripts / synctwitterfriends.php
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
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
22 define('STATUSNET', true);
23 define('LACONICA', true); // compatibility
24
25 $shortoptions = 'di::';
26 $longoptions = array('id::', 'debug');
27
28 $helptext = <<<END_OF_TRIM_HELP
29 Batch script for synching local friends with Twitter friends.
30   -i --id              Identity (default 'generic')
31   -d --debug           Debug (lots of log output)
32
33 END_OF_TRIM_HELP;
34
35 require_once INSTALLDIR . '/scripts/commandline.inc';
36 require_once INSTALLDIR . '/lib/parallelizingdaemon.php';
37
38 /**
39  * Daemon to sync local friends with Twitter friends
40  *
41  * @category Twitter
42  * @package  StatusNet
43  * @author   Zach Copley <zach@status.net>
44  * @author   Evan Prodromou <evan@status.net>
45  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
46  * @link     http://status.net/
47  */
48
49 $helptext = <<<END_OF_TWITTER_HELP
50 Batch script for synching local friends with Twitter friends.
51
52 END_OF_TWITTER_HELP;
53
54 require_once INSTALLDIR . '/scripts/commandline.inc';
55 require_once INSTALLDIR . '/lib/parallelizingdaemon.php';
56
57 class SyncTwitterFriendsDaemon extends ParallelizingDaemon
58 {
59     /**
60      *  Constructor
61      *
62      * @param string  $id           the name/id of this daemon
63      * @param int     $interval     sleep this long before doing everything again
64      * @param int     $max_children maximum number of child processes at a time
65      * @param boolean $debug        debug output flag
66      *
67      * @return void
68      *
69      **/
70
71     function __construct($id = null, $interval = 60,
72                          $max_children = 2, $debug = null)
73     {
74         parent::__construct($id, $interval, $max_children, $debug);
75     }
76
77     /**
78      * Name of this daemon
79      *
80      * @return string Name of the daemon.
81      */
82
83     function name()
84     {
85         return ('synctwitterfriends.' . $this->_id);
86     }
87
88     /**
89      * Find all the Twitter foreign links for users who have requested
90      * automatically subscribing to their Twitter friends locally.
91      *
92      * @return array flinks an array of Foreign_link objects
93      */
94     function getObjects()
95     {
96         $flinks = array();
97         $flink = new Foreign_link();
98
99         $conn = &$flink->getDatabaseConnection();
100
101         $flink->service = TWITTER_SERVICE;
102         $flink->orderBy('last_friendsync');
103         $flink->limit(25);  // sync this many users during this run
104         $flink->find();
105
106         while ($flink->fetch()) {
107             if (($flink->friendsync & FOREIGN_FRIEND_RECV) == FOREIGN_FRIEND_RECV) {
108                 $flinks[] = clone($flink);
109             }
110         }
111
112         $conn->disconnect();
113
114         global $_DB_DATAOBJECT;
115         unset($_DB_DATAOBJECT['CONNECTIONS']);
116
117         return $flinks;
118     }
119
120     function childTask($flink) {
121
122         // Each child ps needs its own DB connection
123
124         // Note: DataObject::getDatabaseConnection() creates
125         // a new connection if there isn't one already
126
127         $conn = &$flink->getDatabaseConnection();
128
129         $this->subscribeTwitterFriends($flink);
130
131         $flink->last_friendsync = common_sql_now();
132         $flink->update();
133
134         $conn->disconnect();
135
136         // XXX: Couldn't find a less brutal way to blow
137         // away a cached connection
138
139         global $_DB_DATAOBJECT;
140         unset($_DB_DATAOBJECT['CONNECTIONS']);
141     }
142
143     function fetchTwitterFriends($flink)
144     {
145         $friends = array();
146
147         $client = null;
148
149         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
150             $token = TwitterOAuthClient::unpackToken($flink->credentials);
151             $client = new TwitterOAuthClient($token->key, $token->secret);
152             common_debug($this->name() . '- Grabbing friends IDs with OAuth.');
153         } else {
154             $client = new TwitterBasicAuthClient($flink);
155             common_debug($this->name() . '- Grabbing friends IDs with basic auth.');
156         }
157
158         try {
159             $friends_ids = $client->friendsIds();
160         } catch (Exception $e) {
161             common_log(LOG_WARNING, $this->name() .
162                        ' - cURL error getting friend ids ' .
163                        $e->getCode() . ' - ' . $e->getMessage());
164             return $friends;
165         }
166
167         if (empty($friends_ids)) {
168             common_debug($this->name() .
169                          " - Twitter user $flink->foreign_id " .
170                          'doesn\'t have any friends!');
171             return $friends;
172         }
173
174         common_debug($this->name() . ' - Twitter\'s API says Twitter user id ' .
175                      "$flink->foreign_id has " .
176                      count($friends_ids) . ' friends.');
177
178         // Calculate how many pages to get...
179         $pages = ceil(count($friends_ids) / 100);
180
181         if ($pages == 0) {
182             common_debug($this->name() . " - $user seems to have no friends.");
183         }
184
185         for ($i = 1; $i <= $pages; $i++) {
186
187         try {
188             $more_friends = $client->statusesFriends(null, null, null, $i);
189         } catch (Exception $e) {
190             common_log(LOG_WARNING, $this->name() .
191                        ' - cURL error getting Twitter statuses/friends ' .
192                        "page $i - " . $e->getCode() . ' - ' .
193                        $e->getMessage());
194         }
195
196             if (empty($more_friends)) {
197                 common_log(LOG_WARNING, $this->name() .
198                            " - Couldn't retrieve page $i " .
199                            "of Twitter user $flink->foreign_id friends.");
200                 continue;
201             } else {
202                 $friends = array_merge($friends, $more_friends);
203             }
204         }
205
206         return $friends;
207     }
208
209     function subscribeTwitterFriends($flink)
210     {
211         $friends = $this->fetchTwitterFriends($flink);
212
213         if (empty($friends)) {
214             common_debug($this->name() .
215                          ' - Couldn\'t get friends from Twitter for ' .
216                          "Twitter user $flink->foreign_id.");
217             return false;
218         }
219
220         $user = $flink->getUser();
221
222         foreach ($friends as $friend) {
223
224             $friend_name = $friend->screen_name;
225             $friend_id = (int) $friend->id;
226
227             // Update or create the Foreign_user record for each
228             // Twitter friend
229
230             if (!save_twitter_user($friend_id, $friend_name)) {
231                 common_log(LOG_WARNING, $this-name() .
232                            " - Couldn't save $screen_name's friend, $friend_name.");
233                 continue;
234             }
235
236             // Check to see if there's a related local user
237
238             $friend_flink = Foreign_link::getByForeignID($friend_id,
239                                                          TWITTER_SERVICE);
240
241             if (!empty($friend_flink)) {
242
243                 // Get associated user and subscribe her
244
245                 $friend_user = User::staticGet('id', $friend_flink->user_id);
246
247                 if (!empty($friend_user)) {
248                     $result = subs_subscribe_to($user, $friend_user);
249
250                     if ($result === true) {
251                         common_log(LOG_INFO,
252                                    $this->name() . ' - Subscribed ' .
253                                    "$friend_user->nickname to $user->nickname.");
254                     } else {
255                         common_debug($this->name() .
256                                      ' - Tried subscribing ' .
257                                      "$friend_user->nickname to $user->nickname - " .
258                                      $result);
259                     }
260                 }
261             }
262         }
263
264         return true;
265     }
266
267 }
268
269 $id    = null;
270 $debug = null;
271
272 if (have_option('i')) {
273     $id = get_option_value('i');
274 } else if (have_option('--id')) {
275     $id = get_option_value('--id');
276 } else if (count($args) > 0) {
277     $id = $args[0];
278 } else {
279     $id = null;
280 }
281
282 if (have_option('d') || have_option('debug')) {
283     $debug = true;
284 }
285
286 $syncer = new SyncTwitterFriendsDaemon($id, 60, 2, $debug);
287 $syncer->runOnce();
288