-
Notifications
You must be signed in to change notification settings - Fork 1
/
users.py
executable file
·211 lines (150 loc) · 5.24 KB
/
users.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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import os
import traceback
import urllib
import urllib2
import dateutil.parser
from pymongo import MongoClient
import common
import config.users as g_config
INVALID_HANDLES_FPATH = "config/invalid_handles"
DOZE = 0.5
ERROR_WAIT = 20
def quote_handle(handle):
return urllib.quote(handle.encode("utf-8"))
def refine_user(d):
d[u"handle"] = d[u"handle"].lower()
for key in (u"createdAt", u"updatedAt",):
d[key] = dateutil.parser.parse(d[key])
def user_skills(d):
handle = quote_handle(d[u"handle"])
request = common.make_request(u"/v3/members/%s/skills/" % handle)
raw = common.open_request_and_read(request).decode("utf-8")
skills = common.to_json(raw)
skills = skills[u"result"][u"content"][u"skills"]
for dd in skills.values():
del dd[u"hidden"]
d[u"skills"] = skills
def user_stats(d):
extra_info(d, u"stats")
def user_external_accounts(d):
extra_info(d, u"externalAccounts")
def extra_info(d, category):
handle = quote_handle(d[u"handle"])
request = common.make_request(u"/v3/members/%s/%s/" % (handle, category))
raw = common.open_request_and_read(request).decode("utf-8")
info = common.to_json(raw)[u"result"][u"content"]
if info is None:
raise Exception(u"Failed to get `%s` info for %s" % (category, d[u"handle"]))
del info[u"handle"]
del info[u"userId"]
if u"handleLower" in info:
del info[u"handleLower"]
del info[u"createdBy"]
del info[u"createdAt"]
del info[u"updatedBy"]
del info[u"updatedAt"]
d[category] = info
# noinspection PyBroadException
def main():
common.prepare(use_proxy=g_config.use_proxy)
client = MongoClient()
db = client.topcoder
print "Crawling users..."
print "Current:", db.users.count()
if g_config.recrawl_all:
print "Recrawl all users"
if g_config.recheck_invalid_handles:
print "Recheck invalid handles"
invalid = set()
def add_invalid_handle(hdl):
invalid.add(hdl)
with open(INVALID_HANDLES_FPATH, "w") as fp:
for h in sorted(invalid):
try:
fp.write(h.encode("utf-8") + '\n')
except UnicodeDecodeError:
pass
if os.path.exists(INVALID_HANDLES_FPATH):
for line in open(INVALID_HANDLES_FPATH):
line = line.strip()
if line:
invalid.add(line.decode("utf-8"))
handles = set()
query = {u"handle": None}
field = {u"_id": 1}
nb_challeges = db.challenges.count()
for index, challenge in enumerate(db.challenges.find()):
if (index + 1) % 100 == 0:
print "Challenges: %d/%d" % (index + 1, nb_challeges)
for reg in challenge[u"registrants"]:
handle = reg[u"handle"].lower()
for ch in ur" \/":
if ch in handle:
continue
if handle in invalid:
continue
if handle in handles:
continue
if not g_config.recrawl_all:
query[u"handle"] = handle
if db.users.find_one(query, field) is not None:
continue
handles.add(handle)
if g_config.recheck_invalid_handles or g_config.recrawl_all:
handles.update(invalid)
invalid = set()
if os.path.exists(INVALID_HANDLES_FPATH):
os.rename(INVALID_HANDLES_FPATH, INVALID_HANDLES_FPATH + ".bak")
print len(handles), "users to be crawled"
print "-----"
for index, handle in enumerate(handles):
print "[%d/%d]" % (index + 1, len(handles)), handle
while True:
try:
try:
quoted = quote_handle(handle)
except KeyError:
add_invalid_handle(handle)
break
request = common.make_request(u"/v3/members/" + quoted)
s = common.open_request_and_read(request).decode("utf-8")
d = common.to_json(s)[u"result"][u"content"]
try:
refine_user(d)
user_skills(d)
user_stats(d)
user_external_accounts(d)
except:
traceback.print_exc()
add_invalid_handle(handle)
common.random_sleep(DOZE)
break
db.users.insert_one(d)
common.random_sleep(DOZE)
break
except urllib2.HTTPError, e:
if e.code in (404, 403,):
add_invalid_handle(handle)
common.random_sleep(DOZE)
break
else:
print "HTTP Error", e.code, e.msg
print e.geturl()
print e.fp.read()
except KeyboardInterrupt:
return
except:
traceback.print_exc()
common.random_sleep(ERROR_WAIT)
if __name__ == "__main__":
while True:
# noinspection PyBroadException
try:
main()
break
except KeyboardInterrupt:
break
except:
traceback.print_exc()