diff --git a/accounts/urls.py b/accounts/urls.py index 8f3cf285c..cf43f320b 100644 --- a/accounts/urls.py +++ b/accounts/urls.py @@ -27,7 +27,9 @@ import bookmarks.views as bookmarks import follow.views as follow import apiv2.views as api -from utils.frontend_handling import redirect_if_beastwhoosh_inline +from utils.urlpatterns import redirect_inline + + # By putting some URLs at the top that are the same as the ones listed in # django.contrib.auth.urls, we can override some configuration: @@ -40,13 +42,13 @@ path('cleanup/', accounts.multi_email_cleanup, name="accounts-multi-email-cleanup"), path('password_reset/', login_redirect( - redirect_if_beastwhoosh_inline( + redirect_inline( auth_views.PasswordResetView.as_view(form_class=FsPasswordResetForm), redirect_url_name='front-page', query_string='loginProblems=1')), name='password_reset'), path('password_reset/done/', - redirect_if_beastwhoosh_inline( + redirect_inline( auth_views.PasswordResetDoneView.as_view(), redirect_url_name='front-page'), name='password_reset_done'), diff --git a/accounts/views.py b/accounts/views.py index 4344491c1..a9b050def 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -51,7 +51,7 @@ 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 +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 @@ -82,7 +82,7 @@ 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.frontend_handling import render, using_beastwhoosh, redirect_if_beastwhoosh +from utils.frontend_handling import using_beastwhoosh 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 @@ -381,46 +381,13 @@ def send_activation(user): send_mail_template(settings.EMAIL_SUBJECT_ACTIVATION_LINK, 'emails/email_activation.txt', tvars, user_to=user) -@redirect_if_beastwhoosh('front-page', query_string='loginProblems=1') def resend_activation(request): - if request.method == 'POST': - form = ReactivationForm(request.POST) - if form.is_valid(): - username_or_email = form.cleaned_data['user'] - try: - user = User.objects.get((Q(email__iexact=username_or_email)\ - | Q(username__iexact=username_or_email))\ - & Q(is_active=False)) - send_activation(user) - except User.DoesNotExist: - pass - return render(request, 'accounts/resend_activation_done.html') - else: - form = ReactivationForm() + return HttpResponseRedirect(reverse('front-page') + '?loginProblems=1') - return render(request, 'accounts/resend_activation.html', {'form': form}) - -@redirect_if_beastwhoosh('front-page', query_string='loginProblems=1') def username_reminder(request): - if request.method == 'POST': - form = UsernameReminderForm(request.POST) - if form.is_valid(): - email = form.cleaned_data['user'] - - try: - user = User.objects.get(email__iexact=email) - send_mail_template(settings.EMAIL_SUBJECT_USERNAME_REMINDER, 'emails/email_username_reminder.txt', - {'user': user}, user_to=user) - except User.DoesNotExist: - pass - - 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}) - + return HttpResponseRedirect(reverse('front-page') + '?loginProblems=1') + @login_required def home(request): @@ -822,8 +789,8 @@ def process_filter_and_sort_options(request, sort_options, tab): @login_required +@transaction.atomic() def edit_sounds(request): - if not using_beastwhoosh(request): raise Http404 return edit_and_describe_sounds_helper(request) # Note that the list of sounds to describe is stored in the session object @@ -951,157 +918,11 @@ def describe_pack(request): @login_required +@transaction.atomic() def describe_sounds(request): - if using_beastwhoosh(request): - return edit_and_describe_sounds_helper(request) # Note that the list of sounds to describe is stored in the session object - - forms = [] - sounds_to_process = [] - sounds = request.session.get('describe_sounds', False) - if not sounds: - msg = 'Please pick at least one sound.' - messages.add_message(request, messages.WARNING, msg) - return HttpResponseRedirect(reverse('accounts-describe')) - sounds_to_describe = sounds[0:settings.SOUNDS_PER_DESCRIBE_ROUND] - request.session['describe_sounds_number'] = len(request.session.get('describe_sounds')) - selected_license = request.session.get('describe_license', False) - selected_pack = request.session.get('describe_pack', False) - - # If there are no files in the session redirect to the first describe page - if len(sounds_to_describe) <= 0: - msg = 'You have finished describing your sounds.' - messages.add_message(request, messages.WARNING, msg) - return HttpResponseRedirect(reverse('accounts-describe')) - - tvars = { - 'sounds_per_round': settings.SOUNDS_PER_DESCRIBE_ROUND, - 'forms': forms, - 'last_latlong': request.user.profile.get_last_latlong(), - } - - if request.method == 'POST': - # 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, explicit_disable=False) - forms[i]['geotag'] = GeotaggingForm(request.POST, prefix=prefix) - forms[i]['pack'] = PackForm(Pack.objects.filter(user=request.user).exclude(is_deleted=True), - request.POST, - prefix=prefix) - forms[i]['license'] = LicenseForm(request.POST, prefix=prefix, hide_old_license_versions=True) - # 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(): - # If at least one form is not valid, render template with form errors - return render(request, 'accounts/describe_sounds.html', tvars) - - # All valid, then create sounds and moderation tickets - dirty_packs = [] - for i in range(len(sounds_to_describe)): - sound_fields = { - 'name': forms[i]['description'].cleaned_data['name'], - 'dest_path': forms[i]['sound'].full_path, - 'license': forms[i]['license'].cleaned_data['license'], - 'description': forms[i]['description'].cleaned_data.get('description', ''), - 'tags': forms[i]['description'].cleaned_data.get('tags', ''), - 'is_explicit': forms[i]['description'].cleaned_data['is_explicit'], - } - - 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: - sound_fields['pack'] = new_pack - elif pack: - sound_fields['pack'] = pack - - data = forms[i]['geotag'].cleaned_data - if not data.get('remove_geotag') and data.get('lat'): # if 'lat' is in data, we assume other fields are too - geotag = '%s,%s,%d' % (data.get('lat'), data.get('lon'), data.get('zoom')) - sound_fields['geotag'] = geotag - - try: - user = request.user - sound = utils.sound_upload.create_sound(user, sound_fields, process=False) - sounds_to_process.append(sound) - if user.profile.is_whitelisted: - messages.add_message(request, messages.INFO, - 'File %s has been described and has been added to freesound.' % \ - (sound.get_absolute_url(), sound.original_filename)) - else: - messages.add_message(request, messages.INFO, - 'File %s has been described and is now awaiting processing ' - 'and moderation.' % (sound.get_absolute_url(), sound.original_filename)) - - # Invalidate affected caches in user header - invalidate_user_template_caches(request.user.id) - for moderator in Group.objects.get(name='moderators').user_set.all(): - invalidate_user_template_caches(moderator.id) - - except utils.sound_upload.NoAudioException: - # If for some reason audio file does not exist, skip creating this sound - messages.add_message(request, messages.ERROR, - f"Something went wrong with accessing the file {forms[i]['description'].cleaned_data['name']}.") - except utils.sound_upload.AlreadyExistsException as e: - messages.add_message(request, messages.WARNING, str(e)) - except utils.sound_upload.CantMoveException as e: - upload_logger.error(str(e)) - - # Remove the files we just described from the session and redirect to this page - request.session['describe_sounds'] = request.session['describe_sounds'][len(sounds_to_describe):] - - # Process sounds and packs - # 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. - # In the future if django-workers do not write to the db this might be changed - try: - for s in sounds_to_process: - s.process_and_analyze() - except Exception as e: - sounds_logger.error(f'Sound with id {s.id} could not be scheduled. ({str(e)})') - for p in dirty_packs: - p.process() - - # Check if all sounds have been described after that round and redirect accordingly - 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 home page. ' \ - 'Once your sounds have been processed, you can also get information about the moderation ' \ - 'status in the uploaded sounds awaiting moderation' \ - ' page.' % (reverse('accounts-home'), reverse('accounts-pending')) - messages.add_message(request, messages.WARNING, msg) - clear_session_edit_and_describe_data(request) - 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).exclude(is_deleted=True), - prefix=prefix, - initial={'pack': selected_pack.id}) - else: - forms[i]['pack'] = PackForm(Pack.objects.filter(user=request.user).exclude(is_deleted=True), - prefix=prefix) - if selected_license: - forms[i]['license'] = LicenseForm(initial={'license': selected_license}, - prefix=prefix, hide_old_license_versions=True) - else: - forms[i]['license'] = LicenseForm(prefix=prefix, hide_old_license_versions=True) - - return render(request, 'accounts/describe_sounds.html', tvars) - + return edit_and_describe_sounds_helper(request) # 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()))\ @@ -1264,56 +1085,8 @@ def create_user_rank(uploaders, posters, commenters, weights=dict()): return user_rank, sort_list -@redirect_if_beastwhoosh('charts') 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) - - # Most active users in last num_days, newest active users in last num_days and logged in users - 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") - user_rank, sort_list = create_user_rank(latest_uploaders, latest_posters, latest_commenters) - 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=list(user_rank.keys())).order_by('-date_joined')[:num_active_users+5] - logged_users = User.objects.select_related("profile").filter(id__in=get_online_users()) - 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] - - # All time most active users (these queries are kind of slow, but page is cached) - 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, we could add 'num_comments' to user profile - all_time_commenters = Comment.objects.all().values("user_id").annotate(Count('id'))\ - .order_by("-id__count")[:num_all_time_active_users] - all_time_user_rank, all_time_sort_list = create_user_rank(all_time_uploaders, all_time_posters, all_time_commenters) - all_time_most_active_users = User.objects.select_related("profile")\ - .filter(id__in=[u[1] for u in sorted(all_time_sort_list, reverse=True)[:num_all_time_active_users]]) - all_time_most_active_users_display = [[u, all_time_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: all_time_user_rank[usr[0].id]['score'], - reverse=True) - - tvars = { - 'num_days': num_days, - '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, - } - return render(request, 'accounts/accounts.html', tvars) + return HttpResponseRedirect(reverse('charts')) def compute_charts_stats(): diff --git a/apiv2/views.py b/apiv2/views.py index bb1c59d4f..dc22f63ea 100755 --- a/apiv2/views.py +++ b/apiv2/views.py @@ -34,6 +34,7 @@ from django.db import IntegrityError from django.db.models import Exists, OuterRef from django.http import HttpResponseRedirect, Http404 +from django.shortcuts import render from django.urls import reverse from oauth2_provider.models import Grant, AccessToken from oauth2_provider.views import AuthorizationView as ProviderAuthorizationView @@ -65,7 +66,7 @@ from sounds.models import Sound, Pack, License, SoundAnalysis from utils.downloads import download_sounds from utils.filesystem import generate_tree -from utils.frontend_handling import render, using_beastwhoosh +from utils.frontend_handling import using_beastwhoosh from utils.nginxsendfile import sendfile, prepare_sendfile_arguments_for_sound_download from utils.tags import clean_and_split_tags diff --git a/bookmarks/views.py b/bookmarks/views.py index f7ed5ec3f..8a7f3b71f 100755 --- a/bookmarks/views.py +++ b/bookmarks/views.py @@ -24,13 +24,13 @@ from django.db import transaction from django.db.models import Count from django.http import Http404, HttpResponseRedirect, JsonResponse -from django.shortcuts import get_object_or_404 +from django.shortcuts import get_object_or_404, render from django.urls import reverse from bookmarks.forms import BookmarkForm, BwBookmarkForm from bookmarks.models import Bookmark, BookmarkCategory from sounds.models import Sound -from utils.frontend_handling import using_beastwhoosh, render +from utils.frontend_handling import using_beastwhoosh from utils.pagination import paginate from utils.username import redirect_if_old_username_or_404, raise_404_if_user_is_deleted diff --git a/comments/views.py b/comments/views.py index 2f27d04d8..cd0a27090 100644 --- a/comments/views.py +++ b/comments/views.py @@ -29,7 +29,7 @@ from comments.models import Comment from sounds.models import Sound -from utils.frontend_handling import render, using_beastwhoosh +from utils.frontend_handling import using_beastwhoosh from utils.pagination import paginate from utils.username import redirect_if_old_username_or_404, raise_404_if_user_is_deleted diff --git a/donations/views.py b/donations/views.py index 5ee304bec..f0c6bd9f4 100644 --- a/donations/views.py +++ b/donations/views.py @@ -10,14 +10,14 @@ from django.contrib.auth.models import User from django.contrib.sites.models import Site from django.http import HttpResponse, JsonResponse, HttpResponseRedirect -from django.shortcuts import redirect +from django.shortcuts import redirect, render from django.urls import reverse from django.views.decorators.csrf import csrf_exempt from django.views.generic import ListView from .forms import DonateForm, BwDonateForm from .models import Donation, DonationCampaign -from utils.frontend_handling import render, using_beastwhoosh, BwCompatibleTemplateResponse +from utils.frontend_handling import using_beastwhoosh from utils.mail import send_mail_template web_logger = logging.getLogger('web') @@ -256,7 +256,6 @@ def donate(request): class DonationsList(ListView): - response_class = BwCompatibleTemplateResponse model = Donation paginate_by = settings.DONATIONS_PER_PAGE ordering = ["-created"] diff --git a/follow/views.py b/follow/views.py index 6fe96ef5b..d33ae3270 100644 --- a/follow/views.py +++ b/follow/views.py @@ -26,14 +26,14 @@ from django.contrib.auth.models import User from django.db import transaction from django.http import HttpResponse, HttpResponseRedirect -from django.shortcuts import get_object_or_404 +from django.shortcuts import get_object_or_404, render from django.urls import reverse from follow import follow_utils from follow.models import FollowingQueryItem from follow.models import FollowingUserItem from utils.cache import invalidate_user_template_caches -from utils.frontend_handling import using_beastwhoosh, render +from utils.frontend_handling import using_beastwhoosh from utils.pagination import paginate from utils.username import redirect_if_old_username_or_404, raise_404_if_user_is_deleted diff --git a/forum/views.py b/forum/views.py index ee1890b4c..2b0f7d93b 100644 --- a/forum/views.py +++ b/forum/views.py @@ -37,7 +37,7 @@ from forum.forms import PostReplyForm, BwPostReplyForm, NewThreadForm, BwNewThreadForm, PostModerationForm, BwPostModerationForm from forum.models import Forum, Thread, Post, Subscription from utils.cache import invalidate_template_cache, invalidate_all_moderators_header_cache -from utils.frontend_handling import render, using_beastwhoosh +from utils.frontend_handling import using_beastwhoosh from utils.mail import send_mail_template from utils.pagination import paginate from utils.search.search_forum import add_posts_to_search_engine diff --git a/freesound/middleware.py b/freesound/middleware.py index 9e6a812d3..253ccb9e5 100644 --- a/freesound/middleware.py +++ b/freesound/middleware.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -import json import logging from admin_reorder.middleware import ModelAdminReorder @@ -77,26 +76,6 @@ def __call__(self, request): return response -class FrontendPreferenceHandler: - def __init__(self, get_response): - self.get_response = get_response - - def __call__(self, request): - """ - This middleware sets a session variable when the parameter 'new_frontend' is received. - The 'render' method will use this session variable to display the new/old frontend - """ - if request.GET.get(settings.FRONTEND_CHOOSER_REQ_PARAM_NAME, None): - selected_ui = request.GET.get(settings.FRONTEND_CHOOSER_REQ_PARAM_NAME) - current_ui = request.session.get(settings.FRONTEND_SESSION_PARAM_NAME, None) - if selected_ui != current_ui: - web_logger.info('Frontend activation (%s)' % json.dumps({'name': selected_ui, - 'username': request.user.username})) - request.session[settings.FRONTEND_SESSION_PARAM_NAME] = selected_ui - response = self.get_response(request) - return response - - class TosAcceptanceHandler: """Checks if the user has accepted the updates to the Terms of Service in 2022. This replaces the agreement to the original ToS (2013, 2fd543f3a). diff --git a/freesound/settings.py b/freesound/settings.py index 420feba3f..005069e26 100644 --- a/freesound/settings.py +++ b/freesound/settings.py @@ -38,7 +38,6 @@ 'freesound.middleware.UpdateEmailHandler', 'freesound.middleware.OnlineUsersHandler', 'corsheaders.middleware.CorsMiddleware', - 'freesound.middleware.FrontendPreferenceHandler', ] INSTALLED_APPS = [ @@ -807,16 +806,11 @@ # ------------------------------------------------------------------------------- # Frontend handling -FRONTEND_CHOOSER_REQ_PARAM_NAME = 'fend' -FRONTEND_SESSION_PARAM_NAME = 'frontend' -FRONTEND_NIGHTINGALE = 'ng' # https://freesound.org/people/reinsamba/sounds/14854/ -FRONTEND_BEASTWHOOSH = 'bw' # https://freesound.org/people/martian/sounds/403973/ -FRONTEND_DEFAULT = FRONTEND_BEASTWHOOSH TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ - os.path.join(os.path.dirname(__file__), '../templates_bw'), + os.path.join(os.path.dirname(__file__), '../templates'), ], 'APP_DIRS': True, 'OPTIONS': { @@ -831,29 +825,7 @@ 'django.contrib.messages.context_processors.messages', 'freesound.context_processor.context_extra', ], - }, - 'NAME': FRONTEND_BEASTWHOOSH, - }, - { - 'BACKEND': 'django.template.backends.django.DjangoTemplates', - 'DIRS': [ - os.path.join(os.path.dirname(__file__), '../templates') - ], - 'APP_DIRS': True, - 'OPTIONS': { - 'context_processors': [ - 'django.contrib.auth.context_processors.auth', - 'django.template.context_processors.debug', - 'django.template.context_processors.i18n', - 'django.template.context_processors.media', - 'django.template.context_processors.static', - 'django.template.context_processors.tz', - 'django.template.context_processors.request', - 'django.contrib.messages.context_processors.messages', - 'freesound.context_processor.context_extra', - ], - }, - 'NAME': FRONTEND_NIGHTINGALE, + } }, ] diff --git a/freesound/urls.py b/freesound/urls.py index 3076395eb..90fe8616f 100644 --- a/freesound/urls.py +++ b/freesound/urls.py @@ -96,9 +96,6 @@ re_path(r'^browse/geotags/(?P[\w-]+)?/?$', geotags.views.geotags, name="geotags"), path('browse/geotags_box/', geotags.views.geotags_box, name="geotags-box"), - path('browse/remixed/', sounds.views.remixed, name="remix-groups"), - path('browse/remixed//', sounds.views.remix_group, name="remix-group"), - path('contact/', support.views.contact, name="contact"), path('search/', search.views.search, name='sounds-search'), diff --git a/geotags/views.py b/geotags/views.py index 8308de0d1..6ec2ad9e2 100644 --- a/geotags/views.py +++ b/geotags/views.py @@ -27,13 +27,13 @@ from django.conf import settings from django.core.cache import cache from django.http import Http404, HttpResponse -from django.shortcuts import get_object_or_404 +from django.shortcuts import get_object_or_404, render from django.urls import reverse from django.views.decorators.cache import cache_page from django.views.decorators.clickjacking import xframe_options_exempt from sounds.models import Sound, Pack -from utils.frontend_handling import render, using_beastwhoosh +from utils.frontend_handling import using_beastwhoosh from utils.logging_filters import get_client_ip from utils.username import redirect_if_old_username_or_404, raise_404_if_user_is_deleted diff --git a/messages/views.py b/messages/views.py index 72b2f260a..e6232cb7f 100644 --- a/messages/views.py +++ b/messages/views.py @@ -29,12 +29,13 @@ from django.db.models import Q from django.http import HttpResponse, JsonResponse from django.http import HttpResponseRedirect, Http404 +from django.shortcuts import render from django.urls import reverse from messages.forms import MessageReplyForm, MessageReplyFormWithCaptcha, BwMessageReplyForm, BwMessageReplyFormWithCaptcha from messages.models import Message, MessageBody from utils.cache import invalidate_user_template_caches -from utils.frontend_handling import render, using_beastwhoosh +from utils.frontend_handling import using_beastwhoosh from utils.mail import send_mail_template from utils.pagination import paginate diff --git a/monitor/views.py b/monitor/views.py index 29be25152..6c16cafd8 100644 --- a/monitor/views.py +++ b/monitor/views.py @@ -27,16 +27,15 @@ from django.contrib.auth.models import User from django.core.cache import cache from django.db.models import Count -from django.http import JsonResponse, HttpResponse -from django.shortcuts import redirect -from django.shortcuts import render +from django.http import JsonResponse, HttpResponse, HttpResponseRedirect +from django.shortcuts import redirect, render from django.urls import reverse import tickets from freesound.celery import get_queues_task_counts from sounds.models import Sound, SoundAnalysis from tickets import TICKET_STATUS_CLOSED -from utils.frontend_handling import render, using_beastwhoosh, redirect_if_beastwhoosh +from utils.frontend_handling import using_beastwhoosh @login_required @@ -215,27 +214,12 @@ def monitor_stats(request): return render(request, 'monitor/stats.html', tvars) -@redirect_if_beastwhoosh('monitor-moderation') @login_required @user_passes_test(lambda u: u.is_staff, login_url='/') def moderators_stats(request): - time_span = datetime.datetime.now() - datetime.timedelta((6 * 365) // 12) - #Maybe we should user created and not modified - user_ids = tickets.models.Ticket.objects.filter( - status=TICKET_STATUS_CLOSED, - created__gt=time_span, - assignee__isnull=False - ).values_list("assignee_id", flat=True) - - counter = Counter(user_ids) - moderators = User.objects.filter(id__in=list(counter.keys())) - - moderators = [(counter.get(m.id), m) for m in moderators.all()] - ordered = sorted(moderators, key=lambda m: m[0], reverse=True) - tvars = {"moderators": ordered} - return render(request, 'monitor/moderators_stats.html', tvars) - + return HttpResponseRedirect(reverse('monitor-moderation')) + def queries_stats_ajax(request): try: auth = (settings.GRAYLOG_USERNAME, settings.GRAYLOG_PASSWORD) diff --git a/search/views.py b/search/views.py index 5e139b7a0..52b558d1e 100644 --- a/search/views.py +++ b/search/views.py @@ -28,8 +28,7 @@ from django.core.cache import cache from django.conf import settings from django.http import JsonResponse -from django.shortcuts import get_object_or_404 -from django.shortcuts import reverse +from django.shortcuts import get_object_or_404, reverse, render from ratelimit.decorators import ratelimit import forum @@ -38,7 +37,7 @@ NUM_TAGS_SHOWN_PER_CLUSTER_FACET from clustering.interface import cluster_sound_results, get_sound_ids_from_search_engine_query from forum.models import Post -from utils.frontend_handling import render, using_beastwhoosh +from utils.frontend_handling import using_beastwhoosh from utils.logging_filters import get_client_ip from utils.ratelimit import key_for_ratelimiting, rate_per_ip from utils.search.search_sounds import perform_search_engine_query, search_prepare_parameters, \ diff --git a/sounds/views.py b/sounds/views.py index 3f0375e1a..38aa37f54 100644 --- a/sounds/views.py +++ b/sounds/views.py @@ -40,7 +40,7 @@ from django.http import HttpResponse from django.http import HttpResponseRedirect, Http404, \ HttpResponsePermanentRedirect, JsonResponse -from django.shortcuts import get_object_or_404, redirect +from django.shortcuts import get_object_or_404, redirect, render from django.template import loader from django.urls import reverse, resolve from django.views.decorators.clickjacking import xframe_options_exempt @@ -62,7 +62,7 @@ from utils.cache import invalidate_user_template_caches from utils.downloads import download_sounds, should_suggest_donation from utils.encryption import sign_with_timestamp, unsign_with_timestamp -from utils.frontend_handling import render, using_beastwhoosh, redirect_if_beastwhoosh +from utils.frontend_handling import using_beastwhoosh from utils.mail import send_mail_template, send_mail_template_to_support from utils.nginxsendfile import sendfile, prepare_sendfile_arguments_for_sound_download from utils.pagination import paginate @@ -119,33 +119,8 @@ def get_sound_of_the_day_id(): return random_sound -@redirect_if_beastwhoosh('sounds-search', query_string='s=Date+added+(newest+first)&g=1') def sounds(request): - latest_sounds = Sound.objects.latest_additions(num_sounds=5, period_days=2) - latest_packs = Pack.objects.select_related().filter(num_sounds__gt=0).exclude(is_deleted=True).order_by("-last_updated")[0:20] - last_week = get_n_weeks_back_datetime(n_weeks=1) - popular_sounds = Sound.public.select_related('license', 'user') \ - .annotate(greatest_date=Greatest('created', 'moderation_date')) \ - .filter(greatest_date__gte=last_week).order_by("-num_downloads")[0:5] - popular_packs = Pack.objects.select_related('user').filter(created__gte=last_week).exclude(is_deleted=True).order_by("-num_downloads")[0:5] - random_sound_id = get_sound_of_the_day_id() - if random_sound_id: - try: - random_sound = Sound.objects.bulk_query_id([random_sound_id])[0] - except IndexError: - # Clear existing cache for random sound of the day as it contains invalid sound id - cache.delete(settings.RANDOM_SOUND_OF_THE_DAY_CACHE_KEY) - random_sound = None - else: - random_sound = None - tvars = { - 'latest_sounds': latest_sounds, - 'latest_packs': latest_packs, - 'popular_sounds': popular_sounds, - 'popular_packs': popular_packs, - 'random_sound': random_sound - } - return render(request, 'sounds/sounds.html', tvars) + return HttpResponseRedirect(reverse('sounds-search') + '?s=Date+added+(newest+first)&g=1') @ratelimit(key=key_for_ratelimiting, rate=rate_per_ip, group=settings.RATELIMIT_SEARCH_GROUP, block=True) @@ -174,18 +149,8 @@ def random(request): reverse('sound', args=[sound_obj.user.username, sound_obj.id]))) -@redirect_if_beastwhoosh('sounds-search', query_string='s=Date+added+(newest+first)&g=1&only_p=1') def packs(request): - order = request.GET.get("order", "name") - if order not in ["name", "-last_updated", "-created", "-num_sounds", "-num_downloads"]: - order = "name" - qs = Pack.objects.select_related() \ - .filter(num_sounds__gt=0) \ - .exclude(is_deleted=True) \ - .order_by(order) - tvars = {'order': order} - tvars.update(paginate(request, qs, settings.PACKS_PER_PAGE)) - return render(request, 'sounds/browse_packs.html', tvars) + return HttpResponseRedirect(reverse('sounds-search') + '?s=Date+added+(newest+first)&g=1&only_p=1') def front_page(request): @@ -916,31 +881,8 @@ def pack_delete(request, username, pack_id): @login_required -@redirect_if_beastwhoosh('sound-edit', kwarg_keys=['username', 'sound_id']) -@transaction.atomic() def sound_edit_sources(request, username, sound_id): - sound = get_object_or_404(Sound, id=sound_id) - if sound.user.username.lower() != username.lower(): - raise Http404 - - if not (request.user.is_superuser or sound.user == request.user): - raise PermissionDenied - - current_sources = Sound.objects.ordered_ids([element['id'] for element in sound.sources.all().values('id')]) - sources_string = ",".join(map(str, [source.id for source in current_sources])) - if request.method == 'POST': - form = RemixForm(sound, request.POST) - if form.is_valid(): - form.save() - sound.invalidate_template_caches() - else: - form = RemixForm(sound, initial=dict(sources=sources_string)) - tvars = { - 'sound': sound, - 'form': form, - 'current_sources': current_sources - } - return render(request, 'sounds/sound_edit_sources.html', tvars) + return HttpResponseRedirect(reverse('sound-edit', args=[username, sound_id])) def add_sounds_modal_helper(request, username=None): @@ -1020,24 +962,6 @@ def remixes(request, username, sound_id): else: tvars.update({'sound': sound}) return render(request, 'sounds/modal_remix_group.html', tvars) - - -@redirect_if_beastwhoosh('front-page') -def remixed(request): - # NOTE: the page listing remix groups no longer exists in the new UI. Instead, users can filter - # search queries by "remixed" property - qs = RemixGroup.objects.all().order_by('-group_size') - tvars = dict() - tvars.update(paginate(request, qs, settings.SOUND_COMMENTS_PER_PAGE)) - return render(request, 'sounds/remixed.html', tvars) - - -@redirect_if_beastwhoosh('front-page') -def remix_group(request, group_id): - # NOTE: there is no dedicated page to a remix group in the new UI, instead, users can open a modal and - # show the remix group of a particular sound - tvars = _remix_group_view_helper(request, group_id) - return render(request, 'sounds/remixes.html', tvars) @redirect_if_old_username_or_404 diff --git a/tags/views.py b/tags/views.py index 7134d10b8..a559bd483 100644 --- a/tags/views.py +++ b/tags/views.py @@ -30,7 +30,7 @@ from follow import follow_utils from search.views import search_view_helper from tags.models import Tag, FS1Tag -from utils.frontend_handling import render, using_beastwhoosh +from utils.frontend_handling import using_beastwhoosh from utils.search import SearchEngineException from utils.search.search_sounds import perform_search_engine_query diff --git a/templates/404.html b/templates/404.html index ca6857e46..6bbd6db72 100644 --- a/templates/404.html +++ b/templates/404.html @@ -1,7 +1,9 @@ -{% extends "base.html" %} +{% extends "simple_page.html" %} -{% block content %} -

Page not found

+{% block title %}Page not found{% endblock %} +{% block page-title %}Page not found{% endblock %} + +{% block page-content %}

It seems that either we've pointed you in the wrong direction or misplaced something -or- that you've requested a page that doesn't exist. Either way, you've reached a dead end.

We recommend you click the browser's back button and curse at the screen for a minute. Then listen to some of Freesound's diff --git a/templates/429.html b/templates/429.html index 56e61b464..e959c30b9 100644 --- a/templates/429.html +++ b/templates/429.html @@ -1,7 +1,9 @@ -{% extends "base.html" %} +{% extends "simple_page.html" %} -{% block content %} -

Not so fast, cowboy

+{% block title %}Not so fast, cowboy{% endblock %} +{% block page-title %}Not so fast, cowboy{% endblock %} + +{% block page-content %}

It seems that either we've pointed you in the wrong direction or that you're trying to access a page and our server refuse to respond. Maybe you're trying to navigate Freesound too fast?

Please take your time with each page, make sure you listen to all of the nice sounds before moving diff --git a/templates/500.html b/templates/500.html index d91f6f5be..141e7d862 100644 --- a/templates/500.html +++ b/templates/500.html @@ -1,183 +1,98 @@ - - - - - - - Freesound - 500 Internal Server Error - - - - - - -

+ + \ No newline at end of file diff --git a/templates/accounts/_notab.html b/templates/accounts/_notab.html deleted file mode 100644 index c2d683764..000000000 --- a/templates/accounts/_notab.html +++ /dev/null @@ -1,10 +0,0 @@ -{% extends "base.html" %} - -{% block content %} -
- -{% block section_content %} -{% endblock %} - -
-{% endblock %} diff --git a/templates/accounts/_people.html b/templates/accounts/_people.html deleted file mode 100644 index c31e579df..000000000 --- a/templates/accounts/_people.html +++ /dev/null @@ -1,12 +0,0 @@ -{% extends "base.html" %} - -{% block tab_people_active %}active_tab{% endblock %} - -{% block content %} -
- -{% block section_content %} -{% endblock %} - -
-{% endblock %} diff --git a/templates/accounts/_section.html b/templates/accounts/_section.html deleted file mode 100644 index 3397a8412..000000000 --- a/templates/accounts/_section.html +++ /dev/null @@ -1,12 +0,0 @@ -{% extends "base.html" %} - -{% block tab_home_active %}active_tab{% endblock %} - -{% block content %} -
- -{% block section_content %} -{% endblock %} - -
-{% endblock %} diff --git a/templates/accounts/account.html b/templates/accounts/account.html index 37bc4ffdb..b51c8f52f 100644 --- a/templates/accounts/account.html +++ b/templates/accounts/account.html @@ -1,392 +1,206 @@ -{% extends "accounts/_notab.html" %} +{% extends "base.html" %} {% load display_sound %} -{% load tags %} +{% load display_pack %} +{% load static %} {% load filter_img %} -{% load maps_js_scripts %} - -{% block title %}{% if home %}home{% else %}{{user.username}}{% endif %}{% endblock %} - -{% block head %} - {{ block.super }} - {% maps_js_scripts %} -{% endblock head %} - -{% block tab_home_active %}{% if home %}active_tab{% endif %}{% endblock %} -{% block tab_people_active %}{% if not home %}active_tab{% endif %}{% endblock %} - -{% block section_content %} - - - - {% if home %} - -

Home

- -
- -
- - -
-
- {% else %} - -

{{user.username}}

- - {% if user.profile and not user.profile.is_anonymized_user %} - -
+{% load bw_templatetags %} +{% load tags %} +{% load util %} +{% load cache %} - +{% block title %}{{ user.username }}{% endblock %} - {% if request.user.is_authenticated %} - {# don't allow a user to follow himself/herself #} - {% if user.username != request.user.username and not show_unfollow_button %} - +{% block content %} +
+