]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/twitterstatusfetcher.php
Remove more contractions
[quix0rs-gnu-social.git] / plugins / TwitterBridge / daemons / twitterstatusfetcher.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 // Tune number of processes and how often to poll Twitter
24 // XXX: Should these things be in config.php?
25 define('MAXCHILDREN', 2);
26 define('POLL_INTERVAL', 60); // in seconds
27
28 $shortoptions = 'di::';
29 $longoptions = array('id::', 'debug');
30
31 $helptext = <<<END_OF_TRIM_HELP
32 Batch script for retrieving Twitter messages from foreign service.
33
34   -i --id              Identity (default 'generic')
35   -d --debug           Debug (lots of log output)
36
37 END_OF_TRIM_HELP;
38
39 require_once INSTALLDIR . '/scripts/commandline.inc';
40 require_once INSTALLDIR . '/lib/common.php';
41 require_once INSTALLDIR . '/lib/daemon.php';
42 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
43 require_once INSTALLDIR . '/plugins/TwitterBridge/twitterbasicauthclient.php';
44 require_once INSTALLDIR . '/plugins/TwitterBridge/twitteroauthclient.php';
45
46 /**
47  * Fetcher for statuses from Twitter
48  *
49  * Fetches statuses from Twitter and inserts them as notices in local
50  * system.
51  *
52  * @category Twitter
53  * @package  StatusNet
54  * @author   Zach Copley <zach@status.net>
55  * @author   Evan Prodromou <evan@status.net>
56  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
57  * @link     http://status.net/
58  */
59
60 // NOTE: an Avatar path MUST be set in config.php for this
61 // script to work: e.g.: $config['avatar']['path'] = '/statusnet/avatar';
62
63 class TwitterStatusFetcher extends ParallelizingDaemon
64 {
65     /**
66      *  Constructor
67      *
68      * @param string  $id           the name/id of this daemon
69      * @param int     $interval     sleep this long before doing everything again
70      * @param int     $max_children maximum number of child processes at a time
71      * @param boolean $debug        debug output flag
72      *
73      * @return void
74      *
75      **/
76     function __construct($id = null, $interval = 60,
77                          $max_children = 2, $debug = null)
78     {
79         parent::__construct($id, $interval, $max_children, $debug);
80     }
81
82     /**
83      * Name of this daemon
84      *
85      * @return string Name of the daemon.
86      */
87
88     function name()
89     {
90         return ('twitterstatusfetcher.'.$this->_id);
91     }
92
93     /**
94      * Find all the Twitter foreign links for users who have requested
95      * importing of their friends' timelines
96      *
97      * @return array flinks an array of Foreign_link objects
98      */
99
100     function getObjects()
101     {
102         global $_DB_DATAOBJECT;
103
104         $flink = new Foreign_link();
105         $conn = &$flink->getDatabaseConnection();
106
107         $flink->service = TWITTER_SERVICE;
108         $flink->orderBy('last_noticesync');
109         $flink->find();
110
111         $flinks = array();
112         common_log(LOG_INFO, "hello");
113
114         while ($flink->fetch()) {
115
116             if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
117                 FOREIGN_NOTICE_RECV) {
118                 $flinks[] = clone($flink);
119                 common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
120             } else {
121                 common_log(LOG_INFO, "nothing to sync");
122             }
123         }
124
125         $flink->free();
126         unset($flink);
127
128         $conn->disconnect();
129         unset($_DB_DATAOBJECT['CONNECTIONS']);
130
131         return $flinks;
132     }
133
134     function childTask($flink) {
135
136         // Each child ps needs its own DB connection
137
138         // Note: DataObject::getDatabaseConnection() creates
139         // a new connection if there is not one already
140
141         $conn = &$flink->getDatabaseConnection();
142
143         $this->getTimeline($flink);
144
145         $flink->last_friendsync = common_sql_now();
146         $flink->update();
147
148         $conn->disconnect();
149
150         // XXX: Could not find a less brutal way to blow
151         // away a cached connection
152
153         global $_DB_DATAOBJECT;
154         unset($_DB_DATAOBJECT['CONNECTIONS']);
155     }
156
157     function getTimeline($flink)
158     {
159         if (empty($flink)) {
160             common_log(LOG_WARNING, $this->name() .
161                        " - Cannot retrieve Foreign_link for foreign ID $fid");
162             return;
163         }
164
165         common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
166                      $flink->foreign_id);
167
168         // XXX: Biggest remaining issue - How do we know at which status
169         // to start importing?  How many statuses?  Right now I'm going
170         // with the default last 20.
171
172         $client = null;
173
174         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
175             $token = TwitterOAuthClient::unpackToken($flink->credentials);
176             $client = new TwitterOAuthClient($token->key, $token->secret);
177             common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
178         } else {
179             $client = new TwitterBasicAuthClient($flink);
180             common_debug($this->name() . ' - Grabbing friends timeline with basic auth.');
181         }
182
183         $timeline = null;
184
185         try {
186             $timeline = $client->statusesFriendsTimeline();
187         } catch (Exception $e) {
188             common_log(LOG_WARNING, $this->name() .
189                        ' - Twitter client unable to get friends timeline for user ' .
190                        $flink->user_id . ' - code: ' .
191                        $e->getCode() . 'msg: ' . $e->getMessage());
192         }
193
194         if (empty($timeline)) {
195             common_log(LOG_WARNING, $this->name() .  " - Empty timeline.");
196             return;
197         }
198
199         // Reverse to preserve order
200
201         foreach (array_reverse($timeline) as $status) {
202
203             // Hacktastic: filter out stuff coming from this StatusNet
204
205             $source = mb_strtolower(common_config('integration', 'source'));
206
207             if (preg_match("/$source/", mb_strtolower($status->source))) {
208                 common_debug($this->name() . ' - Skipping import of status ' .
209                              $status->id . ' with source ' . $source);
210                 continue;
211             }
212
213             $this->saveStatus($status, $flink);
214         }
215
216         // Okay, record the time we synced with Twitter for posterity
217
218         $flink->last_noticesync = common_sql_now();
219         $flink->update();
220     }
221
222     function saveStatus($status, $flink)
223     {
224         $id = $this->ensureProfile($status->user);
225
226         $profile = Profile::staticGet($id);
227
228         if (empty($profile)) {
229             common_log(LOG_ERR, $this->name() .
230                 ' - Problem saving notice. No associated Profile.');
231             return null;
232         }
233
234         // XXX: change of screen name?
235
236         $uri = 'http://twitter.com/' . $status->user->screen_name .
237             '/status/' . $status->id;
238
239         $notice = Notice::staticGet('uri', $uri);
240
241         // check to see if we've already imported the status
242
243         if (empty($notice)) {
244
245             $notice = new Notice();
246
247             $notice->profile_id = $id;
248             $notice->uri        = $uri;
249             $notice->created    = strftime('%Y-%m-%d %H:%M:%S',
250                                            strtotime($status->created_at));
251             $notice->content    = common_shorten_links($status->text); // XXX
252             $notice->rendered   = common_render_content($notice->content, $notice);
253             $notice->source     = 'twitter';
254             $notice->reply_to   = null; // XXX: lookup reply
255             $notice->is_local   = Notice::GATEWAY;
256
257             if (Event::handle('StartNoticeSave', array(&$notice))) {
258                 $id = $notice->insert();
259                 Event::handle('EndNoticeSave', array($notice));
260             }
261         }
262
263         if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
264                                          'user_id' => $flink->user_id))) {
265             // Add to inbox
266             $inbox = new Notice_inbox();
267
268             $inbox->user_id   = $flink->user_id;
269             $inbox->notice_id = $notice->id;
270             $inbox->created   = $notice->created;
271             $inbox->source    = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
272
273             $inbox->insert();
274         }
275     }
276
277     function ensureProfile($user)
278     {
279         // check to see if there's already a profile for this user
280
281         $profileurl = 'http://twitter.com/' . $user->screen_name;
282         $profile = Profile::staticGet('profileurl', $profileurl);
283
284         if (!empty($profile)) {
285             common_debug($this->name() .
286                          " - Profile for $profile->nickname found.");
287
288             // Check to see if the user's Avatar has changed
289
290             $this->checkAvatar($user, $profile);
291             return $profile->id;
292
293         } else {
294             common_debug($this->name() . ' - Adding profile and remote profile ' .
295                          "for Twitter user: $profileurl.");
296
297             $profile = new Profile();
298             $profile->query("BEGIN");
299
300             $profile->nickname = $user->screen_name;
301             $profile->fullname = $user->name;
302             $profile->homepage = $user->url;
303             $profile->bio = $user->description;
304             $profile->location = $user->location;
305             $profile->profileurl = $profileurl;
306             $profile->created = common_sql_now();
307
308             $id = $profile->insert();
309
310             if (empty($id)) {
311                 common_log_db_error($profile, 'INSERT', __FILE__);
312                 $profile->query("ROLLBACK");
313                 return false;
314             }
315
316             // check for remote profile
317
318             $remote_pro = Remote_profile::staticGet('uri', $profileurl);
319
320             if (empty($remote_pro)) {
321
322                 $remote_pro = new Remote_profile();
323
324                 $remote_pro->id = $id;
325                 $remote_pro->uri = $profileurl;
326                 $remote_pro->created = common_sql_now();
327
328                 $rid = $remote_pro->insert();
329
330                 if (empty($rid)) {
331                     common_log_db_error($profile, 'INSERT', __FILE__);
332                     $profile->query("ROLLBACK");
333                     return false;
334                 }
335             }
336
337             $profile->query("COMMIT");
338
339             $this->saveAvatars($user, $id);
340
341             return $id;
342         }
343     }
344
345     function checkAvatar($twitter_user, $profile)
346     {
347         global $config;
348
349         $path_parts = pathinfo($twitter_user->profile_image_url);
350
351         $newname = 'Twitter_' . $twitter_user->id . '_' .
352             $path_parts['basename'];
353
354         $oldname = $profile->getAvatar(48)->filename;
355
356         if ($newname != $oldname) {
357             common_debug($this->name() . ' - Avatar for Twitter user ' .
358                          "$profile->nickname has changed.");
359             common_debug($this->name() . " - old: $oldname new: $newname");
360
361             $this->updateAvatars($twitter_user, $profile);
362         }
363
364         if ($this->missingAvatarFile($profile)) {
365             common_debug($this->name() . ' - Twitter user ' .
366                          $profile->nickname .
367                          ' is missing one or more local avatars.');
368             common_debug($this->name() ." - old: $oldname new: $newname");
369
370             $this->updateAvatars($twitter_user, $profile);
371         }
372
373     }
374
375     function updateAvatars($twitter_user, $profile) {
376
377         global $config;
378
379         $path_parts = pathinfo($twitter_user->profile_image_url);
380
381         $img_root = substr($path_parts['basename'], 0, -11);
382         $ext = $path_parts['extension'];
383         $mediatype = $this->getMediatype($ext);
384
385         foreach (array('mini', 'normal', 'bigger') as $size) {
386             $url = $path_parts['dirname'] . '/' .
387                 $img_root . '_' . $size . ".$ext";
388             $filename = 'Twitter_' . $twitter_user->id . '_' .
389                 $img_root . "_$size.$ext";
390
391             $this->updateAvatar($profile->id, $size, $mediatype, $filename);
392             $this->fetchAvatar($url, $filename);
393         }
394     }
395
396     function missingAvatarFile($profile) {
397
398         foreach (array(24, 48, 73) as $size) {
399
400             $filename = $profile->getAvatar($size)->filename;
401             $avatarpath = Avatar::path($filename);
402
403             if (file_exists($avatarpath) == FALSE) {
404                 return true;
405             }
406         }
407
408         return false;
409     }
410
411     function getMediatype($ext)
412     {
413         $mediatype = null;
414
415         switch (strtolower($ext)) {
416         case 'jpg':
417             $mediatype = 'image/jpg';
418             break;
419         case 'gif':
420             $mediatype = 'image/gif';
421             break;
422         default:
423             $mediatype = 'image/png';
424         }
425
426         return $mediatype;
427     }
428
429     function saveAvatars($user, $id)
430     {
431         global $config;
432
433         $path_parts = pathinfo($user->profile_image_url);
434         $ext = $path_parts['extension'];
435         $end = strlen('_normal' . $ext);
436         $img_root = substr($path_parts['basename'], 0, -($end+1));
437         $mediatype = $this->getMediatype($ext);
438
439         foreach (array('mini', 'normal', 'bigger') as $size) {
440             $url = $path_parts['dirname'] . '/' .
441                 $img_root . '_' . $size . ".$ext";
442             $filename = 'Twitter_' . $user->id . '_' .
443                 $img_root . "_$size.$ext";
444
445             if ($this->fetchAvatar($url, $filename)) {
446                 $this->newAvatar($id, $size, $mediatype, $filename);
447             } else {
448                 common_log(LOG_WARNING, $this->id() .
449                            " - Problem fetching Avatar: $url");
450             }
451         }
452     }
453
454     function updateAvatar($profile_id, $size, $mediatype, $filename) {
455
456         common_debug($this->name() . " - Updating avatar: $size");
457
458         $profile = Profile::staticGet($profile_id);
459
460         if (empty($profile)) {
461             common_debug($this->name() . " - Could not get profile: $profile_id!");
462             return;
463         }
464
465         $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
466         $avatar = $profile->getAvatar($sizes[$size]);
467
468         // Delete the avatar, if present
469
470         if ($avatar) {
471             $avatar->delete();
472         }
473
474         $this->newAvatar($profile->id, $size, $mediatype, $filename);
475     }
476
477     function newAvatar($profile_id, $size, $mediatype, $filename)
478     {
479         global $config;
480
481         $avatar = new Avatar();
482         $avatar->profile_id = $profile_id;
483
484         switch($size) {
485         case 'mini':
486             $avatar->width  = 24;
487             $avatar->height = 24;
488             break;
489         case 'normal':
490             $avatar->width  = 48;
491             $avatar->height = 48;
492             break;
493         default:
494
495             // Note: Twitter's big avatars are a different size than
496             // StatusNet's (StatusNet's = 96)
497
498             $avatar->width  = 73;
499             $avatar->height = 73;
500         }
501
502         $avatar->original = 0; // we do not have the original
503         $avatar->mediatype = $mediatype;
504         $avatar->filename = $filename;
505         $avatar->url = Avatar::url($filename);
506
507         $avatar->created = common_sql_now();
508
509         $id = $avatar->insert();
510
511         if (empty($id)) {
512             common_log_db_error($avatar, 'INSERT', __FILE__);
513             return null;
514         }
515
516         common_debug($this->name() .
517                      " - Saved new $size avatar for $profile_id.");
518
519         return $id;
520     }
521
522     /**
523      * Fetch a remote avatar image and save to local storage.
524      *
525      * @param string $url avatar source URL
526      * @param string $filename bare local filename for download
527      * @return bool true on success, false on failure
528      */
529     function fetchAvatar($url, $filename)
530     {
531         common_debug($this->name() . " - Fetching Twitter avatar: $url");
532
533         $request = HTTPClient::start();
534         $response = $request->get($url);
535         if ($response->isOk()) {
536             $avatarfile = Avatar::path($filename);
537             $ok = file_put_contents($avatarfile, $response->getBody());
538             if (!$ok) {
539                 common_log(LOG_WARNING, $this->name() .
540                            " - Could not open file $filename");
541                 return false;
542             }
543         } else {
544             return false;
545         }
546
547         return true;
548     }
549 }
550
551 $id    = null;
552 $debug = null;
553
554 if (have_option('i')) {
555     $id = get_option_value('i');
556 } else if (have_option('--id')) {
557     $id = get_option_value('--id');
558 } else if (count($args) > 0) {
559     $id = $args[0];
560 } else {
561     $id = null;
562 }
563
564 if (have_option('d') || have_option('debug')) {
565     $debug = true;
566 }
567
568 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);
569 $fetcher->runOnce();
570