]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/synctwitterfriends.php
8b8ffbfd496bdbaaa0382f71c4bf12db2469a4a7
[quix0rs-gnu-social.git] / plugins / TwitterBridge / daemons / 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
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 dirname(__DIR__) . '/twitter.php';
35
36 /**
37  * Daemon to sync local friends with Twitter friends
38  *
39  * @category Twitter
40  * @package  StatusNet
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/
45  */
46 class SyncTwitterFriendsDaemon extends ParallelizingDaemon
47 {
48     /**
49      *  Constructor
50      *
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
55      *
56      * @return void
57      *
58      **/
59     function __construct($id = null, $interval = 60,
60                          $max_children = 2, $debug = null)
61     {
62         parent::__construct($id, $interval, $max_children, $debug);
63     }
64
65     /**
66      * Name of this daemon
67      *
68      * @return string Name of the daemon.
69      */
70     function name()
71     {
72         return ('synctwitterfriends.' . $this->_id);
73     }
74
75     /**
76      * Find all the Twitter foreign links for users who have requested
77      * automatically subscribing to their Twitter friends locally.
78      *
79      * @return array flinks an array of Foreign_link objects
80      */
81     function getObjects()
82     {
83         $flinks = array();
84         $flink = new Foreign_link();
85
86         $conn = &$flink->getDatabaseConnection();
87
88         $flink->service = TWITTER_SERVICE;
89         $flink->orderBy('last_friendsync');
90         $flink->limit(25);  // sync this many users during this run
91         $flink->find();
92
93         while ($flink->fetch()) {
94             if (($flink->friendsync & FOREIGN_FRIEND_RECV) == FOREIGN_FRIEND_RECV) {
95                 $flinks[] = clone($flink);
96             }
97         }
98
99         $conn->disconnect();
100
101         global $_DB_DATAOBJECT;
102         unset($_DB_DATAOBJECT['CONNECTIONS']);
103
104         return $flinks;
105     }
106
107     function childTask($flink) {
108         // Each child ps needs its own DB connection
109
110         // Note: DataObject::getDatabaseConnection() creates
111         // a new connection if there isn't one already
112         $conn = &$flink->getDatabaseConnection();
113
114         $this->subscribeTwitterFriends($flink);
115
116         $flink->last_friendsync = common_sql_now();
117         $flink->update();
118
119         $conn->disconnect();
120
121         // XXX: Couldn't find a less brutal way to blow
122         // away a cached connection
123         global $_DB_DATAOBJECT;
124         unset($_DB_DATAOBJECT['CONNECTIONS']);
125     }
126
127     function fetchTwitterFriends($flink)
128     {
129         $friends = array();
130
131         $client = null;
132
133         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
134             $token = TwitterOAuthClient::unpackToken($flink->credentials);
135             $client = new TwitterOAuthClient($token->key, $token->secret);
136             common_debug($this->name() . '- Grabbing friends IDs with OAuth.');
137         } else {
138             common_debug("Skipping Twitter friends for {$flink->user_id} since not OAuth.");
139             return $friends;
140         }
141
142         try {
143             $friends_ids = $client->friendsIds();
144         } catch (Exception $e) {
145             common_log(LOG_WARNING, $this->name() .
146                        ' - error getting friend ids: ' .
147                        $e->getMessage());
148             return $friends;
149         }
150
151         if (empty($friends_ids)) {
152             common_debug($this->name() .
153                          " - Twitter user $flink->foreign_id " .
154                          'doesn\'t have any friends!');
155             return $friends;
156         }
157
158         common_debug($this->name() . ' - Twitter\'s API says Twitter user id ' .
159                      "$flink->foreign_id has " .
160                      count($friends_ids) . ' friends.');
161
162         // Calculate how many pages to get...
163         $pages = ceil(count($friends_ids) / 100);
164
165         if ($pages == 0) {
166             common_debug($this->name() . " - $user seems to have no friends.");
167         }
168
169         for ($i = 1; $i <= $pages; $i++) {
170
171         try {
172             $more_friends = $client->statusesFriends(null, null, null, $i);
173         } catch (Exception $e) {
174             common_log(LOG_WARNING, $this->name() .
175                        ' - cURL error getting Twitter statuses/friends ' .
176                        "page $i - " . $e->getCode() . ' - ' .
177                        $e->getMessage());
178         }
179
180             if (empty($more_friends)) {
181                 common_log(LOG_WARNING, $this->name() .
182                            " - Couldn't retrieve page $i " .
183                            "of Twitter user $flink->foreign_id friends.");
184                 continue;
185             } else {
186                 $friends = array_merge($friends, $more_friends);
187             }
188         }
189
190         return $friends;
191     }
192
193     function subscribeTwitterFriends($flink)
194     {
195         $friends = $this->fetchTwitterFriends($flink);
196
197         if (empty($friends)) {
198             common_debug($this->name() .
199                          ' - Couldn\'t get friends from Twitter for ' .
200                          "Twitter user $flink->foreign_id.");
201             return false;
202         }
203
204         $profile = $flink->getProfile();
205
206         foreach ($friends as $friend) {
207
208             $friend_name = $friend->screen_name;
209             $friend_id = (int) $friend->id;
210
211             // Update or create the Foreign_user record for each
212             // Twitter friend
213
214             if (!save_twitter_user($friend_id, $friend_name)) {
215                 common_log(LOG_WARNING, $this->name() .
216                            " - Couldn't save $screen_name's friend, $friend_name.");
217                 continue;
218             }
219
220             // Check to see if there's a related local user
221
222             $friend_flink = Foreign_link::getByForeignID($friend_id,
223                                                          TWITTER_SERVICE);
224
225             if (!empty($friend_flink)) {
226
227                 // Get associated user and subscribe her
228
229                 $friend_profile = Profile::getKV('id', $friend_flink->user_id);
230
231                 if ($friend_profile instanceof Profile) {
232                     try {
233                         $other = Profile::getKV('id', $invites->user_id);
234                         Subscription::start($profile, $friend_profile);
235                         common_log(LOG_INFO,
236                                    $this->name() . ' - Subscribed ' .
237                                    "{$friend_profile->nickname} to {$profile->nickname}.");
238                     } catch (Exception $e) {
239                         common_debug($this->name() .
240                                      ' - Tried and failed subscribing ' .
241                                      "{$friend_profile->nickname} to {$profile->nickname} - " .
242                                      $e->getMessage());
243                     }
244                 }
245             }
246         }
247
248         return true;
249     }
250
251 }
252
253 $id    = null;
254 $debug = null;
255
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) {
261     $id = $args[0];
262 } else {
263     $id = null;
264 }
265
266 if (have_option('d') || have_option('debug')) {
267     $debug = true;
268 }
269
270 $syncer = new SyncTwitterFriendsDaemon($id, 60, 2, $debug);
271 $syncer->runOnce();