forked from derand/kanojo_server
-
Notifications
You must be signed in to change notification settings - Fork 2
/
web_job.py
1836 lines (1654 loc) · 68.8 KB
/
web_job.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
# -*- coding: utf-8 -*-
__author__ = 'Andrey Derevyagin, Goujer'
__copyright__ = 'Copyright © 2014-2015, 2020-2022'
import atexit
import os.path
import re
import ssl
import urllib.parse
from hashlib import sha224
from html import escape
import pymongo.errors
from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask, Response, abort, json, jsonify, redirect, render_template, request, send_file, \
send_from_directory, session
from flask_api.decorators import set_parsers
from activity import ActivityManager
from bkmultipartparser import BKMultipartParser
from constants import *
from geo_ip import GEOIP_WEB_SERVICE, GeoIP
from images import save_kanojo_profile_image, save_product_image, save_resized_image
from kanojo import *
from reactionword import ReactionwordManager
from store import StoreManager
from thread_post import Post
from user import *
if config.USE_HTTPS:
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.load_cert_chain(config.SSL_CERTIFICATE_FILE, keyfile=config.SSL_PRIVATEKEY_FILE)
app = Flask(__name__)
app.debug = config.DEBUG
app.secret_key = config.SESSION_SECRET_KEY
#app.config['SESSION_COOKIE_DOMAIN'] = '192.168.1.19'
#session.permanent = True
#app.permanent_session_lifetime = datetime.timedelta(minutes=5)
#app.config['DEFAULT_PARSERS'] = []
#Set Up Debug From WSGI
from werkzeug.debug import DebuggedApplication
application = DebuggedApplication(app, config.DEBUG)
mdb_connection_string = config.MDB_CONNECTION_STRING_REAL
db_name = mdb_connection_string.split('/')[-1]
db2 = MongoClient(mdb_connection_string)[db_name]
mdb_connection_string = config.MDB_CONNECTION_STRING
db_name = mdb_connection_string.split('/')[-1]
db = MongoClient(mdb_connection_string)[db_name]
kanojo_manager = KanojoManager(db,
clothes_magic=config.CLOTHES_MAGIC,
generate_secret=config.KANOJO_SECRET
)
store = StoreManager()
activity_manager = ActivityManager(db=db)
user_manager = UserManager(db, kanojo_manager=kanojo_manager, store=store, activity_manager=activity_manager)
geoIP = GeoIP(db, secret1=config.GEOIP_SECRET1, secret2=config.GEOIP_SECRET2, secret3=config.GEOIP_SECRET3)
reactionword = ReactionwordManager()
@app.template_filter('date_format')
def timectime(s):
dt = time.gmtime(s)
return '%d-%02d-%02d'%(dt.tm_year, dt.tm_mon, dt.tm_mday)
def order_dict_cmp(x, y):
order = ('code', )
x,y = x[0], y[0]
if x in order and y in order:
return order.index(x)-order.index(y)
elif x in order:
return -1
elif y in order:
return 1
return (x > y) - (x < y)
def json_response(data):
if isinstance(data, dict):
data = OrderedDict(sorted(list(data.items()), key=cmp_to_key(order_dict_cmp)))
rtext = json.dumps(data)
if request.method == 'POST':
if request.form.get('callback', False):
rtext = '%s(%s);'%(request.form.get('callback', ''), rtext)
else:
if request.args.get('callback', False):
rtext = '%s(%s);'%(request.args.get('callback', ''), rtext)
return Response(rtext, status=200, mimetype='application/json')
def server_url():
if config.USE_HTTPS:
return request.url_root.replace('http:/', 'https:/')
return request.url_root
def get_remote_ip():
if not request.headers.getlist("X-Forwarded-For"):
remote_ip = request.remote_addr
else:
remote_ip = request.headers.getlist("X-Forwarded-For")[0]
return remote_ip
@app.route('/')
def index():
remote_ip = get_remote_ip()
tz_string = geoIP.ip2timezone(remote_ip, service_type=GEOIP_WEB_SERVICE)
#print remote_ip, tz_string
val = {}
posts = []
#for p in db.posts_rejected.find().sort('time', 1):
for p in db.posts.find().sort('time', 1):
posts.append(Post(post=p, timezone_string=tz_string))
val['posts'] = posts
return render_template('thread.html', **val)
@app.route('/robots.txt')
@app.route('/favicon.ico')
def robots_txt():
return send_from_directory(app.static_folder, request.path[1:])
def check_post_request(post_request):
ban_rules = (
#{
# 'ip': '127.0.0.1'
#},
{
'ip': '46.161.41.34',
#'User-Agent': 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)'
},
#{
# 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 YaBrowser/15.2.2214.3643 Safari/537.36'
#},
)
tmp = db.settings.find_one({ 'ban_rules': { '$exists': True } })
if tmp:
ban_rules = tmp.get('ban_rules', list())
reject_rule = None
remote_ip = get_remote_ip()
for rule in ban_rules:
if 'ip' in rule and remote_ip != rule.get('ip'):
continue
flag = True
for k in [el for el in list(rule.keys()) if el!='ip']:
if post_request.headers.get(k) != rule.get(k):
flag = False
break
if flag:
#if rule.has_key('ip') and post_request.remote_addr != rule.get('ip'):
# continue
reject_rule = rule
if reject_rule is not None:
print('Rejected by rule:', rule)
break
if reject_rule is None:
print(post_request.headers)
return reject_rule
@app.route('/post', methods=['POST'])
def post():
reject_rule = check_post_request(request)
#if not check_post_request(request):
# return 'You are banned for this thread.'
prms = request.form
name = 'Сырно' if len(prms.get('nya1').strip()) == 0 else prms.get('nya1').strip()
msg = escape(prms.get('nya2').strip())
pwd = prms.get('password', '').strip()
if len(msg):
msg = message_marking(msg)
msg = clickableURLs(msg)
msg = checkRefLinks(msg, 1)
msg = checkQuotes(msg)
if reject_rule is None:
seqs_collection = 'posts'
else:
seqs_collection = 'posts_rejected'
pid = db.seqs.find_and_modify(
query = {'collection': seqs_collection},
update = {'$inc': {'id': 1}},
fields = {'id': 1, '_id': 0},
new = True
)
while db.posts.find_one({'id': pid if pid else 1}):
pid += 1
if pid is None:
pid = {
'collection': seqs_collection,
'id': 1
}
try:
db.seqs.insert_one(pid)
except pymongo.errors.DuplicateKeyError as e:
abort(500)
post = {
'pid': pid.get('id'),
'post': msg.replace("\n", '<br>'),
'poster': name,
'time': int(time.time())
}
if pwd:
post['password'] = sha224(pwd).hexdigest()
if reject_rule is None:
db.posts.insert_one(post)
else:
post['reject_rule'] = reject_rule
db.posts_rejected.insert_one(post)
return 'You are banned for this thread.'
return redirect("/", code=302)
marking_rules = (
(re.compile('\*\*(?P<bold>.*?)\*\*', re.VERBOSE), r'<b>\g<bold></b>'),
(re.compile('__(?P<underline>.*?)__', re.VERBOSE), r'<span class="underline">\g<underline></span>'),
(re.compile('--(?P<strike>.*?)--', re.VERBOSE), r'<strike>\g<strike></strike>'),
(re.compile('%%(?P<spoiler>.*?)%%', re.VERBOSE), r'<span class="spoiler">\g<spoiler></span>'),
(re.compile('\*(?P<italic>.*?)\*', re.VERBOSE), r'<i>\g<italic></i>'),
(re.compile('_(?P<italic>.*?)_', re.VERBOSE), r'<i>\g<italic></i>'),
(re.compile('`(?P<code>.*?)`', re.VERBOSE), r'<code>\g<code></code>'),
)
def message_marking(message):
l = []
for line in message.split('\n'):
line = line.strip()
for (p, mark_sub) in marking_rules:
line = p.sub(mark_sub, line)
l.append(line)
return '\n'.join(l)
def refLinksReplace(match):
match = match.group()
postid = match[len('>>'):]
parentid = 1
if parentid != 0:
if postid == parentid:
return r'<a href="/.html" onclick="javascript:highlight(' + '\'' + postid + '\'' + r', true);">>>' + postid + '</a>'
else:
return '<a href="#' + postid + r'" onclick="javascript:highlight(' + '\'' + postid + '\'' + r', true);">>>' + postid + '</a>'
return match
def checkQuotes(message):
message = re.compile(r'^>(.*)$', re.MULTILINE).sub(r'<span class="unkfunc">>\1</span>', message)
return message
def checkRefLinks(message, parentid):
message = re.compile(r'>>([0-9]+)').sub(refLinksReplace, message)
return message
def clickableURLs(message):
translate_prog = prog = re.compile(r'\b(http|ftp|https)://\S+(\b|/)|\b[-.\w]+@[-.\w]+')
i = 0
list = []
while 1:
m = prog.search(message, i)
if not m:
break
j = m.start()
list.append(message[i:j])
i = j
url = m.group(0)
while url[-1] in '();:,.?\'"<>':
url = url[:-1]
i = i + len(url)
url = url
if ':' in url:
repl = '<a href="%s">%s</a>' % (url, url)
else:
repl = '<a href="mailto:%s"><%s></a>' % (url, url)
list.append(repl)
j = len(message)
list.append(message[i:j])
return ''.join(list)
@app.route('/last_kanojos.html')
def last_kanojos_html():
val = {}
return render_template('last_kanojos.html', **val)
@app.route('/last_kanojos.json')
def last_kanojos():
data = {
'code': 200,
'kanojos': []
}
for i in db.info.find().sort('timestamp', -1).limit(100):
i.pop('_id', None)
i.pop('timestamp', None)
kid = i.get('kid')
if kid is None:
kid = i.get('img_url', '').split('/')[-1].split('.')[0]
if kid.isdigit():
kid = int(kid)
if isinstance(kid, int):
i['url'] = f'http://www.barcodekanojo.com/kanojo/{kid}/{i.get("name", "_")}'
data['kanojos'].append(i)
return json_response(data)
@app.route('/add_job', methods=['POST'])
def add_job():
data = request.form.get('nya')
#data = 'https://www.barcodekanojo.com/user/407529/Everyone http://www.barcodekanojo.com/kanojo/2606490/아...바타 fsdf'
re_u = re.compile('^https?://www\.barcodekanojo\.com/user/(\d+)/.+$')
re_k = re.compile('^https?://www\.barcodekanojo\.com/kanojo/(\d+)/.+$')
users = []
kanojos = []
errors = []
for line in data.split():
s = re_u.search(line.strip())
if s:
users.append(int(s.groups()[0]))
else:
k = re_k.search(line.strip())
if k:
kanojos.append(int(k.groups()[0]))
else:
errors.append(line.strip())
val = {
'users': users,
'kanojos': kanojos,
'errors': errors,
}
if len(users) or len(kanojos):
dt = {}
if len(users):
dt['users'] = users
if len(kanojos):
dt['kanojos'] = kanojos
db2.save_jobs.insert_one(dt)
return render_template('add_job.html', **val)
'''
@app.route('/images/<fn>', methods=['GET'])
def images_root(fn):
return send_from_directory('%s/images'%app.static_folder, fn)
@app.route('/images/api/item/basic/<fn>')
@app.route('/images/store/<fn>')
def images_store(fn):
return send_from_directory('%s/images/store'%app.static_folder, fn)
@app.route('/images/profile_bkgr/<fn>')
def images_profile_bkgr(fn):
return send_from_directory('%s/images/profile_bkgr'%app.static_folder, fn)
'''
@app.route('/images/<path:path>', methods=['GET'])
def images_dir(path):
filename = f'{app.static_folder}/images/{path.lower()}'
if os.path.isfile(filename):
return send_file(filename)
abort(404)
### --------------- storage.barcodekanojo.com ---------------
@app.route('/avatar/<path:path>')
def avatar(path):
#if request.headers['Host'] == 'storage.barcodekanojo.com':
filename = '%s/avatar_data/%s'%(app.static_folder, path.lower())
if os.path.isfile(filename):
return send_file(filename)
abort(404)
### --------------- DRESS UP ---------------
@app.route('/dress_up')
def dress_up():
return redirect('/dress_up/index.html', code=302)
@app.route('/dress_up/<fn>')
def dress_up_file(fn):
filename = '%s/dress_up/%s'%(app.static_folder, fn)
if os.path.isfile(filename):
return send_file(filename)
abort(404)
def dresup_json_to_barcode(dressup_json):
keys = ["c_skin", "c_hair", "c_eye", "c_clothes", "body", "hair", "face", "fringe", "mouth", "eye", "nose", "brow", "ear", "spot", "glasses", "accessory", "clothes"]
r_keys = list(dressup_json.keys())
for k in keys:
if k not in r_keys:
rv = {'code': 400}
return json_response(rv)
bc = {
'skin_color': dressup_json.get('c_skin'),
'hair_color': dressup_json.get('c_hair'),
'eye_color': dressup_json.get('c_eye'),
'clothes_color': dressup_json.get('c_clothes'),
'body_type': dressup_json.get('body'),
'hair_type': dressup_json.get('hair'),
'face_type': dressup_json.get('face'),
'fringe_type': dressup_json.get('fringe'),
'mouth_type': dressup_json.get('mouth'),
'eye_type': dressup_json.get('eye'),
'nose_type': dressup_json.get('nose'),
'brow_type': dressup_json.get('brow'),
'ear_type': dressup_json.get('ear'),
'spot_type': dressup_json.get('spot'),
'glasses_type': dressup_json.get('glasses'),
'accessory_type': dressup_json.get('accessory'),
'clothes_type': dressup_json.get('clothes')
}
return bc
@app.route('/search_barcode.json', methods=['POST'])
def search_barcode():
data = request.get_json()
query = {
'$or': [
{ 'owner_user_id': { '$exists': False } },
{ 'owner_user_id': 0 }
]
}
query.update(dresup_json_to_barcode(data))
query.pop('clothes_color', None)
kanojo = db2.kanojo.find_one(query)
if kanojo:
rv = { 'code': 200 }
rv['barcode'] = kanojo.get('barcode')
else:
rv = { 'code': 404 }
return json_response(rv)
def _genarete_barcode(bid):
#55.{10}[1]
n = bid * config.BARCODE_SECRET % 9999999999
str12 = '55' + str(n).zfill(10)
sum1 = 0
sum2 = 0
i = 1
for digit in str12:
if i%2:
sum1 += int(digit)
else:
sum2 += int(digit)
i = i+1
rv = (10 - (sum2*3 + sum1) % 10) % 10
return f'{str12}{rv:d}'
@app.route('/generate_barcode.json', methods=['POST'])
def generate_barcode():
data = request.get_json()
barcode = dresup_json_to_barcode(data)
barcode['race_type'] = 10
barcode['eye_position'] = 0
barcode['brow_position'] = 0
barcode['mouth_position'] = 0
barcode['sexual'] = randint(0, 99)
barcode['recognition'] = randint(0, 99)
barcode['consumption'] = randint(0, 99)
barcode['possession'] = randint(0, 99)
barcode['flirtable'] = randint(0, 99)
bc = None
while True:
bid = db.seqs.find_and_modify(
query = {'collection': 'barcode_counter'},
update = {'$inc': {'id': 1}},
fields = {'id': 1, '_id': 0},
new = True
)
while db.barcode_tmp.find_one({'id': bid if bid else 1}):
bid += 1
if not bid:
bid = {
'collection': 'barcode_counter',
'id': 1
}
try:
db.seqs.insert_one(bid)
except pymongo.errors.DuplicateKeyError as e:
return jsonify({ 'code': 500 })
bid = bid.get('id')
if bid > 9999999999:
return jsonify({ 'code': 500 })
bc = _genarete_barcode(bid)
q = { 'barcode': bc }
if db.kanojos.find_one(q) or db.barcode_tmp.find_one(q):
continue
break
barcode['barcode'] = bc
barcode['timestamp'] = int(time.time())
db.barcode_tmp.replace_one({'barcode': barcode['barcode']}, barcode, True)
rv = { 'code': 200 }
rv['barcode'] = bc
return json_response(rv)
### --------------- BARCODE STATISTIC ---------------
@app.route('/barcode_stat')
def barcode_stat():
return redirect('/barcode_stat/index.html', code=302)
@app.route('/barcode_stat/<fn>')
def barcode_stat_file(fn):
filename = '%s/barcode_stat/%s'%(app.static_folder, fn)
if os.path.isfile(filename):
return send_file(filename)
abort(404)
### --------------- LAST ACTIVITY ---------------
@app.route('/last_activity.json')
def last_activity():
prms = request.args
try:
since_id = int(prms.get('since_id', 0))
except ValueError as e:
return json_response({ "code": 400 })
activities = activity_manager.all_activities(since_id=since_id)
uids = activity_manager.user_ids(activities)
kids = activity_manager.kanojo_ids(activities)
users = user_manager.users(uids)
kanojos = kanojo_manager.kanojos(kids)
activities = activity_manager.fill_activities(activities, users, kanojos, user_manager.default_user, kanojo_manager.default_kanojo, fill_type=1)
rspns = { "code": 200 }
rspns['last_id'] = activities[0].get('id') if len(activities) else since_id
rspns['activities'] = activities
return json_response(rspns)
@app.route('/user/<uid>.html')
def user_html(uid):
try:
uid = int(uid)
except ValueError as e:
return abort(400)
user = user_manager.user(uid=uid, clear=CLEAR_NONE)
if not user:
abort(404)
user = user_manager.fill_fields(user)
user.pop('_id', None)
kids = copy.copy(user.get('kanojos'))
if len(kids) > 18:
kids = kids[:18]
uids = copy.copy(user.get('enemies'))
if len(uids) > 18:
uids = uids[:18]
activities = activity_manager.user_activities_4html(uid, limit=10)
uids.extend(activity_manager.user_ids(activities))
kids.extend(activity_manager.kanojo_ids(activities))
uids = list(set(uids))
kids = list(set(kids))
kanojos = kanojo_manager.kanojos(kids)
users = user_manager.users(uids)
for i in range(min(18, len(user.get('kanojos')))):
user['kanojos'][i] = next((k for k in kanojos if k.get('id') == user['kanojos'][i]), kanojo_manager.default_kanojo)
for i in range(min(18, len(user.get('enemies')))):
user['enemies'][i] = next((u for u in users if u.get('id') == user['enemies'][i]), user_manager.default_user)
activities = activity_manager.fill_activities(activities, users, kanojos, user_manager.default_user, kanojo_manager.default_kanojo, fill_type=1)
val = {
'stamina_percentage': user.get('stamina') * 10 / (user.get('level') + 9),
'is_dict': lambda x: isinstance(x, dict),
'len_zero': lambda x: len(x)==0,
'activities_html': activity_manager.create_html_block(activities),
}
val.update(user)
return render_template('user.html', **val)
@app.route('/kanojo/<kid>.html')
def kanojo_html(kid):
try:
kid = int(kid)
except ValueError as e:
return abort(400)
kanojo = kanojo_manager.kanojo(kid, clear=CLEAR_NONE)
if kanojo is None:
abort(404)
kanojo = kanojo_manager.fill_fields(kanojo)
kanojo.pop('_id', None)
uids = copy.copy(kanojo.get('followers'))
if len(uids) > 18:
uids = uids[:18]
if kanojo.get('owner_user_id') and kanojo.get('owner_user_id') not in uids:
uids.append(kanojo.get('owner_user_id'))
activities = activity_manager.kanojo_activities_4html(kanojo.get('id'), limit=10)
uids.extend(activity_manager.user_ids(activities))
#kids.extend(activity_manager.kanojo_ids(activities))
users = user_manager.users(uids)
kanojo['owner_user'] = next((u for u in users if u.get('id') == kanojo.get('owner_user_id')), user_manager.default_user)
for i in range(min(18, len(kanojo.get('followers')))):
kanojo['followers'][i] = next((u for u in users if u.get('id') == kanojo['followers'][i]), user_manager.default_user)
activities = activity_manager.fill_activities(activities, users, [kanojo, ], user_manager.default_user, kanojo_manager.default_kanojo, fill_type=1)
val = {
'red_level': lambda x: x < 30,
'len_zero': lambda x: len(x)==0,
'is_dict': lambda x: isinstance(x, dict),
'like_rate0': 5-kanojo.get('like_rate', 0),
'activities_html': activity_manager.create_html_block(activities),
}
val.update(kanojo)
#print json.dumps(kanojo)
return render_template('kanojo.html', **val)
### --------------- KANOJO SERVER ---------------
@app.route('/api/account/verify.json', methods=['GET', 'POST'])
def acc_verify():
prms = request.form if request.method == 'POST' else request.args
uuid = prms.get('uuid')
email = prms.get('email')
password = prms.get('password')
api = prms.get('api')
language = prms.get('language')
if api and language:
ip_hash = hashlib.md5(get_remote_ip().encode('utf-8'), usedforsecurity=False).hexdigest()
client_data = {'client':ip_hash,
'api':int(api),
'language':language}
db['analytics'].replace_one({'client': ip_hash}, client_data, True)
if uuid:
user = user_manager.login(uuid=uuid, email=email, password=password)
if not user:
return jsonify({ "code": 404, "alerts": [{"body": "User not found", "title": "Warning"}]})
session['id'] = user.get('id')
return jsonify({ "code": 200, "user": user })
else:
return jsonify({ "code": 400 })
@app.route('/api/account/signup.json', methods=['POST'])
def acc_signup():
prms = request.form
uuid = prms.get('uuid')
name = prms.get('name', generate_name())
password = prms.get('password')
email = prms.get('email').lower()
birthday = int(time.mktime(time.strptime('%s-%s-%s 12:00:00' % (prms.get('birth_year', 1990), prms.get('birth_month', 1), prms.get('birth_day', 1)), '%Y-%m-%d %H:%M:%S'))) - time.timezone
sex = prms.get('sex', 'Not Sure')
profile_image_data = prms.get('profile_image_data')
if uuid and email and password:
query = {
"email": {
"$exists": True,
"$eq": email
}
}
existing_user = db.users.find_one(query)
if existing_user:
return jsonify({"code": 400, "alerts": [{"body": "Email already in use.", "title": ""}]})
else:
user = user_manager.create(uuid, name, password, email, birthday, sex, profile_image_data)
if not user:
return jsonify({"code": 507})
else:
session['id'] = user.get('id')
return jsonify({"code": 200, "user": user_manager.clear(user, clear=CLEAR_SELF)})
else:
return jsonify({"code": 400})
@app.route('/api/account/delete.json', methods=['POST'])
def acc_delete():
if 'id' not in session:
return jsonify({ "code": 401 })
else:
user_id = int(request.form.get('user_id'))
if user_id == session['id']:
user = user_manager.delete_user(uid=user_id)
if user:
return jsonify({"code": 200, "user": user, 'alerts': [{'body': f'User has been deleted', 'title': 'Info'}]})
else:
return jsonify({"code": 500})
else:
return jsonify({"code": 400})
@app.route('/api/account/show.json', methods=['GET'])
def account_show():
if 'id' not in session:
return json_response({ "code": 401 })
user = user_manager.user(uid=session['id'], clear=CLEAR_SELF)
if user:
return jsonify({ "code": 200, "user": user })
else:
return jsonify({ "code": 404 })
#TODO Fix Search
@app.route('/user/current_kanojos.json', methods=['GET','POST'])
def user_currentkanojos():
#kanojo_manager.server = request.url_root[:-1]
kanojo_manager.server = server_url()[:-1]
if 'id' not in session:
return jsonify({ "code": 401 })
prms = request.form if request.method == 'POST' else request.args
if prms.get('user_id') is None or prms.get('index') is None or prms.get('limit') is None:
return json_response({ "code": 400 })
user_id = int(prms.get('user_id'))
index = int(prms.get('index'))
limit = int(prms.get('limit'))
search = prms.get('search')
user = user_manager.user(uid=user_id, clear=CLEAR_NONE)
if user is None:
return jsonify({ "code": 200, "user": user })
rspns = {"code":200}
kanojos_ids = user.get('kanojos')
current_kanojos = []
if search is not None:
self_user = user_manager.user(uid=session['id'], clear=CLEAR_NONE)
current_kanojos = kanojo_manager.kanojos(kanojo_ids=kanojos_ids, search=search, self_user=self_user, clear=CLEAR_NONE)
if index < len(current_kanojos):
current_kanojos = []
else:
if (index + limit) > len(current_kanojos):
current_kanojos = current_kanojos[index:]
else:
current_kanojos = current_kanojos[index:index + limit]
current_kanojos = kanojo_manager.fill_owners_info(current_kanojos, owner_users=(self_user, user), self_user=self_user)
rspns['search_result'] = {'hit_count': len(current_kanojos)}
elif index < len(kanojos_ids):
if (index+limit) > len(kanojos_ids):
kanojos_ids = kanojos_ids[index:]
else:
kanojos_ids = kanojos_ids[index:index+limit]
self_user = user_manager.user(uid=session['id'], clear=CLEAR_NONE)
current_kanojos = kanojo_manager.kanojos(kanojo_ids=kanojos_ids, search=search, self_user=self_user, clear=CLEAR_NONE)
current_kanojos = kanojo_manager.fill_owners_info(current_kanojos, owner_users=(self_user, user), self_user=self_user)
rspns['current_kanojos'] = current_kanojos
rspns['user'] = user_manager.clear(user, CLEAR_OTHER, self_uid=session['id'])
return json_response(rspns)
@app.route('/api/user/friend_kanojos.json', methods=['GET','POST'])
def user_friendkanojos():
if 'id' not in session:
return json_response({ "code": 401 })
prms = request.form if request.method == 'POST' else request.args
if prms.get('user_id') is None or prms.get('index') is None or prms.get('limit') is None:
return json_response({ "code": 400 })
user_id = int(prms.get('user_id'))
index = int(prms.get('index'))
limit = int(prms.get('limit'))
search = prms.get('search')
user = user_manager.user(uid=user_id, clear=CLEAR_NONE)
if user is None:
return json_response({ "code": 200, "user": None })
rspns = { "code": 200 }
kanojos_ids = user.get('friends')
friend_kanojos = []
if search is not None:
self_user = user_manager.user(uid=session['id'], clear=CLEAR_NONE)
friend_kanojos = kanojo_manager.kanojos(kanojo_ids=kanojos_ids, search=search, self_user=self_user, clear=CLEAR_NONE)
if index < len(friend_kanojos):
friend_kanojos = []
else:
if (index + limit) > len(friend_kanojos):
friend_kanojos = friend_kanojos[index:]
else:
friend_kanojos = friend_kanojos[index:index + limit]
user_ids = kanojo_manager.kanojos_owner_users(friend_kanojos)
users = user_manager.users(user_ids, self_user=self_user)
friend_kanojos = kanojo_manager.fill_owners_info(friend_kanojos, owner_users=users, self_user=self_user)
rspns['search_result'] = {'hit_count':len(friend_kanojos)}
elif index < len(kanojos_ids):
if (index+limit) > len(kanojos_ids):
kanojos_ids = kanojos_ids[index:]
else:
kanojos_ids = kanojos_ids[index:index+limit]
self_user = user_manager.user(uid=session['id'], clear=CLEAR_NONE)
friend_kanojos = kanojo_manager.kanojos(kanojo_ids=kanojos_ids, self_user=self_user, clear=CLEAR_NONE)
user_ids = kanojo_manager.kanojos_owner_users(friend_kanojos)
users = user_manager.users(user_ids, self_user=self_user)
friend_kanojos = kanojo_manager.fill_owners_info(friend_kanojos, owner_users=users, self_user=self_user)
rspns['friend_kanojos'] = friend_kanojos
rspns['user'] = user_manager.clear(user, CLEAR_OTHER, self_uid=session['id'])
return json_response(rspns)
@app.route('/api/kanojo/like_rankings.json', methods=['GET','POST'])
def kanojo_likerankings():
if 'id' not in session:
return json_response({ "code": 401 })
prms = request.form if request.method == 'POST' else request.args
if prms.get('index') is None or prms.get('limit') is None:
return json_response({ "code": 400 })
index = int(prms.get('index'))
limit = int(prms.get('limit'))
query = {}
order = [
('like_rate', -1),
('id', -1),
]
kanojos = db.kanojos.find(query).sort(order).skip(index).limit(limit)
self_user = user_manager.user(uid=session['id'], clear=CLEAR_NONE)
rspns = { "code": 200 }
like_ranking_kanojos = []
for k in kanojos:
like_ranking_kanojos.append(k)
user_ids = kanojo_manager.kanojos_owner_users(like_ranking_kanojos)
users = user_manager.users(user_ids, self_user=self_user)
like_ranking_kanojos = kanojo_manager.fill_owners_info(like_ranking_kanojos, owner_users=users, self_user=self_user)
rspns['like_ranking_kanojos'] = like_ranking_kanojos
return jsonify(rspns)
@app.route('/api/kanojo/show.json', methods=['GET','POST'])
def kanojo_show():
if 'id' not in session:
return json_response({ "code": 401 })
prms = request.form if request.method == 'POST' else request.args
if prms.get('kanojo_id') is None or prms.get('screen') is None:
return json_response({ "code": 400 })
kanojo_id = int(prms.get('kanojo_id'))
rspns = { "code": 200 }
rspns['messages'] = {"notify_amendment_information": "This information is already used by other users.\nIf your amendment would be incorrect, you will be restricted user."}
self_user = user_manager.user(uid=session['id'], clear=CLEAR_NONE)
kanojo = kanojo_manager.kanojo(kanojo_id, self_user=self_user, clear=CLEAR_NONE)
if kanojo:
owner_user = user_manager.user(uid=kanojo.get('owner_user_id'), clear=CLEAR_NONE)
rspns['kanojo'] = kanojo_manager.clear(kanojo, self_user, owner_user=owner_user, clear=CLEAR_OTHER, check_clothes=True)
rspns['owner_user'] = user_manager.clear(owner_user, CLEAR_OTHER, self_user=self_user)
rspns['product'] = as_product(kanojo)
kanojo_date_alert = kanojo_manager.kanojo_date_alert(kanojo)
if kanojo_date_alert:
rspns['alerts'] = [ kanojo_date_alert, ]
else:
rspns = { "code": 404 }
rspns['alerts'] = [{"body": "The Requested KANOJO was not found.", "title": ""}]
return json_response(rspns)
@app.route('/user/enemy_users.json', methods=['GET','POST'])
def user_enemy_users():
if 'id' not in session:
return json_response({ "code": 401 })
prms = request.form if request.method == 'POST' else request.args
if prms.get('user_id') is None or prms.get('index') is None or prms.get('limit') is None:
return json_response({ "code": 400 })
user_id = int(prms.get('user_id'))
index = int(prms.get('index'))
limit = int(prms.get('limit'))
user = user_manager.user(uid=user_id, clear=CLEAR_NONE)
rspns = { "code": 200 }
rspns['user'] = user_manager.clear(user, CLEAR_OTHER, self_uid=session['id'])
enemy_users = []
# TODO: get enemy users
rspns['enemy_users'] = enemy_users
return json_response(rspns)
@app.route('/api/communication/play_on_live2d.json', methods=['GET', 'POST'])
def communication_play_on_live2d():
'''
actions codes (reverse direction):
10 - swipe
11 - shake
12 - touch head
20 - kiss
21 - touch breasts
'''
if 'id' not in session:
return json_response({ "code": 401 })
prms = request.form if request.method == 'POST' else request.args
if prms.get('kanojo_id') is None or prms.get('actions') is None:
return json_response({ "code": 400 })
try:
kanojo_id = int(prms.get('kanojo_id'))
except ValueError:
return json_response({ "code": 400 })
actions = prms.get('actions')
rspns = { "code": 200 }
self_user = user_manager.user(uid=session['id'], clear=CLEAR_NONE)
kanojo = kanojo_manager.kanojo(kanojo_id, self_user=self_user, clear=CLEAR_NONE)
if kanojo:
owner_user = user_manager.user(uid=kanojo.get('owner_user_id'), clear=CLEAR_NONE)
rspns['owner_user'] = user_manager.clear(owner_user, CLEAR_OTHER, self_user=self_user)
#url = request.url_root+'apibanner/kanojoroom/reactionword.html'
url = server_url() + 'web/reactionword.html'
if actions and len(actions):
dt = user_manager.user_action(self_user, kanojo, action_string=actions, current_owner=owner_user)
if 'love_increment' in dt and 'info' in dt:
tmp = dt.get('info', {})
prms = { key: tmp[key] for key in ['pod', 'a'] if key in tmp }
dt['love_increment']['reaction_word'] = f'{url}?{urllib.parse.urlencode(prms)}'
#print dt['love_increment']['reaction_word']
dt.pop('info', None)
rspns.update(dt)
rspns['self_user'] = user_manager.clear(self_user, CLEAR_SELF, self_user=self_user)
rspns['kanojo'] = kanojo_manager.clear(kanojo, self_user, clear=CLEAR_OTHER)
else:
rspns = { "code": 404 }
rspns['alerts'] = [{"body": "The Requested KANOJO was not found.", "title": ""}]
return json_response(rspns)
# this url builds in 'communication_play_on_live2d'
@app.route('/apibanner/kanojoroom/reactionword.html')
@app.route('/web/reactionword.html')
def apibanner_kanojoroom_reactionword():
'''
a - action param
1 - gift to kanojo
2 - extended gift
3 - date
4 - extended date (not use)
10,11,12 - main touch action
20,21 - main touch by stamina action
pod - part of day param
0 - night
1 - morning
2 - day
3 - evening
'''
# TODO: add more text strings
prms = request.args
if prms.get('a') is None or prms.get('pod') is None:
return json_response({ "code": 400 })
try:
a = int(prms.get('a'))
pod = int(prms.get('pod'))
except ValueError:
return json_response({ "code": 400 })
val = {
'text': reactionword.reactionword_json(a, pod)
}
return render_template('apibanner_kanojoroom_reactionword.html', **val)
@app.route('/api/kanojo/vote_like.json', methods=['GET', 'POST'])
def kanojo_vote_like():
if 'id' not in session:
return json_response({ "code": 401 })
prms = request.form if request.method == 'POST' else request.args
if prms.get('kanojo_id') is None or prms.get('like') is None:
return json_response({ "code": 400 })
try:
kanojo_id = int(prms.get('kanojo_id'))
like = prms.get('like').lower() == 'true'
except ValueError:
return json_response({ "code": 400 })
rspns = { "code": 200 }
self_user = user_manager.user(uid=session['id'], clear=CLEAR_NONE)
kanojo = kanojo_manager.kanojo(kanojo_id, self_user=self_user, clear=CLEAR_NONE)
if not user_manager.set_like(self_user, kanojo, like, update_db_record=True):
return json_response({"code": 500})
rspns['kanojo'] = kanojo_manager.clear(kanojo, self_user, clear=CLEAR_OTHER)
return json_response(rspns)
@app.route('/api/resource/product_category_list.json', methods=['GET','POST'])
def resource_product_category_list():
if 'id' not in session:
return jsonify({"code": 401})
rspns = {"code": 200}
with open('product_category_list.json') as json_file:
rspns.update(json.load(json_file))
#rspns['categories'] = [{"id": "1", "name": "Drink"}, {"id": "2", "name": "Food"}, {"id": "3", "name": "Snack"}, {"id": "4", "name": "Alcohol"}, {"id": "5", "name": "Beer"}, {"id": "6", "name": "Tabacco"}, {"id": "7", "name": "Magazines"}, {"id": "8", "name": "Stationary"}, {"id": "9", "name": "Industrial tool"}, {"id": "10", "name": "Electronics"}, {"id": "11", "name": "Kitchenware"}, {"id": "12", "name": "Clothes"}, {"id": "13", "name": "Accessory"}, {"id": "14", "name": "Music"}, {"id": "15", "name": "DVD"}, {"id": "16", "name": "TVgame"}, {"id": "17", "name": "Sports gear"}, {"id": "18", "name": "Health & beauty"}, {"id": "19", "name": "Medicine"}, {"id": "20", "name": "Medical supplies"}, {"id": "22", "name": "Book"}, {"id": "21", "name": "others"}]
return jsonify(rspns)
@app.route('/activity/user_timeline.json', methods=['GET','POST'])
def activity_usertimeline():
'''
activity_type
01 - ("Nightmare has scanned on 2014/10/04 05:31:50.\n")
02 - ("Violet was generated from 星光産業 .")
05 - Me add new friend ("Filter added 葵 to friend list.")
07 - approached my kanojo ("KH approached めりい.")
08 - me stole kanojo ("Devourer stole うる from Nobody.")
09 - my kanojo was stollen ("ふみえ was stolen by Nobody.")
10 - other user added my kanojo ("呪いのBlu-ray added ぽいと to friend list.")
11 - ("Everyone became Lev.\"99\".")
15 - me married ("Devourer get married with うる.")
'''
'''
rv = {
'activities': [
{
'kanojo': null,
'product': null,
'user': null,