-
Notifications
You must be signed in to change notification settings - Fork 28
/
views.py
2509 lines (2360 loc) · 125 KB
/
views.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
# -*- coding: utf-8 -*-
from __future__ import division
import math
from django.shortcuts import render, redirect, get_object_or_404
from django import template
from django.http import HttpResponse, Http404
from django.template import RequestContext, loader
from django.utils.http import is_safe_url, urlsafe_base64_decode
from django.core.files.images import ImageFile
from django.contrib.auth.models import User, Group
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.views import login as login_view
from django.contrib.auth.views import password_reset_confirm as password_reset_confirm_view
from django.db.models import Count, Q, F
from django.db.models import Prefetch
from django.db import connection
from django.views.decorators.csrf import csrf_exempt
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.http import HttpResponseRedirect
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _, string_concat
from django.conf import settings
from dateutil.relativedelta import relativedelta
from django.forms.util import ErrorList
from django.forms.models import model_to_dict
from django.http import JsonResponse
from api import models, raw
from contest import models as contest_models
from web import forms, donations, transfer_code, raw as web_raw
from web.links import links as links_list
from web.templatetags.imageurl import ownedcardimageurl, eventimageurl, _imageurl
from utils import *
from collections import OrderedDict
import urllib, hashlib
import datetime, time, pytz
import random
import re
import json
import collections
import operator
def contextAccounts(request):
accounts = request.user.accounts_set.all().order_by('-rank')
return accounts
def globalContext(request):
context ={
'hide_back_button': False,
'show_filter_button': False,
'current_url': request.get_full_path() + ('?' if request.get_full_path()[-1] == '/' else '&'),
'interfaceColor': 'default',
'btnColor': 'Smile',
'debug': settings.DEBUG,
'hidenavbar': 'hidenavbar' in request.GET,
'current_contests': settings.CURRENT_CONTESTS,
'last_update': settings.GENERATED_DATE,
'high_traffic': settings.HIGH_TRAFFIC,
}
if request.user.is_authenticated() and not request.user.is_anonymous():
context['accounts'] = contextAccounts(request)
if request.user.preferences.color:
context['interfaceColor'] = request.user.preferences.color
context['btnColor'] = request.user.preferences.color
if 'notification' in request.GET:
try:
context['notification'] = web_raw.notifications[request.GET['notification']].copy()
context['notification']['link'] = context['notification']['link'].format(*(request.GET['notification_link_variables'].split(',')))
except KeyError: pass
return context
def findAccount(id, accounts, forceGetAccount=False):
try:
id = int(id)
except:
return None
for account in accounts:
if account.id == id:
return account
if forceGetAccount:
try: return models.Account.objects.get(id=id)
except: return None
return None
def findOwnedCard(id, ownedCards, forceGetOwnedCard=False):
try:
id = int(id)
except:
return None
for ownedCard in ownedCards:
if ownedCard.id == id:
return ownedCard
if forceGetOwnedCard:
try: return models.OwnedCard.objects.get(id=id)
except: return None
return None
def hasJP(accounts):
for account in accounts:
if account.language == 'JP':
return True
return False
def onlyJP(context):
if 'accounts' not in context:
return False
accounts = context['accounts']
if not accounts:
return False
for account in accounts:
if account.language != 'JP':
return False
return True
def getUserAvatar(user, size):
return user.preferences.avatar(size)
def _pushActivity_cacheaccount(account, account_owner=None):
if not account_owner:
account_owner = account.owner
return {
'account_link': '/user/' + account_owner.username + '/#' + str(account.id),
'account_picture': account_owner.preferences.avatar(size=100),
'account_name': unicode(account),
}
def pushActivity(message, number=None, ownedcard=None, eventparticipation=None, message_data=None, right_picture=None,
# Prefetch:
account=None, account_owner=None, card=None, event=None):
"""
Will handle cache and duplicate depending on activity type (message).
To avoid useless SQL queries, make sure your prefetch or specify the following:
All:
- account owner & preferences (or specify account owner with preferences)
For ownedcard activities (added/idolized):
- card (or specify card)
- account (or specify account)
Eventparticipation (for ranked in event):
- account (or specify account)
- event (or specify event)
Rank up + Verified must specify:
- account
- number
Trivia must specify:
- number (= score)
- message_data (= sentence)
Custom must specify:
- account
- message_data
- (optional) right_picture
"""
if ownedcard is not None:
if ownedcard.card.rarity == 'R' or ownedcard.card.rarity == 'N':
return
if eventparticipation is not None and not eventparticipation.ranking:
return
if message == 'Added a card' or message == 'Idolized a card' or message == 'Update card':
if not account:
account = ownedcard.owner_account
if not card:
card = ownedcard.card
defaults = {
'account': account,
'eventparticipation': None,
'message': message,
'number': None,
'message_data': concat_args(unicode(card), ownedcard.stored),
'right_picture_link': '/cards/' + str(card.id) + '/',
'right_picture': ownedcardimageurl({}, ownedcard),
}
defaults.update(_pushActivity_cacheaccount(account, account_owner))
if message == 'Added a card':
models.Activity.objects.create(ownedcard=ownedcard, **defaults)
else:
if message == 'Update card':
del(defaults['message'])
updated = models.Activity.objects.filter(ownedcard=ownedcard).update(**defaults)
if not updated:
models.Activity.objects.create(ownedcard=ownedcard, message='Added a card', **defaults)
elif message == 'Rank Up' or message == 'Verified':
defaults = {
'account': account,
'message': message,
'message_data': concat_args(number) if message == 'Rank Up' else models.VERIFIED_DICT[number],
'number': number,
}
defaults.update(_pushActivity_cacheaccount(account, account_owner))
models.Activity.objects.update_or_create(account=account, message=message, number=number, defaults=defaults)
elif message == 'Ranked in event':
if not account:
account = eventparticipation.account
if not event:
event = eventparticipation.event
defaults = {
'account': account,
'ownedcard': None,
'eventparticipation': eventparticipation,
'message': message,
'number': None,
'message_data': concat_args(eventparticipation.ranking, unicode(event)),
'right_picture': eventimageurl({}, event, english=(account.language != 'JP')),
'right_picture_link': '/events/' + event.japanese_name + '/',
}
defaults.update(_pushActivity_cacheaccount(account, account_owner))
models.Activity.objects.update_or_create(eventparticipation=eventparticipation, defaults=defaults)
elif message == 'Trivia':
defaults = {
'account': account,
'message': message,
'number': number,
'message_data': concat_args(number, message_data),
}
defaults.update(_pushActivity_cacheaccount(account, account_owner))
activity = models.Activity.objects.create(**defaults)
return activity
elif message == 'Custom':
defaults = {
'account': account,
'message': message,
'message_data': message_data,
'right_picture': right_picture,
}
defaults.update(_pushActivity_cacheaccount(account, account_owner))
models.Activity.objects.create(**defaults)
def index(request):
"""
SQL Queries:
- Context
- JP event
- EN event
- Random card
"""
context = globalContext(request)
# Get current events
try:
context['current_jp'] = models.Event.objects.order_by('-beginning')[0]
context['current_jp'].is_current = context['current_jp'].is_japan_current()
context['current_jp'].slide_position = len(contest['current_contests']) + 1
except: pass
try:
context['current_en'] = models.Event.objects.filter(english_beginning__isnull=False).order_by('-english_beginning')[0]
context['current_en'].is_current = context['current_en'].is_world_current()
context['current_en'].slide_position = len(contest['current_contests'])
except: pass
context['trivia_slide_position'] = len(context['current_contests']) + 2
context['total_donators'] = settings.TOTAL_DONATORS
context['total_backgrounds'] = settings.TOTAL_BACKGROUNDS
# Get random character
context['character'] = None
if not context['character'] and request.user.is_authenticated() and context['accounts'] and bool(random.getrandbits(1)):
random_account = random.choice(context['accounts'])
if random_account.center_id:
context['character'] = random_account.center_card_transparent_image
if not context['character']:
card = models.Card.objects.filter(transparent_idolized_image__isnull=False).exclude(transparent_idolized_image='').order_by('?')
if request.user.is_authenticated() and request.user.preferences.best_girl:
card = card.filter(name=request.user.preferences.best_girl)
else:
card = card.filter(idol__main=True)
if card:
card = card[0]
context['character'] = card.transparent_idolized_image
if card.transparent_image and bool(random.getrandbits(1)):
context['character'] = card.transparent_image
return render(request, 'index.html', context)
def links(request):
context = globalContext(request)
context['links'] = links_list
query = 'SELECT f.id, f.transparent_idolized_image, f.name FROM (SELECT card.id, card.transparent_idolized_image, idol.name FROM api_card AS card JOIN api_idol AS idol WHERE card.idol_id = idol.id AND idol.main = 1 AND card.transparent_idolized_image IS NOT NULL AND card.transparent_idolized_image != \'\' ORDER BY ' + (settings.RANDOM_ORDERING_DATABASE) + '()) AS f GROUP BY f.name'
cards_objects = models.Card.objects.raw(query)
cards = {}
for card in cards_objects:
cards[card.name] = card
context['cards'] = cards
return render(request, 'links.html', context)
def password_reset_confirm(request, uidb64, token):
try:
uid = urlsafe_base64_decode(uidb64)
user = User.objects.get(pk=uid)
except(TypeError, ValueError, OverflowError, User.DoesNotExist):
user = None
accounts_with_transfer_code = 0
if user is not None:
accounts_with_transfer_code = user.accounts_set.exclude(transfer_code__isnull=True).exclude(transfer_code__exact='').count()
response = password_reset_confirm_view(request, uidb64=uidb64, token=token, extra_context={'accounts_with_transfer_code': accounts_with_transfer_code})
if isinstance(response, HttpResponseRedirect) and user is not None:
accounts_with_transfer_code = user.accounts_set.all().update(transfer_code='')
return response
def create(request):
if request.user.is_authenticated() and not request.user.is_anonymous():
raise PermissionDenied()
if request.method == "POST":
form = forms.CreateUserForm(request.POST)
if form.is_valid():
new_user = User.objects.create_user(**form.cleaned_data)
user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
preferences = models.UserPreferences.objects.create(user=user)
login(request, user)
return redirect('/addaccount/' + ('?next=' + request.GET['next'] if 'next' in request.GET else ''))
else:
form = forms.CreateUserForm()
context = globalContext(request)
context['form'] = form
context['current'] = 'create'
context['next'] = request.GET.get('next', None)
return render(request, 'create.html', context)
def login_custom_view(request):
response = login_view(request, template_name='login.html', extra_context={'interfaceColor': 'default', 'next': request.GET['next'] if 'next' in request.GET else None})
if (isinstance(response, HttpResponseRedirect) and 'password' in request.POST
and request.user.is_authenticated() and not request.user.is_anonymous()):
accounts = request.user.accounts_set.all()
for account in accounts:
if account.transfer_code and not transfer_code.is_encrypted(account.transfer_code):
account.transfer_code = transfer_code.encrypt(account.transfer_code, request.POST['password'])
account.save()
return response
def setaccountonlogin(request):
context = globalContext(request)
try:
account = next(iter(context['accounts']))
except StopIteration:
return redirect('addaccount')
return redirect('cards')
def get_cards_queryset(request, context, card=None):
# Set defaults
request_get = {
'ordering': 'id',
'reverse_order': True,
}
if card is None:
# Apply filters
cards = models.Card.objects.filter()
if 'search' in request.GET:
request_get['search'] = request.GET['search']
if request.GET['search']:
cards = cards.filter(Q(name__icontains=request.GET['search'])
| Q(idol__japanese_name__icontains=request.GET['search'])
| Q(skill__icontains=request.GET['search'])
| Q(japanese_skill__icontains=request.GET['search'])
| Q(skill_details__icontains=request.GET['search'])
| Q(japanese_skill_details__icontains=request.GET['search'])
| Q(center_skill__icontains=request.GET['search'])
| Q(japanese_collection__icontains=request.GET['search'])
| Q(translated_collection__icontains=request.GET['search'])
| Q(promo_item__icontains=request.GET['search'])
| Q(event__english_name__icontains=request.GET['search'])
| Q(event__japanese_name__icontains=request.GET['search'])
)
if 'name' in request.GET and request.GET['name']:
cards = cards.filter(name__exact=request.GET['name'])
request_get['name'] = request.GET['name']
if 'collection' in request.GET and request.GET['collection']:
cards = cards.filter(japanese_collection__exact=request.GET['collection'])
request_get['collection'] = request.GET['collection']
if 'translated_collection' in request.GET and request.GET['translated_collection']:
cards = cards.filter(translated_collection__exact=request.GET['translated_collection'])
request_get['translated_collection'] = request.GET['translated_collection']
if 'sub_unit' in request.GET and request.GET['sub_unit']:
cards = cards.filter(idol__sub_unit__exact=request.GET['sub_unit'])
request_get['sub_unit'] = request.GET['sub_unit']
if 'idol_year' in request.GET and request.GET['idol_year']:
cards = cards.filter(idol__year__exact=request.GET['idol_year'])
request_get['idol_year'] = request.GET['idol_year']
if 'idol_school' in request.GET and request.GET['idol_school']:
cards = cards.filter(idol__school__exact=request.GET['idol_school'])
request_get['idol_school'] = request.GET['idol_school']
if 'rarity' in request.GET and request.GET['rarity']:
cards = cards.filter(rarity__exact=request.GET['rarity'])
request_get['rarity'] = request.GET['rarity']
if 'attribute' in request.GET and request.GET['attribute']:
cards = cards.filter(attribute__exact=request.GET['attribute'])
request_get['attribute'] = request.GET['attribute']
if 'skill' in request.GET and request.GET['skill']:
cards = cards.filter(skill__exact=request.GET['skill'])
request_get['skill'] = request.GET['skill']
if 'ids' in request.GET and request.GET['ids']:
cards= cards.filter(pk__in=request.GET['ids'].split(','))
if 'is_event' in request.GET and request.GET['is_event'] == 'on':
cards = cards.filter(event__isnull=False)
request_get['is_event'] = 'on'
elif 'is_event' in request.GET and request.GET['is_event'] == 'off':
cards = cards.filter(event__isnull=True)
request_get['is_event'] = 'off'
if 'is_special' in request.GET and request.GET['is_special'] == 'on':
cards = cards.filter(is_special__exact=True)
request_get['is_special'] = 'on'
elif 'is_special' in request.GET and request.GET['is_special'] == 'off':
cards = cards.filter(is_special__exact=False)
request_get['is_special'] = 'off'
if 'release_after' in request.GET and request.GET['release_after']:
cards = cards.filter(release_date__gte=datetime.datetime.strptime(request.GET['release_after'] + '-01', "%Y-%m-%d"))
request_get['release_after'] = request.GET['release_after']
if 'release_before' in request.GET and request.GET['release_before']:
cards = cards.filter(release_date__lte=datetime.datetime.strptime(request.GET['release_before'] + '-01', "%Y-%m-%d"))
request_get['release_before'] = request.GET['release_before']
if 'account' in request.GET and request.GET['account'] and request.user.is_authenticated() and not request.user.is_anonymous():
account = findAccount(request.GET['account'], context['accounts'], forceGetAccount=request.user.is_staff)
if account:
request_get['account'] = account.id
if 'max_level' in request.GET and request.GET['max_level'] == '1':
cards = cards.filter(id__in=models.OwnedCard.objects.filter(owner_account=account, max_level=True).values('card'))
request_get['max_level'] = '1'
elif 'max_level' in request.GET and request.GET['max_level'] == '-1':
cards = cards.exclude(id__in=models.OwnedCard.objects.filter(owner_account=account, max_level=True).values('card'))
request_get['max_level'] = '-1'
if 'max_bond' in request.GET and request.GET['max_bond'] == '1':
cards = cards.filter(id__in=models.OwnedCard.objects.filter(owner_account=account, max_bond=True).values('card'))
request_get['max_bond'] = '1'
elif 'max_bond' in request.GET and request.GET['max_bond'] == '-1':
cards = cards.exclude(id__in=models.OwnedCard.objects.filter(owner_account=account, max_bond=True).values('card'))
request_get['max_bond'] = '-1'
if 'idolized' in request.GET and request.GET['idolized'] == '1':
cards = cards.filter(id__in=models.OwnedCard.objects.filter(owner_account=account, idolized=True).values('card'))
request_get['idolized'] = '1'
elif 'idolized' in request.GET and request.GET['idolized'] == '-1':
cards = cards.exclude(id__in=models.OwnedCard.objects.filter(owner_account=account, idolized=True).values('card'))
request_get['idolized'] = '-1'
if 'stored' in request.GET and request.GET['stored']:
if request.GET['stored'] == 'Album':
cards = cards.filter(ownedcards__owner_account=account).filter(Q(ownedcards__stored='Deck') | Q(ownedcards__stored='Album'))
else:
cards = cards.filter(ownedcards__owner_account=account, ownedcards__stored=request.GET['stored'])
cards = cards.distinct()
request_get['stored'] = request.GET['stored']
if ('accounts' in context and not hasJP(context['accounts'])
and 'search' not in request.GET or 'is_world' in request.GET and request.GET['is_world']):
if 'is_world' in request.GET and request.GET['is_world'] == 'off':
cards = cards.filter(japan_only=True)
else:
cards = cards.filter(japan_only=False)
context['show_discover_banner'] = True
request_get['is_world'] = True
if ('accounts' in context and not hasJP(context['accounts'])
and 'search' not in request.GET or 'is_promo' in request.GET and request.GET['is_promo']):
if 'is_promo' not in request.GET or request.GET['is_promo'] == 'off':
cards = cards.filter(is_promo=False)
request_get['is_promo'] = 'off'
else:
cards = cards.filter(is_promo=True)
request_get['is_promo'] = 'on'
if 'ordering' in request.GET and request.GET['ordering']:
request_get['ordering'] = request.GET['ordering']
request_get['reverse_order'] = 'reverse_order' in request.GET and request.GET['reverse_order']
prefix = '-' if request_get['reverse_order'] else ''
cards = cards.order_by(prefix + request_get['ordering'], prefix +'id')
else:
context['total_results'] = 1
cards = models.Card.objects.filter(pk=int(card))
context['single'] = cards[0]
context['request_get'] = request_get
return context, cards
def get_cards_form_filters(request, cardsinfo):
# Get filters info for the form
return {
'idols': forms.getGirls(with_total=True, with_japanese_name=request.LANGUAGE_CODE == 'ja'),
'collections': cardsinfo['collections'],
'translated_collections': cardsinfo['translated_collections'],
'sub_units': cardsinfo['sub_units'] if 'sub_units' in cardsinfo else [],
'skills': cardsinfo['skills'],
'rarity_choices': models.RARITY_CHOICES,
'attribute_choices': models.ATTRIBUTE_CHOICES,
'idol_year_choices': cardsinfo['years'] if 'years' in cardsinfo else [],
'idol_school_choices': cardsinfo['schools'] if 'schools' in cardsinfo else [],
'stored_choices': models.STORED_CHOICES,
'ordering_choices': (
('id', _('Card #ID')),
('release_date', _('Release date')),
('name', _('Idol')),
('idolized_maximum_statistics_smile', _('Smile\'s statistics')),
('idolized_maximum_statistics_pure', _('Pure\'s statistics')),
('idolized_maximum_statistics_cool', _('Cool\'s statistics')),
('total_owners', string_concat(_('Most popular'), ' (', _('Deck'), ')')),
('total_wishlist', string_concat(_('Most popular'), ' (', _('Wish List'), ')')),
('hp', _('HP'))
)
}
def cards(request, card=None, ajax=False):
"""
SQL Queries:
- Context
- Total cards
- Cards (JOIN + idol + event + ur pair)
- Owned Cards
"""
if len(request.GET.getlist('page')) > 1:
raise PermissionDenied()
if 'view' in request.GET and request.GET['view'] == 'albumbuilder':
return redirect('/cards/albumbuilder/' + get_parameters_to_string(request))
page = 0
context = globalContext(request)
context['total_results'] = 0
if len(request.GET) == 1 and 'name' in request.GET:
return redirect('/idol/' + request.GET['name'] + '/')
cardsinfo = settings.CARDS_INFO
max_stats = cardsinfo['max_stats']
context, cards = get_cards_queryset(request=request, context=context, card=card)
if card is None:
context['total_results'] = cards.count()
# Set limit
page_size = 18
if 'page' in request.GET and request.GET['page']:
page = int(request.GET['page']) - 1
if page < 0:
page = 0
cards = cards[(page * page_size):((page * page_size) + page_size)]
context['total_pages'] = int(math.ceil(context['total_results'] / page_size))
if request.user.is_authenticated() and not request.user.is_anonymous():
cards = cards.prefetch_related(Prefetch('ownedcards', queryset=models.OwnedCard.objects.filter(owner_account__owner=request.user).order_by('owner_account__language'), to_attr='owned_cards'))
# Get statistics & other information to show in cards
for card in cards:
if card.video_story:
card.embed_video = card.video_story.replace('/watch?v=', '/embed/')
if card.japanese_video_story:
card.embed_japanese_video = card.japanese_video_story.replace('/watch?v=', '/embed/')
card.percent_stats = {
'minimum': {
'Smile': ((card.minimum_statistics_smile if card.minimum_statistics_smile else 0) / max_stats['Smile']) * 100,
'Pure': ((card.minimum_statistics_pure if card.minimum_statistics_pure else 0) / max_stats['Pure']) * 100,
'Cool': ((card.minimum_statistics_cool if card.minimum_statistics_cool else 0) / max_stats['Cool']) * 100,
}, 'non_idolized_maximum': {
'Smile': ((card.non_idolized_maximum_statistics_smile if card.non_idolized_maximum_statistics_smile else 0) / max_stats['Smile']) * 100,
'Pure': ((card.non_idolized_maximum_statistics_pure if card.non_idolized_maximum_statistics_pure else 0) / max_stats['Pure']) * 100,
'Cool': ((card.non_idolized_maximum_statistics_cool if card.non_idolized_maximum_statistics_cool else 0) / max_stats['Cool']) * 100,
}, 'idolized_maximum': {
'Smile': ((card.idolized_maximum_statistics_smile if card.idolized_maximum_statistics_smile else 0) / max_stats['Smile']) * 100,
'Pure': ((card.idolized_maximum_statistics_pure if card.idolized_maximum_statistics_pure else 0) / max_stats['Pure']) * 100,
'Cool': ((card.idolized_maximum_statistics_cool if card.idolized_maximum_statistics_cool else 0) / max_stats['Cool']) * 100,
}
}
sentence, data = card.get_center_skill_details()
if sentence and data:
card.center_skill_details = _(sentence).format(*[_(d) for d in data])
if card.center_skill:
try:
card.center_skill = string_concat(_(card.center_skill.split(' ')[0]), ' ', _(card.center_skill.split(' ')[1]))
except: pass
if not ajax:
context['filters'] = get_cards_form_filters(request, cardsinfo)
context['total_cards'] = len(cards)
if context['total_cards'] > 0:
context['idol'] = cards[0].idol
context['cards'] = enumerate(cards)
context['max_stats'] = max_stats
context['show_filter_button'] = False if 'single' in context and context['single'] else True
context['show_filter_bar'] = context['show_filter_button']
context['show_total_results'] = 'search' in context['request_get']
if 'search' not in context['request_get'] and 'name' in context['request_get']:
context['show_filter_bar'] = False
context['current'] = 'cards'
if request.user.is_authenticated() and not request.user.is_anonymous():
context['quickaddcard_form'] = forms.getOwnedCardForm(forms.QuickOwnedCardForm(), context['accounts'])
context['page'] = page + 1
context['ajax'] = ajax
if ajax:
return render(request, 'cardsPage.html', context)
return render(request, 'cards.html', context)
idol_tabs = ['idol', 'pictures']
def idol(request, idol):
context = globalContext(request)
context['tab'] = 'idol'
if 'tab' in request.GET and request.GET['tab'] in idol_tabs:
context['tab'] = request.GET['tab']
context['idol'] = get_object_or_404(models.Idol, name=idol)
if context['tab'] == 'pictures':
context['idol'].tag = idol.lower().replace(' ', '_')
return render(request, 'idol.html', context)
def _addaccount_savecenter(account):
if account.starter:
center = models.OwnedCard.objects.create(card=account.starter, owner_account=account, stored='Deck')
account.center = center
account.center_card_transparent_image = account.center.card.transparent_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.transparent_image
account.center_card_round_image = account.center.card.round_card_idolized_image if account.center.idolized or account.center.card.is_special else account.center.card.round_card_image
account.center_card_attribute = account.center.card.attribute
account.center_alt_text = unicode(account.center.card)
account.center_card_id = account.center.card.id
account.save()
def addaccount(request):
if not request.user.is_authenticated() or request.user.is_anonymous():
raise PermissionDenied()
if request.method == "POST":
form = forms.AccountForm(request.POST)
if form.is_valid():
account = form.save(commit=False)
account.owner = request.user
if account.rank >= 200:
account.rank = 195
account.save()
_addaccount_savecenter(account)
return redirect((request.GET['next'] if 'next' in request.GET else '/cards/') + '?notification=ADDACCOUNTRANK200¬ification_link_variables=' + str(account.pk))
account.save()
_addaccount_savecenter(account)
return redirect(request.GET['next'] if 'next' in request.GET else '/cards/#tutorialaddcardModal')
else:
form = forms.AccountForm(initial={
'nickname': request.user.username
})
context = globalContext(request)
context['form'] = form
context['current'] = 'addaccount'
return render(request, 'addaccount.html', context)
def addteam(request, account):
"""
SQL Queries
- Context
- Owned cards (JOIN + card)
"""
context = globalContext(request)
account = findAccount(account, context['accounts'])
if not account:
raise Http404
account.deck = account.ownedcards.filter(stored='Deck').select_related('card').order_by('-card__rarity', '-idolized', '-card__attribute', '-card__id')
if request.method == 'POST':
form = forms.TeamForm(request.POST, account=account)
if form.is_valid():
team = models.Team.objects.create(name=form.cleaned_data['name'], owner_account=account)
for i in range(9):
if form.cleaned_data['card' + str(i)] is not None:
models.Member.objects.create(team=team, ownedcard=findOwnedCard(form.cleaned_data['card' + str(i)], account.deck), position=i)
return redirect('/user/' + request.user.username + '/?show' + str(account.id) + '=teams#team' + str(team.id))
else:
form = forms.TeamForm(account=account)
context['account'] = account
context['form'] = form
return render(request, 'addteam.html', context)
def editteam(request, team):
"""
SQL Queries
- Context
- Owned cards (JOIN + card)
"""
context = globalContext(request)
team = get_object_or_404(models.Team.objects.filter(owner_account__owner=request.user).select_related('owner_account').prefetch_related(Prefetch('members', queryset=models.Member.objects.select_related('ownedcard', 'ownedcard__card').order_by('position'), to_attr='all_members')), pk=team)
account = team.owner_account
account.deck = account.ownedcards.filter(stored='Deck').select_related('card').order_by('-card__rarity', '-idolized', '-card__attribute', '-card__id')
context['form_delete'] = forms.ConfirmDelete(initial={'thing_to_delete': team.id})
if request.method == 'POST':
if 'thing_to_delete' in request.POST:
form = forms.TeamForm(instance=team, account=account)
context['form_delete'] = forms.ConfirmDelete(request.POST)
if context['form_delete'].is_valid():
team.delete()
return redirect('/user/' + request.user.username + '/?show' + str(account.id) + '=teams')
else:
old_name = team.name
form = forms.TeamForm(request.POST, instance=team, account=account)
if form.is_valid():
if form.cleaned_data['name'] != old_name:
team.name = form.cleaned_data['name']
team.save()
for i in range(9):
if form.cleaned_data['card' + str(i)] is not None:
models.Member.objects.update_or_create(team=team, position=i, defaults={
'ownedcard': findOwnedCard(form.cleaned_data['card' + str(i)], account.deck),
})
return redirect('/user/' + request.user.username + '/?show' + str(account.id) + '=teams#team' + str(team.id))
else:
form = forms.TeamForm(instance=team, account=account)
context['account'] = account
context['form'] = form
context['team'] = team
return render(request, 'addteam.html', context)
def profile(request, username):
"""
SQL Queries
- Django session
- Request user
- (if me) Preferences
- (if not me) User (JOIN + preferences)
- Accounts
- Deck stats (number of UR/SR in each account, raw SQL query)
- Account queries (see ajaxaccounttab)
- User links
- (if not me) Is following?
- Count followers
- Count following
"""
context = globalContext(request)
if request.user.is_authenticated() and not request.user.is_anonymous() and request.user.username == username:
user = request.user
else:
user = get_object_or_404(User.objects.select_related('preferences'), username=username)
context['profile_user'] = user
context['preferences'] = user.preferences
if request.user.is_staff and (request.user.is_superuser or request.user.preferences.has_verification_permissions):
if request.user.is_superuser:
context['form_preferences'] = forms.UserProfileStaffForm(instance=context['preferences'])
if 'staff' in request.GET:
context['show_staff'] = True
if request.method == 'POST':
if 'editPreferences' in request.POST and request.user.is_superuser:
form_preferences = forms.UserProfileStaffForm(request.POST, instance=context['preferences'])
if form_preferences.is_valid():
prefs = form_preferences.save()
return redirect('/user/' + context['profile_user'].username + '?staff')
if 'addcard' in request.POST:
form_addcard = forms.StaffAddCardForm(request.POST)
if form_addcard.is_valid():
form_addcard.save()
return redirect('/user/' + context['profile_user'].username + '?staff#' + str(form_addcard.cleaned_data['owner_account']))
if user == request.user:
# force execute queryset
[_ for account in context['accounts']]
context['is_me'] = True
context['user_accounts'] = context['accounts']
else:
context['is_me'] = False
context['user_accounts'] = user.accounts_set.all().order_by('-rank')
if request.user.is_staff and 'staff' in request.GET:
deck_queryset = models.OwnedCard.objects.filter(Q(stored='Deck') | Q(stored='Album'))
else:
deck_queryset = models.OwnedCard.objects.filter(stored='Deck')
context['user_accounts'] = context['user_accounts']
if not context['preferences'].private or context['is_me']:
# Get stats of cards
accounts_ids = ','.join([str(account.id) for account in context['user_accounts']])
if accounts_ids:
cursor = connection.cursor()
query = 'SELECT c.rarity, o.owner_account_id, COUNT(c.rarity) FROM api_ownedcard AS o JOIN api_card AS c WHERE o.card_id=c.id AND o.owner_account_id IN (' + accounts_ids + ') AND o.stored=\'Deck\' GROUP BY c.rarity, o.owner_account_id'
cursor.execute(query)
deck_stats = cursor.fetchall()
for account in context['user_accounts']:
# Set stats
try: account.deck_total_sr = (s[2] for s in deck_stats if s[0] == 'SR' and s[1] == account.id).next()
except StopIteration: account.deck_total_sr = 0
try: account.deck_total_ur = (s[2] for s in deck_stats if s[0] == 'UR' and s[1] == account.id).next()
except StopIteration: account.deck_total_ur = 0
account.deck_total = sum([s[2] for s in deck_stats if s[1] == account.id])
# Get opened tab
if 'show' + str(account.id) in request.GET and request.GET['show' + str(account.id)] in models.ACCOUNT_TAB_DICT:
account.opened_tab = request.GET['show' + str(account.id)]
elif request.user.is_staff and 'staff' in request.GET:
account.opened_tab = 'deck'
else:
account.opened_tab = account.default_tab
# Get data of account depending on opened tab
account.owner = user
_context = _ajaxaccounttab_functions[account.opened_tab](account.opened_tab, request, account, more=False)
if account.opened_tab == 'deck':
account.total_cards = account.deck_total
if 'account' in _context:
account = _context['account']
if context['is_me']:
# Form to post custom activity
if request.method == 'POST' and 'account_id' in request.POST and request.POST['account_id'] == str(account.id):
account.form_custom_activity = forms.CustomActivity(request.POST)
if account.form_custom_activity.is_valid():
imgur = None
if account.form_custom_activity.cleaned_data['right_picture']:
imgur = get_imgur_code(account.form_custom_activity.cleaned_data['right_picture'])
pushActivity('Custom', account=account,
message_data=account.form_custom_activity.cleaned_data['message_data'],
right_picture=imgur,
# prefetch:
account_owner=request.user)
context['posted_activity'] = True
account.form_custom_activity = forms.CustomActivity(initial={'account_id': account.id})
else:
account.form_custom_activity = forms.CustomActivity(initial={'account_id': account.id})
# Staff form to edit account
if request.user.is_staff and (request.user.is_superuser or request.user.preferences.has_verification_permissions):
staffFormClass = forms.AccountAdminForm if request.user.is_superuser else forms.AccountStaffForm
account.staff_form_addcard = forms.StaffAddCardForm(initial={'owner_account': account.id})
account.staff_form = staffFormClass(instance=account)
account.staff_form.fields['center'].queryset = models.OwnedCard.objects.filter(owner_account=account, stored='Deck').order_by('card__id').select_related('card')
if request.method == 'POST' and ('editAccount' + str(account.id)) in request.POST:
account.staff_form = staffFormClass(request.POST, instance=account)
if account.staff_form.is_valid():
account = account.staff_form.save(commit=False)
if request.user.is_superuser and 'owner_id' in account.staff_form.cleaned_data and account.staff_form.cleaned_data['owner_id']:
account_new_user = models.User.objects.get(pk=account.staff_form.cleaned_data['owner_id'])
account.owner = account_new_user
account.save()
return redirect('/user/' + context['profile_user'].username + '?staff#' + str(account.id))
# Set links
context['links'] = list(context['profile_user'].links.all().values())
preferences = context['preferences']
if preferences.birthdate:
context['links'].insert(0, {
'type': 'Birthdate',
'value': string_concat(unicode(preferences.birthdate), ' (', str(preferences.age), ' ', _('years old'), ')'),
'flaticon': 'event',
'translate_type': True,
})
if preferences.location:
context['links'].insert(0, {
'type': 'Location',
'value': preferences.location,
'translate_type': True,
'flaticon': 'world',
})
if preferences.best_girl:
context['links'].insert(0, {
'type': 'Best Girl',
'value': preferences.best_girl,
'translate_type': True,
'div': '<div class="chibibestgirl" style="background-image: url(' + chibiimage(preferences.best_girl) + ')"></div>',
})
context['per_line'] = 6
if (len(context['links']) % context['per_line']) < 4:
context['per_line'] = 4
context['accounts_tabs'] = models.ACCOUNT_TAB_ICONS
context['current'] = 'profile'
if not context['is_me']:
context['following'] = isFollowing(user, request)
context['total_following'] = context['preferences'].following.count()
context['total_followers'] = user.followers.count()
context['imgurClientID'] = settings.IMGUR_CLIENT_ID
context['cards_limit'] = settings.CARDS_LIMIT
if context['is_me']:
context['deck_links'] = web_raw.deck_links
return render(request, 'profile.html', context)
def _ajaxaccounttab_ownedcards(tab, request, account, more):
"""
SQL Queries
- Django session
- Request user
- Account (JOIN + owner + owner preferences)
- Owned cards (JOIN + card)
"""
context = {}
context['is_me'] = False
if 'staff' in request.GET:
context['show_staff'] = True
if account.owner == request.user:
context['is_me'] = True
if tab == 'deck' and context['is_me']:
context['deck_links'] = web_raw.deck_links
if account.owner.username != request.user.username and (account.owner.preferences.private or tab == 'presentbox'):
raise PermissionDenied()
ownedcards = account.ownedcards.filter(owner_account=account).select_related('card')
account.total_cards = None
if tab == 'album':
account.album = ownedcards.filter(Q(stored='Album') | Q(stored='Deck')).order_by('card__id')
if more:
account.album = account.album.filter(card__id__gt=settings.CARDS_LIMIT)
else:
account.album = account.album.filter(card__id__lte=settings.CARDS_LIMIT)
album = range(1, settings.CARDS_INFO['total_cards'] + 1) if account.language == 'JP' else settings.CARDS_INFO['en_cards'][:]
account.total_cards = len(album) - settings.CARDS_LIMIT
for owned_card in account.album:
try: album[owned_card.card.id - 1] = owned_card
except IndexError: pass
if more:
account.album = album[settings.CARDS_LIMIT:]
else:
account.album = album[:settings.CARDS_LIMIT]
elif tab == 'deck':
account.deck = ownedcards.filter(stored='Deck').order_by('-card__rarity', '-idolized', '-card__attribute', '-card__id')
if more:
account.deck = account.deck[settings.CARDS_LIMIT:]
else:
account.deck = account.deck[:settings.CARDS_LIMIT]
elif tab == 'wishlist':
account.wishlist = ownedcards.filter(stored='Favorite').order_by('-card__rarity', '-idolized', 'card__id')
account.total_cards = account.wishlist.count()
if more:
account.wishlist = account.wishlist[settings.CARDS_LIMIT:]
else:
account.wishlist = account.wishlist[:settings.CARDS_LIMIT]
elif tab == 'presentbox':
account.presentbox = ownedcards.filter(stored='Box').order_by('card__id')
account.total_cards = account.presentbox.count()
if more:
account.presentbox = account.presentbox[settings.CARDS_LIMIT:]
else:
account.presentbox = account.presentbox[:settings.CARDS_LIMIT]
context['account'] = account
context['cards_limit'] = settings.CARDS_LIMIT
context['more'] = more
return context
def _ajaxaccounttab_eventparticipations(tab, request, account, more):
"""
SQL Queries
- Django session
- Request user
- Account (JOIN + owner + owner preferences)
- Event participations (JOIN + event)
"""
context = {}
account.eventparticipations = models.EventParticipation.objects.filter(account=account).order_by('-event__end').select_related('event')
context['account'] = account
return context
def _ajaxaccounttab_teams(tab, request, account, more):
context = {}
if account.owner == request.user:
context['is_me'] = True
teams = models.Team.objects.filter(owner_account=account).prefetch_related(Prefetch('members', queryset=models.Member.objects.select_related('ownedcard', 'ownedcard__card').order_by('position'), to_attr='all_members'))
range_aligners = [0,1,2,3,4,3,2,1,0]
for team in teams:
team.owner_account = account
members = [{'position': i, 'virtual': True, 'range_align': range(range_aligners[i])} for i in range(9)]
for member in team.all_members:
member.range_align = members[member.position]['range_align']
members[member.position] = member
team.all_members = members
account.all_teams = teams
context['account'] = account
return context
_ajaxaccounttab_functions = {
'deck': _ajaxaccounttab_ownedcards,
'album': _ajaxaccounttab_ownedcards,
'teams': _ajaxaccounttab_teams,
'events': _ajaxaccounttab_eventparticipations,
'wishlist': _ajaxaccounttab_ownedcards,
'presentbox': _ajaxaccounttab_ownedcards,
}
def ajaxaccounttab(request, account, tab, more=False):
account = get_object_or_404(models.Account.objects.select_related('owner', 'owner__preferences'), pk=account)
try:
context = _ajaxaccounttab_functions[tab](tab, request, account, more)
except KeyError:
raise Http404
return render(request, 'include/account_tab_' + tab + '.html', context)
def ajaxaddcard(request):
"""
SQL Queries
- Django session
- Request user
- Account
- Card
- Insert owned card
- Preferences
- (if SR/UR) Insert activity
"""
if request.method != 'POST' or not request.user.is_authenticated() or request.user.is_anonymous():
raise PermissionDenied()
account = get_object_or_404(models.Account.objects.select_related('center', 'center__card'), pk=request.POST['owner_account'], owner=request.user)
card = get_object_or_404(models.Card, pk=request.POST['card'])
ownedcard = models.OwnedCard(card=card,
owner_account=account,
stored='Deck',
skill=1,
idolized=card.is_promo)
ownedcard.save()
if not settings.HIGH_TRAFFIC:
pushActivity(message="Added a card",
ownedcard=ownedcard,
# prefetch:
card=card,
account=account,
account_owner=request.user)
context = {
'owned': ownedcard,
'owner_account': account,
'withcenter': True,
}
return render(request, 'ownedCardOnBottomCard.html', context)