4 * StatusNet - the distributed open-source microblogging tool
5 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));
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
28 $shortoptions = 'di::';
29 $longoptions = array('id::', 'debug');
31 $helptext = <<<END_OF_TRIM_HELP
32 Batch script for retrieving Twitter messages from foreign service.
34 -i --id Identity (default 'generic')
35 -d --debug Debug (lots of log output)
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';
47 * Fetcher for statuses from Twitter
49 * Fetches statuses from Twitter and inserts them as notices in local
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/
60 // NOTE: an Avatar path MUST be set in config.php for this
61 // script to work: e.g.: $config['avatar']['path'] = '/statusnet/avatar';
63 class TwitterStatusFetcher extends ParallelizingDaemon
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
76 function __construct($id = null, $interval = 60,
77 $max_children = 2, $debug = null)
79 parent::__construct($id, $interval, $max_children, $debug);
85 * @return string Name of the daemon.
90 return ('twitterstatusfetcher.'.$this->_id);
94 * Find all the Twitter foreign links for users who have requested
95 * importing of their friends' timelines
97 * @return array flinks an array of Foreign_link objects
100 function getObjects()
102 global $_DB_DATAOBJECT;
104 $flink = new Foreign_link();
105 $conn = &$flink->getDatabaseConnection();
107 $flink->service = TWITTER_SERVICE;
108 $flink->orderBy('last_noticesync');
113 while ($flink->fetch()) {
115 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
116 FOREIGN_NOTICE_RECV) {
117 $flinks[] = clone($flink);
118 common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
120 common_log(LOG_INFO, "nothing to sync");
128 unset($_DB_DATAOBJECT['CONNECTIONS']);
133 function childTask($flink) {
135 // Each child ps needs its own DB connection
137 // Note: DataObject::getDatabaseConnection() creates
138 // a new connection if there isn't one already
140 $conn = &$flink->getDatabaseConnection();
142 $this->getTimeline($flink);
144 $flink->last_friendsync = common_sql_now();
149 // XXX: Couldn't find a less brutal way to blow
150 // away a cached connection
152 global $_DB_DATAOBJECT;
153 unset($_DB_DATAOBJECT['CONNECTIONS']);
156 function getTimeline($flink)
159 common_log(LOG_WARNING, $this->name() .
160 " - Can't retrieve Foreign_link for foreign ID $fid");
164 common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
167 // XXX: Biggest remaining issue - How do we know at which status
168 // to start importing? How many statuses? Right now I'm going
169 // with the default last 20.
173 if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
174 $token = TwitterOAuthClient::unpackToken($flink->credentials);
175 $client = new TwitterOAuthClient($token->key, $token->secret);
176 common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
178 $client = new TwitterBasicAuthClient($flink);
179 common_debug($this->name() . ' - Grabbing friends timeline with basic auth.');
185 $timeline = $client->statusesFriendsTimeline();
186 } catch (Exception $e) {
187 common_log(LOG_WARNING, $this->name() .
188 ' - Twitter client unable to get friends timeline for user ' .
189 $flink->user_id . ' - code: ' .
190 $e->getCode() . 'msg: ' . $e->getMessage());
193 if (empty($timeline)) {
194 common_log(LOG_WARNING, $this->name() . " - Empty timeline.");
198 // Reverse to preserve order
200 foreach (array_reverse($timeline) as $status) {
202 // Hacktastic: filter out stuff coming from this StatusNet
204 $source = mb_strtolower(common_config('integration', 'source'));
206 if (preg_match("/$source/", mb_strtolower($status->source))) {
207 common_debug($this->name() . ' - Skipping import of status ' .
208 $status->id . ' with source ' . $source);
212 $this->saveStatus($status, $flink);
215 // Okay, record the time we synced with Twitter for posterity
217 $flink->last_noticesync = common_sql_now();
221 function saveStatus($status, $flink)
223 $id = $this->ensureProfile($status->user);
225 $profile = Profile::staticGet($id);
227 if (empty($profile)) {
228 common_log(LOG_ERR, $this->name() .
229 ' - Problem saving notice. No associated Profile.');
233 // XXX: change of screen name?
235 $uri = 'http://twitter.com/' . $status->user->screen_name .
236 '/status/' . $status->id;
238 $notice = Notice::staticGet('uri', $uri);
240 // check to see if we've already imported the status
242 if (empty($notice)) {
244 $notice = new Notice();
246 $notice->profile_id = $id;
248 $notice->created = strftime('%Y-%m-%d %H:%M:%S',
249 strtotime($status->created_at));
250 $notice->content = common_shorten_links($status->text); // XXX
251 $notice->rendered = common_render_content($notice->content, $notice);
252 $notice->source = 'twitter';
253 $notice->reply_to = null; // XXX: lookup reply
254 $notice->is_local = Notice::GATEWAY;
256 if (Event::handle('StartNoticeSave', array(&$notice))) {
257 $id = $notice->insert();
258 Event::handle('EndNoticeSave', array($notice));
262 if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
263 'user_id' => $flink->user_id))) {
265 $inbox = new Notice_inbox();
267 $inbox->user_id = $flink->user_id;
268 $inbox->notice_id = $notice->id;
269 $inbox->created = $notice->created;
270 $inbox->source = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
276 function ensureProfile($user)
278 // check to see if there's already a profile for this user
280 $profileurl = 'http://twitter.com/' . $user->screen_name;
281 $profile = Profile::staticGet('profileurl', $profileurl);
283 if (!empty($profile)) {
284 common_debug($this->name() .
285 " - Profile for $profile->nickname found.");
287 // Check to see if the user's Avatar has changed
289 $this->checkAvatar($user, $profile);
293 common_debug($this->name() . ' - Adding profile and remote profile ' .
294 "for Twitter user: $profileurl.");
296 $profile = new Profile();
297 $profile->query("BEGIN");
299 $profile->nickname = $user->screen_name;
300 $profile->fullname = $user->name;
301 $profile->homepage = $user->url;
302 $profile->bio = $user->description;
303 $profile->location = $user->location;
304 $profile->profileurl = $profileurl;
305 $profile->created = common_sql_now();
307 $id = $profile->insert();
310 common_log_db_error($profile, 'INSERT', __FILE__);
311 $profile->query("ROLLBACK");
315 // check for remote profile
317 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
319 if (empty($remote_pro)) {
321 $remote_pro = new Remote_profile();
323 $remote_pro->id = $id;
324 $remote_pro->uri = $profileurl;
325 $remote_pro->created = common_sql_now();
327 $rid = $remote_pro->insert();
330 common_log_db_error($profile, 'INSERT', __FILE__);
331 $profile->query("ROLLBACK");
336 $profile->query("COMMIT");
338 $this->saveAvatars($user, $id);
344 function checkAvatar($twitter_user, $profile)
348 $path_parts = pathinfo($twitter_user->profile_image_url);
350 $newname = 'Twitter_' . $twitter_user->id . '_' .
351 $path_parts['basename'];
353 $oldname = $profile->getAvatar(48)->filename;
355 if ($newname != $oldname) {
356 common_debug($this->name() . ' - Avatar for Twitter user ' .
357 "$profile->nickname has changed.");
358 common_debug($this->name() . " - old: $oldname new: $newname");
360 $this->updateAvatars($twitter_user, $profile);
363 if ($this->missingAvatarFile($profile)) {
364 common_debug($this->name() . ' - Twitter user ' .
366 ' is missing one or more local avatars.');
367 common_debug($this->name() ." - old: $oldname new: $newname");
369 $this->updateAvatars($twitter_user, $profile);
374 function updateAvatars($twitter_user, $profile) {
378 $path_parts = pathinfo($twitter_user->profile_image_url);
380 $img_root = substr($path_parts['basename'], 0, -11);
381 $ext = $path_parts['extension'];
382 $mediatype = $this->getMediatype($ext);
384 foreach (array('mini', 'normal', 'bigger') as $size) {
385 $url = $path_parts['dirname'] . '/' .
386 $img_root . '_' . $size . ".$ext";
387 $filename = 'Twitter_' . $twitter_user->id . '_' .
388 $img_root . "_$size.$ext";
390 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
391 $this->fetchAvatar($url, $filename);
395 function missingAvatarFile($profile) {
397 foreach (array(24, 48, 73) as $size) {
399 $filename = $profile->getAvatar($size)->filename;
400 $avatarpath = Avatar::path($filename);
402 if (file_exists($avatarpath) == FALSE) {
410 function getMediatype($ext)
414 switch (strtolower($ext)) {
416 $mediatype = 'image/jpg';
419 $mediatype = 'image/gif';
422 $mediatype = 'image/png';
428 function saveAvatars($user, $id)
432 $path_parts = pathinfo($user->profile_image_url);
433 $ext = $path_parts['extension'];
434 $end = strlen('_normal' . $ext);
435 $img_root = substr($path_parts['basename'], 0, -($end+1));
436 $mediatype = $this->getMediatype($ext);
438 foreach (array('mini', 'normal', 'bigger') as $size) {
439 $url = $path_parts['dirname'] . '/' .
440 $img_root . '_' . $size . ".$ext";
441 $filename = 'Twitter_' . $user->id . '_' .
442 $img_root . "_$size.$ext";
444 if ($this->fetchAvatar($url, $filename)) {
445 $this->newAvatar($id, $size, $mediatype, $filename);
447 common_log(LOG_WARNING, $this->id() .
448 " - Problem fetching Avatar: $url");
453 function updateAvatar($profile_id, $size, $mediatype, $filename) {
455 common_debug($this->name() . " - Updating avatar: $size");
457 $profile = Profile::staticGet($profile_id);
459 if (empty($profile)) {
460 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
464 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
465 $avatar = $profile->getAvatar($sizes[$size]);
467 // Delete the avatar, if present
473 $this->newAvatar($profile->id, $size, $mediatype, $filename);
476 function newAvatar($profile_id, $size, $mediatype, $filename)
480 $avatar = new Avatar();
481 $avatar->profile_id = $profile_id;
486 $avatar->height = 24;
490 $avatar->height = 48;
494 // Note: Twitter's big avatars are a different size than
495 // StatusNet's (StatusNet's = 96)
498 $avatar->height = 73;
501 $avatar->original = 0; // we don't have the original
502 $avatar->mediatype = $mediatype;
503 $avatar->filename = $filename;
504 $avatar->url = Avatar::url($filename);
506 $avatar->created = common_sql_now();
508 $id = $avatar->insert();
511 common_log_db_error($avatar, 'INSERT', __FILE__);
515 common_debug($this->name() .
516 " - Saved new $size avatar for $profile_id.");
522 * Fetch a remote avatar image and save to local storage.
524 * @param string $url avatar source URL
525 * @param string $filename bare local filename for download
526 * @return bool true on success, false on failure
528 function fetchAvatar($url, $filename)
530 common_debug($this->name() . " - Fetching Twitter avatar: $url");
532 $request = HTTPClient::start();
533 $response = $request->get($url);
534 if ($response->isOk()) {
535 $avatarfile = Avatar::path($filename);
536 $ok = file_put_contents($avatarfile, $response->getBody());
538 common_log(LOG_WARNING, $this->name() .
539 " - Couldn't open file $filename");
553 if (have_option('i')) {
554 $id = get_option_value('i');
555 } else if (have_option('--id')) {
556 $id = get_option_value('--id');
557 } else if (count($args) > 0) {
563 if (have_option('d') || have_option('debug')) {
567 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);