4 * StatusNet - the distributed open-source microblogging tool
5 * Copyright (C) 2008-2010, 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 $shortoptions = 'fi::a';
24 $longoptions = array('id::', 'foreground', 'all');
26 $helptext = <<<END_OF_TWITTERDAEMON_HELP
27 Daemon script for receiving new notices from Twitter users.
29 -i --id Identity (default none)
30 -a --all Handle Twitter for all local sites
31 (requires Stomp queue handler, status_network setup)
32 -f --foreground Stay in the foreground (default background)
34 END_OF_TWITTERDAEMON_HELP;
36 require_once INSTALLDIR.'/scripts/commandline.inc.php';
38 class TwitterDaemon extends SpawningDaemon
40 protected $allsites = false;
42 function __construct($id=null, $daemonize=true, $threads=1, $allsites=false)
45 // This should never happen. :)
46 throw new Exception("TwitterDaemon must run single-threaded");
48 parent::__construct($id, $daemonize, $threads);
49 $this->allsites = $allsites;
54 common_log(LOG_INFO, 'Waiting to listen to Twitter and queues');
56 $master = new TwitterMaster($this->get_id(), $this->processManager());
57 $master->init($this->allsites);
60 common_log(LOG_INFO, 'terminating normally');
62 return $master->respawn ? self::EXIT_RESTART : self::EXIT_SHUTDOWN;
67 class TwitterMaster extends IoMaster
69 protected $processManager;
71 function __construct($id, $processManager)
73 parent::__construct($id);
74 $this->processManager = $processManager;
78 * Initialize IoManagers for the currently configured site
79 * which are appropriate to this instance.
81 function initManagers()
83 $qm = QueueManager::get();
84 $qm->setActiveGroup('twitter');
85 $this->instantiate($qm);
86 $this->instantiate(new TwitterManager());
87 $this->instantiate($this->processManager);
92 class TwitterManager extends IoManager
94 // Recommended resource limits from http://dev.twitter.com/pages/site_streams
95 const MAX_STREAMS = 1000;
96 const USERS_PER_STREAM = 100;
97 const STREAMS_PER_SECOND = 20;
103 * Pull the site's active Twitter-importing users and start spawning
104 * some data streams for them!
106 * @fixme check their last-id and check whether we'll need to do a manual pull.
107 * @fixme abstract out the fetching so we can work over multiple sites.
109 protected function initStreams()
111 common_log(LOG_INFO, 'init...');
112 // Pull Twitter user IDs for all users we want to pull data for
113 $flink = new Foreign_link();
114 $flink->service = TWITTER_SERVICE;
115 // @fixme probably should do the bitfield check in a whereAdd but it's ugly :D
119 while ($flink->fetch()) {
120 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
121 FOREIGN_NOTICE_RECV) {
122 $userIds[] = $flink->foreign_id;
124 if (count($userIds) >= self::USERS_PER_STREAM) {
125 $this->spawnStream($userIds);
131 if (count($userIds)) {
132 $this->spawnStream($userIds);
137 * Prepare a Site Stream connection for the given chunk of users.
138 * The actual connection will be opened later.
140 * @param $userIds array of Twitter-side user IDs
142 protected function spawnStream($userIds)
144 $stream = $this->initSiteStream();
145 $stream->followUsers($userIds);
147 // Slip the stream reader into our list of active streams.
148 // We'll manage its actual connection on the next go-around.
149 $this->streams[] = $stream;
151 // Record the user->stream mappings; this makes it easier for us to know
152 // later if we need to kill something.
153 foreach ($userIds as $id) {
154 $this->users[$id] = $stream;
159 * Initialize a generic site streams connection object.
160 * All our connections will look like this, then we'll add users to them.
162 * @return TwitterStreamReader
164 protected function initSiteStream()
166 $auth = $this->siteStreamAuth();
167 $stream = new TwitterSiteStream($auth);
169 // Add our event handler callbacks. Whee!
170 $this->setupEvents($stream);
175 * Fetch the Twitter OAuth credentials to use to connect to the Site Streams API.
177 * This will use the locally-stored credentials for the applictation's owner account
178 * from the site configuration. These should be configured through the administration
179 * panels or manually in the config file.
181 * Will throw an exception if no credentials can be found -- but beware that invalid
182 * credentials won't cause breakage until later.
184 * @return TwitterOAuthClient
186 protected function siteStreamAuth()
188 $token = common_config('twitter', 'stream_token');
189 $secret = common_config('twitter', 'stream_secret');
190 if (empty($token) || empty($secret)) {
191 throw new ServerException('Twitter site streams have not been correctly configured. Configure the app owner account via the admin panel.');
193 return new TwitterOAuthClient($token, $secret);
197 * Collect the sockets for all active connections for i/o monitoring.
199 * @return array of resources
201 public function getSockets()
204 foreach ($this->streams as $stream) {
205 foreach ($stream->getSockets() as $socket) {
206 $sockets[] = $socket;
213 * We're ready to process input from one of our data sources! Woooooo!
214 * @fixme is there an easier way to map from socket back to owning module? :(
216 * @param resource $socket
217 * @return boolean success
219 public function handleInput($socket)
221 foreach ($this->streams as $stream) {
222 foreach ($stream->getSockets() as $aSocket) {
223 if ($socket === $aSocket) {
224 $stream->handleInput($socket);
232 * Start the i/o system up! Prepare our connections and start opening them.
234 * @fixme do some rate-limiting on the stream setup
235 * @fixme do some sensible backoff on failure etc
237 public function start()
239 $this->initStreams();
240 foreach ($this->streams as $stream) {
247 * Close down our connections when the daemon wraps up for business.
249 public function finish()
251 foreach ($this->streams as $index => $stream) {
253 unset($this->streams[$index]);
258 public static function get()
260 throw new Exception('not a singleton');
264 * Set up event handlers on the streaming interface.
266 * @fixme add more event types as we add handling for them
268 protected function setupEvents(TwitterStreamReader $stream)
273 foreach ($handlers as $event) {
274 $stream->hookEvent($event, array($this, 'onTwitter' . ucfirst($event)));
279 * Event callback notifying that a user has a new message in their home timeline.
280 * We store the incoming message into the queues for processing, keeping our own
281 * daemon running as shiny-fast as possible.
283 * @param object $status JSON data: Twitter status update
284 * @fixme in all-sites mode we may need to route queue items into another site's
285 * destination queues, or multiple sites.
287 protected function onTwitterStatus($status, $context)
291 'for_user' => $context->for_user,
293 $qm = QueueManager::get();
294 $qm->enqueue($data, 'tweetin');
299 if (have_option('i', 'id')) {
300 $id = get_option_value('i', 'id');
301 } else if (count($args) > 0) {
307 $foreground = have_option('f', 'foreground');
308 $all = have_option('a') || have_option('--all');
310 $daemon = new TwitterDaemon($id, !$foreground, 1, $all);