phantasmobile/app/item/views.py
2023-07-24 22:00:43 +01:00

95 lines
2.9 KiB
Python

from datetime import date, datetime, timedelta
import json
from django.utils import timezone
from django.shortcuts import render
from django.db.models import Q
from django.utils.html import mark_safe
from django.conf import settings
from . import models
from . import tasks
from ..signalbot.rpc import send_reaction
from .utils import render_to_json
def index(request):
context = {}
week, archive = models.Item.public()
context['items'] = week
context['archive'] = archive.exists()
return render(request, 'index.html', context)
def archive(request):
context = {}
qs = models.Item.public()
week, archive = models.Item.public()
context['items'] = archive
return render(request, 'archive.html', context)
def item(request, id):
context = {}
item = models.Item.objects.get(id=id)
context['item'] = item
qs = item.comments.order_by('created')
if not request.user.is_staff:
q = ~Q(published=None)
if request.user.is_authenticated:
q |= Q(user=request.user)
if request.session and request.session.session_key:
q |= Q(session_key=request.session.session_key)
qs = qs.filter(q)
comments = []
for comment in qs:
comments.append(comment.json())
context['comments'] = mark_safe(json.dumps(comments))
user = {}
if request.user.is_staff:
user['is_moderator'] = True
if request.user.is_authenticated:
user['username'] = request.user.username
context['user'] = mark_safe(json.dumps(user))
request.session['item'] = id
return render(request, 'item.html', context)
def comment(request):
response = {}
data = json.loads(request.body)
comment = models.Comment()
comment.item = models.Item.objects.get(id=data['item'])
if request.user.is_authenticated:
comment.user = request.user
if comment.user.has_perm('app.item.can_post_comment'):
comment.published = timezone.now()
else:
comment.name = data['name']
comment.email = data['email']
comment.session_key = request.session.session_key
comment.text = data['text']
comment.save()
if not comment.published:
link = request.build_absolute_uri(comment.item.get_absolute_url())
tasks.notify_moderators.delay(comment.id, link)
response = comment.json()
return render_to_json(response)
def publish_comment(request):
response = {}
data = json.loads(request.body)
if request.user.is_staff:
comment = models.Comment.objects.get(id=data['comment'])
comment.published = timezone.now()
comment.save()
if comment.data.get("moderator_ts"):
account = settings.SIGNAL_ACCOUNT
group = settings.SIGNAL_MODERATORS_GROUP
send_reaction(account, comment.data["moderator_ts"], "🎉", group=group)
response['status'] = 'ok'
else:
response['error'] = 'permission denied'
return render_to_json(response)