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