-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathhistorylink.py
3041 lines (2768 loc) · 126 KB
/
historylink.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
#!/usr/bin/env python
#
# Copyright 2012-2019 Jeff Gentes
#
#Python client library for the Geni Platform.
import re
import traceback
import cookielib
import base64
import functools
import json
import hashlib
import hmac
import time
import logging
import os
import httplib #for custom error handler
import threading
import torndb
import tornado.escape
import tornado.httpclient
import tornado.ioloop
import tornado.web
import tornado.wsgi
import urllib
import urllib2
import urlparse
import random
from operator import itemgetter
from collections import Iterable
from tornado.options import define, options
from tornado import gen
from tornado.web import asynchronous
from datetime import datetime, timedelta
from node import Node
from tree import Tree
import time
import geni
# Find a JSON parser
try:
import simplejson as json
except ImportError:
try:
from django.utils import simplejson as json
except ImportError:
import json
_parse_json = json.loads
define("compiled_css_url")
define("compiled_jquery_url")
define("config")
define("cookie_secret")
define("debug", type=bool, default=True)
define("mysql_host")
define("mysql_database")
define("mysql_user")
define("mysql_password")
define("historylink_id")
define("historylink_secret")
define("historylink_canvas_id")
define("service_token")
define("listenport", type=int)
define("silent", type=bool)
define("historyprofiles", type=set)
define("historycache", type=dict)
define("countrycodes", type=dict)
define("statecodes", type=dict)
#class GeniApplication(tornado.wsgi.WSGIApplication):
class GeniApplication(tornado.web.Application):
def __init__(self):
self.linkHolder = LinkHolder()
base_dir = os.path.dirname(__file__)
canvas_id = options.historylink_canvas_id
app_id = options.historylink_id
geni_secret = options.historylink_secret
settings = {
"cookie_secret": options.cookie_secret,
"static_path": os.path.join(base_dir, "static"),
"template_path": os.path.join(base_dir, "templates"),
"debug": options.debug,
"geni_canvas_id": canvas_id,
"geni_app_id": app_id,
"geni_secret": geni_secret,
"ui_modules": {
"TimeConvert": TimeConvert,
"SHAHash": SHAHash,
},
}
#tornado.wsgi.WSGIApplication.__init__(self, [
tornado.web.Application.__init__(self, [
tornado.web.url(r"/", HomeHandler, name="home"),
tornado.web.url(r"/projects", ProjectHandler, name="project"),
tornado.web.url(r"/history", HistoryHandler, name="history"),
tornado.web.url(r"/graph", GraphHandler, name="graph"),
tornado.web.url(r"/privacy", PrivacyHandler, name="privacy"),
tornado.web.url(r"/bio", BioHandler, name="bio"),
tornado.web.url(r"/graphprocess", GraphProcess),
tornado.web.url(r"/graphcount", GraphCount),
tornado.web.url(r"/graphlist", GraphList),
tornado.web.url(r"/graphrender", GraphRender, name="graphrender"),
tornado.web.url(r"/graphjs.svg", GraphJS),
tornado.web.url(r"/historylist", HistoryList),
tornado.web.url(r"/historycount", HistoryCount),
tornado.web.url(r"/historyprocess", HistoryProcess),
tornado.web.url(r"/projectupdate", ProjectUpdate),
tornado.web.url(r"/projectsubmit", ProjectSubmit),
tornado.web.url(r"/projectlist", ProjectList),
tornado.web.url(r"/treecomplete", TreeComplete),
tornado.web.url(r"/leaderboard", LeaderBoard),
tornado.web.url(r"/leaderupdate", LeaderUpdate),
tornado.web.url(r"/leaderadd", LeaderAdd),
tornado.web.url(r"/account", AccountRequest),
tornado.web.url(r"/login", LoginHandler, name="login"),
tornado.web.url(r"/logout", LogoutHandler, name="logout"),
tornado.web.url(r"/geni", GeniCanvasHandler),
], **settings)
class ErrorHandler(tornado.web.RequestHandler):
"""Generates an error response with status_code for all requests."""
def __init__(self, application, request, status_code):
tornado.web.RequestHandler.__init__(self, application, request)
self.set_status(status_code)
def get_error_html(self, status_code, **kwargs):
self.require_setting("static_path")
if status_code in [404, 500, 503, 403]:
filename = os.path.join(self.settings['static_path'], '%d.html' % status_code)
if os.path.exists(filename):
f = open(filename, 'r')
data = f.read()
f.close()
return data
return "<html><title>%(code)d: %(message)s</title>" \
"<body class='bodyErrorPage'>%(code)d: %(message)s</body></html>" % {
"code": status_code,
"message": httplib.responses[status_code],
}
def prepare(self):
raise tornado.web.HTTPError(self._status_code)
## override the tornado.web.ErrorHandler with our default ErrorHandler
tornado.web.ErrorHandler = ErrorHandler
class LinkHolder(object):
cookie = {}
def set(self, id, key, value):
if not id in self.cookie:
self.cookie[id] = {}
self.cookie[id][key] = value
def clear_matches(self, id):
if not id in self.cookie:
self.cookie[id] = {}
self.cookie[id]["matches"] = []
self.cookie[id]["parentmatches"] = {}
self.cookie[id]["gencount"] = {}
self.cookie[id]["history"] = set([])
self.cookie[id]["familyroot"] = []
def add_matches(self, id, profile):
if not id in self.cookie:
self.cookie[id] = {}
if not "matches" in self.cookie[id]:
self.cookie[id]["matches"] = []
exists = None
if "hits" in self.cookie[id]:
self.cookie[id]["hits"] += 1
else:
self.cookie[id]["hits"] = 1
message = None
for items in self.cookie[id]["matches"]:
if items["id"] == profile["id"]:
#Give more weight to parents over aunts/uncles
exists = True
if "aunt" in profile["relation"]:
pass
elif "uncle" in profile["relation"]:
pass
elif "mother" in items["relation"]:
pass
elif "father" in items["relation"]:
pass
else:
items["relation"] = profile["relation"]
if profile["message"] == "Master Profile" and items["message"] == "Master Profile":
message = True
break
elif profile["message"] == "Non-Master Public" and items["message"] == "Non-Master Public":
message = True
break
elif profile["message"] == "Parent Conflict" and items["message"] == "Parent Conflict":
message = True
break
elif profile["message"] == "Merge Pending" and items["message"] == "Merge Pending":
message = True
break
if not exists:
self.cookie[id]["matches"].append(profile)
elif profile["message"] and not message:
self.cookie[id]["matches"].append(profile)
exists = False
return exists
def add_parentmatch(self, id, gen, profile):
if not id in self.cookie:
self.cookie[id] = {}
if not "parentmatches" in self.cookie[id]:
self.cookie[id]["parentmatches"] = {}
if not gen in self.cookie[id]["parentmatches"]:
self.cookie[id]["parentmatches"][gen] = {}
if not profile in self.cookie[id]["parentmatches"][gen]:
self.cookie[id]["parentmatches"][gen][profile] = 1
else:
self.cookie[id]["parentmatches"][gen][profile] += 1
def get_parentmatch(self, id, gen, profile):
if not id in self.cookie:
return 0
if not "parentmatches" in self.cookie[id]:
return 0
if not gen in self.cookie[id]["parentmatches"]:
return 0
if not profile in self.cookie[id]["parentmatches"][gen]:
return 0
return self.cookie[id]["parentmatches"][gen][profile]
def remove_parentmatch(self, id, gen):
if not id in self.cookie:
return
if not "parentmatches" in self.cookie[id]:
return
if not gen in self.cookie[id]["parentmatches"]:
return
else:
self.cookie[id]["parentmatches"][gen] = {}
return
def get_matches(self, id):
if not id in self.cookie:
return []
if not "matches" in self.cookie[id]:
return []
return self.cookie[id]["matches"]
def get_matchcount(self, id):
if not id in self.cookie:
return 0
if not "matches" in self.cookie[id]:
return 0
return len(self.cookie[id]["matches"])
def addParentCount(self, id, gen, parentcount, mastercount):
if not id in self.cookie:
self.cookie[id] = {}
if not "gencount" in self.cookie[id]:
self.cookie[id]["gencount"] = {}
if not str(gen) in self.cookie[id]["gencount"]:
self.cookie[id]["gencount"][str(gen)] = {}
self.cookie[id]["gencount"][str(gen)]["count"] = parentcount
self.cookie[id]["gencount"][str(gen)]["mpcount"] = mastercount
self.cookie[id]["gencount"][str(gen)]["label"] = str(self.getGeneration(gen)) + "s"
else:
self.cookie[id]["gencount"][str(gen)]["count"] += parentcount
self.cookie[id]["gencount"][str(gen)]["mpcount"] += mastercount
def getParentCount(self, id):
if not id in self.cookie:
return None
if not "gencount" in self.cookie[id]:
return None
return self.cookie[id]["gencount"]
def set_familyroot(self, id, root):
if not id in self.cookie:
self.cookie[id] = {}
self.cookie[id]["familyroot"] = root
def append_familyroot(self, id, profile):
if not id in self.cookie:
self.cookie[id] = {}
if not "familyroot" in self.cookie[id]:
self.cookie[id]["familyroot"] = []
if not profile in self.cookie[id]["familyroot"]:
self.cookie[id]["familyroot"].append(profile)
def get_familyroot(self, id):
if not id in self.cookie:
return []
if not "familyroot" in self.cookie[id]:
return []
return self.cookie[id]["familyroot"]
def add_history(self, id, history):
if not id in self.cookie:
self.cookie[id] = {}
if not "history" in self.cookie[id]:
self.cookie[id]["history"] = set(history)
else:
self.cookie[id]["history"].update(history)
def get_history(self, id):
if not id in self.cookie:
return set([])
if not "history" in self.cookie[id]:
return set([])
return self.cookie[id]["history"]
def reset_matchhit(self, id):
if not id in self.cookie:
return
#if "matches" in self.cookie[id]:
#self.cookie[id]["matches"] = []
if "hits" in self.cookie[id]:
self.cookie[id]["hits"] = 0
return
def reset(self, id):
if not id in self.cookie:
self.cookie[id] = {}
self.cookie[id]["hits"] = 0
self.cookie[id]["count"] = 0
self.cookie[id]["mpcount"] = 0
self.cookie[id]["pending"] = 0
self.cookie[id]["pconflict"] = 0
self.cookie[id]["stage"] = "parent's family"
self.clear_matches(id)
def get(self, id, key):
if id in self.cookie:
if key in self.cookie[id]:
return self.cookie[id][key]
if key == "count":
return 0
elif key == "mpcount":
return 0
elif key == "pending":
return 0
elif key == "problems":
return 0
elif key == "pconflict":
return 0
elif key == "stage":
return "parent's family"
elif key == "running":
return 0
elif key == "graphrunning":
return 0
elif key == "hits":
return 0
else:
return None
def getGeneration(self, gen):
stage = "parent"
if gen < 0:
stage = "profile"
elif gen == 1:
stage = "grand parent"
elif gen == 2:
stage = "great grandparent"
elif gen > 2:
stage = self.genPrefix(gen) + " great grandparent"
return stage
def genPrefix(self, gen):
gen -= 1
value = ""
if gen == 2:
value = str(gen) + "nd"
elif gen == 3:
value = str(gen) + "rd"
elif gen > 3:
if gen < 21:
value = str(gen) + "th"
elif gen % 10 == 1:
value = str(gen) + "st"
elif gen % 10 == 2:
value = str(gen) + "nd"
elif gen % 10 == 3:
value = str(gen) + "rd"
else:
value = str(gen) + "th"
return value
def stop(self, id):
if id and id in self.cookie:
if "running" in self.cookie[id]:
self.cookie[id]["running"] = 0
self.reset(id)
class BaseHandler(tornado.web.RequestHandler):
@property
def backend(self):
return Backend.instance()
def prepare(self):
self.set_header('P3P', 'CP="HONK"')
if self.request.protocol == "http":
self.redirect("https://%s" % self.request.full_url()[len("http://"):], permanent=True)
def write_error(self, status_code, **kwargs):
import traceback
if self.settings.get("debug") and "exc_info" in kwargs:
exc_info = kwargs["exc_info"]
trace_info = ''.join(["%s<br/>" % line for line in traceback.format_exception(*exc_info)])
request_info = ''.join(
["<strong>%s</strong>: %s<br/>" % (k, self.request.__dict__[k] ) for k in self.request.__dict__.keys()])
error = exc_info[1]
self.set_header('Content-Type', 'text/html')
try:
self.finish("""<html>
<title>%s</title>
<body>
<h2>Error</h2>
<p>%s</p>
<h2>Traceback</h2>
<p>%s</p>
<h2>Request Info</h2>
<p>%s</p>
</body>
</html>""" % (error, error,
trace_info, request_info))
except:
self.finish()
def get_current_user(self):
if not self.get_secure_cookie("uid"):
return None
if self.get_secure_cookie("uid") == "":
return None
user = {'id': self.get_secure_cookie("uid"), 'access_token': self.get_secure_cookie("access_token"),
'refresh_token': self.get_secure_cookie("refresh_token"),
'name': self.get_secure_cookie("name"), 'account_type': self.get_secure_cookie("account_type"),
'curator': self.get_secure_cookie("curator"), 'big_tree': self.get_secure_cookie("big_tree")}
return user
def login(self, next):
if not self.current_user:
logging.info("Need user grant permission, redirect to oauth dialog.")
oauth_url = self.get_login_url(next)
logging.info(oauth_url)
self.render("oauth.html", oauth_url=oauth_url)
else:
return
def get_refresh_token(self, next=None):
if not next:
next = self.request.full_url()
if not next.startswith("http://") and not next.startswith("https://") and \
not next.startswith("http%3A%2F%2F") and not next.startswith("https%3A%2F%2F"):
next = urlparse.urljoin(self.request.full_url(), next)
next = next.replace("http:", self.request.protocol + ":")
user = self.current_user
if user and "refresh_token" in user:
redirect_uri = self.request.protocol + "://" + self.request.host + self.request.uri
refresh = "https://www.geni.com/platform/oauth/request_token?" + urllib.urlencode({
"refresh_token": user["refresh_token"],
"grant_type": "refresh_token",
"redirect_uri": redirect_uri,
"client_id": self.settings.get("geni_app_id"),
"client_secret": self.settings.get("geni_secret"),
})
response = urllib.urlopen(refresh)
redata = response.read()
if "error" in redata:
return self.get_login_url(next)
else:
mytoken = json.loads(redata)
self.set_secure_cookie("access_token", mytoken["access_token"])
self.set_secure_cookie("refresh_token", mytoken["refresh_token"])
return next
else:
return self.get_login_url(next)
def get_login_url(self, next=None):
if not next:
next = self.request.full_url()
if not next.startswith("http://") and not next.startswith("https://") and \
not next.startswith("http%3A%2F%2F") and not next.startswith("https%3A%2F%2F"):
next = urlparse.urljoin(self.request.full_url(), next)
code = self.get_argument("code", None)
next = next.replace("http:", self.request.protocol + ":")
if code:
return self.request.protocol + "://" + self.request.host + \
self.reverse_url("login") + "?" + urllib.urlencode({
"next": next,
"code": code,
})
redirect_uri = self.request.protocol + "://" + self.request.host + \
self.reverse_url("login") + "?" + urllib.urlencode({"next": next})
loginurl = "https://www.geni.com/platform/oauth/authorize?" + urllib.urlencode({
"client_id": self.settings.get("geni_app_id"),
"redirect_uri": redirect_uri,
})
#if next.endswith("smartlogin"):
#loginurl = loginurl + "&" + urllib.urlencode({"display": "popup"})
return loginurl
def write_json(self, obj):
self.set_header("Content-Type", "application/json; charset=UTF-8")
self.finish(json.dumps(obj))
def render(self, template, **kwargs):
kwargs["error_message"] = self.get_secure_cookie("message")
if kwargs["error_message"]:
kwargs["error_message"] = base64.b64decode(kwargs["error_message"])
self.clear_cookie("message")
tornado.web.RequestHandler.render(self, template, **kwargs)
def set_error_message(self, message):
self.set_secure_cookie("message", base64.b64encode(message))
def isCurator(self, usecookie=None, user=None):
if not user:
user = self.current_user
if user:
if usecookie and "curator" in user:
if user["curator"]:
return user["curator"]
if "id" in user:
curator = self.backend.get_curators(user["id"])
if len(curator) > 0:
return True
return False
def isAuthorized(self, user=None):
details = True
if not user:
details = False
user = self.current_user
if user and "id" in user:
access = self.backend.get_smartaccess(user["id"], details)
if len(access) > 0:
if details:
return json.dumps(access[0])
else:
return "true"
return "false"
def isPro(self, user=None):
selfcheck = False
if not user:
selfcheck = True
user = self.current_user
if user and "account_type" in user and user["account_type"] == "pro":
return True
if selfcheck and user and "id" in user:
profileinfo = self.backend.get_profile(user["id"], user)
if profileinfo and "account_type" in profileinfo and profileinfo["account_type"] == "pro":
user["account_type"] = "pro"
return True
return False
def isClaimed(self, user=None):
if not user:
user = self.current_user
if user and "claimed" in user:
return user["claimed"]
return False
def inBigTree(self, user=None):
if not user:
user = self.current_user
if user and "big_tree" in user:
return user["big_tree"]
return False
class AccountRequest(BaseHandler):
@tornado.web.asynchronous
def get(self):
profile = self.get_argument("profile", None)
action = self.get_argument("action", None)
if action and profile:
curator = self.isCurator()
if curator:
user = self.current_user
profileinfo = self.backend.get_profile(profile, user)
if "id" in profileinfo and "id" in user:
if action == "add_user":
self.backend.add_smartaccess(profileinfo["id"], user["id"])
elif action == "revoke_user":
self.backend.remove_smartaccess(profileinfo["id"], user["id"])
else:
if profile:
user = self.current_user
profileinfo = self.backend.get_profile(profile, user)
bigtree = self.inBigTree(profileinfo)
authorized = self.isAuthorized(profileinfo)
pro = self.isPro(profileinfo)
claimed = self.isClaimed(profileinfo)
curator = self.isCurator(False, profileinfo)
else:
claimed = True
curator = self.isCurator(True)
if curator:
#skip unnecessary request if curator
self.set_secure_cookie("curator", "True")
pro = True
authorized = "true"
bigtree = True
else:
pro = self.isPro()
authorized = self.isAuthorized()
bigtree = self.inBigTree()
self.write('{"curator": ' + str(curator).lower() + ', "pro": ' + str(pro).lower() + ', "big_tree": ' + str(bigtree).lower() + ', "user": ' + authorized + ', "claimed": ' + str(claimed).lower() + '}')
self.finish()
class HomeHandler(BaseHandler):
@tornado.web.asynchronous
def get(self):
self.render("home.html")
class LeaderBoard(BaseHandler):
@tornado.web.asynchronous
@tornado.web.authenticated
def get(self):
user = self.current_user
try:
logging.info("*** " + str(user["name"]) + " checked leaderboard")
except:
logging.info("*** " + str(user["id"]) + " checked leaderboard")
totals = self.get_argument("totals", None)
timeframe = self.get_argument("timeframe", None)
try:
page = int(self.get_argument("page", 1))
except:
page = 1
d = datetime.now()
d.replace(day=15)
nowframe = str(d.year) + "-" + str('%02d' % d.month)
if timeframe:
d = datetime.strptime(timeframe + "-15", "%Y-%m-%d")
if d.year > 2012 or (d.year == 2012 and d.month > 2):
pass
else:
d = datetime.now()
d.replace(day=15)
currentframe = str(d.year) + "-" + str('%02d' % d.month)
backframe = None
nextframe = None
bd = d - timedelta(days=30)
if bd.year > 2012 or (bd.year == 2012 and bd.month > 2):
backframe = str(bd.year) + "-" + str('%02d' % bd.month)
if nowframe != currentframe:
fd = d + timedelta(days=30)
nextframe = str(fd.year) + "-" + str('%02d' % fd.month)
#profile = self.backend.get_profile(user["id"], user)
curator = self.isCurator()
if curator:
if not totals:
mergeleaders = self.backend.get_merge_leaders(currentframe)
updateleaders = self.backend.get_update_leaders(currentframe)
additionleaders = self.backend.get_add_leaders(currentframe)
documentleaders = self.backend.get_doc_leaders(currentframe)
projectleaders = self.backend.get_project_leaders(currentframe)
curatorcounts = self.backend.get_curator_counts(currentframe)
else:
mergeleaders = self.backend.get_merge_total()
updateleaders = self.backend.get_update_total()
additionleaders = self.backend.get_add_total()
documentleaders = self.backend.get_doc_total()
projectleaders = self.backend.get_project_total()
curatorcounts = self.backend.get_curator_total()
updatetime = self.backend.get_leaderupdate()
if curatorcounts[0]["merges"]:
mergecount = "{:,}".format(curatorcounts[0]["merges"])
else:
mergecount = 0
if curatorcounts[0]["updates"]:
updatecount = "{:,}".format(curatorcounts[0]["updates"])
else:
updatecount = 0
if curatorcounts[0]["additions"]:
addcount = "{:,}".format(curatorcounts[0]["additions"])
else:
addcount = 0
if curatorcounts[0]["documentation"]:
doccount = "{:,}".format(curatorcounts[0]["documentation"])
else:
doccount = 0
if curatorcounts[0]["projects"]:
projectcount = "{:,}".format(curatorcounts[0]["projects"])
else:
projectcount = 0
totalleaders = {}
for idx, usr in enumerate(mergeleaders):
if usr["id"] in totalleaders:
value = (100 - idx) + totalleaders[usr["id"]]
else:
value = 100 - idx
totalleaders[usr["id"]] = {"total": value, "mug": usr["mug"], "name": usr["name"], "id": usr["id"]}
for idx, usr in enumerate(updateleaders):
if usr["id"] in totalleaders:
value = (100 - idx) + totalleaders[usr["id"]].get("total")
else:
value = 100 - idx
totalleaders[usr["id"]] = {"total": value, "mug": usr["mug"], "name": usr["name"], "id": usr["id"]}
for idx, usr in enumerate(additionleaders):
if usr["id"] in totalleaders:
value = (100 - idx) + totalleaders[usr["id"]].get("total")
else:
value = 100 - idx
totalleaders[usr["id"]] = {"total": value, "mug": usr["mug"], "name": usr["name"], "id": usr["id"]}
for idx, usr in enumerate(documentleaders):
if usr["id"] in totalleaders:
value = (100 - idx) + totalleaders[usr["id"]].get("total")
else:
value = 100 - idx
totalleaders[usr["id"]] = {"total": value, "mug": usr["mug"], "name": usr["name"], "id": usr["id"]}
for idx, usr in enumerate(projectleaders):
if usr["id"] in totalleaders:
value = (100 - idx) + totalleaders[usr["id"]].get("total")
else:
value = 100 - idx
totalleaders[usr["id"]] = {"total": value, "mug": usr["mug"], "name": usr["name"], "id": usr["id"]}
newleaders = []
for item in totalleaders:
newleaders.append(totalleaders[item])
totalleaders = []
sortedleaders = sorted(newleaders, key=itemgetter("total"), reverse=True)
newleaders = None
for idx, item in enumerate(sortedleaders):
if idx < 100:
totalleaders.append(item)
sortedleaders = None
rawstats = self.backend.get_curator_stats()
curatorstats = "['Month','Merges','Updates','Tree Building','Documents','Projects'],"
for stat in rawstats:
curatorstats = curatorstats + "['" + str(stat["timeframe"]) + "'," + str(stat["merges"]) + "," + str(
stat["updates"]) + "," + str(stat["additions"]) + "," + str(stat["documentation"]) + "," + str(
stat["projects"]) + "],"
curatorstats = curatorstats.rstrip(',')
self.render("leaderboard.html", mergeleaders=mergeleaders, updateleaders=updateleaders,
mergecount=mergecount, updatecount=updatecount, updatetime=updatetime, timeframe=currentframe,
backframe=backframe, nextframe=nextframe, curatorstats=curatorstats, totals=totals,
additionleaders=additionleaders, documentleaders=documentleaders, projectleaders=projectleaders,
totalleaders=totalleaders, addcount=addcount, doccount=doccount, projectcount=projectcount,
page=page)
else:
self.write(
"This page is only available for Curators and Geni Staff. If you're one of these and want access, <a href='https://www.geni.com/profile-16675621'>send me a message</a>.")
self.finish()
class LeaderAdd(BaseHandler):
@tornado.web.asynchronous
@tornado.web.authenticated
def get(self):
user = self.current_user
f = open('curators.html', 'r')
filestring = f.read()
f.close()
r = re.findall('/people/(.*?)&', filestring, re.DOTALL)
profiles = []
for item in r:
part = item.split("/")
guid = "g" + str(part[1])
profile = self.backend.get_profile(guid, user)
mug = profile["mugshot_urls"]["thumb2"]
if "display_name" in profile:
name = profile["display_name"]
else:
name = profile["name"]
id = profile["id"]
self.backend.update_leaderboard(id, name, mug)
self.write("update initiated")
self.finish()
class LeaderUpdate(BaseHandler):
@tornado.web.asynchronous
@tornado.web.authenticated
def get(self):
user = self.current_user
try:
validate = "https://www.geni.com/platform/oauth/validate_token?" + urllib.urlencode({
"access_token": user["access_token"],
})
response = urllib.urlopen(validate)
redata = response.read()
if "error" in redata:
self.redirect(self.get_refresh_token(self.request.uri))
return
except:
self.redirect(self.get_login_url(self.request.uri))
return
self.render("leaderupdate.html")
profiles = self.backend.get_curators()
mergelist = ["profile.merge"]
updatelist = ["profile.update", "union.update", "union.set-birth-orders",
"profile.set-marriage-orders", "surname.update", "profile.update-meta", "profile.remove-manager",
"profile.update-family-settings", "profile.lock-fields"]
documentlist = ["photo.add-tag", "photo.delete-tag", "photo.update-tag", "document.add-tag",
"document.delete-tag", "video.add-tag", "video.remove-tag", "marriage.remove-attendee",
"marriage.add-attendee", "death.add-attendee", "death.remove-attendee",
"divorce.remove-attendee", "divorce.add-attendee"]
addlist = ["profile.add", "union.add-partner", "union.add-child", "union.add-parent", "union.add-sibling",
"profile.add-parent", "profile.add-partner", "profile.add-sibling", "profile.add-child",
"profile.delete",
"profile.undelete", "profile.delete-edge", "profile.set-parents"]
projectlist = ["project.update", "project.add", "project.remove-user", "project.remove-profile",
"project.remove-label",
"project.add-label", "project.add-profile", "project.add-user", "project.delete"]
insertstatement = ""
updatecount = 0
cookiepath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "cookies.txt")
cj = cookielib.MozillaCookieJar(cookiepath)
cj.load()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
for person in profiles:
if person["userid"]:
try:
logging.info(str(person["name"]))
except:
logging.info(str(person["userid"]))
userid = person["userid"]
id = person["id"]
dataurl = "https://www.geni.com/revisions/user_histogram_data?" + urllib.urlencode({
"user_id": userid,
"access_token": user["access_token"]
})
r = []
try:
#print(opener.open(dataurl).read())
histogramdata = opener.open(dataurl).read()
try:
r = json.loads(histogramdata)
except:
logging.info(" * Problem reading JSON *")
logging.info(histogramdata)
continue
mergeidx = []
updateidx = []
addidx = []
projectidx = []
documentidx = []
for idx, item in enumerate(r[0]):
if item in mergelist:
mergeidx.append(idx)
if item in updatelist:
updateidx.append(idx)
if item in addlist:
addidx.append(idx)
if item in projectlist:
projectidx.append(idx)
if item in documentlist:
documentidx.append(idx)
for idx, x in enumerate(r):
if idx > len(r) - 3:
try:
merges = 0
updates = 0
additions = 0
projects = 0
documents = 0
timeframe = x[0]
if timeframe == "Month":
continue
#run = None
#if timeframe.startswith("2013"):
#run = True
#elif timeframe.startswith("2012") and not (timeframe.endswith("01") or timeframe.endswith("02")):
#run = True
if 1 == 1:
for subidx in mergeidx:
merges = merges + x[subidx]
for subidx in updateidx:
updates = updates + x[subidx]
for subidx in addidx:
additions = additions + x[subidx]
for subidx in projectidx:
projects = projects + x[subidx]
for subidx in documentidx:
documents = documents + x[subidx]
insertstatement += 'INSERT INTO leaderstats (id, timeframe, merges, updates, additions, document, projects) VALUES ("%s","%s",%s,%s,%s,%s,%s) ON DUPLICATE KEY UPDATE merges=%s,updates=%s,additions=%s,document=%s,projects=%s;\n' % (
id, timeframe, merges, updates, additions, documents, projects, merges, updates,
additions, documents, projects)
except:
pass
except:
print " Error reading Stat"
traceback.print_exc()
updatecount += 1
if updatecount > 10 and len(insertstatement) > 0:
self.backend.update_all_leaderstats(insertstatement)
insertstatement = ""
updatecount = 0
if len(insertstatement) > 0:
self.backend.update_all_leaderstats(insertstatement)
self.backend.update_leaderupdate()
print ""
print("Update Stats Completed, Updating Names")
for person in profiles:
id = person["id"]
try:
profile = self.backend.get_profile(id, user)
if "mugshot_urls" in profile:
if "thumb2" in profile["mugshot_urls"]:
mug = profile["mugshot_urls"]["thumb2"]
elif "small" in profile["mugshot_urls"]:
mug = profile["mugshot_urls"]["small"]
else:
mug = ""
else:
mug = ""
if "display_name" in profile:
name = profile["display_name"]
else:
name = profile["name"]
self.backend.update_leaderboard(id, name, mug)
except:
print("*** Error updating profile: " + id)
print("Update Completed")
class ProjectUpdate(BaseHandler):
@tornado.web.asynchronous
def get(self):
self.write("update initiated")
self.finish()
user = self.current_user
if not user:
user = {'id': self.settings.get("geni_app_id"), 'access_token': options.service_token, 'name': "HistoryLink App"}
projects = self.backend.get_projectlist()
for item in projects:
try:
print "Updating Project: " + item["name"]
except:
print "Updating Project: project-" + str(item["id"])
self.backend.add_project(str(item["id"]), user)
#Since there is a possible token refresh in the Geni Project API - check match
if user and user["access_token"] != self.get_secure_cookie("access_token"):
self.set_secure_cookie("access_token", user["access_token"])
self.set_secure_cookie("refresh_token", user["refresh_token"])
options.historyprofiles = set(self.backend.query_historyprofiles())
class ProjectSubmit(BaseHandler):
@tornado.web.asynchronous
@tornado.web.authenticated
def post(self):
project = self.get_argument("project", None)
user = self.current_user
try:
logging.info(
" *** " + str(user["name"]) + " (" + str(user["id"]) + ") submitted / updated project " + project)
except:
pass
if not project:
self.finish()
args = {"user": user, "base": self, "project": project}
ProjectWorker(self.worker_done, args).start()
def worker_done(self, value):
try:
self.finish(value)
except:
return
class ProjectWorker(threading.Thread):
user = None
base = None
project = None
def __init__(self, callback=None, *args, **kwargs):