forked from kaansoral/adventureland
-
Notifications
You must be signed in to change notification settings - Fork 1
/
functions.py
2233 lines (2002 loc) · 78.6 KB
/
functions.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
from config import *
shells_to_gold=multipliers["shells_to_gold"]
hp_multiplier=1 #currently the hp levels are a bit in turmoil [03/03/19]
def calculate_game_dynamics(): #I hope this will be an important function, should always stay at top [05/11/18]
#decided to leave gold calculations at server_functions.js for now [06/11/18]
for name in items.keys():
current=items[name]
# 1$ = 120 SHELLS
# 1M = 2$ => 120 SHELLS = 500K
# Originally 240 SHELLS = 288K
# Probably, 120 SHELLS = 160K = BEST - 320,000 / 120 = 1333 ~ 1375
if current.get("cash"): current["g"]=current["cash"]*shells_to_gold #825 from 1375 [15/10/16] 1600 from 825 [22/11/16] 3200 from 1600 [16/12/16] 4800 from 3200 [08/11/17] 32000 from 4800 [03/02/18]
if not current.get("g"):
logging.error("%s doesn't have g!"%name)
current["g"]=1
if hp_multiplier!=1:
if current.get("hp"):
current["hp"]=round(hp_multiplier*current["hp"])
if current.get("upgrade") and current["upgrade"].get("hp"):
current["upgrade"]["hp"]=round(hp_multiplier*current["upgrade"]["hp"])
if current.get("compound") and current["compound"].get("hp"):
current["compound"]["hp"]=round(hp_multiplier*current["compound"]["hp"])
calculate_game_dynamics()
def monster_analysis(logging=None):
if not logging: logging=globals()["logging"]
for monster in monsters:
current=monsters[monster]
gold=monster_gold[monster]*drops["gold"]["base"]+monster_gold[monster]*drops["gold"]["random"]/2
gold+=monster_gold[monster]*10*drops["gold"]["x10"]+monster_gold[monster]*50*drops["gold"]["x50"]
logging.info("%s avg.gold: %.1f"%(monster,gold))
for damage in [120,400,800,1600]:
logging.info("\nfor %d damage/second in 1 hour"%damage)
for monster in monsters:
current=monsters[monster]
gold=monster_gold[monster]*drops["gold"]["base"]+monster_gold[monster]*drops["gold"]["random"]/2
gold+=monster_gold[monster]*10*drops["gold"]["x10"]+monster_gold[monster]*50*drops["gold"]["x50"]
hits=math.ceil(current["hp"]*1.0/damage)
kills=60.0*60/hits
logging.info("%s kills: %.1f gold: %s xp: %s"%(monster,kills,to_pretty_num(gold*kills),to_pretty_num(current["xp"]*kills)))
def calculate_xvalue(name):
drop_value=0
for drop in drops[name]:
prob=drop[0]
name=drop[1]
if name=="open": drop_value+=prob*calculate_xvalue(drop[2])
elif name=="shells": drop_value+=prob*drop[2]*shells_to_gold
else: drop_value+=items[name]["g"]
return drop_value
def monster_analysis2(logging=None):
if not logging: logging=globals()["logging"]
for monster in monsters:
current=monsters[monster]
gold=monster_gold[monster]*drops["gold"]["base"]+monster_gold[monster]*drops["gold"]["random"]/2
gold+=monster_gold[monster]*10*drops["gold"]["x10"]+monster_gold[monster]*50*drops["gold"]["x50"]
mdrops=drops["monsters"].get(monster,[]); drop_value=0
for drop in mdrops:
prob=drop[0]
name=drop[1]
if name=="open": drop_value+=prob*calculate_xvalue(drop[2])
elif name=="shells": drop_value+=prob*drop[2]*shells_to_gold
else: drop_value+=prob*items[name]["g"]
logging.info("%s 100*gold/hp: %s drops: %s totalgold/hp: %s"%(monster,100*gold/current["hp"],drop_value,100*(gold+drop_value)/current["hp"]))
def drop_analysis(logging=None,count=1000,only=None):
if not logging: logging=globals()["logging"]
for name in drops:
try:
if not is_array(drops[name]): continue
if only and name!=only: continue
current=drops[name]
# if not current.get("e"): continue # Normally "items" was traversed instead of "drops"
dropl=drops[name]; total=0; gold=0; loot={}
for drop in dropl: total+=drop[0]
for i in xrange(0,count):
roll=random.uniform(0,total); current=0
for drop in dropl:
current+=drop[0]
if roll<=current:
if drop[1]=="open":
if not loot.get(drop[2]): loot[drop[2]]=0
loot[drop[2]]+=1
else:
if not loot.get(drop[1]): loot[drop[1]]=0
loot[drop[1]]+=(len(drop)<3 and 1) or drop[2]
break
logging.info("%s drops: [x%s]"%(name,count))
for name in loot:
logging.info("\t%s %s"%(name,loot[name]))
logging.info("\n")
except:
log_trace(logging)
logging.info("\nAnalysis failed for %s\n"%name)
def item_value(item):
gold=items[item["name"]]["g"]
if item.get("q",0): gold*=item.get("q",0)
level=item.get("level",0)
if items[item["name"]].get("upgrade"):
if is_sdk: level=min(level,12)
gold*=[1,1,1.1,1.4,1.6,2,4,8,16,50,500,800,1600,20000][level]
if items[item["name"]].get("compound"):
if is_sdk: level=min(level,5)
gold*=[1,3,9,27,81,243,800,3600,15000,50000][level]
return gold
def total_xp(character):
xp=character.xp
for i in range(1,character.level):
xp+=levels["%s"%i]
return xp
def total_worth(element,characters=True):
gold=element.info.gold
i_list=["items"]
for i in xrange(64): i_list.append("items%d"%i)
for c in i_list:
if not gf(element,c,[]): continue
for item in gf(element,c,[]):
if not item: continue
gold+=item_value(item)
if element.k(1).startswith("character|"):
for slot in gf(element,"slots",{}):
item=element.info.slots[slot]
if not item: continue
gold+=item_value(item)
if characters:
for c in gf(element,"characters",[]):
character=get_by_iid("character|%s"%c["id"])
if not character: continue
gold+=total_worth(character)
return gold
def log_items(element,name,logging=None):
if type(element)==type(""): element=get_owner(element)
logging.info("%s %s"%(element.k(1),element.name))
i_list=["items"]
for i in xrange(64): i_list.append("items%d"%i)
for c in i_list:
if not gf(element,c,[]): continue
for item in gf(element,c,[]):
if not item: continue
if item["name"]==name: logging.info("STORAGE %s %s"%(c,item))
if element.k(1).startswith("character|"):
for slot in gf(element,"slots",{}):
item=element.info.slots[slot]
if not item: continue
if item["name"]==name: logging.info("SLOT %s %s"%(element.name,item))
if gf(element,"p") and element.info.p.get("trade_history"):
for i in xrange(len(element.info.p["trade_history"])):
if element.info.p["trade_history"][i][2]["name"]==name:
logging.info("TRADE %s"%(element.info.p["trade_history"][i]))
if not element.k(1).startswith("character|"):
for c in gf(element,"characters",[]):
character=get_by_iid("character|%s"%c["id"])
if not character: continue
log_items(character,name,logging)
def refactor_map(map):
data=map.info.data
if data.get("default") and type(data["default"])!=type(1):
current=0; marked=False
for tile in data.get("tiles",[]):
if tile==data["default"]:
data["default"]=current
marked=True
current+=1
if not marked:
data["tiles"].append(data["default"])
data["default"]=len(data["tiles"])-1
current=0
for tile in data.get("tiles",[]):
if type(tile[3])==type([]):
tile.append(tile[3][1])
tile[3]=tile[3][0]
return data
def process_map(map):
marked={}; last=0; current=0; new_tiles=[]; min_x=900; min_y=900; max_x=-900; max_y=-900; x_lines=[]; y_lines=[]
data=map.info.data
if data.get("x_lines"): data["x_lines"].sort()
if data.get("y_lines"): data["y_lines"].sort()
if data.get("default"): marked[data["default"]]=True
for animation in data.get("animations",[]):
marked[animation[0]]=True
for animation in data.get("lights",[]):
marked[animation[0]]=True
for animation in data.get("nights",[]):
marked[animation[0]]=True
for group in data.get("groups",[]):
for placement in group:
if len(placement)==5 and placement[3]==placement[1] and placement[4]==placement[2]: del placement[3:]
marked[placement[0]]=True
for line in data.get("x_lines",[]):
if line[1]!=line[2]: x_lines.append(line)
#logging.info("%s / %s"%(len(data["x_lines"]),len(x_lines)))
data["x_lines"]=x_lines
for line in data.get("y_lines",[]):
if line[1]!=line[2]: y_lines.append(line)
#logging.info("%s / %s"%(len(data["y_lines"]),len(y_lines)))
data["y_lines"]=y_lines
for placement in data.get("placements",[]):
marked[placement[0]]=True
tile=data["tiles"][placement[0]]
if len(placement)==5 and placement[3]==placement[1] and placement[4]==placement[2]: del placement[3:]
if type(tile[3])==type([]): width,height=tile[3]
else: width=height=tile[3]
if placement[1]<min_x: min_x=placement[1]
if placement[2]<min_y: min_y=placement[2]
if len(placement)==5:
if placement[3]+width>max_x: max_x=placement[3]+width
if placement[4]+height>max_y: max_y=placement[4]+height
else:
if placement[1]+width>max_x: max_x=placement[1]+width
if placement[2]+height>max_y: max_y=placement[2]+height
for tile in data.get("tiles",[]):
if not marked.has_key(current):
logging.info("%s is unused"%current)
else:
marked[current]=last
last+=1
#logging.info("%s is %s"%(current,marked[current]))
new_tiles.append(tile)
current+=1
data["tiles"]=new_tiles
if data.get("default"): data["default"]=marked[data["default"]]
for animation in data.get("animations",[]):
animation[0]=marked[animation[0]]
for animation in data.get("lights",[]):
animation[0]=marked[animation[0]]
for animation in data.get("nights",[]):
animation[0]=marked[animation[0]]
for group in data.get("groups",[]):
for placement in group:
placement[0]=marked[placement[0]]
for placement in data.get("placements",[]):
placement[0]=marked[placement[0]]
if min_x>max_x:
min_x=-10; max_x=10; min_y=-10; max_y=10
data["min_x"]=min_x
data["min_y"]=min_y
data["max_x"]=max_x
data["max_y"]=max_y
def render_selection(self,user,domain,level=80,server=None):
servers=get_servers();
if not server: server=select_server(self,user,servers);
total=0; characters=[]; data=None
for s in servers: total+=gf(s,"players") or 0
if user:
characters=get_characters(user)
domain.characters=characters_to_client(characters)
data=get_user_data(user);
domain.servers=servers_to_client(domain,servers)
if domain.is_cli and (not user or not user.cli_time or user.cli_time<datetime.now()) and level>=70:
domain.is_cli=False; domain.harakiri=True
start=datetime.now(); logging.info("User data in: %s"%ssince(start))
#if domain.no_html=="bot" and self.request.get("auth"): set_cookie(self,"auth",self.request.get("auth"))
whtml(self,"htmls/index.html",domain=domain,user=user,user_data=data,server=server,servers=servers,total=total,characters=characters)
def render_comm(self,user,domain):
servers=get_servers(); server=select_server(self,user,servers); total=0; characters=[]; data={}
for s in servers: total+=gf(s,"players") or 0
domain.servers=servers_to_client(domain,servers)
if user:
characters=get_characters(user)
domain.characters=characters_to_client(characters)
data=get_user_data(user);
whtml(self,"htmls/comm.html",domain=domain,user=user,user_data=data,server=server,servers=servers,total=total,characters=characters)
def selection_info(self,user,domain):
servers=get_servers(); server=select_server(self,user,servers)
return {"type":"content","html":shtml("htmls/contents/selection.html",user=user,domain=domain,server=server,servers=servers,characters=get_characters(user))}
def security_threat(self,domain):
referer=self.request.headers.get('Referer') or self.request.headers.get('Origin') or ""
if not referer: return False
referer=referer.replace("http://","").replace("https://","")
#referer="www.thegame2.com"
logging.info(referer)
if referer.startswith("127.0.0.1"): return False
if referer.startswith("0.0.0.0"): return False
if not (referer.startswith(domain.domain) or referer.startswith("%s.%s.%s/"%(domain.domain[0],domain.domain[1],domain.domain[2])) or referer.startswith("%s.%s/"%(domain.domain[1],domain.domain[2])) or referer=="%s.%s.%s"%(domain.domain[0],domain.domain[1],domain.domain[2]) or referer=="%s.%s"%(domain.domain[1],domain.domain[2])):
self.response.out.write("Threat detected")
return True
# if is_production and domain.cf_always_on and not is_cloudflare(self):
# conditional_response(self,domain,response,"cloudflare")
# st_log(self,"cloudflare")
# return True
return False
def disable_email(email,logging=None):
if not logging: logging=globals()["logging"]
user=get_user(email=email)
if not user: return logging.info("User not found")
user.info.dont_send_emails=True
user.put()
logging.info("Disabled emails for %s"%user)
def get_user(self=None,domain=None,email=None,phrase_check=False,api_override=None):
if email:
try:
email=purify_email(email)
if phrase_check:
mark=get_by_iid("markedphrase|email-%s"%email)
if mark:
user=get_by_iid("user|%s"%mark.owner)
if user: return user
return User.query(User.email == email).get()
except:
logTrace()
elif self:
auth=get_cookie(self,"auth") or self.request.get("auth")
if auth:
id,auth=auth.replace('"',"").split("-")
get_user_data(id,async=True) #trigger the get
user=get_by_iid("user|%s"%id)
if user and (api_override or auth in gf(user,"auths",[])):
return user
def character_in_transaction_routines(character,flags):
if character.referrer and character.level>=50 and not gf(character,"rfreward_50"):
character.info.rfreward_50=datetime.now()
flags.rf50=character.referrer
if character.referrer and character.level>=60 and not gf(character,"rfreward_60"):
character.info.rfreward_60=datetime.now()
flags.rf60=character.referrer
if character.referrer and character.level>=70 and not gf(character,"rfreward_70"):
character.info.rfreward_70=datetime.now()
flags.rf60=character.referrer
def handle_character_flags(flags):
if getattr(flags,"rf50"): pass
def send_verification_email(domain,user):
url="%s/ev/%s/%s"%(domain.base_url,user.k(),user.info.everification)
send_email(domain,user.info.email,html=shtml("htmls/email.html",purpose="verification",url=url,domain=domain,user=user),title="Welcome to %s! Verification Link + Early Game Suggestions Inside"%game_name,text="To Verify Your Email: %s"%url)
def send_password_reminder_email(domain,user):
url="%s/reset/%s/%s"%(domain.base_url,user.k(),user.info.password_key)
send_email(domain,user.info.email,html=shtml("htmls/email.html",purpose="password",domain=domain,url=url),title="Password Reminder from %s"%game_name,text="To reset your password, please visit: %s"%url)
def is_in_game(character):
return character.server and hsince(character.last_sync)<=4 # 5 hours seem logical - instead of 18 hours
return character.server and msince(character.last_sync)<12
def ip_in_range(ip,net):
try:
ipaddr = int(''.join([ '%02x' % int(x) for x in ip.split('.') ]), 16)
netstr, bits = net.split('/')
netaddr = int(''.join([ '%02x' % int(x) for x in netstr.split('.') ]), 16)
mask = (0xffffffff << (32 - int(bits))) & 0xffffffff
return (ipaddr & mask) == (netaddr & mask)
except:
log_trace()
return False
def get_ip(self):
ip=self.request.remote_addr
cloudflare_ip=self.request.headers.get("CF-Connecting-IP")
cloudflare_ranges=[
'103.21.244.0/22',
'103.22.200.0/22',
'103.31.4.0/22',
'104.16.0.0/12',
'108.162.192.0/18',
'131.0.72.0/22',
'141.101.64.0/18',
'162.158.0.0/15',
'172.64.0.0/13',
'173.245.48.0/20',
'188.114.96.0/20',
'190.93.240.0/20',
'197.234.240.0/22',
'198.41.128.0/17',
]
cloudflare_ranges_v6=[
'2400:cb00::/32',
'2405:b500::/32',
'2606:4700::/32',
'2803:f800::/32',
'2c0f:f248::/32',
'2a06:98c0::/29',
]
if cloudflare_ip:
for crange in cloudflare_ranges:
if ip.find(":")==-1 and ip_in_range(ip,crange): return cloudflare_ip
for crange in cloudflare_ranges_v6:
if ip.find(":")!=-1 and ip.startswith(crange[:7]): return cloudflare_ip #not sure 9 or 7 [25/08/13]
return self.request.remote_addr
def get_country(self):
return self.request.headers.get("Cf-Ipcountry") or self.request.headers.get("X-Appengine-Country") or "XX"
def get_character(id,phrase_check=False):
if id.isdigit() and get_by_iid("character|%s"%id): return get_by_iid("character|%s"%id)
else:
id=simplify_name(id)
if phrase_check:
mark=get_by_iid("markedphrase|character-%s"%id)
if mark:
character=get_by_iid("character|%s"%mark.owner)
if character: return character
return Character.query(Character.name == id).get()
def get_owner(name):
char=get_character(name)
if char: return get_by_iid("user|%s"%char.owner)
def process_user_data(user,data):
if hasattr(user,"k"): user=user.k()
if not data: data=InfoElement(key=ndb.Key(InfoElement,"userdata-%s"%user),info=GG())
if not gf(data,"completed_tasks"): data.info.completed_tasks=[] #completed tutorial tasks
if not gf(data,"tutorial_step"): data.info.tutorial_step=0 #tutorial step
calculate_tutorial_step(data)
return data
def get_user_data(user,async=False):
if hasattr(user,"k"): user=user.k()
if async:
return get_by_iid_async("infoelement|userdata-%s"%user)
else:
data=get_by_iid("infoelement|userdata-%s"%user)
data=process_user_data(user,data)
return data
def delete_user_data(user):
if hasattr(user,"k"): user=user.k()
ndb.Key(InfoElement,"userdata-%s"%user).delete()
def reset_tutorial(user):
data=get_user_data(user,async=False)
data.info.completed_tasks=[] #completed tutorial tasks
data.info.tutorial_step=0 #tutorial step
data.put()
return data
def add_ip_exception(ip_a,limit=0,explanation=""):
limit=max(1,min(limit,10))
if limit==1: return remove_ip_exception(ip_a)
ip=get_ip_info(ip_a)
ip.info.limit=limit
if not ip.random_id: ip.random_id=randomStr(20)
ip.exception=True
ip.last_exception=datetime.now()
ip.info.explanation=explanation or "No Explanation Exception"
ip.put()
def remove_ip_exception(ip_a):
ip=get_ip_info(ip_a)
ip.info.limit=1
ip.exception=False
ip.put()
def get_ip_info(ip):
if type(ip) not in types.StringTypes: ip=get_ip(ip)
info=get_by_iid("ip|%s"%ip)
if not info: info=IP(key=ndb.Key(IP,ip),info=cGG(users=[],characters=[],metrics={},last_decay=datetime.now()))
decay_ip_info(info)
return info
def decay_ip_info(ip):
hours=hsince(ip.info.last_decay)
if hours>12:
r=hours/24.0
for k in dir(ip.info):
if k.startswith("limit_"):
if k=="limit_signups": r/=1.2
setattr(ip.info,k,getattr(ip.info,k)-r)
if getattr(ip.info,k)<0: setattr(ip.info,k,0)
ip.info.last_decay=datetime.now()
def put_ip_info(ip,user=None,character=None):
if user and (user.k() not in ip.info.users): ip.info.users.append(user.k())
if character and (character.k() not in ip.info.characters): ip.info.characters.append(character.k())
if len(ip.info.users)>100: ip.info.users=ip.info.users[1:]
if len(ip.info.characters)>100: ip.info.characters=ip.info.characters[1:]
ip.users=ip.info.users; ip.characters=ip.info.characters
ip.put_async()
def characters_to_client(characters_data):
characters=[]
for character in characters_data:
characters.append(character_to_dict(character))
characters.sort(key=(lambda x: x["online"]),reverse=True)
return characters
def servers_to_client(domain,servers_data):
servers=[]
for server in servers_data:
servers.append({"name":server.name,"region":server.region,"players":server.info.players,"key":server.k(),"addr":domain.https and server.ip or server.actual_ip,"port":server.port})
return servers
def get_characters(user,async=False):
characters=[]
for c in user.info.characters:
characters.append(get_by_iid_async("character|%s"%c["id"]))
if async: return characters
for i in xrange(len(characters)):
characters[i]=characters[i].get_result()
return characters
def get_stats(characters):
stats={"monsters":{}}
for character in characters:
monsters=gf(character,"p",{}).get("stats",{}).get("monsters",{})
monsters_diff=gf(character,"p",{}).get("stats",{}).get("monsters_diff",{})
for id in monsters:
if monsters[id]+monsters_diff.get(id,0)>stats["monsters"].get(id,[0,0])[0]:
stats["monsters"][id]=[monsters[id]+monsters_diff.get(id,0),character.info.name]
return stats
def character_to_dict(character):
data={"id":character.k(),"name":character.info.name,"level":character.level,"type":character.type,"online":0}
if character.online:
data["online"]=mssince(character.last_online)
data["server"]=character.server
data["secret"]=gf(character,"secret","12")
if gf(character,"rip"):
data["rip"]=character.info.rip
data["skin"]=character.info.skin
data["cx"]=gf(character,"cx",{})
data["in"]=gf(character,"in",character.info.map)
data["map"]=character.info.map
data["x"]=character.info.x
data["y"]=character.info.y
if gf(character,"p") and character.info.p.has_key("home"):
data["home"]=character.info.p["home"]
return data
def update_user_data(user,data):
user.info.gold=data["gold"]
user.info.rewards=data.get("rewards",[])
user.info.unlocked=data.get("unlocked",{})
user.info.items0=data["items0"]
user.info.items1=data["items1"]
user.info.last_sync=datetime.now()
for i in range(2,48):
setattr(user.info,"items%d"%i,data.get("items%d"%i,False))
def user_to_server(user):
info={
"gold":gf(user,"gold",1000),
"rewards":gf(user,"rewards",[]),
"unlocked":gf(user,"unlocked",{}),
"items0":gf(user,"items0",[]),
"items1":gf(user,"items1",[]),
}
for i in range(2,48):
info["items%d"%i]=gf(user,"items%d"%i,False)
return info
def guild_to_info(guild):
return {
"id":guild.k(),
"name":guild.name,
"short":guild.short}
def update_character(character,data,owner):
character.info.x=data["x"]
character.info.y=data["y"]
character.info.s=data["s"]
character.info.q=data.get("q",{})
#character.info.c=data["c"]
character.info.map=data["map"]
setattr(character.info,"in",data["in"])
character.xp=int(data["xp"] or 0)
character.level=int(data["level"])
character.info.hp=data["hp"]
character.info.mp=data["mp"]
character.info.gold=data["gold"]
character.info.items=data["items"]
character.info.slots=data["slots"]
#character.info.trades=data.get("trades")
character.info.rip=data.get("rip")
if data.get("p",0): character.info.p=data.get("p")
character.info.skin=data.get("skin")
character.info.cx=data.get("cx",{})
character.info.afk=data.get("afk")
character.private=data.get("private")
character.info.owner_name=owner.name
def update_pids(character,data,owner):
fresh=False; platform="web"; pid=""
steam_id=data.get("p",0) and data["p"].get("steam_id","")
mas_auth_id=data.get("p",0) and data["p"].get("mas_auth_id","")
if data.get("p",0) and data["p"].get("platform","")=="steam" and steam_id:
fresh=True
platform="steam"
pid=steam_id
if data.get("p",0) and data["p"].get("platform","")=="mas" and mas_auth_id:
fresh=True
platform="steam"
pid=mas_auth_id
if steam_id:
character.platform="steam"
character.pid=steam_id
elif mas_auth_id:
character.platform="mas"
character.pid=mas_auth_id
if fresh and (owner.platform!=platform or owner.pid!=pid): #there's a chance that a player both have mas and steam accounts, so steam priority logic might be good here [03/05/19]
user=get_by_iid(owner.k('i'))
user.platform=platform
user.pid=pid
user.put()
logging.info("costly operation - changed user platform/pid - %s"%user.k())
elif not fresh and steam_id and not owner.pid:
user=get_by_iid(owner.k('i'))
user.platform="steam"
user.pid=steam_id
user.put()
logging.info("costly operation - set steam user platform/pid - %s"%user.k())
elif not fresh and mas_auth_id and not owner.pid:
user=get_by_iid(owner.k('i'))
user.platform="mas"
user.pid=mas_auth_id
user.put()
logging.info("costly operation - set mas user platform/pid - %s"%user.k())
elif not fresh and (owner.platform!=character.platform or owner.pid!=character.pid):
character.platform=owner.platform
character.pid=owner.pid
def character_to_info(character,user=None,ip=None,guild=None):
drm=False
drm_fail=False
if user and user.created>datetime(2019,02,01,0,0) and not gf(user,"legacy_override"): drm=True
if gf(user,"drm_fail_pid","not")==character.pid: drm_fail=True
info={
"id":character.k(),
"name":character.info.name,
"friends":character.friends,
"level":character.level,
#"gender":character.info.gender,
"gold":character.info.gold,
"type":character.type,
"xp":character.xp,
"items":character.info.items,
"stats":character.info.stats,
"slots":gf(character,"slots",{}),
"skin":character.info.skin,
"cx":gf(character,"cx",[]),
"platform":character.platform,
"pid":character.pid or user and user.pid,
"drm":drm,
"drm_fail":drm_fail,
"x":character.info.x,
"y":character.info.y,
"map":character.info.map,
"owner":character.owner,
"private":character.private,
"created":int(time.mktime(character.created.timetuple()))*1000,
"hp":gf(character,"hp",0),
"mp":gf(character,"mp",0),
"afk":gf(character,"afk",0),
"s":gf(character,"s",{}),
"c":gf(character,"c",{}),
"q":gf(character,"q",{}),
#"trades":gf(character,"trades",0),
"rip":gf(character,"rip",0),
"p":gf(character,"p",{"dt":{}}) or {"dt":{}}, #or is to fix the temporary, pre-server update glitch [12/09/16]
}
if guild:
info["guild"]=guild_to_info(guild)
if ip and ip.exception:
info["ipx"]=ip.info.limit
if user:
info["cash"]=user.cash
info["verified"]=gf(user,"verified",0)
return info
def character_emit(character,method,data):
if character.server:
server=get_by_iid("server|%s"%character.server)
if server: server_eval_safe(server,"var p=players[name_to_id.get('%s')]; if(p) p.socket.emit('%s',data);"%(character.info.name,method),data=data)
def character_eval(character,code,data={}):
if character.server:
server=get_by_iid("server|%s"%character.server)
if server: server_eval_safe(server,"var player=players[name_to_id.get('%s')]; if(player) { %s; }"%(character.info.name,code),data=data)
def notify_friends(character,server_name):
server_list={}
servers=get_servers()
online=Character.query(Character.friends == character.owner,Character.online == True)
for friend in online:
if not friend.server: continue
server_list[friend.server]=server_list.get(friend.server,[])
server_list[friend.server].append(friend.info.name)
for server in servers:
if server_list.get(server.k()):
server_eval(server,"notify_friends(data)",data={"list":server_list[server.k()],"name":character.info.name,"server":server_name})
def update_characters(user,reason=None,name=None,shells=0):
def set_friends():
c=get_by_iid(character.k('i'))
c.friends=user.friends
c.put()
for character in Character.query(Character.online==True,Character.owner==user.k()):
if character.server:
try:
server=get_by_iid("server|%s"%character.server)
ip=server.actual_ip
if is_sdk: ip="0.0.0.0"
if not reason:
fetch_url("http://%s:%s"%(ip,server.port),aevent="cupdate",spass=secrets.SERVER_MASTER,cash=user.cash,id=character.info.name,ncash=shells)
elif reason=="friends":
try: ndb.transaction(set_friends,xg=True,retries=0)
except: log_trace_i()
fetch_url("http://%s:%s"%(ip,server.port),aevent="new_friend",spass=secrets.SERVER_MASTER,name=name,friends=user.friends,id=character.info.name)
elif reason=="not_friends":
try: ndb.transaction(set_friends,xg=True,retries=0)
except: log_trace_i()
fetch_url("http://%s:%s"%(ip,server.port),aevent="lost_friend",spass=secrets.SERVER_MASTER,name=name,friends=user.friends,id=character.info.name)
#character_emit(character,"friend",{"event":"update","friends":user.friends})
except: log_trace()
def send_system_mail(user,subject,message,type=None,info=None):
if not type: type="system"
if not hasattr(user,"k"): user=get_by_iid("user|%s"%user)
mail=Mail(fro="0",to=user.info.name,type=type,owner=["0",user.k()],info=cGG(message=message,subject=subject,sender="0",receiver=user.k()))
mail.put()
user_data=get_user_data(user)
user_data.info.mail=max(0,gf(user_data,"mail",0)-1)
user_data.put()
def pretty_timeleft(t):
left=""
minutes=int((t-datetime.now()).seconds/60.0)
days=(t-datetime.now()).days
if days:
left="%d days"%days
if minutes>60:
left=left+" %d hours"%(int(minutes/60))
minutes=minutes%(60)
left=left+" %d minutes"%minutes
return left
def gdpr_delete(self,user,logging=None):
from api import delete_character_api
if not logging: logging=globals()["logging"]
if not hasattr(user,"k"): user=get_user(email=user)
for c in gf(user,"characters",[]):
user.info.last_delete=really_old
delete_character_api(user=user,self=self,domain=gdi(self),name=c["name"])
logging.info("Deleted %s"%c["name"])
markedphrase=get_by_iid("markedphrase|%s"%dgt("email",user.info.email))
if markedphrase: markedphrase.key.delete()
user.key.delete()
logging.info("Deleted %s"%user.info.email)
def block_account(name,days,reason="",toggle=False):
character=get_character(name)
if not character: return "no character"
owner=get_by_iid("user|%s"%character.owner)
if not owner: return "no owner"
if toggle and gf(owner,"blocked_until") and owner.info.blocked_until>datetime.now(): days=-1
if days<=0:
owner.info.blocked_until=really_old
owner.put()
return "un-blocked %s"%owner.k()
else:
owner.info.blocked_until=datetime.now()+timedelta(seconds=int(days*24*60*60))
owner.info.blocked_reason=reason
owner.banned=True
owner.put()
servers=get_servers()
for server in servers:
server_eval(server,"for(var id in players) { if(players[id].owner=='%s') { players[id].socket.emit('disconnect_reason','blocked'); players[id].socket.disconnect(); } }"%owner.k())
return "blocked %s for %s days"%(owner.k(),days)
def servers_eval(code,data={}):
servers=get_servers()
for server in servers:
server_eval_safe(server,code,data=data)
def chat_analysis(name,logging=None):
for m in Message.query(Message.author==get_owner("orlyowl").k()).order(-Message.created).fetch(100):
logging.info("%s - %s"%(m.created,m.info.message))
def growth_analysis(name,logging=None,days=50,offset=0):
if not logging: logging=globals()["logging"]
owner=get_owner(name); owner_ki=owner.k('i')
latest={}; last_gold=total_worth(owner,characters=False); last_pgold=owner.info.gold; last_xp=0
logging.info("")
logging.info("USER Gold: %s Cash: %s"%(to_pretty_num(owner.info.gold),to_pretty_num(owner.cash)))
for character in Character.query(Character.owner == ""+owner.k()):
#logging.info("%s[%s] %s"%(character.info.name,character.level,to_pretty_num(character.info.gold)))
latest[character.k('i')]=character
last_xp+=total_xp(character)
last_gold+=total_worth(character)
last_pgold+=character.info.gold
logging.info("TODAY GOLD %s XP %s"%(to_pretty_num(last_gold),to_pretty_num(last_xp)))
for i in range(1,days):
cut_off=datetime.now()-timedelta(days=i+offset)
b=Backup.query(Backup.backup_item_id==owner_ki).filter(Backup.backup_created <= cut_off).order(-Backup.backup_created).get()
if b and (cut_off-b.backup_created).days*24+(cut_off-b.backup_created).seconds/3600<=24: owner=b
c_xp=0; c_gold=total_worth(owner,characters=False); c_pgold=owner.info.gold
for n in latest:
ch=latest[n]
c=Backup.query(Backup.backup_item_id==n).filter(Backup.backup_created <= cut_off).order(-Backup.backup_created).get()
if c and (cut_off-c.backup_created).days*24+(cut_off-c.backup_created).seconds/3600<=24:
latest[n]=c
ch=c
c_xp+=total_xp(ch)
c_gold+=total_worth(ch)
c_pgold+=ch.info.gold
logging.info("D[%s] GOLD %s PURE GOLD %s XP %s"%(offset+i,to_pretty_num(last_gold-c_gold),to_pretty_num(last_pgold-c_pgold),to_pretty_num(last_xp-c_xp)))
last_xp=c_xp
last_gold=c_gold
last_pgold=c_pgold
def character_analysis(name,logging=None):
if not logging: logging=globals()["logging"]
character=get_character(name)
servers=get_servers(); players=[]; ip=""; owners=[character.owner]
for server in servers:
cip=server_eval(server,"var cip=''; for(var id in players) { var player=players[id]; if(player.name!='%s') continue; cip=get_ip(player); }; output=cip;"%name)
if cip: ip=cip
for server in servers:
splayers=server_eval(server,"var list=[]; for(var id in players) { var player=players[id]; if(get_ip(player)!='%s') continue; list.push({owner:player.owner,name:player.name,ip:get_ip(player),server:region+' '+server_name,type:player.type,level:player.level,age:player.age,cgold:player.t.cgold,dgold:player.t.dgold,txp:player.t.xp,minutes:msince(player.t.start),dps:player.t.mdamage/ssince(player.t.start),gps:(player.t.cgold+player.t.dgold)/ssince(player.t.start),xps:player.t.xp/ssince(player.t.start)}); }; output=list;"%ip)
for player in splayers:
if player["owner"] not in owners:
owners.append(player["owner"])
logging.info("Secondary owner: %s"%player["owner"])
players.append(player)
for player in players:
logging.info(player)
l=[]
for owner in owners:
oos={}
tos={}
froms={}
owner=get_by_iid("user|"+owner)
logging.info("")
logging.info("USER Gold: %s Cash: %s"%(to_pretty_num(owner.info.gold),to_pretty_num(owner.cash)))
if owner.platform=="steam":
result=fetch_url_async("https://partner.steam-api.com/ISteamUser/CheckAppOwnership/v2/",use_get=True,key=steam_publisher_web_apikey,appid="777150",steamid=owner.pid).get_result()
if result.content.find('"ownsapp":true')!=-1:
logging.info("Steam ownership: YES")
else:
logging.info(result.content)
l.append(owner)
l.append(get_user_data(owner))
names={}
characters=Character.query(Character.owner == ""+owner.k()).fetch(100)
for character in characters: names[character.info.name]=True
i_list=[]
for i in xrange(64): i_list.append("items%d"%i)
for c in i_list:
if not gf(owner,c,[]): continue
for item in gf(owner,c,[]):
if not item: continue
oo=None
if item.get("gf") and item["gf"] not in names:
oo=item["gf"]
elif item.get("o") and item["o"] not in names:
oo=item["o"]
elif item.get("oo") and item["oo"] not in names:
oo=item["oo"]
if oo:
logging.info(item)
oos[oo]=[oos.get(oo,[0,0])[0]+1,oos.get(oo,[0,0])[1]+item_value(item)]
for character in characters:
l.append(character)
for item in gf(character,"items",[]):
if not item: continue
oo=None
if item.get("gf") and item["gf"] not in names:
oo=item["gf"]
elif item.get("o") and item["o"] not in names:
oo=item["o"]
elif item.get("oo") and item["oo"] not in names:
oo=item["oo"]
if oo:
logging.info(item)
oos[oo]=[oos.get(oo,[0,0])[0]+1,oos.get(oo,[0,0])[1]+item_value(item)]
for slot in gf(character,"slots",{}):
item=character.info.slots[slot]
if not item: continue
oo=None
if item.get("gf") and item["gf"] not in names:
oo=item["gf"]
elif item.get("o") and item["o"] not in names:
oo=item["o"]
elif item.get("oo") and item["oo"] not in names:
oo=item["oo"]
if oo:
logging.info(item)
oos[oo]=[oos.get(oo,[0,0])[0]+1,oos.get(oo,[0,0])[1]+item_value(item)]
logging.info("%s[%s] %s"%(character.info.name,character.level,to_pretty_num(character.info.gold)))
for h in gf(character,"p",{}).get("history",[]):
if h.get("from") and not names.has_key(h.get("from")):
e=froms.get(h["from"],[0,0])
e[0]+=1
e[1]+=h.get("amount",0) or h.get("item","") and item_value({"name":h["item"],"level":h.get("level",0)}) or 0
froms[h["from"]]=e
if h.get("to") and not names.has_key(h.get("to")):
e=tos.get(h["to"],[0,0])
e[0]+=1
e[1]+=h.get("amount",0) or h.get("item","") and item_value({"name":h["item"],"level":h.get("level",0)}) or 0
tos[h["to"]]=e
logging.info("OOS:")
logging.info(oos)
logging.info("FROMS:")
logging.info(froms)
logging.info("TOS:")
logging.info(tos)
return l
def game_analysis(logging=None):
if not logging: logging=globals()["logging"]
servers=get_servers(True); players=[]; ips={}
for server in servers:
try:
splayers=server_eval(server,"var list=[]; for(var id in players) { var player=players[id]; list.push({owner:player.owner,name:player.name,ip:get_ip(player),type:player.type,level:player.level,age:player.age,map:player.map,gold:to_pretty_num(player.gold),server:region+' '+server_name,dps:player.t.mdamage/ssince(player.t.start),gps:(player.t.cgold+player.t.dgold)/ssince(player.t.start),xps:player.t.xp/ssince(player.t.start)}); }; output=list;")
for player in splayers:
#player["pvp"]=gf(server,"pvp")
player["server"]="%s %s"%(server.region,server.name)
players.append(player)
except:
log_trace_i()
for player in players:
if not ips.get(player["ip"]): ips[player["ip"]]=[]
ips[player["ip"]].append(player)
for server in servers:
logging.info("%s %s - Gold: %s"%(server.region,server.name,to_pretty_num(gf(server,"data",{}).get("gold",0))))
logging.info("")
for ip in ips:
logging.info("")
owners=[]; dps=0.0001; gps=0
for player in ips[ip]:
if player["owner"] not in owners: owners.append(player["owner"])
if len(owners)>1: logging.info("MULTIPLE PLAYERS FROM ONE IP")
for player in ips[ip]:
logging.info(player)
dps+=player.get("dps",0)
gps+=player.get("gps",0)
logging.info("GPS / DPS: %s"%(gps/dps))
def enforce_limitations():
servers=get_servers()
players=[]; ips={}; mips={}; owners={}; mowners={}; ipx={}; ip_type={}
to_ipdisconnect=[]; to_ownerdisconnect=[]; to_authdisconnect=[]
for server in servers:
if server.gameplay!="normal": continue
try:
splayers=server_eval(server,"var list=[]; for(var id in players) { var player=players[id]; list.push({owner:player.owner,name:player.name,ip:get_ip(player),type:player.type,bot:player.bot||'',free:player.p.free||player.s.licenced||player.role=='gm',ipx:player.ipx||1,temp_auth:player.temp_auth||'',auth_id:player.auth_id||''}); }; output=list;")
for player in splayers:
player["pvp"]=gf(server,"pvp")
players.append(player)
server.players=splayers
#time.sleep(1) #best not to sleep here, otherwise a server change counts +1 [10/12/17]
except:
log_trace_i()
#logging.info(players)
for player in players: #count loop
ip_type[player["ip"]]="real"
if player["free"]: continue #the bot limitations should be enforced at launch - or re-visited later on [03/08/17]
if player["auth_id"]:
if player["type"]!="merchant":
ips[player["ip"]]=ips.get(player["ip"],0)+1 #so steam/mas logins don't allow separate IP logins
else:
mips[player["ip"]]=mips.get(player["ip"],0)+1
player["ip"]=player["auth_id"]
player["ipx"]=1
ip_type[player["ip"]]="auth"
if player["temp_auth"]:
if player["type"]!="merchant":
ips[player["ip"]]=ips.get(player["ip"],0)+1 #so temporary mas logins don't allow separate IP logins
else:
mips[player["ip"]]=mips.get(player["ip"],0)+1
player["ip"]=player.owner
player["ipx"]=1
ip_type[player["ip"]]="owner"
ipx[player["ip"]]=max(ipx.get(player["ip"],0),player["ipx"])
if player["type"]=="merchant":
mowners[player["owner"]]=mowners.get(player["owner"],0)+1
mips[player["ip"]]=mips.get(player["ip"],0)+1