]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/twitterstatusfetcher.php
Merge branch 'master' into 0.9.x
[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/twitteroauthclient.php';
44
45 /**
46  * Fetch statuses from Twitter
47  *
48  * Fetches statuses from Twitter and inserts them as notices
49  *
50  * NOTE: an Avatar path MUST be set in config.php for this
51  * script to work, e.g.:
52  *     $config['avatar']['path'] = $config['site']['path'] . '/avatar/';
53  *
54  * @todo @fixme @gar Fix the above. For some reason $_path is always empty when
55  * this script is run, so the default avatar path is always set wrong in
56  * default.php. Therefore it must be set explicitly in config.php. --Z
57  *
58  * @category Twitter
59  * @package  StatusNet
60  * @author   Zach Copley <zach@status.net>
61  * @author   Evan Prodromou <evan@status.net>
62  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
63  * @link     http://status.net/
64  */
65 class TwitterStatusFetcher extends ParallelizingDaemon
66 {
67     /**
68      *  Constructor
69      *
70      * @param string  $id           the name/id of this daemon
71      * @param int     $interval     sleep this long before doing everything again
72      * @param int     $max_children maximum number of child processes at a time
73      * @param boolean $debug        debug output flag
74      *
75      * @return void
76      *
77      **/
78     function __construct($id = null, $interval = 60,
79                          $max_children = 2, $debug = null)
80     {
81         parent::__construct($id, $interval, $max_children, $debug);
82     }
83
84     /**
85      * Name of this daemon
86      *
87      * @return string Name of the daemon.
88      */
89     function name()
90     {
91         return ('twitterstatusfetcher.'.$this->_id);
92     }
93
94     /**
95      * Find all the Twitter foreign links for users who have requested
96      * importing of their friends' timelines
97      *
98      * @return array flinks an array of Foreign_link objects
99      */
100     function getObjects()
101     {
102         global $_DB_DATAOBJECT;
103         $flink = new Foreign_link();
104         $conn = &$flink->getDatabaseConnection();
105
106         $flink->service = TWITTER_SERVICE;
107         $flink->orderBy('last_noticesync');
108         $flink->find();
109
110         $flinks = array();
111
112         while ($flink->fetch()) {
113
114             if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
115                 FOREIGN_NOTICE_RECV) {
116                 $flinks[] = clone($flink);
117                 common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
118             } else {
119                 common_log(LOG_INFO, "nothing to sync");
120             }
121         }
122
123         $flink->free();
124         unset($flink);
125
126         $conn->disconnect();
127         unset($_DB_DATAOBJECT['CONNECTIONS']);
128
129         return $flinks;
130     }
131
132     function childTask($flink) {
133         // Each child ps needs its own DB connection
134
135         // Note: DataObject::getDatabaseConnection() creates
136         // a new connection if there isn't one already
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         global $_DB_DATAOBJECT;
149         unset($_DB_DATAOBJECT['CONNECTIONS']);
150     }
151
152     function getTimeline($flink)
153     {
154         if (empty($flink)) {
155             common_log(LOG_WARNING, $this->name() .
156                        " - Can't retrieve Foreign_link for foreign ID $fid");
157             return;
158         }
159
160         common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
161                      $flink->foreign_id);
162
163         $client = null;
164
165         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
166             $token = TwitterOAuthClient::unpackToken($flink->credentials);
167             $client = new TwitterOAuthClient($token->key, $token->secret);
168             common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
169         } else {
170             common_debug("Skipping friends timeline for $flink->foreign_id since not OAuth.");
171         }
172
173         $timeline = null;
174
175         $lastId = Twitter_synch_status::getLastId($flink->foreign_id, 'home_timeline');
176
177         common_debug("Got lastId value '{$lastId}' for foreign id '{$flink->foreign_id}' and timeline 'home_timeline'");
178
179         try {
180             $timeline = $client->statusesHomeTimeline($lastId);
181         } catch (Exception $e) {
182             common_log(LOG_WARNING, $this->name() .
183                        ' - Twitter client unable to get friends timeline for user ' .
184                        $flink->user_id . ' - code: ' .
185                        $e->getCode() . 'msg: ' . $e->getMessage());
186         }
187
188         if (empty($timeline)) {
189             common_log(LOG_WARNING, $this->name() .  " - Empty timeline.");
190             return;
191         }
192
193         common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');
194
195         $importer = new TwitterImport();
196
197         // Reverse to preserve order
198
199         foreach (array_reverse($timeline) as $status) {
200             $notice = $importer->importStatus($status);
201
202             if (!empty($notice)) {
203                 Inbox::insertNotice($flink->user_id, $notice->id);
204             }
205         }
206
207         if (!empty($timeline)) {
208             $lastId = twitter_id($timeline[0]);
209             Twitter_synch_status::setLastId($flink->foreign_id, 'home_timeline', $lastId);
210             common_debug("Set lastId value '$lastId' for foreign id '{$flink->foreign_id}' and timeline 'home_timeline'");
211         }
212
213         // Okay, record the time we synced with Twitter for posterity
214         $flink->last_noticesync = common_sql_now();
215         $flink->update();
216     }
217 }
218
219 $id    = null;
220 $debug = null;
221
222 if (have_option('i')) {
223     $id = get_option_value('i');
224 } else if (have_option('--id')) {
225     $id = get_option_value('--id');
226 } else if (count($args) > 0) {
227     $id = $args[0];
228 } else {
229     $id = null;
230 }
231
232 if (have_option('d') || have_option('debug')) {
233     $debug = true;
234 }
235
236 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);
237 $fetcher->runOnce();