Skip to content

Commit

Permalink
Merge branch 'master' into interaction-cooldown
Browse files Browse the repository at this point in the history
  • Loading branch information
leduythuccs authored May 2, 2023
2 parents d65ede2 + d9169b4 commit bffda9b
Show file tree
Hide file tree
Showing 6 changed files with 65 additions and 32 deletions.
3 changes: 2 additions & 1 deletion dmoj/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -536,7 +536,7 @@

BLEACH_USER_SAFE_ATTRS = {
'*': ['id', 'class', 'style', 'data', 'height'],
'img': ['src', 'alt', 'title', 'width', 'height', 'data-src'],
'img': ['src', 'alt', 'title', 'width', 'height', 'data-src', 'align'],
'a': ['href', 'alt', 'title'],
'iframe': ['src', 'height', 'width', 'allow'],
'abbr': ['title'],
Expand All @@ -548,6 +548,7 @@
'audio': ['autoplay', 'controls', 'crossorigin', 'muted', 'loop', 'preload', 'src'],
'video': ['autoplay', 'controls', 'crossorigin', 'height', 'muted', 'loop', 'poster', 'preload', 'src', 'width'],
'source': ['src', 'srcset', 'type'],
'li': ['value'],
}

MARKDOWN_STAFF_EDITABLE_STYLE = {
Expand Down
2 changes: 1 addition & 1 deletion judge/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -460,7 +460,7 @@ def widget_attrs(self, widget):
class TOTPForm(Form):
TOLERANCE = settings.DMOJ_TOTP_TOLERANCE_HALF_MINUTES

totp_or_scratch_code = NoAutoCompleteCharField(required=False)
totp_or_scratch_code = NoAutoCompleteCharField(required=False, widget=forms.TextInput(attrs={'autofocus': True}))

def __init__(self, *args, **kwargs):
self.profile = kwargs.pop('profile')
Expand Down
68 changes: 40 additions & 28 deletions judge/management/commands/import_polygon_package.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from django.conf import settings
from django.contrib.sites.models import Site
from django.core.files import File
from django.core.files.storage import default_storage
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from django.urls import reverse
Expand Down Expand Up @@ -255,23 +256,39 @@ def parse_statements(problem_meta, root, package):
problem_meta['translations'] = []
problem_meta['tutorial'] = ''

image_cache = {}
def process_images(text):
image_cache = problem_meta['image_cache']

def save_image(image_path):
norm_path = os.path.normpath(os.path.join(statement_folder, image_path))
sha1 = hashlib.sha1()
sha1.update(package.open(norm_path, 'r').read())
sha1 = sha1.hexdigest()
def save_image(image_path):
norm_path = os.path.normpath(os.path.join(statement_folder, image_path))
sha1 = hashlib.sha1()
sha1.update(package.open(norm_path, 'r').read())
sha1 = sha1.hexdigest()

if sha1 not in image_cache:
image = File(
file=package.open(norm_path, 'r'),
name=os.path.basename(image_path),
if sha1 not in image_cache:
image = File(
file=package.open(norm_path, 'r'),
name=os.path.basename(image_path),
)
data = json.loads(django_uploader(image))
image_cache[sha1] = data['link']

return image_cache[sha1]

for image_path in set(re.findall(r'!\[image\]\((.+?)\)', text)):
text = text.replace(
f'![image]({image_path})',
f'![image]({save_image(image_path)})',
)
data = json.loads(django_uploader(image))
image_cache[sha1] = data['link']

return image_cache[sha1]
for img_tag in set(re.findall(r'<\s*img[^>]*>', text)):
image_path = re.search(r'<\s*img[^>]+src\s*=\s*(["\'])(.*?)\1[^>]*>', text).group(2)
text = text.replace(
img_tag,
img_tag.replace(image_path, save_image(image_path)),
)

return text

def parse_problem_properties(problem_properties):
description = ''
Expand Down Expand Up @@ -304,20 +321,6 @@ def parse_problem_properties(problem_properties):
description += '\n## Notes\n\n'
description += pandoc_tex_to_markdown(problem_properties['notes'])

# Images
for image_path in set(re.findall(r'!\[image\]\((.+?)\)', description)):
description = description.replace(
f'![image]({image_path})',
f'![image]({save_image(image_path)})',
)

for img_tag in set(re.findall(r'<\s*img[^>]*>', description)):
image_path = re.search(r'<\s*img[^>]+src\s*=\s*(["\'])(.*?)\1[^>]*>', description).group(2)
description = description.replace(
img_tag,
img_tag.replace(image_path, save_image(image_path)),
)

return description

def input_choice(prompt, choices):
Expand Down Expand Up @@ -351,7 +354,7 @@ def input_choice(prompt, choices):
description = parse_problem_properties(problem_properties)
translations.append({
'language': language,
'description': description,
'description': process_images(description),
})

tutorial = problem_properties['tutorial']
Expand All @@ -378,6 +381,9 @@ def input_choice(prompt, choices):
elif len(tutorials) > 0:
problem_meta['tutorial'] = tutorials[0]['tutorial']

# Process images for only the selected tutorial
problem_meta['tutorial'] = process_images(problem_meta['tutorial'])

for t in translations:
language = t['language']
description = t['description']
Expand Down Expand Up @@ -545,6 +551,7 @@ def handle(self, *args, **options):

# A dictionary to hold all problem information.
problem_meta = {}
problem_meta['image_cache'] = {}
problem_meta['code'] = problem_code
problem_meta['tmp_dir'] = tempfile.TemporaryDirectory()
problem_meta['authors'] = problem_authors
Expand All @@ -555,6 +562,11 @@ def handle(self, *args, **options):
parse_statements(problem_meta, root, package)
create_problem(problem_meta)
except Exception:
# Remove imported images
for image_url in problem_meta['image_cache'].values():
path = default_storage.path(os.path.join(settings.MARTOR_UPLOAD_MEDIA_DIR, os.path.basename(image_url)))
os.remove(path)

raise
finally:
problem_meta['tmp_dir'].cleanup()
Expand Down
17 changes: 16 additions & 1 deletion judge/views/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.utils import timezone
from django.utils.decorators import method_decorator
from django.utils.formats import date_format
from django.utils.functional import cached_property
from django.utils.safestring import mark_safe
Expand Down Expand Up @@ -286,9 +287,23 @@ def get_context_data(self, **kwargs):

return context

@method_decorator(require_POST)
def delete_comments(self, request, *args, **kwargs):
if not request.user.is_superuser:
raise PermissionDenied()

user_id = User.objects.get(username=kwargs['user']).id
user = Profile.objects.get(user=user_id)
for comment in Comment.get_newest_visible_comments(viewer=request.user, author=user,
batch=2 * self.paginate_by):
comment.get_descendants(include_self=True).update(hidden=True)
return HttpResponseRedirect(reverse('user_comment', args=(user.user.username,)))

def dispatch(self, request, *args, **kwargs):
if not self.request.user.is_superuser:
raise PermissionDenied()
if request.method == 'POST':
return self.delete_comments(request, *args, **kwargs)
return super().dispatch(request, *args, **kwargs)


Expand Down Expand Up @@ -535,7 +550,7 @@ class UserList(QueryStringSortMixin, InfinitePaginationMixin, DiggPaginatorMixin
paginate_by = 100
all_sorts = frozenset(('points', 'problem_count', 'rating', 'performance_points'))
default_desc = all_sorts
default_sort = '-performance_points'
default_sort = '-rating'

def get_queryset(self):
return (Profile.objects.filter(is_unlisted=False).order_by(self.order)
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ dmoj-wpadmin @ git+https://github.com/DMOJ/dmoj-wpadmin.git
lxml
Pygments<2.12
mistune<2
social-auth-app-django
social-auth-core==4.3.0
social-auth-app-django==5.0.0
pytz
django-statici18n
pika
Expand Down
4 changes: 4 additions & 0 deletions templates/user/comment.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@

{% block body %}
{% block before_comments %}{% endblock %}
<form action="{{url('user_comment', user.username)}}" method="post">
{% csrf_token %}
<button type="submit">Delete all comments</button>
</form>
<ul class="comments top-level-comments new-comments">
{% set logged_in = request.user.is_authenticated %}
{% for comment in comments %}
Expand Down

0 comments on commit bffda9b

Please sign in to comment.