-
Notifications
You must be signed in to change notification settings - Fork 3
/
item_queue.py
244 lines (173 loc) · 7.07 KB
/
item_queue.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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
'''Searches twitter for the upper puush id name and loads items into tracker
Requires Tweepy which can be installed using `pip install tweepy`
Usage python item_queue.py PATH_OF_CONFIG_FILE PATH_OF_MIN_ID_FILE.
The config file is an INI-like config file::
[twitter]
consumer_token: TODO
consumer_secret: TODO
access_token: TODO
access_token_secret: TODO
The min id file contains an integer of the minimum ID to use.
There are currently some hard coded values which may need to be adjusted to
your needs.
Example crontab entry::
@daily cd /home/tracker/puush-grab/ && /usr/bin/env python item_queue.py item_queue.conf item_queue_min_id
'''
from __future__ import print_function
import ConfigParser
import argparse
import httplib
import logging
import logging.handlers
import os
import re
import shutil
import subprocess
import sys
import tempfile
import tweepy
from decentralized_puush_grab import (base62_decode, ALPHABET_PUUSH,
base62_encode)
_logger = logging.getLogger(__name__)
# logging.basicConfig(level=logging.DEBUG)
class Queuer(object):
def __init__(self, tracker_id='puush'):
super(Queuer, self).__init__()
self.tracker_id = tracker_id
_logger.info('Start up')
# stupid twitter api v1.1 requires authentication just to do a public
# search. why do you have to be so difficult. see @fake_api
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('config')
arg_parser.add_argument('min_id_path')
self.args = args = arg_parser.parse_args()
config = ConfigParser.ConfigParser()
config.read(args.config)
self.min_item_id = self.get_min_item_id()
self.max_item_id = None
consumer_token = config.get('twitter', 'consumer_token')
consumer_secret = config.get('twitter', 'consumer_secret')
access_token = config.get('twitter', 'access_token')
access_token_secret = config.get('twitter', 'access_token_secret')
_logger.debug('Set authentication tokens')
auth = tweepy.OAuthHandler(consumer_token, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
if self.check_fail_sentinel_file():
raise Exception('Failure sentinel file exists!')
self.search_for_ids()
if self.max_item_id:
if self.check_valid_id():
self.process_max_item_id()
else:
_logger.info('Received possible malicious ID. Quiting.')
def get_min_item_id(self):
with open(self.args.min_id_path, 'r') as f:
return int(f.read()) + 1
def search_for_ids(self):
_logger.debug('Attempt search')
api = self.api
results = api.search('puu.sh', result_type='recent')
id_names = []
_logger.debug('Got %d items', len(results))
for result in results:
for url_obj in result.entities['urls']:
url = url_obj['expanded_url']
match = re.search(r'puu.sh/([a-zA-Z0-9]{5})', url)
if match:
id_names.append(match.group(1))
id_ints = [base62_decode(s, ALPHABET_PUUSH) for s in id_names]
id_ints = list(sorted(id_ints))
_logger.debug('Got %d item ids', len(id_ints))
if not id_ints:
_logger.info('No IDs found. Quitting.')
return
self.max_item_id = id_ints[-1]
def check_valid_id(self):
id_name = base62_encode(self.max_item_id, ALPHABET_PUUSH)
try:
_logger.debug('Check if %s is valid', id_name)
conn = httplib.HTTPConnection("puu.sh")
conn.request("HEAD", '/' + id_name)
res = conn.getresponse()
_logger.debug('Got %d %s', res.status, res.reason)
if res.status == 200:
return True
except Exception:
_logger.exception('Error checking valid url {}'.format(id_name))
def process_max_item_id(self):
if self.max_item_id <= self.min_item_id:
_logger.info('No new IDs found. Quitting')
return
_logger.info('Adding %d to %d', self.min_item_id, self.max_item_id)
with tempfile.NamedTemporaryFile() as item_list_file:
_logger.debug('Generating item list')
proc = subprocess.Popen(['/usr/bin/env', 'python',
'item_name_gen.py',
'--range', '13',
str(self.min_item_id), str(self.max_item_id)],
stdout=item_list_file)
proc.communicate()
_logger.debug('item_name_gen returned %d', proc.returncode)
if proc.returncode != 0:
raise Exception('item_name_gen failed. return code {}'.format(
proc.returncode))
self.save_fail_sentinel_file()
self.save_new_min_id()
_logger.debug('Queuing item list')
# TODO: make these values configurable
with open(item_list_file.name, 'rb') as f:
proc = subprocess.Popen(['/home/tracker/.rvm/bin/ruby',
'enqueue.rb', self.tracker_id],
stdin=f,
)
proc.communicate()
if proc.returncode != 0:
raise Exception('enqueue failed. return code {}'.format(
proc.returncode))
self.remove_fail_sentinel_file()
def save_new_min_id(self):
old_path = '%s-old' % self.args.min_id_path
new_path = '%s-new' % self.args.min_id_path
shutil.copy2(self.args.min_id_path, old_path)
with open(new_path, 'wb') as f:
f.write(str(self.max_item_id).encode())
_logger.debug('Save new min ID.')
os.rename(new_path, self.args.min_id_path)
def save_fail_sentinel_file(self):
path = '%s-fail' % self.args.min_id_path
with open(path, 'wb'):
pass
def remove_fail_sentinel_file(self):
path = '%s-fail' % self.args.min_id_path
os.remove(path)
def check_fail_sentinel_file(self):
path = '%s-fail' % self.args.min_id_path
return os.path.exists(path)
if __name__ == '__main__':
log_handler = logging.handlers.RotatingFileHandler('item_queue.log',
maxBytes=1048576,
backupCount=10)
formatter = logging.Formatter(
'%(asctime)s %(name)s %(levelname)s %(message)s')
log_handler.setFormatter(formatter)
_logger.setLevel(logging.DEBUG)
_logger.addHandler(log_handler)
lock_file = '/tmp/item_queue_lock'
if os.path.exists(lock_file):
_logger.error('Lock file found. Quitting.')
sys.exit(1)
try:
try:
_logger.debug('Create lock file')
with open(lock_file, 'wb'):
pass
Queuer()
finally:
_logger.debug('Remove lock file')
os.remove(lock_file)
except Exception as e:
_logger.exception('Queuer error!')
error_type, error_value, traceback = sys.exc_info()
raise error_type, error_value, traceback
_logger.info('Done.')