]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/twitterstatusfetcher.php
if something's a retweet, save it as a repeat in bridge
[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-2010, 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  * Fetch statuses from Twitter
48  *
49  * Fetches statuses from Twitter and inserts them as notices
50  *
51  * NOTE: an Avatar path MUST be set in config.php for this
52  * script to work, e.g.:
53  *     $config['avatar']['path'] = $config['site']['path'] . '/avatar/';
54  *
55  * @todo @fixme @gar Fix the above. For some reason $_path is always empty when
56  * this script is run, so the default avatar path is always set wrong in
57  * default.php. Therefore it must be set explicitly in config.php. --Z
58  *
59  * @category Twitter
60  * @package  StatusNet
61  * @author   Zach Copley <zach@status.net>
62  * @author   Evan Prodromou <evan@status.net>
63  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
64  * @link     http://status.net/
65  */
66
67 class TwitterStatusFetcher extends ParallelizingDaemon
68 {
69     /**
70      *  Constructor
71      *
72      * @param string  $id           the name/id of this daemon
73      * @param int     $interval     sleep this long before doing everything again
74      * @param int     $max_children maximum number of child processes at a time
75      * @param boolean $debug        debug output flag
76      *
77      * @return void
78      *
79      **/
80     function __construct($id = null, $interval = 60,
81                          $max_children = 2, $debug = null)
82     {
83         parent::__construct($id, $interval, $max_children, $debug);
84     }
85
86     /**
87      * Name of this daemon
88      *
89      * @return string Name of the daemon.
90      */
91
92     function name()
93     {
94         return ('twitterstatusfetcher.'.$this->_id);
95     }
96
97     /**
98      * Find all the Twitter foreign links for users who have requested
99      * importing of their friends' timelines
100      *
101      * @return array flinks an array of Foreign_link objects
102      */
103
104     function getObjects()
105     {
106         global $_DB_DATAOBJECT;
107
108         $flink = new Foreign_link();
109         $conn = &$flink->getDatabaseConnection();
110
111         $flink->service = TWITTER_SERVICE;
112         $flink->orderBy('last_noticesync');
113         $flink->find();
114
115         $flinks = array();
116
117         while ($flink->fetch()) {
118
119             if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
120                 FOREIGN_NOTICE_RECV) {
121                 $flinks[] = clone($flink);
122                 common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
123             } else {
124                 common_log(LOG_INFO, "nothing to sync");
125             }
126         }
127
128         $flink->free();
129         unset($flink);
130
131         $conn->disconnect();
132         unset($_DB_DATAOBJECT['CONNECTIONS']);
133
134         return $flinks;
135     }
136
137     function childTask($flink) {
138
139         // Each child ps needs its own DB connection
140
141         // Note: DataObject::getDatabaseConnection() creates
142         // a new connection if there isn't one already
143
144         $conn = &$flink->getDatabaseConnection();
145
146         $this->getTimeline($flink);
147
148         $flink->last_friendsync = common_sql_now();
149         $flink->update();
150
151         $conn->disconnect();
152
153         // XXX: Couldn't find a less brutal way to blow
154         // away a cached connection
155
156         global $_DB_DATAOBJECT;
157         unset($_DB_DATAOBJECT['CONNECTIONS']);
158     }
159
160     function getTimeline($flink)
161     {
162         if (empty($flink)) {
163             common_log(LOG_WARNING, $this->name() .
164                        " - Can't retrieve Foreign_link for foreign ID $fid");
165             return;
166         }
167
168         common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
169                      $flink->foreign_id);
170
171         // XXX: Biggest remaining issue - How do we know at which status
172         // to start importing?  How many statuses?  Right now I'm going
173         // with the default last 20.
174
175         $client = null;
176
177         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
178             $token = TwitterOAuthClient::unpackToken($flink->credentials);
179             $client = new TwitterOAuthClient($token->key, $token->secret);
180             common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
181         } else {
182             $client = new TwitterBasicAuthClient($flink);
183             common_debug($this->name() . ' - Grabbing friends timeline with basic auth.');
184         }
185
186         $timeline = null;
187
188         try {
189             $timeline = $client->statusesFriendsTimeline();
190         } catch (Exception $e) {
191             common_log(LOG_WARNING, $this->name() .
192                        ' - Twitter client unable to get friends timeline for user ' .
193                        $flink->user_id . ' - code: ' .
194                        $e->getCode() . 'msg: ' . $e->getMessage());
195         }
196
197         if (empty($timeline)) {
198             common_log(LOG_WARNING, $this->name() .  " - Empty timeline.");
199             return;
200         }
201
202         common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');
203
204         // Reverse to preserve order
205
206         foreach (array_reverse($timeline) as $status) {
207
208             // Hacktastic: filter out stuff coming from this StatusNet
209
210             $source = mb_strtolower(common_config('integration', 'source'));
211
212             if (preg_match("/$source/", mb_strtolower($status->source))) {
213                 common_debug($this->name() . ' - Skipping import of status ' .
214                              $status->id . ' with source ' . $source);
215                 continue;
216             }
217
218             // Don't save it if the user is protected
219             // FIXME: save it but treat it as private
220
221             if ($status->user->protected) {
222                 continue;
223             }
224
225             $this->saveStatus($status, $flink);
226         }
227
228         // Okay, record the time we synced with Twitter for posterity
229
230         $flink->last_noticesync = common_sql_now();
231         $flink->update();
232     }
233
234     function saveStatus($status, $flink=null)
235     {
236         $profile = $this->ensureProfile($status->user);
237
238         if (empty($profile)) {
239             common_log(LOG_ERR, $this->name() .
240                 ' - Problem saving notice. No associated Profile.');
241             return null;
242         }
243
244         $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
245
246         // check to see if we've already imported the status
247
248         $dupe = $this->checkDupe($profile, $statusUri);
249
250         if (!empty($dupe)) {
251             common_log(
252                 LOG_INFO,
253                 $this->name() .
254                 " - Ignoring duplicate import: $statusUri"
255             );
256             return $dupe;
257         }
258
259         // If it's a retweet, save it as a repeat!
260
261         if (!empty($status->retweeted_status)) {
262             $original = $this->saveStatus($status->retweeted_status);
263             return $original->repeat($profile->id, 'twitter');
264         }
265
266         $notice = new Notice();
267
268         $notice->profile_id = $profile->id;
269         $notice->uri        = $statusUri;
270         $notice->url        = $statusUri;
271         $notice->created    = strftime(
272             '%Y-%m-%d %H:%M:%S',
273             strtotime($status->created_at)
274         );
275
276         $notice->source     = 'twitter';
277
278         $notice->reply_to   = null;
279
280         if (!empty($status->in_reply_to_status_id)) {
281             $replyUri = $this->makeStatusURI($status->in_reply_to_screen_name, $status->in_reply_to_status_id);
282             $reply = Notice::staticGet('uri', $replyUri);
283             if (!empty($reply)) {
284                 $notice->reply_to     = $reply->id;
285                 $notice->conversation = $reply->conversation;
286             }
287         }
288
289         if (empty($notice->conversation)) {
290             $conv = Conversation::create();
291             $notice->conversation = $conv->id;
292         }
293
294         $notice->is_local   = Notice::GATEWAY;
295
296         $notice->content    = common_shorten_links($status->text);
297         $notice->rendered   = common_render_content(
298             $notice->content,
299             $notice
300         );
301
302         if (Event::handle('StartNoticeSave', array(&$notice))) {
303
304             $id = $notice->insert();
305
306             if (!$id) {
307                 common_log_db_error($notice, 'INSERT', __FILE__);
308                 common_log(LOG_ERR, $this->name() .
309                     ' - Problem saving notice.');
310             }
311
312             Event::handle('EndNoticeSave', array($notice));
313         }
314
315         if (!empty($flink)) {
316             Inbox::insertNotice($flink->user_id, $notice->id);
317         }
318         $notice->blowOnInsert();
319
320         return $notice;
321     }
322
323     /**
324      * Make an URI for a status.
325      *
326      * @param object $status status object
327      *
328      * @return string URI
329      */
330
331     function makeStatusURI($username, $id)
332     {
333         return 'http://twitter.com/'
334           . $username
335           . '/status/'
336           . $id;
337     }
338
339     /**
340      * Look up a Profile by profileurl field.  Profile::staticGet() was
341      * not working consistently.
342      *
343      * @param string $nickname   local nickname of the Twitter user
344      * @param string $profileurl the profile url
345      *
346      * @return mixed value the first Profile with that url, or null
347      */
348
349     function getProfileByUrl($nickname, $profileurl)
350     {
351         $profile = new Profile();
352         $profile->nickname = $nickname;
353         $profile->profileurl = $profileurl;
354         $profile->limit(1);
355
356         if ($profile->find()) {
357             $profile->fetch();
358             return $profile;
359         }
360
361         return null;
362     }
363
364     /**
365      * Check to see if this Twitter status has already been imported
366      *
367      * @param Profile $profile   Twitter user's local profile
368      * @param string  $statusUri URI of the status on Twitter
369      *
370      * @return mixed value a matching Notice or null
371      */
372
373     function checkDupe($profile, $statusUri)
374     {
375         $notice = new Notice();
376         $notice->uri = $statusUri;
377         $notice->profile_id = $profile->id;
378         $notice->limit(1);
379
380         if ($notice->find()) {
381             $notice->fetch();
382             return $notice;
383         }
384
385         return null;
386     }
387
388     function ensureProfile($user)
389     {
390         // check to see if there's already a profile for this user
391
392         $profileurl = 'http://twitter.com/' . $user->screen_name;
393         $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
394
395         if (!empty($profile)) {
396             common_debug($this->name() .
397                          " - Profile for $profile->nickname found.");
398
399             // Check to see if the user's Avatar has changed
400
401             $this->checkAvatar($user, $profile);
402             return $profile;
403
404         } else {
405
406             common_debug($this->name() . ' - Adding profile and remote profile ' .
407                          "for Twitter user: $profileurl.");
408
409             $profile = new Profile();
410             $profile->query("BEGIN");
411
412             $profile->nickname = $user->screen_name;
413             $profile->fullname = $user->name;
414             $profile->homepage = $user->url;
415             $profile->bio = $user->description;
416             $profile->location = $user->location;
417             $profile->profileurl = $profileurl;
418             $profile->created = common_sql_now();
419
420             try {
421                 $id = $profile->insert();
422             } catch(Exception $e) {
423                 common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
424             }
425
426             if (empty($id)) {
427                 common_log_db_error($profile, 'INSERT', __FILE__);
428                 $profile->query("ROLLBACK");
429                 return false;
430             }
431
432             // check for remote profile
433
434             $remote_pro = Remote_profile::staticGet('uri', $profileurl);
435
436             if (empty($remote_pro)) {
437
438                 $remote_pro = new Remote_profile();
439
440                 $remote_pro->id = $id;
441                 $remote_pro->uri = $profileurl;
442                 $remote_pro->created = common_sql_now();
443
444                 try {
445                     $rid = $remote_pro->insert();
446                 } catch (Exception $e) {
447                     common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
448                 }
449
450                 if (empty($rid)) {
451                     common_log_db_error($profile, 'INSERT', __FILE__);
452                     $profile->query("ROLLBACK");
453                     return false;
454                 }
455             }
456
457             $profile->query("COMMIT");
458
459             $this->saveAvatars($user, $id);
460
461             return $profile;
462         }
463     }
464
465     function checkAvatar($twitter_user, $profile)
466     {
467         global $config;
468
469         $path_parts = pathinfo($twitter_user->profile_image_url);
470
471         $newname = 'Twitter_' . $twitter_user->id . '_' .
472             $path_parts['basename'];
473
474         $oldname = $profile->getAvatar(48)->filename;
475
476         if ($newname != $oldname) {
477             common_debug($this->name() . ' - Avatar for Twitter user ' .
478                          "$profile->nickname has changed.");
479             common_debug($this->name() . " - old: $oldname new: $newname");
480
481             $this->updateAvatars($twitter_user, $profile);
482         }
483
484         if ($this->missingAvatarFile($profile)) {
485             common_debug($this->name() . ' - Twitter user ' .
486                          $profile->nickname .
487                          ' is missing one or more local avatars.');
488             common_debug($this->name() ." - old: $oldname new: $newname");
489
490             $this->updateAvatars($twitter_user, $profile);
491         }
492     }
493
494     function updateAvatars($twitter_user, $profile) {
495
496         global $config;
497
498         $path_parts = pathinfo($twitter_user->profile_image_url);
499
500         $img_root = substr($path_parts['basename'], 0, -11);
501         $ext = $path_parts['extension'];
502         $mediatype = $this->getMediatype($ext);
503
504         foreach (array('mini', 'normal', 'bigger') as $size) {
505             $url = $path_parts['dirname'] . '/' .
506                 $img_root . '_' . $size . ".$ext";
507             $filename = 'Twitter_' . $twitter_user->id . '_' .
508                 $img_root . "_$size.$ext";
509
510             $this->updateAvatar($profile->id, $size, $mediatype, $filename);
511             $this->fetchAvatar($url, $filename);
512         }
513     }
514
515     function missingAvatarFile($profile) {
516         foreach (array(24, 48, 73) as $size) {
517             $filename = $profile->getAvatar($size)->filename;
518             $avatarpath = Avatar::path($filename);
519             if (file_exists($avatarpath) == FALSE) {
520                 return true;
521             }
522         }
523         return false;
524     }
525
526     function getMediatype($ext)
527     {
528         $mediatype = null;
529
530         switch (strtolower($ext)) {
531         case 'jpg':
532             $mediatype = 'image/jpg';
533             break;
534         case 'gif':
535             $mediatype = 'image/gif';
536             break;
537         default:
538             $mediatype = 'image/png';
539         }
540
541         return $mediatype;
542     }
543
544     function saveAvatars($user, $id)
545     {
546         global $config;
547
548         $path_parts = pathinfo($user->profile_image_url);
549         $ext = $path_parts['extension'];
550         $end = strlen('_normal' . $ext);
551         $img_root = substr($path_parts['basename'], 0, -($end+1));
552         $mediatype = $this->getMediatype($ext);
553
554         foreach (array('mini', 'normal', 'bigger') as $size) {
555             $url = $path_parts['dirname'] . '/' .
556                 $img_root . '_' . $size . ".$ext";
557             $filename = 'Twitter_' . $user->id . '_' .
558                 $img_root . "_$size.$ext";
559
560             if ($this->fetchAvatar($url, $filename)) {
561                 $this->newAvatar($id, $size, $mediatype, $filename);
562             } else {
563                 common_log(LOG_WARNING, $id() .
564                            " - Problem fetching Avatar: $url");
565             }
566         }
567     }
568
569     function updateAvatar($profile_id, $size, $mediatype, $filename) {
570
571         common_debug($this->name() . " - Updating avatar: $size");
572
573         $profile = Profile::staticGet($profile_id);
574
575         if (empty($profile)) {
576             common_debug($this->name() . " - Couldn't get profile: $profile_id!");
577             return;
578         }
579
580         $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
581         $avatar = $profile->getAvatar($sizes[$size]);
582
583         // Delete the avatar, if present
584
585         if ($avatar) {
586             $avatar->delete();
587         }
588
589         $this->newAvatar($profile->id, $size, $mediatype, $filename);
590     }
591
592     function newAvatar($profile_id, $size, $mediatype, $filename)
593     {
594         global $config;
595
596         $avatar = new Avatar();
597         $avatar->profile_id = $profile_id;
598
599         switch($size) {
600         case 'mini':
601             $avatar->width  = 24;
602             $avatar->height = 24;
603             break;
604         case 'normal':
605             $avatar->width  = 48;
606             $avatar->height = 48;
607             break;
608         default:
609
610             // Note: Twitter's big avatars are a different size than
611             // StatusNet's (StatusNet's = 96)
612
613             $avatar->width  = 73;
614             $avatar->height = 73;
615         }
616
617         $avatar->original = 0; // we don't have the original
618         $avatar->mediatype = $mediatype;
619         $avatar->filename = $filename;
620         $avatar->url = Avatar::url($filename);
621
622         $avatar->created = common_sql_now();
623
624         try {
625             $id = $avatar->insert();
626         } catch (Exception $e) {
627             common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
628         }
629
630         if (empty($id)) {
631             common_log_db_error($avatar, 'INSERT', __FILE__);
632             return null;
633         }
634
635         common_debug($this->name() .
636                      " - Saved new $size avatar for $profile_id.");
637
638         return $id;
639     }
640
641     /**
642      * Fetch a remote avatar image and save to local storage.
643      *
644      * @param string $url avatar source URL
645      * @param string $filename bare local filename for download
646      * @return bool true on success, false on failure
647      */
648     function fetchAvatar($url, $filename)
649     {
650         common_debug($this->name() . " - Fetching Twitter avatar: $url");
651
652         $request = HTTPClient::start();
653         $response = $request->get($url);
654         if ($response->isOk()) {
655             $avatarfile = Avatar::path($filename);
656             $ok = file_put_contents($avatarfile, $response->getBody());
657             if (!$ok) {
658                 common_log(LOG_WARNING, $this->name() .
659                            " - Couldn't open file $filename");
660                 return false;
661             }
662         } else {
663             return false;
664         }
665
666         return true;
667     }
668 }
669
670 $id    = null;
671 $debug = null;
672
673 if (have_option('i')) {
674     $id = get_option_value('i');
675 } else if (have_option('--id')) {
676     $id = get_option_value('--id');
677 } else if (count($args) > 0) {
678     $id = $args[0];
679 } else {
680     $id = null;
681 }
682
683 if (have_option('d') || have_option('debug')) {
684     $debug = true;
685 }
686
687 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);
688 $fetcher->runOnce();
689