]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/synctwitterfriends.php
1bd75bac111170e4db3b3f6e72cb1d187f0f3b4c
[quix0rs-gnu-social.git] / scripts / synctwitterfriends.php
1 #!/usr/bin/env php
2 <?php
3 /*
4  * Laconica - a distributed open-source microblogging tool
5  * Copyright (C) 2008, 2009, Control Yourself, 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
23 $shortoptions = 'di::';
24 $longoptions = array('id::', 'debug');
25
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)
30
31 END_OF_TRIM_HELP;
32
33 require_once INSTALLDIR . '/scripts/commandline.inc';
34 require_once INSTALLDIR . '/lib/parallelizingdaemon.php';
35
36 /**
37  * Daemon to sync local friends with Twitter friends
38  *
39  * @category Twitter
40  * @package  Laconica
41  * @author   Zach Copley <zach@controlyourself.ca>
42  * @author   Evan Prodromou <evan@controlyourself.ca>
43  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
44  * @link     http://laconi.ca/
45  */
46
47 $helptext = <<<END_OF_TWITTER_HELP
48 Batch script for synching local friends with Twitter friends.
49
50 END_OF_TWITTER_HELP;
51
52 require_once INSTALLDIR . '/scripts/commandline.inc';
53 require_once INSTALLDIR . '/lib/parallelizingdaemon.php';
54
55 class SyncTwitterFriendsDaemon extends ParallelizingDaemon
56 {
57     function __construct($id = null, $interval = 60,
58                          $max_children = 2, $debug = null)
59     {
60         parent::__construct($id, $interval, $max_children, $debug);
61     }
62
63     /**
64      * Name of this daemon
65      *
66      * @return string Name of the daemon.
67      */
68
69     function name()
70     {
71         return ('synctwitterfriendsdaemon.' . $this->_id);
72     }
73
74     function getObjects()
75     {
76         $flinks = array();
77         $flink = new Foreign_link();
78
79         $conn = &$flink->getDatabaseConnection();
80
81         $flink->service = TWITTER_SERVICE;
82         $flink->orderBy('last_friendsync');
83         $flink->limit(25);  // sync this many users during this run
84         $flink->find();
85
86         while ($flink->fetch()) {
87             if (($flink->friendsync & FOREIGN_FRIEND_RECV) == FOREIGN_FRIEND_RECV) {
88                 $flinks[] = clone($flink);
89             }
90         }
91
92         $conn->disconnect();
93
94         global $_DB_DATAOBJECT;
95         unset($_DB_DATAOBJECT['CONNECTIONS']);
96
97         return $flinks;
98     }
99
100     function childTask($flink) {
101
102         // Each child ps needs its own DB connection
103
104         // Note: DataObject::getDatabaseConnection() creates
105         // a new connection if there isn't one already
106
107         $conn = &$flink->getDatabaseConnection();
108
109         $this->subscribeTwitterFriends($flink);
110
111         $flink->last_friendsync = common_sql_now();
112         $flink->update();
113
114         $conn->disconnect();
115
116         // XXX: Couldn't find a less brutal way to blow
117         // away a cached connection
118
119         global $_DB_DATAOBJECT;
120         unset($_DB_DATAOBJECT['CONNECTIONS']);
121     }
122
123     function fetchTwitterFriends($flink)
124     {
125         $friends = array();
126
127         $client = new TwitterOAuthClient($flink->token, $flink->credentials);
128
129         try {
130             $friends_ids = $client->friends_ids();
131         } catch (OAuthCurlException $e) {
132             common_log(LOG_WARNING, $this->name() .
133                        ' - cURL error getting friend ids ' .
134                        $e->getCode() . ' - ' . $e->getMessage());
135             return $friends;
136         }
137
138         if (empty($friends_ids)) {
139             common_debug($this->name() .
140                          " - Twitter user $flink->foreign_id " .
141                          'doesn\'t have any friends!');
142             return $friends;
143         }
144
145         common_debug($this->name() . ' - Twitter\'s API says Twitter user id ' .
146                      "$flink->foreign_id has " .
147                      count($friends_ids) . ' friends.');
148
149         // Calculate how many pages to get...
150         $pages = ceil(count($friends_ids) / 100);
151
152         if ($pages == 0) {
153             common_debug($this->name() . " - $user seems to have no friends.");
154         }
155
156         for ($i = 1; $i <= $pages; $i++) {
157
158         try {
159             $more_friends = $client->statuses_friends(null, null, null, $i);
160         } catch (OAuthCurlException $e) {
161             common_log(LOG_WARNING, $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                 $friends = array_merge($friends, $more_friends);
174             }
175         }
176
177         return $friends;
178     }
179
180     function subscribeTwitterFriends($flink)
181     {
182         $friends = $this->fetchTwitterFriends($flink);
183
184         if (empty($friends)) {
185             common_debug($this->name() .
186                          ' - Couldn\'t get friends from Twitter for ' .
187                          "Twitter user $flink->foreign_id.");
188             return false;
189         }
190
191         $user = $flink->getUser();
192
193         foreach ($friends as $friend) {
194
195             $friend_name = $friend->screen_name;
196             $friend_id = (int) $friend->id;
197
198             // Update or create the Foreign_user record for each
199             // Twitter friend
200
201             if (!save_twitter_user($friend_id, $friend_name)) {
202                 common_log(LOG_WARNING, $this-name() .
203                            " - Couldn't save $screen_name's friend, $friend_name.");
204                 continue;
205             }
206
207             // Check to see if there's a related local user
208
209             $friend_flink = Foreign_link::getByForeignID($friend_id,
210                                                          TWITTER_SERVICE);
211
212             if (!empty($friend_flink)) {
213
214                 // Get associated user and subscribe her
215
216                 $friend_user = User::staticGet('id', $friend_flink->user_id);
217
218                 if (!empty($friend_user)) {
219                     $result = subs_subscribe_to($user, $friend_user);
220
221                     if ($result === true) {
222                         common_log(LOG_INFO,
223                                    $this->name() . ' - Subscribed ' .
224                                    "$friend_user->nickname to $user->nickname.");
225                     } else {
226                         common_debug($this->name() .
227                                      ' - Tried subscribing ' .
228                                      "$friend_user->nickname to $user->nickname - " .
229                                      $result);
230                     }
231                 }
232             }
233         }
234
235         return true;
236     }
237
238 }
239
240 declare(ticks = 1);
241
242 $id    = null;
243 $debug = null;
244
245 if (have_option('i')) {
246     $id = get_option_value('i');
247 } else if (have_option('--id')) {
248     $id = get_option_value('--id');
249 } else if (count($args) > 0) {
250     $id = $args[0];
251 } else {
252     $id = null;
253 }
254
255 if (have_option('d') || have_option('debug')) {
256     $debug = true;
257 }
258
259 $syncer = new SyncTwitterFriendsDaemon($id, 60, 2, $debug);
260 $syncer->runOnce();
261