-
Notifications
You must be signed in to change notification settings - Fork 26
/
collect.py
182 lines (159 loc) · 5.66 KB
/
collect.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
from multiprocessing import Process
from tweepy import OAuthHandler, API, AppAuthHandler
from collection.accounts_post_2013 import start_streamer, start_lookup
from collection.accounts_pre_2013 import fetch_accounts, DEFAULT_MAX_ID, DEFAULT_MIN_ID
from collection.models import Account
from manager.streamer import StdoutStreamer, JSONStreamer
from manager.queue import RedisQueue
import os
import sys
import argparse
import logging
CHECKIN_THRESHOLD = 1000
def parse_args():
"""Parses the command line arguments.
"""
parser = argparse.ArgumentParser(
description='Enumerate public Twitter profiles and tweets')
parser.add_argument(
'--max-id',
type=int,
help='Max Twitter ID to use for enumeration',
default=DEFAULT_MAX_ID),
parser.add_argument(
'--min-id',
type=int,
help='Minimum ID to use for enumeration',
default=DEFAULT_MIN_ID)
parser.add_argument(
'--enum-percentage',
'-p',
type=int,
default=100,
help='The percentage of 32bit account space to enumerate (0-100).')
parser.add_argument(
'--no-stream',
dest='stream',
action='store_false',
help='Disable the streaming',
default=True)
parser.add_argument(
'--no-enum',
dest='enum',
action='store_false',
help='Disable the account id enumeration',
default=True)
parser.add_argument(
'--stream-query',
'-q',
type=str,
help='The query to use when streaming results',
default=None)
parser.add_argument(
'--account-filename',
'-af',
type=str,
help='The filename to store compressed account JSON data',
default='accounts.json.gz')
parser.add_argument(
'--stdout',
action='store_true',
dest='stdout',
help='Print JSON to stdout instead of a file',
default=False)
return parser.parse_args()
def main():
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
level=logging.INFO)
logger = logging.getLogger(__name__)
args = parse_args()
consumer_key = os.environ.get('TWEEPY_CONSUMER_KEY')
consumer_secret = os.environ.get('TWEEPY_CONSUMER_SECRET')
access_token = os.environ.get('TWEEPY_ACCESS_TOKEN')
access_token_secret = os.environ.get('TWEEPY_ACCESS_TOKEN_SECRET')
if not (consumer_key and consumer_secret and access_token
and access_token_secret):
logger.error('Need to specify the OAuth configuration.')
sys.exit(1)
user_auth = OAuthHandler(consumer_key, consumer_secret)
user_auth.set_access_token(access_token, access_token_secret)
user_api = API(
user_auth, wait_on_rate_limit_notify=True, wait_on_rate_limit=True)
api_auth = AppAuthHandler(consumer_key, consumer_secret)
app_api = API(
api_auth, wait_on_rate_limit_notify=True, wait_on_rate_limit=True)
account_queue = RedisQueue('accounts')
lookup_queue = RedisQueue('lookup')
streamer_class = JSONStreamer
if args.stdout:
streamer_class = StdoutStreamer
account_streamer = streamer_class(args.account_filename)
processes = []
if args.stream:
stream_process = Process(
target=start_streamer,
args=[user_api, account_queue, lookup_queue],
kwargs={'query': args.stream_query})
processes.append(stream_process)
else:
logger.info('Skipping stream')
if args.enum:
enumerate_process = Process(
target=fetch_accounts,
args=[user_api, account_queue],
kwargs={
'min_id': args.min_id,
'max_id': args.max_id,
'percentage': args.enum_percentage
})
processes.append(enumerate_process)
else:
logger.info('Skipping enum')
# if args.tweets:
# fetch_tweets_process = Process(
# target=fetch_tweets,
# args=[app_api, tweet_streamer],
# kwargs={
# 'lookup_queue': lookup_queue,
# 'minimum_tweets': args.min_tweets
# },
# )
# processes.append(fetch_tweets_process)
# else:
# logger.info('Skipping tweets')
lookup_account_process = Process(
target=start_lookup, args=[app_api, lookup_queue, account_queue])
processes.append(lookup_account_process)
for p in processes:
p.start()
# The main loop's job is simple - it simply fetches account dicts coming
# from the various processes and saves them to the database so the tweet
# fetcher can process them.
try:
account_count = 0
while True:
try:
account = account_queue.get()
# Verify the account isn't already in our database
if Account.exists(account['id']):
continue
account_count += 1
if account_count % CHECKIN_THRESHOLD == 0:
logger.info(
'Accounts discovered: {}'.format(account_count))
# Add the account to our database cache
Account.from_dict(account).save()
# Write the account to our account streamer
account_streamer.write_row(account)
except Exception as e:
print('Error fetching account: {}'.format(e))
except KeyboardInterrupt:
print('\nCtrl+C received. Shutting down...')
for p in processes:
p.terminate()
p.join()
account_streamer.close()
if __name__ == '__main__':
main()