This repository has been archived by the owner on Nov 28, 2021. It is now read-only.
/
crawler.py
1115 lines (985 loc) · 43.6 KB
/
crawler.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime
import pytz
from socket import gaierror
from urllib.parse import urlparse
import re
from tornado.httpclient import HTTPError
from tornado.gen import coroutine, Return, sleep
from tornado.ioloop import IOLoop
from tornado.locks import Event
from ..hadapi.hadapi import UserSortBy
from ..db.model import User, Group, Session, UserDetail, \
UserLink, Avatar, Tag, NewestUserPageRefresh, \
UserWord, UserWordAdjacent, UserToken, Word, WordAdjacent, \
DeferredUser, Hostname, UserHostname, NewUser, AvatarHash
from ..wordstat import tokenise, frequency, adjacency
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy import or_
from .. import extdlog
from .tldcache import TopLevelDomainCache
from ..traits.trait import Trait
# Patterns to look for:
CHECK_PATTERNS = (
# Hyperlink
re.compile(r'<a .*?href=".*?">.*?</a>'),
# US-style telephone number
re.compile(r'\([0-9]+?\)[ 0-9\-]+?'),
# International telephone number
re.compile(r'\+[0-9]+?[ 0-9\-]+?'),
# Hybrid telephone (US/International)
re.compile(r'\+[0-9]+? *\([0-9]+?\)[ 0-9\-]+?'),
)
# URI whitelist
URI_WHITELIST = (
# Google Plus
re.compile(r'^https?://plus.google.com/'),
# Linked In
re.compile(r'^https?://([a-z]{2}|www)\.linkedin\.com/in/[^/]+(|/.*)$'),
# Github
re.compile(r'^https?://github.com/[^/]+(|/.*)$'),
re.compile(r'^https?://github.com/?$'),
# Twitter
re.compile(r'^https?://(mobile\.|www\.|)twitter.com/[^/]+(|/.*)$'),
re.compile(r'^https?://twitter.com/?$'),
# Youtube
re.compile(r'^https?://(www.|)youtube.com/channel/'),
# Hackaday.com
re.compile(r'^https?://hackaday.com(|/.*)$'),
# Hackaday.io
re.compile(r'^https?://hackaday.io(|/.*)$'),
)
class InvalidUser(ValueError):
pass
class NoUsersReturned(ValueError):
pass
class Crawler(object):
DEFAULT_CONFIG = {
'init_delay': 5.0,
'new_user_fetch_interval': 900.0,
'new_check_interval': 5.0,
'defer_delay': 900.0,
'deferred_check_interval': 900.0,
'defer_min_age': 3600.0,
'defer_max_age': 2419200.0,
'defer_max_count': 5,
'old_user_fetch_interval': 300.0,
'old_user_fetch_interval_lastpage': 604800.0,
'admin_user_fetch_interval': 86400.0,
'api_blocked_delay': 86400.0,
'tld_suffix_uri': TopLevelDomainCache.PUBLICSUFFIX_URI,
'tld_suffix_cache_duration': TopLevelDomainCache.CACHE_DURATION,
}
def __init__(self, project_id, admin_uid, db, api, hasher, log,
config=None, io_loop=None):
self._hasher = hasher
self._project_id = project_id
self._admin_uid = admin_uid
self._admin_uid_scanned = False
self._log = log
self._db = db
self._api = api
log.trace('Given config is %s', config)
self._config = self.DEFAULT_CONFIG.copy()
self._config.update(config or {})
log.trace('Running config is %s',
self._config)
self._refresh_hist_page = None
if io_loop is None:
io_loop = IOLoop.current()
self._io_loop = io_loop
self._refresh_admin_group_timeout = None
self._io_loop.add_timeout(
self._io_loop.time() + self._config['init_delay'],
self._background_fetch_new_users)
self._io_loop.add_timeout(
self._io_loop.time() + self._config['init_delay'],
self._background_fetch_hist_users)
self._io_loop.add_timeout(
self._io_loop.time() + self._config['init_delay'],
self._background_inspect_deferred)
self._io_loop.add_timeout(
self._io_loop.time() + self._config['init_delay'],
self._background_inspect_new)
self._tld_cache = TopLevelDomainCache(
list_uri=self._config['tld_suffix_uri'],
cache_duration=self._config['tld_suffix_cache_duration'],
log=log.getChild('tldcache'))
# Event to indicate when new users have been added
self.new_user_event = Event()
# Deleted users, by ID
self._deleted_users = set()
@coroutine
def get_avatar(self, avatar_url):
# Ensure it exists, do nothing if already present
yield self._db.query(
'''
INSERT INTO "avatar"
(url)
VALUES
(%s)
ON CONFLICT DO NOTHING
''', avatar_url, commit=True)
# Fetch the avatar
avatars = yield Avatar.fetch(self._db,
'url=%s LIMIT 1', avatar_url)
raise Return(avatars[0])
@coroutine
def fetch_avatar(self, avatar):
# Do we have their avatar on file?
if isinstance(avatar, str):
avatar = yield self.get_avatar(avatar)
if not avatar.avatar_type:
# We don't have the avatar yet
self._log.debug('Retrieving avatar at %s',
avatar.url)
avatar_res = yield self._api.api_fetch(
avatar.url)
avatar.avatar_type = avatar_res.headers['Content-Type']
avatar.avatar=avatar_res.body
yield avatar.commit()
raise Return(avatar)
@coroutine
def _inspect_user(self, user_data, user=None, defer=True):
"""
Inspect the user, see if they're worth investigating.
"""
if user_data['id'] in self._deleted_users:
self._log.trace('User %d is deleted', user_data['id'])
return
try:
if user is None:
users = yield User.fetch(self._db,
'user_id=%s', user_data['id'])
user = users[0]
# Has the user been classified?
user_groups = yield user.get_groups()
classified = ('legit' in user_groups) or ('suspect' in user_groups)
self._log.trace('User %s [#%d] is in groups %s (classified %s)',
user.screen_name, user.user_id, user_groups, classified)
# Is the link valid?
try:
while True:
try:
result = yield self._api.api_fetch(
user.url, method='HEAD')
break
except gaierror:
continue
except HTTPError as e:
if e.code not in (404, 410):
raise
self._log.info('Link to user %s [#%d] no longer valid',
user.screen_name, user.user_id)
yield self._db.query('''
DELETE FROM "new_user"
WHERE user_id=%s
''', user.user_id, commit=True)
yield self._db.query('''
DELETE FROM "user"
WHERE user_id=%s
CASCADE
''', user.user_id, commit=True)
self._deleted_users.add(user_data['id'])
raise InvalidUser('no longer valid')
if user.last_update is not None:
age = datetime.datetime.now(tz=pytz.utc) - user.last_update;
if age.total_seconds() < 300:
return
if classified:
match = False
else:
# Tokenise the users' content.
user_freq = {}
user_host_freq = {}
user_adj_freq = {}
user_tokens = {}
def tally(field):
wordlist = tokenise(field)
frequency(wordlist, user_freq)
if len(wordlist) > 2:
adjacency(wordlist, user_adj_freq)
# Does the user have any hyperlinks or other patterns in their
# profile?
self._log.debug('Inspecting user %s [#%d]',
user_data['screen_name'], user_data['id'])
match = False
for field in ('about_me', 'who_am_i', 'location',
'what_i_would_like_to_do'):
for pattern in CHECK_PATTERNS:
pmatch = pattern.search(user_data[field])
if pmatch:
self._log.info('Found match for %s (%r) in '\
'%s of %s [#%d]',
pattern.pattern, pmatch.group(0), field,
user_data['screen_name'], user_data['id'])
try:
user_tokens[pmatch.group(0)] += 1
except KeyError:
user_tokens[pmatch.group(0)] = 1
match = True
break
# Tally up word usage in this field.
tally(user_data[field])
# Does the user have any hyperlinks? Not an indicator that they're
# a spammer, just one of the traits.
pg_idx = 1
pg_cnt = 1 # Don't know how many right now, but let's start here
while pg_idx <= pg_cnt:
link_res = yield self._api.get_user_links(user.user_id,
page=pg_idx, per_page=50)
self._log.trace('Retrieved user %s link page %d of %d',
user,
link_res.get('page',pg_idx),
link_res.get('last_page',pg_cnt))
if link_res['links'] == 0:
# No links, yes sometimes it's an integer.
break
try:
for link in link_res['links']:
# Ignore if the link URL or title is empty
if (not link['title']) or (not link['url']):
continue
# Count the link title up
tally(link['title'])
try:
# Count up the hostname/domain frequencies
uri_domains = yield self._tld_cache.splitdomain(
urlparse(link['url']).hostname)
for hostname in uri_domains:
user_host_freq[hostname] = \
user_host_freq.get(hostname, 0) + 1
except:
self._log.warning(
'Failed to count up domain frequency for '
'user %s [#%d] link %s <%s>',
user_data['screen_name'],
user_data['id'],
link['title'], link['url'], exc_info=1)
# Insert the link if not already present.
yield self._db.query(
'''
INSERT INTO "user_link"
(user_id, url, title)
VALUES
(%s, %s, title)
ON CONFLICT DO UPDATE
SET
title=%s
WHERE
user_id=%s
AND
url=%s
''', user.user_id, link['url'],
link['title'], link['title'],
user.user_id, link['url'],
commit=True)
if not match:
# Ignore the link if it's in the whitelist
uri_matched = False
for pattern in URI_WHITELIST:
if pattern.match(link['url']):
uri_matched = True
break
match = match or (not uri_matched)
except:
self._log.error('Failed to process link result %r', link_res)
raise
pg_cnt = link_res['last_page']
# Next page
pg_idx = link_res['page'] + 1
# Does the user have a lot of projects in a short time?
age = (datetime.datetime.now(tz=pytz.utc) - \
user.had_created).total_seconds()
# How about the content of those projects?
if user_data.get('projects'):
try:
pg_idx = 1
pg_cnt = 1
while pg_idx <= pg_cnt:
prj_res = yield self._api.get_user_projects(
user.user_id,
page=pg_idx, per_page=50)
self._log.audit('Projects for %s: %s',
user, prj_res)
raw_projects = prj_res.get('projects')
if isinstance(raw_projects, list):
for raw_prj in raw_projects:
# Tokenise the name, summary and description
for field in ('name', 'summary', 'description'):
if field not in raw_prj:
continue
tally(raw_prj[field])
pg_cnt = prj_res.get('last_page',1)
# Next page
pg_idx = prj_res.get('page',1) + 1
except:
self._log.error('Failed to process user %s projects',
user, exc_info=1)
# Carry on!
# How about the user's pages?
try:
pg_idx = 1
pg_cnt = 1
while pg_idx <= pg_cnt:
page_res = yield self._api.get_user_pages(user.user_id,
page=pg_idx, per_page=50)
self._log.audit('Pages for %s: %s',
user, page_res)
raw_pages = page_res.get('pages')
if isinstance(raw_pages, list):
for raw_page in raw_pages:
# Tokenise the name, summary and description
for field in ('title', 'body'):
if field not in raw_page:
continue
tally(raw_page[field])
pg_cnt = page_res.get('last_page',1)
# Next page
pg_idx = page_res.get('page',1) + 1
except:
self._log.error('Failed to process user %s pages',
user, exc_info=1)
# Carry on!
if (age > 300.0) and ((user_data['projects'] / 60.0) > 5):
# More than 5 projects a minute on average.
self._log.debug('User %s [#%d] has %d projects in %d seconds',
user.screen_name, user.user_id, user_data['projects'], age)
match = True
# Stash any tokens
for token, count in user_tokens.items():
if count > 0:
yield self._db.query('''
INSERT INTO "user_token"
(user_id, token, count)
VALUES
(%s, %s, %s)
ON CONFLICT ON CONSTRAINT user_token_pkey DO UPDATE
SET
count=%s
WHERE
user_id=%s
AND
token=%s
''', user.user_id, token, count,
count, user.user_id, token,
commit=True)
else:
yield self._db.query('''
DELETE FROM "user_token"
WHERE
user_id=%s
AND
token=%s
''', user.user_id, token, commit=True)
# Retrieve all the hostnames
if user_host_freq:
yield self._db.query('''
INSERT INTO "hostname"
(hostname, score, count)
VALUES
%(insert_template)s
ON CONFLICT ON CONSTRAINT hostname_pkey DO NOTHING
''' % {
'insert_template': ', '.join([
'(%s, 0, 0)' for x
in range(0, len(user_host_freq))
])
}, *tuple(user_host_freq.keys()), commit=True)
hostnames = dict([
(h.hostname, h) for h in
(yield Hostname.fetch(self._db,
'hostname IN %s',
tuple(user_host_freq.keys())))
])
else:
hostnames = {}
# Retrieve all the words
if user_freq:
yield self._db.query('''
INSERT INTO "word"
(word, score, count)
VALUES
%(insert_template)s
ON CONFLICT ON CONSTRAINT ix_word_word DO NOTHING
''' % {
'insert_template': ', '.join([
'(%s, 0, 0)' for x
in range(0, len(user_freq))
])
}, *tuple(user_freq.keys()), commit=True)
words = dict([
(w.word, w) for w in
(yield Word.fetch(self._db,
'word IN %s',
tuple(user_freq.keys())))
])
else:
words = {}
# Retrieve all the word adjacencies
if user_adj_freq:
yield self._db.query('''
INSERT INTO "word_adjacenct"
(proceeding_id, following_id, score, count)
VALUES
%(insert_template)s
ON CONFLICT ON CONSTRAINT word_adjacent_pkey DO NOTHING
''' % {
'insert_template': ', '.join([
'(%s, %s, 0, 0)' for x
in range(0, len(user_freq))
])
}, *tuple([
word[w].word_id
for w in sum(user_adj_freq.keys(), ())
]),
commit=True)
# There's no clean way I know of to retrieve
# composite keys in an IN query.
word_adj = {}
for (proc_w, follow_w) in user_adj_freq.keys():
word_adjs = yield WordAdjacent.fetch(self._db,
'proceeding_id=%s AND following_id=%s',
word[proc_w], word[follow_w])
word_adj[(proc_w, follow_w)] = word_adjs[0]
# Add the user words, compute user's score
score = []
for word, count in user_freq.items():
w = words[word]
if count > 0:
yield self._db.query('''
INSERT INTO "user_word"
(user_id, word_id, count)
VALUES
(%s, %s, %s)
ON CONFLICT ON CONSTRAINT user_word_pkey DO UPDATE
SET
count=%s
WHERE
user_id=%s
AND
word_id=%s
''', user.user_id, w.word_id, count,
count, user.user_id,
w.word_id, commit=True)
else:
yield self._db.query('''
DELETE FROM "user_word"
WHERE
user_id=%s
AND
word_id=%s''',
user.user_id, w.word_id,
commit=True)
if w.count > 0:
score.append(float(w.score) / float(w.count))
# Add the user host names
for hostname, count in user_host_freq.items():
h = hostnames[hostname]
if count > 0:
yield self._db.query('''
INSERT INTO "user_hostname"
(user_id, hostname_id, count)
VALUES
(%s, %s, %s)
ON CONFLICT ON CONSTRAINT user_hostname_pkey DO UPDATE
SET
count=%s
WHERE
user_id=%s
AND
hostname_id=%s
''', user.user_id, h.hostname_id, count,
count, user.user_id,
h.hostname_id, commit=True)
else:
yield self._db.query('''
DELETE FROM "user_hostname"
WHERE
user_id=%s
AND
hostname_id=%s''',
user.user_id, h.hostname_id,
commit=True)
if h.count > 0:
score.append(float(h.score) / float(h.count))
# Add the user word adjcancies
for (proc_word, follow_word), count in user_adj_freq.items():
wa = word_adj[(proc_word, follow_word)]
proc_w = words[proc_word]
follow_w = words[follow_word]
if count > 0:
yield self._db.query('''
INSERT INTO "user_word_adjacent"
(user_id, proceeding_id, following_id, count)
VALUES
(%s, %s, %s, %s)
ON CONFLICT ON CONSTRAINT user_word_adjacent_pkey DO UPDATE
SET
count=%s
WHERE
user_id=%s
AND
proceeding_id=%s
AND
following_id=%s
''', user.user_id, proc_w.word_id,
follow_w.word_id, count,
count, user.user_id, proc_w.word_id,
follow_w.word_id, commit=True)
else:
yield self._db.query('''
DELETE FROM "user_word_adjacent"
WHERE
user_id=%s
AND
proceeding_id=%s
AND
following_id=%s''',
user.user_id, proc_w.word_id,
follow_w.word_id, commit=True)
if wa.count > 0:
score.append(float(wa.score) / float(wa.count))
# Append each traits' weighted score
for trait in Trait.assess(user,
self._log.getChild('user%d' % user.user_id)):
score.append(trait.weighted_score)
trait.persist()
# Compute score
score.sort()
score = sum(score[:10])
if (defer and (abs(score < 0.5) \
or (age < self._config['defer_min_age']))) \
and (age < self._config['defer_max_age']):
# There's nothing to score. Inspect again later.
yield self._db.query('''
INSERT INTO "deferred_user"
(user_id, inspect_time, inspections)
VALUES
(%s, CURRENT_TIMESTAMP + make_interval(secs => %s), 1)
ON CONFLICT ON CONSTRAINT deferred_user_pkey DO UPDATE
SET
inspect_time=CURRENT_TIMESTAMP + make_interval(secs => (%s * (inspections+1))),
inspections=inspections+1
WHERE
user_id=%s''', user_data['id'],
config['defer_delay'],
config['defer_delay'],
user_data['id'], commit=True)
else:
yield self._db.query('''
DELETE FROM "deferred_user"
WHERE
user_id=%s
''', user_data['id'], commit=True)
self._log.debug('User %s [#%d] has score %f',
user.screen_name, user.user_id, score)
if score < -0.5:
match = True
# Record the user information
yield self._db.query('''
INSERT INTO "user_detail"
(user_id, about_me, who_am_i, location,
projects, what_i_would_like_to_do)
VALUES
(%s, %s, %s, %s, %s, %s)
ON CONFLICT ON CONSTRAINT user_detail_pkey DO UPDATE
SET
about_me=%s,
who_am_i=%s,
location=%s,
projects=%s,
what_i_would_like_to_do=%s
WHERE
user_id=%s
''',
user_data['id'],
user_data['about_me'],
user_data['who_am_i'],
user_data['location'],
user_data['projects'],
user_data['what_i_would_like_to_do'],
user_data['about_me'],
user_data['who_am_i'],
user_data['location'],
user_data['projects'],
user_data['what_i_would_like_to_do'],
user_data['id'], commit=True)
if match:
# Auto-Flag the user as "suspect"
if not classified:
self._log.debug('Auto-classifying %s [#%d] as suspect',
user.screen_name, user.user_id)
yield user.add_groups('auto_suspect')
yield user.rm_groups('auto_legit')
elif not classified:
# Auto-Flag the user as "legit"
self._log.debug('Auto-classifying %s [#%d] as legitmate',
user.screen_name, user.user_id)
yield user.add_groups('auto_legit')
yield user.rm_groups('auto_suspect')
# Remove the user from the "new" list
yield self._db.query('''
DELETE FROM "new_user"
WHERE user_id=%s
''', user_data['id'], commit=True)
self._log.audit('Finished inspecting %s', user_data)
except:
self._log.error('Failed to process user data %r',
user_data, exc_info=1)
raise
@coroutine
def update_user_from_data(self, user_data, inspect_all=True,
defer=True):
"""
Update a user in the database from data retrieved via the API.
"""
self._log.audit('Inspecting user data: %s', user_data)
avatar = yield self.get_avatar(user_data['image_url'])
user_created = datetime.datetime.fromtimestamp(
user_data['created'], tz=pytz.utc)
# See if the user exists:
user = yield User.fetch(self._db, 'user_id=%s', user_data['id'], single=True)
if user is None:
# Nope, create the user.
yield self._db.query('''
INSERT INTO "user"
(user_id, screen_name, url, avatar_id, created,
had_created)
VALUES
(%s, %s, %s, %s, CURRENT_TIMESTAMP, %s)
''',
user_data['id'], user_data['screen_name'],
user_data['url'], avatar.avatar_id,
user_created, commit=True)
# Try again
user = yield User.fetch(self._db, 'user_id=%s', user_data['id'], single=True)
else:
# Update the user
user.screen_name = user_data['screen_name']
user.url = user_data['url']
user.avatar_id = avatar.avatar_id
user.last_update = datetime.datetime.now(tz=pytz.utc)
yield user.commit()
# Inspect the user
if inspect_all or (user.last_update is None):
yield self._inspect_user(user_data, user=user, defer=defer)
user.last_update = datetime.datetime.now(tz=pytz.utc)
yield user.commit()
self._log.debug('User %s up-to-date', user)
# User clearly exists, so remove it from the new user list
yield self._db.query('''
DELETE FROM "new_user"
WHERE user_id=%s
''', user.user_id, commit=True)
raise Return(user)
@coroutine
def _fetch_last_refresh_page(self):
page_num = yield self._db.query('''
SELECT
max(page_num)
FROM
"newest_user_page_refresh"
''')
assert len(page_num) == 1
raise Return(page_num[0][0])
@coroutine
def _background_fetch_new_users(self):
"""
Try to retrieve users newer than our current set.
"""
page = 1
page_count = 0
if self._refresh_hist_page is None:
self._refresh_hist_page = yield self._fetch_last_refresh_page()
try:
while (page < max([self._refresh_hist_page,2])) \
and (page_count < 10):
self._log.info('Scanning for new users page %d', page)
page = yield self.fetch_new_user_ids(
page=page, inspect_all=True,
defer=True)
page_count += 1
except NoUsersReturned:
# Okay, so we've got nothing, move along.
pass
except SQLAlchemyError:
# SQL cock up, roll back.
self._db.rollback()
self._log.exception('Failed to retrieve newer users'\
': database rolled back')
except:
self._log.exception('Failed to retrieve newer users')
delay = self._config['new_user_fetch_interval']
next_time = self._io_loop.time()
next_time += (delay - (next_time % delay))
delay = next_time - self._io_loop.time()
self._log.info('Next new user scan in %.3f sec', delay)
self._io_loop.add_timeout(
self._io_loop.time() + delay,
self._background_fetch_new_users)
@coroutine
def _background_inspect_deferred(self):
"""
Inspect previously deferred users
"""
if not self._api.is_forbidden:
delay = self._config['deferred_check_interval']
self._log.info('Scanning deferred users')
try:
# Grab a handful of deferred users
ids = yield self._db.query('''
SELECT
user_id
FROM
"deferred_user"
WHERE
inspections < %s
AND
inspect_time < CURRENT_TIMESTAMP
ORDER BY
inspect_time ASC,
inspections DESC
LIMIT 50''',
self._config['defer_max_count'])
ids = [r[0] for r in ids]
if ids:
self._log.trace('Scanning %s', ids)
user_data = yield self._api.get_users(ids=ids, per_page=50)
self._log.audit('Received deferred users: %s', user_data)
if isinstance(user_data['users'], list):
for this_user_data in user_data['users']:
while True:
try:
yield self.update_user_from_data(
this_user_data, inspect_all=True)
break
except InvalidUser:
pass
except SQLAlchemyError:
self._db.rollback()
else:
# Mark as checked
yield self._db.query('''
UPDATE
"deferred_user"
SET
inspections=inspections+1,
inspect_time=CURRENT_TIMESTAMP
+ make_interval(secs => (%s * (inspections + 1)))
WHERE
user_id IN %s
''', self._config['defer_delay'],
tuple(ids), commit=True)
self._log.debug('Successfully fetched deferred users')
except:
self._log.exception('Failed to retrieve deferred users')
else:
self._log.warning('API blocked, cannot inspect deferred users')
delay = self._config['api_blocked_delay']
self._log.info('Next deferred user scan in %.3f sec', delay)
self._io_loop.add_timeout(
self._io_loop.time() + delay,
self._background_inspect_deferred)
@coroutine
def _background_inspect_new(self):
"""
Inspect new users
"""
if not self._api.is_forbidden:
delay = self._config['new_check_interval']
self._log.info('Scanning new users')
try:
# Grab a handful of new users
ids = yield self._db.query('''
SELECT
user_id
FROM
"new_user"
ORDER BY
user_id DESC
LIMIT 50''')
ids = [r[0] for r in ids]
if ids:
self._log.debug('Scanning %s', ids)
user_data = yield self._api.get_users(
ids=ids, per_page=50)
self._log.audit('Received new users: %s', user_data)
if isinstance(user_data['users'], list):
user_data['users'].sort(
key=lambda u : u.get('id') or 0,
reverse=True)
for this_user_data in user_data['users']:
user = yield self.update_user_from_data(
this_user_data, inspect_all=True)
# Clean up the new user list
yield self._db.query('''
DELETE FROM
"new_user"
WHERE
user_id IN (
SELECT
user_id
FROM
"user"
WHERE
user_id IN %s
)
''', tuple(ids), commit=True)
self._log.debug('Successfully fetched new users')
except:
self._log.exception('Failed to retrieve new users')
else:
delay = self._config['api_blocked_delay']
self._log.warning('API blocked, cannot inspect new users')
self._log.info('Next new user scan in %.3f sec', delay)
self._io_loop.add_timeout(
self._io_loop.time() + delay,
self._background_inspect_new)
@coroutine
def _background_fetch_hist_users(self):
"""
Try to retrieve users registered earlier.
"""
self._log.info('Beginning historical user retrieval')
delay = self._config['old_user_fetch_interval']
if self._refresh_hist_page is None:
self._refresh_hist_page = yield self._fetch_last_refresh_page()
try:
self._refresh_hist_page = \
yield self.fetch_new_user_ids(
page=self._refresh_hist_page,
defer=False)
except SQLAlchemyError:
# SQL cock up, roll back.
self._db.rollback()
self._log.exception('Failed to retrieve older users'\
': database rolled back')
except NoUsersReturned:
self._log.info('Last user page reached')
delay = self._config['old_user_fetch_interval_lastpage']
except:
self._log.exception('Failed to retrieve older users')
self._log.info('Next historical user fetch in %.3f sec', delay)
self._io_loop.add_timeout(
self._io_loop.time() + delay,
self._background_fetch_hist_users)
@coroutine
def fetch_new_user_ids(self, page=1, inspect_all=False, defer=True):
"""
Retrieve new users IDs not currently known from the Hackaday.io API.
"""
last_refresh = None
num_uids = 0
pages = 0
now = datetime.datetime.now(tz=pytz.utc)
while (num_uids < 10) and (pages < 10):
if page > 1:
last_refresh = yield NewestUserPageRefresh.fetch(self._db, 'page_num=%s', page)
if len(last_refresh) == 1:
last_refresh = last_refresh[0]
self._log.audit('Page %s last refreshed on %s',
last_refresh.page_num, last_refresh.refresh_date)
if (now - last_refresh.refresh_date).total_seconds() \
< 2592000.0: # 30 days
# Skip this page for now
self._log.audit('Skipping page %d', page)
page += 1
yield sleep(0.001)
continue
self._log.trace('Retrieving newest user page %d', page)