-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathviews.py
1655 lines (1457 loc) · 78.3 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
#
# Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA
#
# Freesound is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# Freesound is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# Authors:
# See AUTHORS file.
#
import io
import csv
import datetime
import errno
import json
import logging
import os
import tempfile
import time
import uuid
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import user_passes_test
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth.views import LoginView, PasswordResetCompleteView, PasswordResetConfirmView, \
PasswordChangeView, PasswordChangeDoneView
from django.contrib.postgres.search import SearchQuery, SearchVector
from django.core.cache import cache
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.core.files.uploadedfile import TemporaryUploadedFile
from django.db import transaction
from django.db.models import Count, Sum, Q
from django.db.models.expressions import Value
from django.db.models.fields import CharField
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseBadRequest, Http404, \
HttpResponsePermanentRedirect, HttpResponseServerError, JsonResponse
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils.http import base36_to_int
from django.utils.http import int_to_base36
from django.views.decorators.cache import never_cache
from django.views.decorators.csrf import csrf_exempt
from general.templatetags.absurl import url2absurl
from oauth2_provider.models import AccessToken
import tickets.views as TicketViews
import utils.sound_upload
from general.tasks import DELETE_USER_DELETE_SOUNDS_ACTION_NAME, DELETE_USER_KEEP_SOUNDS_ACTION_NAME
from accounts.forms import EmailResetForm, FsPasswordResetForm, FsSetPasswordForm, \
UploadFileForm, FlashUploadFileForm, FileChoiceForm, RegistrationForm, \
ProfileForm, AvatarForm, TermsOfServiceForm, DeleteUserForm, EmailSettingsForm, BulkDescribeForm, \
UsernameField, ProblemsLoggingInForm, username_taken_by_other_user, FsPasswordChangeForm
from general.templatetags.util import license_with_version
from accounts.models import Profile, ResetEmailRequest, UserFlag, DeletedUser, UserDeletionRequest
from bookmarks.models import Bookmark
from comments.models import Comment
from follow import follow_utils
from forum.models import Post
from general import tasks
from messages.models import Message
from sounds.forms import LicenseForm, PackForm
from sounds.models import Sound, Pack, Download, SoundLicenseHistory, BulkUploadProgress, PackDownload
from sounds.views import edit_and_describe_sounds_helper
from tickets.models import TicketComment, Ticket, UserAnnotation
from utils.cache import invalidate_user_template_caches
from utils.dbtime import DBTime
from utils.filesystem import generate_tree, remove_directory_if_empty
from utils.images import extract_square
from utils.logging_filters import get_client_ip
from utils.mail import send_mail_template, send_mail_template_to_support
from utils.mirror_files import copy_avatar_to_mirror_locations, \
copy_uploaded_file_to_mirror_locations, remove_uploaded_file_from_mirror_locations, \
remove_empty_user_directory_from_mirror_locations
from utils.onlineusers import get_online_users
from utils.pagination import paginate
from utils.username import redirect_if_old_username_or_404, raise_404_if_user_is_deleted
sounds_logger = logging.getLogger('sounds')
upload_logger = logging.getLogger('file_upload')
web_logger = logging.getLogger('web')
volatile_logger = logging.getLogger('volatile')
@login_required
@user_passes_test(lambda u: u.is_staff, login_url='/')
def crash_me(request):
raise Exception
def ratelimited_error(request, exception):
if 'similar' in request.path:
path = '/people/<username>/sounds/<sound_id>/similar/'
else:
path = request.path
if not path.endswith('/'):
path += '/'
volatile_logger.info(f"Rate limited IP ({json.dumps({'ip': get_client_ip(request), 'path': path})})")
return render(request, '429.html', status=429)
def login(request, template_name, authentication_form):
# Freesound-specific login view to check if a user has multiple accounts
# with the same email address. We can switch back to the regular django view
# once all accounts are adapted
response = LoginView.as_view(
template_name='accounts/login.html',
authentication_form=authentication_form)(request)
if isinstance(response, HttpResponseRedirect):
# If there is a redirect it's because the login was successful
# Now we check if the logged in user has shared email problems
if request.user.profile.has_shared_email():
# If the logged in user has an email shared with other accounts, we redirect to the email update page
redirect_url = reverse("accounts-multi-email-cleanup")
next_param = request.POST.get('next', None)
if next_param:
redirect_url += f'?next={next_param}'
return HttpResponseRedirect(redirect_url)
else:
return response
return response
def password_reset_confirm(request, uidb64, token):
"""
Password reset = change password without user being logged in (classic "forgot password" feature).
This view is called after user has received an email with instructions for resetting the password and clicks the
reset link.
We set 'next_path' parameter so we configure login modal to redirect to front page after successful login
instead of staying in PasswordResetCompleteView (the current path).
"""
response = PasswordResetConfirmView.as_view(
template_name='accounts/password_reset_confirm.html',
form_class=FsSetPasswordForm,
extra_context={'next_path': reverse('accounts-home')}
)(request, uidb64=uidb64, token=token)
return response
def password_reset_complete(request):
"""
Password reset = change password without user being logged in (classic "forgot password" feature).
This view is called when the password has been reset successfully.
We set 'next_path' parameter so we configure login modal to redirect to front page after successful login
instead of staying in PasswordResetCompleteView (the current path).
"""
response = PasswordResetCompleteView.as_view(
template_name='accounts/password_reset_complete.html',
extra_context={'next_path': reverse('accounts-home')})(request)
return response
def password_change_form(request):
"""
Password change = change password from the account settings page, while user is logged in.
This view is called when user requests to change the password and contains the form to do so.
"""
response = PasswordChangeView.as_view(
form_class=FsPasswordChangeForm,
template_name='accounts/password_change_form.html',
extra_context={'activePage': 'password'})(request)
return response
def password_change_done(request):
"""
Password change = change password from the account settings page, while user is logged in.
This view is called when user has successfully changed the password by filling in the password change form.
"""
response = PasswordChangeDoneView.as_view(
template_name='accounts/password_change_done.html',
extra_context={'activePage': 'password'})(request)
return response
@login_required
@transaction.atomic()
def multi_email_cleanup(request):
# If user does not have shared email problems, then it should have not visited this page
if not request.user.profile.has_shared_email():
return HttpResponseRedirect(reverse('accounts-home'))
# Check if shared email problems have been fixed (if user changed one of the two emails)
same_user = request.user.profile.get_sameuser_object()
email_issues_still_valid = True
if same_user.main_user_changed_email():
# Then assign original email to secondary user (if user didn't change it)
if not same_user.secondary_user_changed_email():
same_user.secondary_user.email = same_user.orig_email
same_user.secondary_user.save()
email_issues_still_valid = False
if same_user.secondary_user_changed_email():
# Then the email problems have been fixeed when email of secondary user was changed
# No need to re-assign emails here
email_issues_still_valid = False
if not email_issues_still_valid:
# If problems have been fixed, remove same_user object to users are not redirected here again
same_user.delete()
# Redirect to where the user was going (in this way this whole process will have been transparent)
return HttpResponseRedirect(request.GET.get('next', reverse('accounts-home')))
else:
# If email issues are still valid, then we show the email cleanup page with the instructions
return render(request, 'accounts/multi_email_cleanup.html', {
'same_user': same_user, 'next': request.GET.get('next', reverse('accounts-home'))})
def check_username(request):
"""AJAX endpoint to check if a specified username is available to be registered.
This checks against the normal username validator, and then also verifies to see
if the username already exists in the database.
Returns JSON {'result': true} if the username is valid and can be used"""
username = request.GET.get('username', None)
username_valid = False
username_field = UsernameField()
if username:
try:
username_field.run_validators(username)
# If the validator passes, check if the username is indeed available
username_valid = not username_taken_by_other_user(username)
except ValidationError:
username_valid = False
return JsonResponse({'result': username_valid})
@login_required
@transaction.atomic()
def bulk_license_change(request):
if request.method == 'POST':
form = LicenseForm(request.POST, hide_old_license_versions=True)
if form.is_valid():
selected_license = form.cleaned_data['license']
Sound.objects.filter(user=request.user).update(license=selected_license, is_index_dirty=True)
for sound in Sound.objects.filter(user=request.user).all():
SoundLicenseHistory.objects.create(sound=sound, license=selected_license)
request.user.profile.has_old_license = False
request.user.profile.save()
return HttpResponseRedirect(reverse('accounts-home'))
else:
form = LicenseForm(hide_old_license_versions=True)
tvars = {'form': form}
return render(request, 'accounts/choose_new_license.html', tvars)
@login_required
def tos_acceptance(request):
has_sounds_with_old_cc_licenses = request.user.profile.has_sounds_with_old_cc_licenses()
if request.method == 'POST':
form = TermsOfServiceForm(request.POST)
if form.is_valid():
profile = request.user.profile
profile.agree_to_gdpr()
if form.cleaned_data['accepted_license_change']:
profile.upgrade_old_cc_licenses_to_new_cc_licenses()
if form.cleaned_data['next']:
return HttpResponseRedirect(form.cleaned_data['next'])
else:
return HttpResponseRedirect(reverse('accounts-home'))
else:
next_param = request.GET.get('next')
form = TermsOfServiceForm(initial={'next': next_param})
tvars = {'form': form, 'has_sounds_with_old_cc_licenses': has_sounds_with_old_cc_licenses}
return render(request, 'accounts/gdpr_consent.html', tvars)
@login_required
def update_old_cc_licenses(request):
request.user.profile.upgrade_old_cc_licenses_to_new_cc_licenses()
next = request.GET.get('next', None)
if next is not None:
return HttpResponseRedirect(next)
else:
return HttpResponseRedirect(reverse('accounts-home'))
@transaction.atomic()
def registration_modal(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
user = form.save()
send_activation(user)
# If the form is valid we will return a JSON response with the URL where
# the user should be redirected (a URL which will include the "Almost done" message). The browser
# will then take this URL and redirect the user.
next_param = request.GET.get('next', None)
if next_param is not None:
return JsonResponse({'redirectURL': next_param + '?feedbackRegistration=1' if '?' not in next_param \
else next_param + '&feedbackRegistration=1'})
else:
return JsonResponse({'redirectURL': reverse('front-page') + '?feedbackRegistration=1'})
else:
# If the form is NOT valid we return the Django rendered HTML version of the
# registration modal (which includes the form and error messages) so the browser can show the updated
# modal contents to the user
return render(request, 'accounts/modal_registration.html', {'registration_form': form})
else:
form = RegistrationForm()
return render(request, 'accounts/modal_registration.html', {'registration_form': form})
def activate_user(request, username, uid_hash):
# NOTE: in these views we set "next_path" variable so we make sure that if the
# login modal is used the user will be redirected to the front-page instead of that same page
try:
user = User.objects.get(username__iexact=username)
except User.DoesNotExist:
return render(request, 'accounts/activate.html', {'user_does_not_exist': True,
'next_path': reverse('accounts-home')})
if not default_token_generator.check_token(user, uid_hash):
return render(request, 'accounts/activate.html', {'decode_error': True,
'next_path': reverse('accounts-home')})
user.is_active = True
user.save()
return render(request, 'accounts/activate.html', {'all_ok': True, 'next_path': reverse('accounts-home')})
def send_activation(user):
token = default_token_generator.make_token(user)
username = user.username
tvars = {
'user': user,
'username': username,
'hash': token
}
send_mail_template(settings.EMAIL_SUBJECT_ACTIVATION_LINK, 'emails/email_activation.txt', tvars, user_to=user)
def resend_activation(request):
return HttpResponseRedirect(reverse('front-page') + '?loginProblems=1')
def username_reminder(request):
return HttpResponseRedirect(reverse('front-page') + '?loginProblems=1')
@login_required
def home(request):
# In BW we no longer have the concept of "home", thus we redirect to the account page
# This view is however still useful as we can redirect to the account page of the request.user
# uing the path /home/ without needing to construct the URL with the username in it
return HttpResponseRedirect(reverse('account', args=[request.user.username]))
@login_required
def edit_email_settings(request):
if request.method == "POST":
form = EmailSettingsForm(request.POST)
if form.is_valid():
email_type_ids = form.cleaned_data['email_types']
request.user.profile.set_enabled_email_types(email_type_ids)
messages.add_message(request, messages.INFO, 'Your email notification preferences have been updated')
else:
# Get list of enabled email_types
all_emails = request.user.profile.get_enabled_email_types()
form = EmailSettingsForm(initial={
'email_types': all_emails,
})
tvars = {
'form': form,
'activePage': 'notifications'
}
return render(request, 'accounts/edit_email_settings.html', tvars)
@login_required
@transaction.atomic()
def edit(request):
profile = request.user.profile
def is_selected(prefix):
if request.method == "POST":
for name in request.POST.keys():
if name.startswith(prefix + '-'):
return True
if request.FILES:
for name in request.FILES.keys():
if name.startswith(prefix + '-'):
return True
return False
if is_selected("profile"):
profile_form = ProfileForm(request, request.POST, instance=profile, prefix="profile")
old_sound_signature = profile.sound_signature
if profile_form.is_valid():
# Update username, this will create an entry in OldUsername
request.user.username = profile_form.cleaned_data['username']
request.user.save()
invalidate_user_template_caches(request.user.id)
profile.save()
msg_txt = "Your profile has been updated correctly."
if old_sound_signature != profile.sound_signature:
msg_txt += " Please note that it might take some time until your sound signature is updated in all your sounds."
messages.add_message(request, messages.INFO, msg_txt)
return HttpResponseRedirect(reverse("accounts-edit"))
else:
profile_form = ProfileForm(request, instance=profile, prefix="profile")
if is_selected("image"):
image_form = AvatarForm(request.POST, request.FILES, prefix="image")
if image_form.is_valid():
if image_form.cleaned_data["remove"]:
profile.has_avatar = False
profile.save()
else:
handle_uploaded_image(profile, image_form.cleaned_data["file"])
profile.has_avatar = True
profile.save()
invalidate_user_template_caches(request.user.id)
msg_txt = "Your profile has been updated correctly."
messages.add_message(request, messages.INFO, msg_txt)
return HttpResponseRedirect(reverse("accounts-edit"))
else:
image_form = AvatarForm(prefix="image")
has_granted_permissions = AccessToken.objects.filter(user=request.user).count()
has_old_avatar = False
if not os.path.exists(profile.locations('avatar.XL.path')) and os.path.exists(profile.locations('avatar.L.path')):
has_old_avatar = True
if os.path.exists(profile.locations('avatar.XL.path')) and os.path.exists(profile.locations('avatar.L.path')):
if os.path.getsize(profile.locations('avatar.XL.path')) == os.path.getsize(profile.locations('avatar.L.path')):
has_old_avatar = True
tvars = {
'user': request.user,
'profile': profile,
'profile_form': profile_form,
'image_form': image_form,
'has_granted_permissions': has_granted_permissions,
'has_old_avatar': has_old_avatar,
'uploads_enabled': settings.UPLOAD_AND_DESCRIPTION_ENABLED,
'activePage': 'profile',
}
return render(request, 'accounts/edit.html', tvars)
@transaction.atomic()
def handle_uploaded_image(profile, f):
upload_logger.info("\thandling profile image upload")
os.makedirs(os.path.dirname(profile.locations("avatar.L.path")), exist_ok=True)
ext = os.path.splitext(os.path.basename(f.name))[1]
tmp_image_path = tempfile.mktemp(suffix=ext, prefix=str(profile.user.id))
try:
upload_logger.info("\topening file: %s", tmp_image_path)
destination = open(tmp_image_path, 'wb')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
upload_logger.info("\tfile upload done")
except Exception as e:
upload_logger.info("\tfailed writing file error: %s", str(e))
upload_logger.info("\tcreating thumbnails")
path_s = profile.locations("avatar.S.path")
path_m = profile.locations("avatar.M.path")
path_l = profile.locations("avatar.L.path")
path_xl = profile.locations("avatar.XL.path")
try:
extract_square(tmp_image_path, path_s, 32)
upload_logger.info("\tcreated small thumbnail")
profile.has_avatar = True
profile.save()
except Exception as e:
upload_logger.info("\tfailed creating small thumbnails: " + str(e))
try:
extract_square(tmp_image_path, path_m, 40)
upload_logger.info("\tcreated medium thumbnail")
except Exception as e:
upload_logger.info("\tfailed creating medium thumbnails: " + str(e))
try:
extract_square(tmp_image_path, path_l, 70)
upload_logger.info("\tcreated large thumbnail")
except Exception as e:
upload_logger.info("\tfailed creating large thumbnails: " + str(e))
try:
extract_square(tmp_image_path, path_xl, 100)
upload_logger.info("\tcreated extra-large thumbnail")
except Exception as e:
upload_logger.info("\tfailed creating extra-large thumbnails: " + str(e))
copy_avatar_to_mirror_locations(profile)
os.unlink(tmp_image_path)
@login_required
@transaction.atomic()
def manage_sounds(request, tab):
def process_filter_and_sort_options(request, sort_options, tab):
sort_by = request.GET.get('s', sort_options[0][0])
filter_query = request.GET.get('q', '')
try:
sort_by_db = \
[option_db_name for option_name, _, option_db_name in sort_options if option_name == sort_by][0]
except IndexError:
sort_by_db = sort_options[0][2]
filter_db = None
if filter_query:
filter_db = SearchQuery(filter_query)
return {
'sort_by': sort_by,
'filter_query': filter_query,
'sort_options': sort_options,
}, sort_by_db, filter_db
# First do some stuff common to all tabs
sounds_published_base_qs = Sound.public.filter(user=request.user)
sounds_moderation_base_qs = \
Sound.objects.filter(user=request.user, processing_state="OK").exclude(moderation_state="OK")
sounds_processing_base_qs = Sound.objects.filter(user=request.user).exclude(processing_state="OK")
sounds_published_count = sounds_published_base_qs.count()
sounds_moderation_count = sounds_moderation_base_qs.count()
sounds_processing_count = sounds_processing_base_qs.count()
packs_base_qs = Pack.objects.filter(user=request.user).exclude(is_deleted=True)
packs_count = packs_base_qs.count()
file_structure, files = generate_tree(request.user.profile.locations()['uploads_dir'])
sounds_pending_description_count = len(files)
tvars = {
'tab': tab,
'sounds_published_count': sounds_published_count,
'sounds_moderation_count': sounds_moderation_count,
'sounds_processing_count': sounds_processing_count,
'sounds_pending_description_count': sounds_pending_description_count,
'packs_count': packs_count,
}
# Then do dedicated processing for each tab
if tab == 'pending_description':
unclosed_bulkdescribe = BulkUploadProgress.objects.filter(user=request.user).exclude(progress_type="C")
tvars.update({'unclosed_bulkdescribe': unclosed_bulkdescribe})
tvars_or_redirect = sounds_pending_description_helper(request, file_structure, files)
if isinstance(tvars_or_redirect, dict):
tvars.update(tvars_or_redirect)
else:
return tvars_or_redirect
elif tab == 'packs':
if request.POST and ('edit' in request.POST or 'delete_confirm' in request.POST):
try:
pack_ids = [int(part) for part in request.POST.get('object-ids', '').split(',')]
except ValueError:
pack_ids = []
packs = Pack.objects.ordered_ids(pack_ids)
# Just as a sanity check, filter out packs not owned by the user
packs = [pack for pack in packs if pack.user == pack.user]
if packs:
if 'edit' in request.POST:
# There will be only one pack selected (otherwise the button is disabled)
# Redirect to the edit pack page
pack = packs[0]
return HttpResponseRedirect(reverse('pack-edit', args=[pack.user.username, pack.id]) + '?next=' + request.path)
elif 'delete_confirm' in request.POST:
# Delete the selected packs
n_packs_deleted = 0
for pack in packs:
web_logger.info(f"User {request.user.username} requested to delete pack {pack.id}")
pack.delete_pack(remove_sounds=False)
n_packs_deleted += 1
messages.add_message(request, messages.INFO,
f'Successfully deleted {n_packs_deleted} '
f'pack{"s" if n_packs_deleted != 1 else ""}')
return HttpResponseRedirect(reverse('accounts-manage-sounds', args=[tab]))
sort_options = [
('updated_desc', 'Last modified (newest first)', '-last_updated'),
('updated_asc', 'Last modified (oldest first)', 'last_updated'),
('created_desc', 'Date added (newest first)', '-created'),
('created_asc', 'Date added (oldest first)', 'created'),
('name', 'Name', 'name'),
('num_sounds', 'Number of sounds', 'num_sounds'),
]
extra_tvars, sort_by_db, filter_db = process_filter_and_sort_options(request, sort_options, tab)
tvars.update(extra_tvars)
if filter_db is not None:
packs_base_qs = packs_base_qs.annotate(search=SearchVector('name', 'id', 'description')).filter(search=filter_db).distinct()
packs = packs_base_qs.order_by(sort_by_db)
pack_ids = list(packs.values_list('id', flat=True))
paginator = paginate(request, pack_ids, 12)
tvars.update(paginator)
packs_to_select = Pack.objects.ordered_ids(paginator['page'].object_list, exclude_deleted=False)
for pack in packs_to_select:
pack.show_unpublished_sounds_warning = True
tvars['packs_to_select'] = packs_to_select
elif tab in ['published', 'pending_moderation', 'processing']:
# If user has selected sounds to edit or to re-process
if request.POST and ('edit' in request.POST or 'process' in request.POST or 'delete_confirm' in request.POST):
try:
sound_ids = [int(part) for part in request.POST.get('object-ids', '').split(',')]
except ValueError:
sound_ids = []
sounds = Sound.objects.ordered_ids(sound_ids)
# Just as a sanity check, filter out sounds not owned by the user
sounds = [sound for sound in sounds if sound.user == request.user]
if sounds:
if 'edit' in request.POST:
# Edit the selected sounds
session_key_prefix = str(uuid.uuid4())[0:8] # Use a new so we don't interfere with other active description/editing processes
request.session[f'{session_key_prefix}-edit_sounds'] = sounds # Add the list of sounds to edit in the session object
request.session[f'{session_key_prefix}-len_original_edit_sounds'] = len(sounds)
return HttpResponseRedirect(reverse('accounts-edit-sounds') + f'?next={request.path}&session={session_key_prefix}')
elif 'delete_confirm' in request.POST:
# Delete the selected sounds
n_sounds_deleted = 0
for sound in sounds:
web_logger.info(f"User {request.user.username} requested to delete sound {sound.id}")
try:
ticket = sound.ticket
tc = TicketComment(
sender=request.user,
text=f"User {request.user} deleted the sound",
ticket=ticket,
moderator_only=False)
tc.save()
except Ticket.DoesNotExist:
pass
sound.delete()
n_sounds_deleted += 1
messages.add_message(request, messages.INFO,
f'Successfully deleted {n_sounds_deleted} '
f'sound{"s" if n_sounds_deleted != 1 else ""}')
return HttpResponseRedirect(reverse('accounts-manage-sounds', args=[tab]))
elif 'process' in request.POST:
# Send selected sounds to re-process
n_send_to_processing = 0
for sound in sounds:
if sound.process():
n_send_to_processing += 1
sounds_skipped_msg_part = ''
if n_send_to_processing != len(sounds):
sounds_skipped_msg_part = f' {len(sounds) - n_send_to_processing} sounds were not send to ' \
f'processing due to many failed processing attempts.'
messages.add_message(request, messages.INFO,
f'Sent { n_send_to_processing } '
f'sound{ "s" if n_send_to_processing != 1 else "" } '
f'to re-process.{ sounds_skipped_msg_part }')
return HttpResponseRedirect(reverse('accounts-manage-sounds', args=[tab]))
# Process query and filter options
sort_options = [
('created_desc', 'Date added (newest first)', '-created'),
('created_asc', 'Date added (oldest first)', 'created'),
('name', 'Name', 'original_filename'),
]
extra_tvars, sort_by_db, filter_db = process_filter_and_sort_options(request, sort_options, tab)
tvars.update(extra_tvars)
# Select relevant sound ids depending on tab/filters
if tab == 'published':
sounds = sounds_published_base_qs
elif tab == 'pending_moderation':
sounds = sounds_moderation_base_qs
elif tab == 'processing':
sounds = sounds_processing_base_qs
if filter_db is not None:
sounds = sounds.annotate(search=SearchVector('original_filename', 'id', 'description', 'tags__tag__name')).filter(search=filter_db).distinct()
sounds = sounds.order_by(sort_by_db)
sound_ids = list(sounds.values_list('id', flat=True))
# Paginate and get corresponding sound objects
paginator = paginate(request, sound_ids, 9)
tvars.update(paginator)
sounds_to_select = Sound.objects.ordered_ids(paginator['page'].object_list)
for sound in sounds_to_select:
# We set these properties below so display_sound templatetag adds a bit more info to the sound display
if tab == 'pending_moderation':
sound.show_moderation_ticket = True
elif tab == 'processing':
sound.show_processing_status = True
tvars['sounds_to_select'] = sounds_to_select
else:
raise Http404 # Non-existing tab
return render(request, 'accounts/manage_sounds.html', tvars)
@login_required
@transaction.atomic()
def edit_sounds(request):
session_key_prefix = request.GET.get('session', '')
return edit_and_describe_sounds_helper(request, session_key_prefix=session_key_prefix) # Note that the list of sounds to describe is stored in the session object
def sounds_pending_description_helper(request, file_structure, files):
file_structure.name = ''
if request.method == 'POST':
form = FileChoiceForm(files, request.POST, prefix='sound')
csv_form = BulkDescribeForm(request.POST, request.FILES, prefix='bulk')
if csv_form.is_valid():
directory = os.path.join(settings.CSV_PATH, str(request.user.id))
os.makedirs(directory, exist_ok=True)
extension = csv_form.cleaned_data['csv_file'].name.rsplit('.', 1)[-1].lower()
new_csv_filename = str(uuid.uuid4()) + f'.{extension}'
path = os.path.join(directory, new_csv_filename)
destination = open(path, 'wb')
f = csv_form.cleaned_data['csv_file']
for chunk in f.chunks():
destination.write(chunk)
destination.close()
bulk = BulkUploadProgress.objects.create(user=request.user, csv_filename=new_csv_filename,
original_csv_filename=f.name)
tasks.validate_bulk_describe_csv.delay(bulk_upload_progress_object_id=bulk.id)
return HttpResponseRedirect(reverse("accounts-bulk-describe", args=[bulk.id]))
elif form.is_valid():
if "delete_confirm" in request.POST:
for f in form.cleaned_data["files"]:
try:
os.remove(files[f].full_path)
utils.sound_upload.clean_processing_before_describe_files(files[f].full_path)
remove_uploaded_file_from_mirror_locations(files[f].full_path)
except OSError as e:
if e.errno == errno.ENOENT:
upload_logger.info("Failed to remove file %s", str(e))
else:
raise
# Remove user uploads directory if there are no more files to describe
user_uploads_dir = request.user.profile.locations()['uploads_dir']
remove_directory_if_empty(user_uploads_dir)
remove_empty_user_directory_from_mirror_locations(user_uploads_dir)
return HttpResponseRedirect(reverse('accounts-manage-sounds', args=['pending_description']))
elif "describe" in request.POST:
session_key_prefix = str(uuid.uuid4())[0:8] # Use a new so we don't interfere with other active description/editing processes
request.session[f'{session_key_prefix}-describe_sounds'] = [files[x] for x in form.cleaned_data["files"]]
request.session[f'{session_key_prefix}-len_original_describe_sounds'] = len(request.session[f'{session_key_prefix}-describe_sounds'])
# If only one file is choosen, go straight to the last step of the describe process, otherwise go to license selection step
if len(request.session[f'{session_key_prefix}-describe_sounds']) > 1:
return HttpResponseRedirect(reverse('accounts-describe-license') + f'?session={session_key_prefix}')
else:
return HttpResponseRedirect(reverse('accounts-describe-sounds') + f'?session={session_key_prefix}')
else:
form = FileChoiceForm(files)
tvars = {'form': form, 'file_structure': file_structure}
return tvars
else:
csv_form = BulkDescribeForm(prefix='bulk')
form = FileChoiceForm(files, prefix='sound')
tvars = {
'form': form,
'file_structure': file_structure,
'n_files': len(files),
'csv_form': csv_form,
'describe_enabled': settings.UPLOAD_AND_DESCRIPTION_ENABLED
}
return tvars
@login_required
def describe_license(request):
session_key_prefix = request.GET.get('session', '')
if request.method == 'POST':
form = LicenseForm(request.POST, hide_old_license_versions=True)
if form.is_valid():
request.session[f'{session_key_prefix}-describe_license'] = form.cleaned_data['license']
return HttpResponseRedirect(reverse('accounts-describe-pack') + f'?session={session_key_prefix}')
else:
form = LicenseForm(hide_old_license_versions=True)
tvars = {
'form': form,
'num_files': request.session.get(f'{session_key_prefix}-len_original_describe_sounds', 0),
'session_key_prefix': session_key_prefix
}
return render(request, 'accounts/describe_license.html', tvars)
@login_required
def describe_pack(request):
packs = Pack.objects.filter(user=request.user).exclude(is_deleted=True)
session_key_prefix = request.GET.get('session', '')
if request.method == 'POST':
form = PackForm(packs, request.POST, prefix="pack")
if form.is_valid():
data = form.cleaned_data
if data['new_pack']:
pack, created = Pack.objects.get_or_create(user=request.user, name=data['new_pack'])
request.session[f'{session_key_prefix}-describe_pack'] = pack
elif data['pack']:
request.session[f'{session_key_prefix}-describe_pack'] = data['pack']
else:
request.session[f'{session_key_prefix}-describe_pack'] = False
return HttpResponseRedirect(reverse('accounts-describe-sounds') + f'?session={session_key_prefix}')
else:
form = PackForm(packs, prefix="pack")
tvars = {
'form': form,
'num_files': request.session.get(f'{session_key_prefix}-len_original_describe_sounds', 0),
'session_key_prefix': session_key_prefix
}
return render(request, 'accounts/describe_pack.html', tvars)
@login_required
@transaction.atomic()
def describe_sounds(request):
session_key_prefix = request.GET.get('session', '')
return edit_and_describe_sounds_helper(request, describing=True, session_key_prefix=session_key_prefix) # Note that the list of sounds to describe is stored in the session object
@login_required
def attribution(request):
qs_sounds = Download.objects.annotate(download_type=Value("sound", CharField()))\
.values('download_type', 'sound_id', 'sound__user__username', 'sound__original_filename',
'license__name', 'license__deed_url', 'sound__license__name', 'sound__license__deed_url', 'created').filter(user=request.user)
qs_packs = PackDownload.objects.annotate(download_type=Value("pack", CharField()))\
.values('download_type', 'pack_id', 'pack__user__username', 'pack__name', 'pack__name', 'pack__name',
'pack__name', 'pack__name', 'created').filter(user=request.user)
# NOTE: in the query above we duplicate 'pack__name' so that qs_packs has same num columns than qs_sounds. This is
# a requirement for doing QuerySet.union below. Also as a result of using QuerySet.union, the names of the columns
# (keys in each dictionary element) are unified and taken from the main query set. This means that after the union,
# queryset entries corresponding to PackDownload will have corresponding field names from entries corresponding to
# Download. Therefore to access the pack_id (which is the second value in the list), you'll need to do
# item['sound_id'] instead of item ['pack_id']. See the template of this view for an example of this.
qs = qs_sounds.union(qs_packs).order_by('-created')
tvars = {'format': request.GET.get("format", "regular")}
tvars.update(paginate(request, qs, 40))
return render(request, 'accounts/attribution.html', tvars)
@login_required
def download_attribution(request):
content = {'csv': 'csv',
'txt': 'plain',
'json': 'json'}
qs_sounds = Download.objects.annotate(download_type=Value('sound', CharField()))\
.values('download_type', 'sound_id', 'sound__user__username', 'sound__original_filename',
'license__name', 'license__deed_url', 'sound__license__name', 'sound__license__deed_url', 'created').filter(user=request.user)
qs_packs = PackDownload.objects.annotate(download_type=Value('pack', CharField()))\
.values('download_type', 'pack_id', 'pack__user__username', 'pack__name', 'pack__name', 'pack__name',
'pack__name', 'pack__name', 'created').filter(user=request.user)
# NOTE: see the above view, attribution. Note that we need to use .encode('utf-8') in some fields that can contain
# non-ascii characters even if these seem wrongly named due to the fact of using .union() in the QuerySet.
qs = qs_sounds.union(qs_packs).order_by('-created')
download = request.GET.get('dl', '')
now = datetime.datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
filename = f'{request.user}_{now}_attribution.{download}'
if download in ['csv', 'txt']:
response = HttpResponse(content_type=f'text/{content[download]}')
response['Content-Disposition'] = f'attachment; filename="{filename}"'
output = io.StringIO()
if download == 'csv':
output.write('Download Type,File Name,User,License,Timestamp\r\n')
csv_writer = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for row in qs:
csv_writer.writerow(
[row['download_type'][0].upper(), row['sound__original_filename'],
row['sound__user__username'],
license_with_version(row['license__name'] or row['sound__license__name'],
row['license__deed_url'] or row['sound__license__deed_url']),
row['created']])
elif download == 'txt':
for row in qs:
output.write("{}: {} by {} | License: {} | Timestamp: {}\n".format(row['download_type'][0].upper(),
row['sound__original_filename'], row['sound__user__username'],
license_with_version(row['license__name'] or row['sound__license__name'],
row['license__deed_url'] or row['sound__license__deed_url']),
row['created']))
response.writelines(output.getvalue())
return response
elif download == 'json':
output = []
for row in qs:
if row['download_type'][0].upper() == 'S':
output.append({
'sound_url': url2absurl(reverse("sound", args=[row['sound__user__username'], row['sound_id']])),
'sound_name': row['sound__original_filename'],
'author_url': url2absurl(reverse("account", args=[row['sound__user__username']])),
'author_name': row['sound__user__username'],
'license_url': row['license__deed_url'] or row['sound__license__deed_url'],
'license_name': license_with_version(row['license__name'] or row['sound__license__name'],
row['license__deed_url'] or row['sound__license__deed_url']),
'timestamp': str(row['created'])
})
elif row['download_type'][0].upper() == 'P':
output.append({
'pack_url': url2absurl(reverse("pack", args=[row['sound__user__username'], row['sound_id']])),
'pack_name': row['sound__original_filename'],
'author_url': url2absurl(reverse("account", args=[row['sound__user__username']])),
'author_name': row['sound__user__username'],
'license_url': row['license__deed_url'] or row['sound__license__deed_url'],
'license_name': license_with_version(row['license__name'] or row['sound__license__name'],
row['license__deed_url'] or row['sound__license__deed_url']),
'timestamp': str(row['created'])
})
return JsonResponse(output, safe=False)
else:
return HttpResponseRedirect(reverse('accounts-attribution'))
@redirect_if_old_username_or_404
@raise_404_if_user_is_deleted
def downloaded_sounds(request, username):
if not request.GET.get('ajax'):
# If not loading as a modal, redirect to the account page with parameter to open modal
return HttpResponseRedirect(reverse('account', args=[username]) + '?downloaded_sounds=1')
user = request.parameter_user
qs = Download.objects.filter(user_id=user.id).order_by('-created')
num_items_per_page = settings.DOWNLOADED_SOUNDS_PACKS_PER_PAGE
paginator = paginate(request, qs, num_items_per_page, object_count=user.profile.num_sound_downloads)
page = paginator["page"]
sound_ids = [d.sound_id for d in page]
sounds_dict = Sound.objects.dict_ids(sound_ids)
download_list = []
for d in page:
sound = sounds_dict.get(d.sound_id, None)
if sound is not None:
download_list.append({"created": d.created, "sound": sound})
tvars = {"username": username,
"user": user,
"download_list": download_list,
"type_sounds": True}
tvars.update(paginator)
return render(request, 'accounts/modal_downloads.html', tvars)
@redirect_if_old_username_or_404
@raise_404_if_user_is_deleted
def downloaded_packs(request, username):
if not request.GET.get('ajax'):
# If not loaded as a modal, redirect to account page with parameter to open modal
return HttpResponseRedirect(reverse('account', args=[username]) + '?downloaded_packs=1')
user = request.parameter_user
qs = PackDownload.objects.filter(user=user.id).order_by('-created')
num_items_per_page = settings.DOWNLOADED_SOUNDS_PACKS_PER_PAGE
paginator = paginate(request, qs, num_items_per_page, object_count=user.profile.num_pack_downloads)
page = paginator["page"]
pack_ids = [d.pack_id for d in page]
packs_dict = Pack.objects.dict_ids(pack_ids)
download_list = []
for d in page:
pack = packs_dict.get(d.pack_id, None)
if pack is not None:
download_list.append({"created": d.created, "pack": pack})
tvars = {"username": username,
"download_list": download_list,
"type_sounds": False}
tvars.update(paginator)
return render(request, 'accounts/modal_downloads.html', tvars)
def latest_content_type(scores):
if scores['uploads'] >= scores['posts'] and scores['uploads'] >= scores['comments']:
return 'sound'
elif scores['posts'] >= scores['uploads'] and scores['posts'] > scores['comments']:
return 'post'
elif scores['comments'] >= scores['uploads'] and scores['comments'] > scores['posts']:
return 'comment'
def create_user_rank(uploaders, posters, commenters, weights=dict()):
upload_weight = weights.get('upload', 1)
post_weight = weights.get('post', 0.4)
comment_weight = weights.get('comment', 0.05)
user_rank = {}
for user in uploaders:
user_rank[user['user']] = {'uploads': user['id__count'], 'posts': 0, 'comments': 0, 'score': 0}
for user in posters:
if user['author_id'] in user_rank: