Skip to content

Commit

Permalink
fixes for isort, flake8, black, broken postgres tests (#184)
Browse files Browse the repository at this point in the history
* fixes for isort, flake8, black

* fix broken test

* fix unit test

* fix coding style

---------

Co-authored-by: lcduong <[email protected]>
  • Loading branch information
it-tma-tri and lcduong committed Aug 27, 2024
1 parent 1d10de6 commit b66574d
Show file tree
Hide file tree
Showing 34 changed files with 348 additions and 242 deletions.
8 changes: 8 additions & 0 deletions doc/administrator/commands.rst
Original file line number Diff line number Diff line change
Expand Up @@ -192,3 +192,11 @@ This command generates new migration files for database changed. It should ONLY
be used during pretalx development, even if you are running a custom
installation, or if the console output of pretalx tells you to run it in case
of changes to database models.

``create_social_apps``
~~~~~~~~~~~~~~~~~~~~~~~
This command is used to create SocialApp entries for Eventyay-ticket Provider

``sync_customer_account``
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This command is used to sync customer accounts from Eventyay Ticket
2 changes: 1 addition & 1 deletion doc/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@
htmlhelp_basename = 'pretalxdoc'

# Example configuration for intersphinx: refer to the Python standard library.
intersphinx_mapping = {'https://docs.python.org/': None}
intersphinx_mapping = {'https://docs.python.org/': ('https://docs.python.org/3', None)}

linkcheck_ignore = [
'https://pretalx.yourdomain.com',
Expand Down
4 changes: 2 additions & 2 deletions doc/developer/plugins/general.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,13 @@ Core
----

.. automodule:: pretalx.common.signals
:members: periodic_task, register_locales
:members: periodic_task, register_locales, register_data_exporters, register_my_data_exporters

.. automodule:: pretalx.submission.signals
:members: submission_state_change

.. automodule:: pretalx.schedule.signals
:members: schedule_release
:members: schedule_release, register_my_data_exporters

.. automodule:: pretalx.mail.signals
:members: register_mail_placeholders, queuedmail_post_send
Expand Down
9 changes: 5 additions & 4 deletions src/pretalx/agenda/views/schedule.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,9 @@ def get_exporter(self, request):
exporter = (
exporter[len("export.") :] if exporter.startswith("export.") else exporter
)
responses = (register_data_exporters.send(request.event)
+ register_my_data_exporters.send(request.event))
responses = register_data_exporters.send(
request.event
) + register_my_data_exporters.send(request.event)
for __, response in responses:
ex = response(request.event)
if ex.identifier == exporter:
Expand All @@ -114,8 +115,8 @@ def get(self, request, *args, **kwargs):

exporter.schedule = self.schedule
if "-my" in exporter.identifier and self.request.user.id is None:
if request.GET.get('talks'):
exporter.talk_ids = request.GET.get('talks').split(',')
if request.GET.get("talks"):
exporter.talk_ids = request.GET.get("talks").split(",")
else:
return HttpResponseRedirect(self.request.event.urls.login)
favs_talks = SubmissionFavourite.objects.filter(user=self.request.user.id)
Expand Down
8 changes: 4 additions & 4 deletions src/pretalx/agenda/views/talk.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,13 @@ def get_permission_object(self):

def get_contrast_color(self, bg_color):
if not bg_color:
return ''
bg_color = bg_color.lstrip('#')
return ""
bg_color = bg_color.lstrip("#")
r = int(bg_color[0:2], 16)
g = int(bg_color[2:4], 16)
b = int(bg_color[4:6], 16)
brightness = (r * 299 + g * 587 + b * 114) / 1000
return 'black' if brightness > 128 else 'white'
return "black" if brightness > 128 else "white"

@cached_property
def recording(self):
Expand Down Expand Up @@ -104,7 +104,7 @@ def get_context_data(self, **kwargs):
.select_related("room")
)
ctx["submission_tags"] = self.submission.tags.all()
for tag_item in ctx['submission_tags']:
for tag_item in ctx["submission_tags"]:
tag_item.contrast_color = self.get_contrast_color(tag_item.color)
result = []
other_slots = (
Expand Down
4 changes: 2 additions & 2 deletions src/pretalx/api/serializers/speaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,12 @@ def get_avatar(obj):

@staticmethod
def get_avatar_source(obj):
if obj.user.has_avatar and obj.user.avatar_source != '':
if obj.user.has_avatar and obj.user.avatar_source != "":
return obj.user.avatar_source

@staticmethod
def get_avatar_license(obj):
if obj.user.has_avatar and obj.user.avatar_license != '':
if obj.user.has_avatar and obj.user.avatar_license != "":
return obj.user.avatar_license

@staticmethod
Expand Down
4 changes: 3 additions & 1 deletion src/pretalx/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,7 @@
path("me", user.MeView.as_view(), name="user.me"),
path("auth/", obtain_auth_token),
path("events/<event>/", include(event_router.urls)),
path("events/<event>/favourite-talk/", submission.SubmissionFavouriteView.as_view()),
path(
"events/<event>/favourite-talk/", submission.SubmissionFavouriteView.as_view()
),
]
96 changes: 60 additions & 36 deletions src/pretalx/api/views/submission.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import datetime as dt
import json
import jwt
import logging
import datetime as dt
import requests

import jwt
import requests
from django.db import IntegrityError
from django.http import Http404, JsonResponse
from django.shortcuts import get_object_or_404
Expand All @@ -13,8 +13,7 @@
from django.views.decorators.csrf import csrf_exempt
from django_filters import rest_framework as filters
from django_scopes import scopes_disabled
from rest_framework import viewsets, status
from rest_framework.views import APIView
from rest_framework import status, viewsets
from rest_framework.authentication import get_authorization_header

from pretalx.api.serializers.submission import (
Expand All @@ -25,20 +24,25 @@
SubmissionSerializer,
TagSerializer,
)
from pretalx.schedule.models import Schedule
from pretalx.common import exceptions
from pretalx.person.models import User
from pretalx.schedule.models import Schedule
from pretalx.submission.models import Submission, SubmissionStates, Tag
from pretalx.submission.models.submission import SubmissionFavourite, \
SubmissionFavouriteSerializer
from pretalx.submission.models.submission import (
SubmissionFavourite,
SubmissionFavouriteSerializer,
)

with scopes_disabled():

class SubmissionFilter(filters.FilterSet):
state = filters.MultipleChoiceFilter(choices=SubmissionStates.get_choices())

class Meta:
model = Submission
fields = ("state", "content_locale", "submission_type")


logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -168,13 +172,16 @@ def get(self, request, *args, **kwargs) -> JsonResponse:
# user_id = 52
fav_talks = get_object_or_404(SubmissionFavourite, user=user_id)
return JsonResponse(fav_talks.talk_list, safe=False)
except Http404 as e:
except Http404:
# As user not have any favourite talk yet
return JsonResponse([], safe=False)
except Exception as e:
logger.error(f"unexpected error happened: {str(e)}")
return JsonResponse({'error': str(e)}, safe=False,
status=status.HTTP_503_SERVICE_UNAVAILABLE)
return JsonResponse(
{"error": str(e)},
safe=False,
status=status.HTTP_503_SERVICE_UNAVAILABLE,
)

@staticmethod
def post(request, *args, **kwargs) -> JsonResponse:
Expand All @@ -184,49 +191,61 @@ def post(request, *args, **kwargs) -> JsonResponse:
try:
user_id = request.user.id
if user_id is None:
user_id = SubmissionFavouriteView.get_user_from_token(request, request.event.venueless_settings)
user_id = SubmissionFavouriteView.get_user_from_token(
request, request.event.venueless_settings
)
talk_list = json.loads(request.body.decode())
talk_list_valid = []
for talk in talk_list:
with scopes_disabled():
if Submission.objects.filter(code=talk).exists():
talk_list_valid.append(talk)

data = {
"user": user_id,
"talk_list": talk_list_valid
}
data = {"user": user_id, "talk_list": talk_list_valid}
serializer = SubmissionFavouriteSerializer(data=data)
if serializer.is_valid():
fav_talks = serializer.save(user_id, talk_list_valid)
# call to video for update favourite talks
token = SubmissionFavouriteView.get_user_video_token(request.user.code,
request.event.venueless_settings)
token = SubmissionFavouriteView.get_user_video_token(
request.user.code, request.event.venueless_settings
)
video_url = request.event.venueless_settings.url + "favourite-talk/"
header = {
"Content-Type": "application/json",
"Authorization": f"Bearer {token}"
"Authorization": f"Bearer {token}",
}
requests.post(video_url, data=json.dumps(talk_list_valid), headers=header)
requests.post(
video_url, data=json.dumps(talk_list_valid), headers=header
)
else:
logger.error(f"Validation error: {serializer.errors}")
return JsonResponse({'error': serializer.errors}, safe=False,
status=status.HTTP_400_BAD_REQUEST)
return JsonResponse(
{"error": serializer.errors},
safe=False,
status=status.HTTP_400_BAD_REQUEST,
)

return JsonResponse(fav_talks.talk_list, safe=False,
status=status.HTTP_200_OK)
return JsonResponse(
fav_talks.talk_list, safe=False, status=status.HTTP_200_OK
)

except Http404:
logger.info("User not login yet, so can't add favourite talks.")
return JsonResponse('user_not_logged_in', safe=False, status=status.HTTP_400_BAD_REQUEST)
return JsonResponse(
"user_not_logged_in", safe=False, status=status.HTTP_400_BAD_REQUEST
)
except IntegrityError as e:
logger.error(f"Integrity error: {str(e)}")
return JsonResponse({'error': str(e)}, safe=False,
status=status.HTTP_400_BAD_REQUEST)
return JsonResponse(
{"error": str(e)}, safe=False, status=status.HTTP_400_BAD_REQUEST
)
except Exception as e:
logger.error(f"Unexpected error: {str(e)}")
return JsonResponse({'error': str(e)}, safe=False,
status=status.HTTP_503_SERVICE_UNAVAILABLE)
return JsonResponse(
{"error": str(e)},
safe=False,
status=status.HTTP_503_SERVICE_UNAVAILABLE,
)

@staticmethod
def get_user_video_token(user_code, video_settings):
Expand All @@ -247,16 +266,21 @@ def get_user_from_token(request, video_settings):
auth_header = get_authorization_header(request).split()
if not auth_header:
raise Http404
if auth_header and auth_header[0].lower() == b'bearer':
if auth_header and auth_header[0].lower() == b"bearer":
if len(auth_header) == 1:
raise exceptions.AuthenticationFailed('Invalid token header. No credentials provided.')
raise exceptions.AuthenticationFailed(
"Invalid token header. No credentials provided."
)
elif len(auth_header) > 2:
raise exceptions.AuthenticationFailed(
'Invalid token header. Token string should not contain spaces.')
token_decode = jwt.decode(auth_header[1], video_settings.secret,
algorithms=["HS256"],
audience=video_settings.audience,
issuer=video_settings.issuer,
"Invalid token header. Token string should not contain spaces."
)
token_decode = jwt.decode(
auth_header[1],
video_settings.secret,
algorithms=["HS256"],
audience=video_settings.audience,
issuer=video_settings.issuer,
)
user_code = token_decode.get("uid")
return get_object_or_404(User, code=user_code).id
19 changes: 11 additions & 8 deletions src/pretalx/cfp/views/user.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import logging
import textwrap
import urllib
import logging

from csp.decorators import csp_update
from django.contrib import messages
Expand All @@ -27,19 +27,19 @@

from pretalx.cfp.forms.submissions import SubmissionInvitationForm
from pretalx.cfp.views.event import LoggedInEventPageMixin
from pretalx.common.exceptions import SendMailException
from pretalx.common.middleware.event import get_login_redirect
from pretalx.common.phrases import phrases
from pretalx.common.views import is_form_bound
from pretalx.common.exceptions import SendMailException
from pretalx.person.forms import LoginInfoForm, SpeakerProfileForm
from pretalx.person.permissions import person_can_view_information
from pretalx.schedule.forms import AvailabilitiesFormMixin
from pretalx.submission.forms import InfoForm, QuestionsForm, ResourceForm
from pretalx.submission.models import Resource, Submission, SubmissionStates


logger = logging.getLogger(__name__)


@method_decorator(csp_update(IMG_SRC="https://www.gravatar.com"), name="dispatch")
class ProfileView(LoggedInEventPageMixin, TemplateView):
template_name = "cfp/event/user_profile.html"
Expand Down Expand Up @@ -403,12 +403,15 @@ def form_valid(self, form):
form.instance.update_review_scores()
if form.instance.pk and "additional_speaker" in form.changed_data:
try:
form.instance.send_invite(to=[form.cleaned_data.get('additional_speaker')],
_from=self.request.user)
form.instance.send_invite(
to=[form.cleaned_data.get("additional_speaker")],
_from=self.request.user,
)
except SendMailException as exception:
logger.warning('Failed to send email with error: %s', exception)
messages.warning(self.request,
phrases.cfp.submission_email_fail)
logger.warning("Failed to send email with error: %s", exception)
messages.warning(
self.request, phrases.cfp.submission_email_fail
)
form.instance.log_action(
"pretalx.submission.update", person=self.request.user
)
Expand Down
4 changes: 4 additions & 0 deletions src/pretalx/common/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ class SubmissionError(Exception):
pass


class AuthenticationFailed(Exception):
pass


class PretalxExceptionReporter(ExceptionReporter):
def get_traceback_text(self): # pragma: no cover
traceback_text = super().get_traceback_text()
Expand Down
2 changes: 1 addition & 1 deletion src/pretalx/common/exporter.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import base64
from io import StringIO, BytesIO
from io import BytesIO, StringIO
from urllib.parse import quote

import qrcode
Expand Down
Loading

0 comments on commit b66574d

Please sign in to comment.