/
views.py
1210 lines (1024 loc) · 52.4 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 datetime, logging, os, tempfile, uuid, shutil, hashlib, base64
from accounts.forms import UploadFileForm, FileChoiceForm, RegistrationForm, \
ReactivationForm, UsernameReminderForm, ProfileForm, AvatarForm, TermsOfServiceForm
from accounts.models import Profile, ResetEmailRequest, UserFlag
from comments.models import Comment
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.exceptions import PermissionDenied
from django.core.urlresolvers import reverse
from django.db.models import Count, Max
from django.http import HttpResponseRedirect, HttpResponse, \
HttpResponseBadRequest, HttpResponseNotFound, Http404, \
HttpResponsePermanentRedirect, HttpResponseServerError, HttpRequest
from django.shortcuts import render_to_response, get_object_or_404, render
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from forum.models import Post
from operator import itemgetter
from sounds.models import Sound, Pack, Download, License
from sounds.forms import NewLicenseForm, PackForm, SoundDescriptionForm, GeotaggingForm, RemixForm
from utils.cache import invalidate_template_cache
from utils.dbtime import DBTime
from utils.onlineusers import get_online_users
from utils.encryption import decrypt, encrypt, create_hash
from utils.filesystem import generate_tree, md5file
from utils.functional import combine_dicts
from utils.images import extract_square
from utils.pagination import paginate
from utils.text import slugify, remove_control_chars
from geotags.models import GeoTag
from django.contrib import messages
from tickets.models import Ticket, Queue, LinkedContent, TicketComment
from tickets import QUEUE_SOUND_MODERATION, TICKET_SOURCE_NEW_SOUND, \
TICKET_STATUS_NEW, TICKET_STATUS_ACCEPTED
from utils.audioprocessing import get_sound_type
from django.core.cache import cache
import django.contrib.auth.views as authviews
from django.contrib.auth.forms import AuthenticationForm
from tickets.views import new_sound_tickets_count, new_support_tickets_count
from django.contrib.auth.tokens import default_token_generator
from accounts.forms import EmailResetForm
from django.views.decorators.cache import never_cache
from django.utils.http import base36_to_int
from django.template import loader
from django.utils.http import int_to_base36
from django.contrib.sites.models import get_current_site
from utils.mail import send_mail, send_mail_template
from django.db import transaction
from bookmarks.models import Bookmark
from django.contrib.auth.decorators import user_passes_test
import json
from utils.tagrecommendation_utilities import get_recommended_tags
from messages.models import Message
from django.contrib.contenttypes.models import ContentType
import tickets.views as TicketViews
from django.contrib.auth.models import Group
from provider.oauth2.models import AccessToken
from follow import follow_utils
audio_logger = logging.getLogger('audio')
logger = logging.getLogger("upload")
research_logger = logging.getLogger('tagrecommendation_research')
@login_required
@user_passes_test(lambda u: u.is_staff, login_url='/')
def crash_me(request):
raise Exception
@login_required
def bulk_license_change(request):
if request.method == 'POST':
form = NewLicenseForm(request.POST)
if form.is_valid():
selected_license = form.cleaned_data['license']
Sound.objects.filter(user=request.user).update(license=selected_license, is_index_dirty=True)
Profile.objects.filter(user=request.user).update(has_old_license=False)
cache.set('has-old-license-%s' % request.user.id,
[False, Sound.objects.filter(user=request.user).exists()], 2592000)
return HttpResponseRedirect(reverse('accounts-home'))
else:
form = NewLicenseForm()
tvars = {'form': form}
return render(request, 'accounts/choose_new_license.html', tvars)
@login_required
def tos_acceptance(request):
if request.method == 'POST':
form = TermsOfServiceForm(request.POST)
if form.is_valid():
Profile.objects.filter(user=request.user).update(accepted_tos=True)
cache.set('has-accepted-tos-%s' % request.user.id, 'yes', 2592000)
return HttpResponseRedirect(reverse('accounts-home'))
else:
form = TermsOfServiceForm()
tvars = {'form': form}
return render(request, 'accounts/accept_terms_of_service.html', tvars)
def registration(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts-home'))
if request.method == 'POST':
form = RegistrationForm(request, request.POST)
if form.is_valid():
user = form.save()
send_activation(user)
return render(request, 'accounts/registration_done.html')
else:
form = RegistrationForm(request)
return render(request, 'accounts/registration.html', {'form': form})
def activate_user(request, username, uid_hash):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts-home'))
try:
user = User.objects.get(username__iexact=username)
except User.DoesNotExist:
return render(request, 'accounts/activate.html', {'user_does_not_exist': True})
new_hash = create_hash(user.id)
if new_hash != uid_hash:
return render(request, 'accounts/activate.html', {'decode_error': True})
user.is_active = True
user.save()
return render(request, 'accounts/activate.html', {'all_ok': True})
def send_activation(user):
uid_hash = create_hash(user.id)
username = user.username
tvars = {
'user': user,
'username': username,
'hash': uid_hash
}
send_mail_template(u'activation link.', 'accounts/email_activation.txt', tvars, None, user.email)
def resend_activation(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts-home'))
if request.method == 'POST':
form = ReactivationForm(request.POST)
if form.is_valid():
user = form.cleaned_data['user']
send_activation(user)
return render(request, 'accounts/registration_done.html')
else:
form = ReactivationForm()
return render(request, 'accounts/resend_activation.html', {'form': form})
def username_reminder(request):
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('accounts-home'))
if request.method == 'POST':
form = UsernameReminderForm(request.POST)
if form.is_valid():
user = form.cleaned_data['user']
send_mail_template(u'username reminder.', 'accounts/email_username_reminder.txt', {'user': user},
None, user.email)
return render(request, 'accounts/username_reminder.html', {'form': form, 'sent': True})
else:
form = UsernameReminderForm()
return render(request, 'accounts/username_reminder.html', {'form': form, 'sent': False})
@login_required
def home(request):
user = request.user
# Tagcloud
tags = user.profile.get_user_tags()
# Sounds
latest_sounds = Sound.objects.bulk_sounds_for_user(user_id=user.id, limit=5)
unprocessed_sounds = Sound.objects.select_related().filter(user=user).exclude(processing_state="OK")
unmoderated_sounds = TicketViews.get_pending_sounds(request.user)
unmoderated_sounds_count = len(unmoderated_sounds)
num_more_unmoderated_sounds = 0
if unmoderated_sounds_count > settings.MAX_UNMODERATED_SOUNDS_IN_HOME_PAGE:
num_more_unmoderated_sounds = unmoderated_sounds_count - settings.MAX_UNMODERATED_SOUNDS_IN_HOME_PAGE
unmoderated_sounds = unmoderated_sounds[:settings.MAX_UNMODERATED_SOUNDS_IN_HOME_PAGE]
# Packs
latest_packs = Pack.objects.select_related().filter(user=user).filter(num_sounds__gt=0).order_by("-last_updated")[0:5]
packs_without_sounds = Pack.objects.select_related().filter(user=user).filter(num_sounds=0)
# 'packs_without_sounds' also includes packs that only contain unmoderated or unprocessed sounds
# Moderation stats
new_support = new_posts = 0
if request.user.has_perm('tickets.can_moderate'):
new_support = new_support_tickets_count()
if request.user.has_perm('forum.can_moderate_forum'):
new_posts = Post.objects.filter(moderation_state='NM').count()
# Followers
following, followers, following_tags, following_count, followers_count, following_tags_count \
= follow_utils.get_vars_for_home_view(user)
tvars = {
'home': True,
'latest_sounds': latest_sounds,
'unprocessed_sounds': unprocessed_sounds,
'unmoderated_sounds': unmoderated_sounds,
'unmoderated_sounds_count': unmoderated_sounds_count,
'num_more_unmoderated_sounds': num_more_unmoderated_sounds,
'latest_packs': latest_packs,
'packs_without_sounds': packs_without_sounds,
'new_support': new_support,
'new_posts': new_posts,
'following': following,
'followers': followers,
'following_tags': following_tags,
'following_count': following_count,
'followers_count': followers_count,
'following_tags_count': following_tags_count,
'tags': tags,
}
return render(request, 'accounts/account.html', tvars)
@login_required
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"):
had_enabled_stream_emails = profile.enabled_stream_emails
profile_form = ProfileForm(request, request.POST, instance=profile, prefix="profile")
if profile_form.is_valid():
enabled_stream_emails = profile_form.cleaned_data.get("enabled_stream_emails")
# If is enabling stream emails, set last_stream_email_sent to now
if not had_enabled_stream_emails and enabled_stream_emails:
profile.last_stream_email_sent = datetime.datetime.now()
profile.save()
return HttpResponseRedirect(reverse("accounts-home"))
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()
return HttpResponseRedirect(reverse("accounts-home"))
else:
image_form = AvatarForm(prefix="image")
has_granted_permissions = AccessToken.objects.filter(user=request.user).count()
tvars = {
'profile': profile,
'profile_form': profile_form,
'image_form': image_form,
'has_granted_permissions': has_granted_permissions
}
return render(request, 'accounts/edit.html', tvars)
def handle_uploaded_image(profile, f):
logger.info("\thandling profile image upload")
try:
os.mkdir(os.path.dirname(profile.locations("avatar.L.path")))
except Exception, e:
logger.info("\tfailed creating directory with error: %s" % str(e))
pass
ext = os.path.splitext(os.path.basename(f.name))[1]
tmp_image_path = tempfile.mktemp(suffix=ext, prefix=str(profile.user.id))
try:
logger.info("\topening file: %s", tmp_image_path)
destination = open(tmp_image_path, 'wb')
for chunk in f.chunks():
destination.write(chunk)
destination.close()
logger.info("\tfile upload done")
except Exception, e:
logger.error("\tfailed writing file error: %s", str(e))
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")
try:
extract_square(tmp_image_path, path_s, 32)
logger.info("\tcreated small thumbnail")
profile.has_avatar = True
profile.save()
except Exception, e:
logger.error("\tfailed creating small thumbnails: " + str(e))
try:
extract_square(tmp_image_path, path_m, 40)
logger.info("\tcreated medium thumbnail")
except Exception, e:
logger.error("\tfailed creating medium thumbnails: " + str(e))
try:
extract_square(tmp_image_path, path_l, 70)
logger.info("\tcreated large thumbnail")
except Exception, e:
logger.error("\tfailed creating large thumbnails: " + str(e))
os.unlink(tmp_image_path)
@login_required
def describe(request):
file_structure, files = generate_tree(os.path.join(settings.UPLOADS_PATH, str(request.user.id)))
file_structure.name = ''
if request.method == 'POST':
form = FileChoiceForm(files, request.POST)
if form.is_valid():
if "delete" in request.POST:
filenames = [files[x].name for x in form.cleaned_data["files"]]
tvars = {'form': form, 'filenames': filenames}
return render(request, 'accounts/confirm_delete_undescribed_files.html', tvars)
elif "delete_confirm" in request.POST:
for f in form.cleaned_data["files"]:
os.remove(files[f].full_path)
return HttpResponseRedirect(reverse('accounts-describe'))
elif "describe" in request.POST:
request.session['describe_sounds'] = [files[x] for x in form.cleaned_data["files"]]
# 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['describe_sounds']) > 1:
return HttpResponseRedirect(reverse('accounts-describe-license'))
else:
return HttpResponseRedirect(reverse('accounts-describe-sounds'))
else:
form = FileChoiceForm(files)
tvars = {'form': form, 'file_structure': file_structure}
return render(request, 'accounts/describe.html', tvars)
else:
form = FileChoiceForm(files)
tvars = {'form': form, 'file_structure': file_structure}
return render(request, 'accounts/describe.html', tvars)
@login_required
def describe_license(request):
if request.method == 'POST':
form = NewLicenseForm(request.POST)
if form.is_valid():
request.session['describe_license'] = form.cleaned_data['license']
return HttpResponseRedirect(reverse('accounts-describe-pack'))
else:
form = NewLicenseForm({'license': License.objects.get(name='Attribution')})
tvars = {'form': form}
return render(request, 'accounts/describe_license.html', tvars)
@login_required
def describe_pack(request):
packs = Pack.objects.filter(user=request.user)
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['describe_pack'] = pack
elif data['pack']:
request.session['describe_pack'] = data['pack']
else:
request.session['describe_pack'] = False
return HttpResponseRedirect(reverse('accounts-describe-sounds'))
else:
form = PackForm(packs, prefix="pack")
tvars = {'form': form}
return render(request, 'accounts/describe_pack.html', tvars)
@login_required
@transaction.autocommit
def describe_sounds(request):
sounds_to_process = []
sounds = request.session.get('describe_sounds', False)
selected_license = request.session.get('describe_license', False)
selected_pack = request.session.get('describe_pack', False)
# For tag recommendation research only
ALTERNATIVE_INTERFACE = False
use_alternative_interface = request.GET.get("alt", False) or request.session.get('use_alternative_interface', False)
if use_alternative_interface:
ALTERNATIVE_INTERFACE = True
n_sounds = len(sounds)
# This is to prevent people browsing to the /home/describe/sounds page
# without going through the necessary steps.
# selected_pack can be False, but license and sounds have to be picked at least
if not (sounds):
msg = 'Please pick at least one sound.'
messages.add_message(request, messages.WARNING, msg)
return HttpResponseRedirect(reverse('accounts-describe'))
# So settings.SOUNDS_PER_DESCRIBE_ROUND is available in the template
sounds_per_round = settings.SOUNDS_PER_DESCRIBE_ROUND
sounds_to_describe = sounds[0:sounds_per_round]
forms = []
request.session['describe_sounds_number'] = len(request.session.get('describe_sounds'))
# If there are no files in the session redirect to the first describe page
if len(sounds_to_describe) <= 0:
# Check if there is at least one message which is not saying that the sound was already part of freesound
msg = 'You have finished describing your sounds.'
messages.add_message(request, messages.WARNING, msg)
return HttpResponseRedirect(reverse('accounts-describe'))
if request.method == 'POST':
# this is for tag recommendation logging purposes. can be deleted in a future
# TAGRECOMMENDATION CODE
try:
tag_recommendation_random_session_id = int(request.POST['random_session_id'])
except:
tag_recommendation_random_session_id = False
# first get all the data
n_sounds_already_part_of_freesound = 0
for i in range(len(sounds_to_describe)):
prefix = str(i)
forms.append({})
forms[i]['sound'] = sounds_to_describe[i]
forms[i]['description'] = SoundDescriptionForm(request.POST, prefix=prefix)
forms[i]['geotag'] = GeotaggingForm(request.POST, prefix=prefix)
forms[i]['pack'] = PackForm(Pack.objects.filter(user=request.user),
request.POST,
prefix=prefix)
forms[i]['license'] = NewLicenseForm(request.POST, prefix=prefix)
# validate each form
for i in range(len(sounds_to_describe)):
for f in ['license', 'geotag', 'pack', 'description']:
if not forms[i][f].is_valid():
return render_to_response('accounts/describe_sounds.html',
locals(),
context_instance=RequestContext(request))
# all valid, then create sounds and moderation tickets
dirty_packs = []
# TAGRECOMMENDATION CODE
tag_recommendation_session_sound_id_links = []
for i in range(len(sounds_to_describe)):
sound = Sound()
sound.user = request.user
sound.original_filename = forms[i]['description'].cleaned_data['name']
sound.original_path = forms[i]['sound'].full_path
sound.filesize = os.path.getsize(sound.original_path)
try:
sound.md5 = md5file(forms[i]['sound'].full_path)
except IOError:
messages.add_message(request, messages.ERROR, 'Something went wrong with accessing the file %s.' % sound.original_path)
continue
sound.type = get_sound_type(sound.original_path)
# check if file exists or not
try:
existing_sound = Sound.objects.get(md5=sound.md5)
n_sounds_already_part_of_freesound += 1
msg = 'The file %s is already part of freesound and has been discarded, see <a href="%s">here</a>' % \
(forms[i]['sound'].name, reverse('sound', args=[existing_sound.user.username, existing_sound.id]))
messages.add_message(request, messages.WARNING, msg)
os.remove(forms[i]['sound'].full_path)
continue
except Sound.DoesNotExist, e:
pass
# set the license
sound.license = forms[i]['license'].cleaned_data['license']
sound.save()
# now move the original
orig = os.path.splitext(os.path.basename(sound.original_filename))[0]
sound.base_filename_slug = "%d__%s__%s" % (sound.id, slugify(sound.user.username), slugify(orig))
new_original_path = sound.locations("path")
if sound.original_path != new_original_path:
try:
os.makedirs(os.path.dirname(new_original_path))
except OSError:
pass
try:
shutil.move(sound.original_path, new_original_path)
#shutil.copy(sound.original_path, new_original_path)
except IOError, e:
logger.info("failed to move file from %s to %s" % (sound.original_path, new_original_path), e)
logger.info("moved original file from %s to %s" % (sound.original_path, new_original_path))
sound.original_path = new_original_path
sound.save()
# set the pack (optional)
pack = forms[i]['pack'].cleaned_data.get('pack', False)
new_pack = forms[i]['pack'].cleaned_data.get('new_pack', False)
if not pack and new_pack:
pack, created = Pack.objects.get_or_create(user=request.user, name=new_pack)
if pack:
sound.pack = pack
dirty_packs.append(sound.pack)
# set the geotag (if 'lat' is there, all fields are)
data = forms[i]['geotag'].cleaned_data
if not data.get('remove_geotag') and data.get('lat'):
geotag = GeoTag(user=request.user,
lat=data.get('lat'),
lon=data.get('lon'),
zoom=data.get('zoom'))
geotag.save()
sound.geotag = geotag
# set the tags and descriptions
data = forms[i]['description'].cleaned_data
sound.description = remove_control_chars(data.get('description', ''))
if ALTERNATIVE_INTERFACE:
tags_data = forms[i]['description'].data['%i-tags' % i]
processed_tags = list()
for tag in tags_data.split(' '):
if not ':' in tag:
processed_tags.append(tag)
else:
processed_tags += tag.split(':')[1:]
print processed_tags
from utils.tags import clean_and_split_tags
processed_tags = clean_and_split_tags(' '.join(processed_tags))
sound.set_tags(processed_tags)
else:
sound.set_tags(data.get('tags'))
sound.save()
# add sound info in tagrecommendation log
# TAGRECOMMENDATION CODE
tag_recommendation_session_sound_id_links.append((forms[i]['description'].auto_id % i, sound.id))
# remember to process the file
sounds_to_process.append(sound)
if request.user.profile.is_whitelisted:
sound.moderation_state = 'OK'
sound.save()
messages.add_message(request, messages.INFO,
'File <a href="%s">%s</a> has been described and has been added to freesound.' % \
(sound.get_absolute_url(), forms[i]['sound'].name))
else:
# create moderation ticket!
ticket = Ticket()
ticket.title = 'Moderate sound %s' % sound.original_filename
ticket.source = TICKET_SOURCE_NEW_SOUND
ticket.status = TICKET_STATUS_NEW
ticket.queue = Queue.objects.get(name='sound moderation')
ticket.sender = request.user
lc = LinkedContent()
lc.content_object = sound
lc.save()
ticket.content = lc
ticket.save()
tc = TicketComment()
tc.sender = request.user
tc.text = "I've uploaded %s. Please moderate!" % sound.original_filename
tc.ticket = ticket
tc.save()
# add notification that the file was described successfully
messages.add_message(request, messages.INFO,
'File <a href="%s">%s</a> has been described and is now awaiting processing and moderation.' % \
(sound.get_absolute_url(), forms[i]['sound'].name))
# TODO: comment here
invalidate_template_cache("user_header", ticket.sender.id)
moderators = Group.objects.get(name='moderators').user_set.all()
for moderator in moderators:
invalidate_template_cache("user_header", moderator.id)
# compute crc
# TEMPORARY
try:
sound.compute_crc()
except:
pass
# Save tag recommendation info in tagrecommendationresearch log
# TAGRECOMMENDATION CODE
if tag_recommendation_session_sound_id_links:
research_logger.info('%s000#describing#%s#%i#-#SoundsSaved:%s' % (datetime.datetime.today().strftime('%s'),
tag_recommendation_random_session_id,
sound.user.id,
','.join(['%s|%i' % (div_id, sound_id) for div_id, sound_id in tag_recommendation_session_sound_id_links])))
for i in range(len(sounds_to_describe)):
original_tags = forms[i]['description'].data['%i-tags' % i]
research_logger.info('%s000#describing#%s#%i#-#OriginalSoundTagsSound%i:%s' % (datetime.datetime.today().strftime('%s'),
tag_recommendation_random_session_id,
sound.user.id, int(tag_recommendation_session_sound_id_links[i][1]), original_tags))
# remove the files we described from the session and redirect to this page
request.session['describe_sounds'] = request.session['describe_sounds'][len(sounds_to_describe):]
# Process the sound
# N.B. we do this at the end to avoid conflicts between django-web and django-workers
# If we're not careful django's save() functions will overwrite any processing we
# do on the workers.
try:
for sound in sounds_to_process:
sound.process()
except Exception, e:
audio_logger.error('Sound with id %s could not be scheduled. (%s)' % (sound.id, str(e)))
for p in dirty_packs:
p.process()
if len(request.session['describe_sounds']) <= 0:
if len(sounds_to_describe) != n_sounds_already_part_of_freesound:
msg = 'You have described all the selected files and are now awaiting processing and moderation. ' \
'You can check the status of your uploaded sounds in your <a href="%s">home page</a>. ' \
'Once your sounds have been processed, you can also get information about the moderation ' \
'status in the <a href="%s">uploaded sounds awaiting moderation</a> page.' % (reverse('accounts-home'), reverse('accounts-pending'))
messages.add_message(request, messages.WARNING, msg)
return HttpResponseRedirect(reverse('accounts-describe'))
else:
return HttpResponseRedirect(reverse('accounts-describe-sounds'))
else:
for i in range(len(sounds_to_describe)):
prefix = str(i)
forms.append({})
forms[i]['sound'] = sounds_to_describe[i]
forms[i]['description'] = SoundDescriptionForm(initial={'name': forms[i]['sound'].name}, prefix=prefix)
forms[i]['geotag'] = GeotaggingForm(prefix=prefix)
if selected_pack:
forms[i]['pack'] = PackForm(Pack.objects.filter(user=request.user),
prefix=prefix,
initial={'pack': selected_pack.id})
else:
forms[i]['pack'] = PackForm(Pack.objects.filter(user=request.user),
prefix=prefix)
if selected_license:
forms[i]['license'] = NewLicenseForm(initial={'license': selected_license},
prefix=prefix)
else:
forms[i]['license'] = NewLicenseForm(prefix=prefix)
# cannot include this right now because the remix sources form needs a sound object
#forms[prefix]['remix'] = RemixForm(prefix=prefix)
#request.session['describe_sounds'] = request.session['describe_sounds'][5:]
return render_to_response('accounts/describe_sounds.html', locals(), context_instance=RequestContext(request))
@login_required
def attribution(request):
qs = Download.objects.select_related('sound', 'sound__user__username', 'sound__license', 'pack', 'pack__user__username').filter(user=request.user)
format = request.GET.get("format", "regular")
tvars = {'format': format}
tvars.update(paginate(request, qs, 40))
return render(request, 'accounts/attribution.html', tvars)
def downloaded_sounds(request, username):
user = get_object_or_404(User, username__iexact=username)
qs = Download.objects.filter(user_id=user.id, sound_id__isnull=False)
paginator = paginate(request, qs, settings.SOUNDS_PER_PAGE)
page = paginator["page"]
sound_ids = [d.sound_id for d in page]
sounds = Sound.objects.ordered_ids(sound_ids)
tvars = {"username": username,
"user": user,
"sounds": sounds
}
tvars.update(paginator)
return render(request, 'accounts/downloaded_sounds.html', tvars)
def downloaded_packs(request, username):
user=get_object_or_404(User, username__iexact=username)
qs = Download.objects.filter(user=user.id, pack__isnull=False)
return render_to_response('accounts/downloaded_packs.html', combine_dicts(paginate(request, qs, settings.PACKS_PER_PAGE), locals()), context_instance=RequestContext(request))
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):
upload_weight = 1
post_weight = 0.7
comment_weight = 0.0
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.keys():
user_rank[user['author_id']]['posts'] = user['id__count']
else:
user_rank[user['author_id']] = {'uploads':0, 'posts':user['id__count'], 'comments':0, 'score':0}
for user in commenters:
if user['user_id'] in user_rank.keys():
user_rank[user['user_id']]['comments'] = user['id__count']
else:
user_rank[user['user_id']] = {'uploads':0, 'posts':0, 'comments':user['id__count'], 'score':0}
sort_list = []
for user in user_rank.keys():
user_rank[user]['score'] = user_rank[user]['uploads'] * upload_weight + \
user_rank[user]['posts'] * post_weight + user_rank[user]['comments'] * comment_weight
sort_list.append([user_rank[user]['score'],user])
return user_rank, sort_list
def accounts(request):
num_days = 14
num_active_users = 10
num_all_time_active_users = 10
last_time = DBTime.get_last_time() - datetime.timedelta(num_days)
# select active users last num_days
latest_uploaders = Sound.public.filter(created__gte=last_time).values("user").annotate(Count('id')).order_by("-id__count")
latest_posters = Post.objects.filter(created__gte=last_time).values("author_id").annotate(Count('id')).order_by("-id__count")
latest_commenters = Comment.objects.filter(created__gte=last_time).values("user_id").annotate(Count('id')).order_by("-id__count")
# rank
user_rank,sort_list = create_user_rank(latest_uploaders,latest_posters,latest_commenters)
#retrieve users lists
most_active_users = User.objects.select_related("profile").filter(id__in=[u[1] for u in sorted(sort_list,reverse=True)[:num_active_users]])
new_users = User.objects.select_related("profile").filter(date_joined__gte=last_time).filter(id__in=user_rank.keys()).order_by('-date_joined')[:num_active_users+5]
logged_users = User.objects.select_related("profile").filter(id__in=get_online_users())
# prepare for view
most_active_users_display = [[u, latest_content_type(user_rank[u.id]), user_rank[u.id]] for u in most_active_users]
most_active_users_display=sorted(most_active_users_display, key=lambda usr: user_rank[usr[0].id]['score'],reverse=True)
new_users_display = [[u, latest_content_type(user_rank[u.id]), user_rank[u.id]] for u in new_users]
# select all time active users
# We store aggregate counts on the user profile for faster querying.
all_time_uploaders = Profile.objects.extra(select={'id__count': 'num_sounds'}).order_by("-num_sounds").values("user", "id__count")[:num_all_time_active_users]
all_time_posters = Profile.objects.extra(select={'id__count': 'num_posts', 'author_id': 'user_id'}).order_by("-num_posts").values("author_id", "id__count")[:num_all_time_active_users]
# Performing a count(*) on Comment table is slow
# TODO: Create num_comments on profile and query as above
all_time_commenters = Comment.objects.all().values("user_id").annotate(Count('id')).order_by("-id__count")[:num_all_time_active_users]
# rank
user_rank,sort_list = create_user_rank(all_time_uploaders,all_time_posters,all_time_commenters)
#retrieve users list
all_time_most_active_users = User.objects.select_related("profile").filter(id__in=[u[1] for u in sorted(sort_list,reverse=True)[:num_all_time_active_users]])
all_time_most_active_users_display = [[u, user_rank[u.id]] for u in all_time_most_active_users]
all_time_most_active_users_display=sorted(all_time_most_active_users_display, key=lambda usr: user_rank[usr[0].id]['score'],reverse=True)
return render_to_response('accounts/accounts.html', dict(most_active_users=most_active_users_display, all_time_most_active_users= all_time_most_active_users_display, new_users = new_users_display, logged_users = logged_users, user_rank=user_rank,num_days=num_days), context_instance=RequestContext(request))
def account(request, username):
try:
user = User.objects.select_related('profile').get(username__iexact=username)
except User.DoesNotExist:
raise Http404
# expand tags because we will definitely be executing, and otherwise tags is called multiple times
tags = user.profile.get_user_tags() if user.profile else []
latest_sounds = Sound.objects.bulk_sounds_for_user(user.id, settings.SOUNDS_PER_PAGE)
latest_packs = Pack.objects.select_related().filter(user=user).filter(num_sounds__gt=0).order_by("-last_updated")[0:10]
google_api_key = settings.GOOGLE_API_KEY
following, followers, following_tags, following_count, followers_count, following_tags_count = follow_utils.get_vars_for_account_view(user)
follow_user_url = reverse('follow-user', args=[username])
unfollow_user_url = reverse('unfollow-user', args=[username])
# true if the logged user is following the user of the current viewed profile page
show_unfollow_button = False
if request.user.is_authenticated():
show_unfollow_button = follow_utils.is_user_following_user(request.user, user)
home = False
has_bookmarks = Bookmark.objects.filter(user=user).exists()
if not user.is_active:
messages.add_message(request, messages.INFO, 'This account has <b>not been activated</b> yet.')
return render_to_response('accounts/account.html', locals(), context_instance=RequestContext(request))
def handle_uploaded_file(user_id, f):
# handle a file uploaded to the app. Basically act as if this file was uploaded through FTP
directory = os.path.join(settings.UPLOADS_PATH, str(user_id))
logger.info("\thandling file upload")
try:
os.mkdir(directory)
except:
logger.info("\tfailed creating directory, probably already exist")
pass
path = os.path.join(directory, os.path.basename(f.name))
try:
logger.info("\topening file: %s", path)
destination = open(path.encode("utf-8"), 'wb')
for chunk in f.chunks():
destination.write(chunk)
logger.info("file upload done")
except Exception, e:
logger.warning("failed writing file error: %s", str(e))
return False
return True
@csrf_exempt
def upload_file(request):
""" upload a file. This function does something weird: it gets the session id from the
POST variables. This is weird but... as far as we know it's not too bad as we only need
the user login """
logger.info("start uploading file")
# get the current session engine
engine = __import__(settings.SESSION_ENGINE, {}, {}, [''])
session_data = engine.SessionStore(request.POST.get('sessionid', ''))
try:
user_id = session_data['_auth_user_id']
logger.info("\tuser id %s", str(user_id))
except KeyError:
logger.warning("failed to get user id from session")
return HttpResponseBadRequest("You're not logged in. Log in and try again.")
try:
request.user = User.objects.get(id=user_id)
logger.info("\tfound user: %s", request.user.username)
except User.DoesNotExist:
logger.warning("user with this id does not exist")
return HttpResponseBadRequest("user with this ID does not exist.")
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
logger.info("\tform data is valid")
if handle_uploaded_file(user_id, request.FILES["file"]):
return HttpResponse("File uploaded OK")
else:
return HttpResponseServerError("Error in file upload")
else:
logger.warning("form data is invalid: %s", str(form.errors))
return HttpResponseBadRequest("Form is not valid.")
else:
logger.warning("no data in post")
return HttpResponseBadRequest("No POST data in request")
@login_required
def upload(request, no_flash = False):
form = UploadFileForm()
success = False
error = False
if no_flash:
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
if handle_uploaded_file(request.user.id, request.FILES["file"]):
uploaded_file=request.FILES["file"]
success = True
else:
error = True
return render_to_response('accounts/upload.html', locals(), context_instance=RequestContext(request))
@login_required
def delete(request):
import time
encrypted_string = request.GET.get("user", None)
waited_too_long = False
num_sounds = request.user.sounds.all().count()
if encrypted_string != None:
try:
user_id, now = decrypt(encrypted_string).split("\t")
user_id = int(user_id)
if user_id != request.user.id:
raise PermissionDenied
link_generated_time = float(now)
if abs(time.time() - link_generated_time) < 10:
from forum.models import Post, Thread
from comments.models import Comment
from sounds.models import DeletedSound
deleted_user = User.objects.get(id=settings.DELETED_USER_ID)
for post in Post.objects.filter(author=request.user):
post.author = deleted_user
post.save()
for thread in Thread.objects.filter(author=request.user):
thread.author = deleted_user
thread.save()
for comment in Comment.objects.filter(user=request.user):
comment.user = deleted_user
comment.save()
for sound in DeletedSound.objects.filter(user=request.user):
sound.user = deleted_user
sound.save()
request.user.delete()
return HttpResponseRedirect(reverse("front-page"))
else:
waited_too_long = True
except:
pass
encrypted_link = encrypt(u"%d\t%f" % (request.user.id, time.time()))
return render_to_response('accounts/delete.html', locals(), context_instance=RequestContext(request))
def old_user_link_redirect(request):
user_id = request.GET.get('id', False)
if user_id:
try:
user = get_object_or_404(User, id=int(user_id))
return HttpResponsePermanentRedirect(reverse("account", args=[user.username]))
except ValueError:
raise Http404
else:
raise Http404
# got characters from rfc3986 (minus @, + which are valid for django usernames)
BAD_USERNAME_CHARACTERS = {':': '_colon_',
'/': '_slash_',
'?': '_qmark_',
'#': '_hash_',
'[': '_lbrack1_',
']': '_rbrack1_',
'!': '_emark_',
'$': '_dollar_',
'&': '_amper_',
"'": '_quote_',
'(': '_lbrack2_',
')': '_rbrack2_',
'*': '_stardom_',
',': '_comma_',
';': '_scolon_',
'=': '_equal_',
'{': '_lbrack3_',
'}': '_rbrack3_'
}