-
Notifications
You must be signed in to change notification settings - Fork 86
/
step3_extend_users.py
executable file
·222 lines (177 loc) · 7.15 KB
/
step3_extend_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
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ai ts=4 sts=4 et sw=4 nu
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import os
import json
import time
from dateutil import parser as du_parser
from datetime import datetime
import StringIO
import logging
import requests
from requests.auth import HTTPBasicAuth
import html5lib
from html5lib import treebuilders
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG)
GITHUB_TOKEN = os.environ.get('GITHUB_TOKEN')
last_id = None
one_minute = 60
one_hour = one_minute * 60
min_remaining_tostop = 30
reqs = 0
# reqs_limit = None
# reqs_remaining = None
headers = {}
TOKEN_AUTH = HTTPBasicAuth(GITHUB_TOKEN, "x-oauth-basic")
def check_limits(headers):
reqs_limit = int(headers.get('X-RateLimit-Limit', 0))
reqs_remaining = int(headers.get('X-RateLimit-Remaining', 0))
if reqs_remaining <= min_remaining_tostop:
logger.info("Reached %d requests over %d. Pausing one hour."
% (reqs_limit - reqs_remaining, reqs_limit))
pause(one_hour)
def pause(duration):
''' basic sleep with periodic logging (to show progess) '''
interval = 10
tick = duration / interval
for i in xrange(interval):
logger.info(u"Pause (%dmn) Elapsed: %dmn" % (duration / one_minute,
tick * i / one_minute))
time.sleep(tick)
existing_users = json.load(open('step2.json'))
try:
all_users = json.load(open('step3.json'))
except:
all_users = []
def getElementsByClassName(root, tag, className):
return [e for e in root.getElementsByTagName(tag)
if className in e.getAttribute('class')]
def extend_user(user):
print(user.get('username'))
def get_activity_from_html(username):
r = requests.get('https://github.com/%s' % username,
headers=headers, auth=TOKEN_AUTH)
if r.status_code == 404:
return None
parser = html5lib.HTMLParser(tree=treebuilders.getTreeBuilder("dom"))
dom = parser.parse(StringIO.StringIO(r.content))
divs = dom.getElementsByTagName('div')
contrib_columns = [d for d in divs
if 'contrib-column' in
d.getAttribute('class')]
if not len(contrib_columns):
return {'contrib_total_num': 0,
'contrib_total_start': None,
'contrib_total_end': None,
'contrib_long_num': 0,
'contrib_long_start': None,
'contrib_long_end': None}
total_str = getElementsByClassName(
contrib_columns[0], "span",
"contrib-number")[0].firstChild.nodeValue
# logger.debug("total_str: {}".format(total_str))
total_dates_dom = getElementsByClassName(
contrib_columns[0], "span", "text-muted")[1]
total_dates = "".join([n.nodeValue
for n in total_dates_dom.childNodes])
# logger.debug("total_dates: {}".format(total_dates))
total_start = du_parser.parse(total_dates.split(u'–')[0])
total_end = du_parser.parse(total_dates.split(u'–')[1])
# logger.debug("total_start: {}".format(total_start))
# logger.debug("total_end: {}".format(total_end))
long_str = getElementsByClassName(
contrib_columns[1], "span",
"contrib-number")[0].firstChild.nodeValue
# logger.debug("long_str: {}".format(long_str))
long_dates_dom = getElementsByClassName(
contrib_columns[1], "span", "text-muted")[1]
long_dates = "".join([n.nodeValue
for n in long_dates_dom.childNodes])
# logger.debug("total_dates: {}".format(total_dates))
# logger.debug("long_dates: {}".format(long_dates))
if long_dates == "No recent contributions":
long_start = None
long_end = None
else:
long_start = du_parser.parse(long_dates.split(u'–')[0].strip())
if long_start.year > total_end.year:
long_start = datetime(long_start.year - 1,
long_start.month, long_start.year.day)
long_end = du_parser.parse(long_dates.split(u'–')[1].strip())
if long_end.year > total_end.year:
long_end = datetime(long_end.year - 1, long_end.month,
long_end.year.day)
return {
'contrib_total_num': int(total_str.split()[0].replace(',', '')),
'contrib_total_start': total_start.isoformat(),
'contrib_total_end': total_end.isoformat(),
'contrib_long_num': int(long_str.split()[0].replace(',', '')),
'contrib_long_start':
long_start.isoformat() if long_start is not None else None,
'contrib_long_end':
long_end.isoformat() if long_end is not None else None}
def get_profile(user):
r = requests.get(
'https://api.github.com/users/%s' % user.get('username'),
headers=headers, auth=TOKEN_AUTH)
check_limits(r.headers)
nd = {}
data = json.loads(r.content)
for col in data.keys():
if 'url' in col and not col == 'avatar_url':
continue
if col in user.keys():
continue
nd.update({col: data[col]})
return nd
def get_orgs(username):
orgs = {}
r = requests.get('https://api.github.com/users/%s/orgs' % username,
headers=headers, auth=TOKEN_AUTH)
check_limits(r.headers)
data = json.loads(r.content)
orgs.update({'orgs_num': len(data)})
for i, org in enumerate(data):
org_name = org.get('login')
prefix = 'org%d_' % i
rorg = requests.get('https://api.github.com/orgs/%s' % org_name,
headers=headers, auth=TOKEN_AUTH)
check_limits(rorg.headers)
data_org = json.loads(rorg.content)
nd = {}
for col in data_org.keys():
if 'url' in col and not col == 'avatar_url':
continue
nd.update({prefix + col: data_org[col]})
orgs.update(nd)
return orgs
try:
acitiviy = get_activity_from_html(user.get('username'))
except Exception as e:
logger.exception(e)
raise
acitiviy = {}
from pprint import pprint as pp ; pp(acitiviy)
if acitiviy is None:
return None
profile = get_profile(user)
orgs = get_orgs(user.get('username'))
user.update(acitiviy)
user.update(profile)
user.update(orgs)
return user
# extend_user({'username': 'tensystems'})
# raise
all_usernames = [u['username'] for u in all_users]
for user in existing_users:
if user['username'] in all_usernames:
continue
user_update = extend_user(user)
if user_update is None:
continue
all_users.append(user_update)
json.dump(all_users, open('step3.json', 'w'), indent=4)
json.dump(all_users, open('step3.json', 'w'), indent=4)