Titivillus/quest/views.py

197 lines
5.9 KiB
Python
Raw Permalink Normal View History

2018-08-10 08:39:51 -04:00
#!/usr/bin/env python3
"""
Quest and quest accessory views.
"""
2018-09-30 15:20:42 -04:00
from datetime import timedelta, datetime, timezone
2018-10-02 13:31:58 -04:00
import bleach
2018-10-12 10:34:57 -04:00
from user_messages import api
2018-10-02 13:31:58 -04:00
from django.views.decorators.http import require_POST
2018-09-25 11:58:07 -04:00
from django.contrib import messages
from django.shortcuts import render, redirect
from django.db.models import F
2018-10-08 10:22:36 -04:00
from django.conf import settings
from django.urls import reverse
2018-08-10 08:39:51 -04:00
2018-10-02 12:38:17 -04:00
from .models import Quest, DiceRoll, PollOption, PollVote, Page, Post
from .forms import EditQuestForm, QuestForm, PostForm
2018-10-03 12:41:38 -04:00
from user.models import User
2018-10-11 09:10:55 -04:00
from .tools import download_img, send_to_websocket
2018-08-13 13:17:51 -04:00
2018-08-10 08:39:51 -04:00
def index(request):
2018-10-03 12:41:38 -04:00
"""The quest page index."""
search_terms = request.GET.get('search_terms')
search_type = request.GET.get('search_type')
2018-10-04 14:44:07 -04:00
tags = request.GET.get('tags')
order_by = request.GET.get('order_by')
order_way = request.GET.get('order_way', 'desc')
order_keys = {
'ceation_date': 'id',
'last_post': 'latest_post_date',
'next_live': 'live_time',
}
order_by = order_keys.get(order_by, 'id')
2018-10-04 14:44:07 -04:00
results = Quest.objects.all()
if search_terms:
if search_type == 'title':
results = results.filter(title__unaccent__icontains=search_terms)
elif search_type == 'author':
results = results.filter(
owner__username__unaccent__icontains=search_terms)
2018-10-04 14:44:07 -04:00
if tags:
results = results.filter(tags__name__in=tags.split()).distinct()
if order_way == 'asc':
results = results.order_by(F(order_by).asc(nulls_last=True))
elif order_way == 'desc':
results = results.order_by(F(order_by).desc(nulls_last=True))
2018-10-03 12:41:38 -04:00
context = locals()
return render(request, 'quest/index.html', context)
2018-08-10 08:39:51 -04:00
2018-10-02 11:35:39 -04:00
def quest(request, quest_id, page_num='0'):
2018-08-10 08:39:51 -04:00
"""
Arbituary quest page view.
"""
2018-09-25 11:58:07 -04:00
# TODO: 404 quest not found
2018-08-13 13:17:51 -04:00
quest = Quest.objects.get(id=quest_id)
2018-09-25 11:58:07 -04:00
pages = Page.objects.filter(
quest=quest, appendix=False).order_by('page_num')
appendices = Page.objects.filter(
quest=quest, appendix=True).order_by('title')
chat_messages = reversed(quest.message_set.all().order_by('-id')[:50])
2018-09-25 11:58:07 -04:00
try:
page = Page.objects.get(quest=quest, page_num=page_num)
except Page.DoesNotExist:
messages.error(request, "Page not found, redirecting you.")
2018-10-01 08:35:24 -04:00
return redirect('quest:quest', quest_id=quest.id, page_num='0')
2018-09-25 11:58:07 -04:00
posts = quest.post_set.filter(page=page)
2018-09-24 13:46:46 -04:00
# TODO: filter by page_num as well
dice_rolls = DiceRoll.objects.filter(dicecall__post__quest=quest)
poll_options = PollOption.objects.filter(poll__post__quest=quest)
poll_votes = PollVote.objects.filter(option__poll__post__quest=quest)
2018-09-03 17:59:41 -04:00
ip_address = request.META['REMOTE_ADDR']
2018-10-08 10:22:36 -04:00
server_user_id = settings.SERVER_USER_ID
2018-08-24 21:51:03 -04:00
context = locals()
2018-10-01 08:35:24 -04:00
if page_num == '0':
return render(request, 'quest/quest_homepage.html', context)
else:
return render(request, 'quest/quest.html', context)
2018-09-05 12:48:24 -04:00
2018-10-02 13:51:58 -04:00
def edit_quest(request, quest_id, page_num='0'):
2018-09-05 12:48:24 -04:00
"""
Edit quest page. Only available to the QM.
"""
quest = Quest.objects.get(id=quest_id)
2018-10-12 10:34:57 -04:00
prev_live = quest.live
2018-09-05 12:48:24 -04:00
if quest.owner != request.user:
return redirect('quest:quest', quest_id=quest_id, page_num=page_num)
if request.method == 'POST':
2018-09-24 08:22:01 -04:00
form = EditQuestForm(request.POST)
2018-09-21 14:18:54 -04:00
if form.is_valid():
quest.title = form.cleaned_data['quest_title']
2018-09-21 14:18:54 -04:00
quest.anon_name = form.cleaned_data['anon_name']
2018-09-30 15:20:42 -04:00
quest.live = form.cleaned_data['live']
quest.description = form.cleaned_data['description']
quest.banner_url = download_img(form.cleaned_data['banner_url'])
if not quest.banner_url.startswith('http'):
quest.banner_url = None
2018-09-30 15:20:42 -04:00
live_date = form.cleaned_data['live_date']
live_time = form.cleaned_data['live_time']
if live_date and live_time:
live_datetime = datetime.combine(
live_date,
live_time,
timezone.utc
)
tz_delta = timedelta(minutes=form.cleaned_data['timezone'])
live_datetime = live_datetime + tz_delta
quest.live_time = live_datetime
else:
quest.live_time = None
2018-09-21 14:18:54 -04:00
quest.save()
data = {
'live': quest.live,
'live_time': quest.live_time,
}
if data['live_time']:
data['live_time'] =data['live_time'].strftime('%Y-%m-%d %H:%M')
send_to_websocket('live', quest_id, data)
2018-10-12 10:34:57 -04:00
if prev_live == False and quest.live == True:
subscribers = quest.user_set.all()
for subscriber in subscribers:
api.info(
subscriber,
f"{quest.title} has gone live!",
extra_tags='subscription',
meta={
'url': reverse(
'quest:quest',
args=(quest.id, 0),
),
},
deliver_once=False,
2018-10-12 10:34:57 -04:00
)
2018-09-21 14:18:54 -04:00
return redirect('quest:quest',quest_id=quest.id, page_num=page_num)
else:
messages.error(request, "Error")
2018-09-05 12:48:24 -04:00
else:
pass
context = locals()
return render(request, 'quest/edit_quest.html', context)
2018-10-02 12:38:17 -04:00
def new_quest(request):
"""
The page for creating new quests.
"""
2018-10-02 13:31:58 -04:00
if not request.user.is_authenticated:
return redirect('login:index')
2018-10-02 12:38:17 -04:00
if request.method == 'POST':
# TODO: clean the post body
quest_form = QuestForm(request.POST)
if quest_form.is_valid():
quest = quest_form.save(commit=False)
quest.owner = request.user
2018-10-11 09:10:55 -04:00
quest.banner_url = download_img(quest.banner_url)
if not quest.banner_url.startswith('http'):
quest.banner_url = None
2018-10-02 12:38:17 -04:00
quest.save()
quest_form.save_m2m()
print(quest.tags.names())
page = Page(
2018-10-02 12:38:17 -04:00
quest=quest,
page_num=0,
title="Homepage",
appendix=False,
)
page.save()
2018-10-02 12:38:17 -04:00
return redirect('quest:quest', quest_id=quest.id)
else:
quest_form = QuestForm()
context = locals()
2018-10-02 12:38:17 -04:00
return render(request, 'quest/new_quest.html', context)
2018-10-02 13:31:58 -04:00
@require_POST
def new_tag(request, quest_id):
"""Endpoint for adding new tags to a quest."""
if not request.user.is_authenticated:
return redirect('login:index')
tag = request.POST.get('tag', '').strip()
if not tag:
return redirect('quest:quest', quest_id=quest_id, page_num='0')
quest = Quest.objects.get(id=quest_id)
tag = bleach.clean(tag)
if tag in quest.tags.names():
return redirect('quest:quest', quest_id=quest_id, page_num='0')
quest.tags.add(tag)
return redirect('quest:quest', quest_id=quest_id, page_num='0')