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