<filename>blog/views.py
from django.shortcuts import render
from django.shortcuts import get_object_or_404, Http404, redirect, reverse
from .models import Post, Page, Tag
from django.conf import settings
from math import ceil
from .util import verify_hcaptcha, send_mail

# Create your views here.


def index(request):
    posts = Post.objects.order_by('-date_posted').filter(published=True)[:settings.POSTS_PER_PAGE]
    return render(request, 'index.html', context={'posts': posts})


def blog(request):
    tagname = request.GET.get('tag')
    if tagname:
        tag = get_object_or_404(Tag, name=tagname)
        posts = Post.objects.filter(published=True, tags__in=[tag]).order_by('-date_posted')
    else:
        posts = Post.objects.filter(published=True).order_by('-date_posted')

    if not posts:
        raise Http404

    page_count = ceil(posts.count() / settings.POSTS_PER_PAGE)
    page_number = int(request.GET.get('p') or 1)
    if page_number > page_count or page_number < 1:
        raise Http404
    prev_page = None if page_number == 1 else page_number - 1
    next_page = None if page_number == page_count else page_number + 1

    return render(request, 'blog.html', context={
        'active_link': 'blog', 'tagname': tagname,
        'prev_page': prev_page, 'current_page': page_number, 'next_page': next_page,
        'posts': posts[(page_number - 1) * settings.POSTS_PER_PAGE: page_number * settings.POSTS_PER_PAGE],
    })


def post(request, slug):
    post_obj = get_object_or_404(Post, slug=slug, published=True)
    if request.method == 'POST':
        if request.POST.get('password') == post_obj.password:
            request.session[slug] = True
    accessible = (not post_obj.password) or (slug in request.session)
    return render(request, 'post.html', context={'post': post_obj, 'accessible': accessible})


def page(request, slug):
    flat_page = get_object_or_404(Page, slug=slug, published=True)
    return render(request, 'page.html', context={'content': flat_page.content, 'active_link': flat_page.slug})


def contact(request):
    if not settings.SITE_SETTINGS['CONTACT_ENABLED']:
        raise Http404
    if request.method == 'GET':
        return render(request, 'contact.html', context={'errors': {}})
    elif request.method == 'POST':
        errors = {}

        if settings.SITE_SETTINGS['HCAPTCHA_ENABLED']:
            if not verify_hcaptcha(settings.SITE_SETTINGS['HCAPTCHA_SECRET'], request.POST.get('h-captcha-response')):
                errors['hcaptcha'] = True

        if settings.SITE_SETTINGS['PRIVACY_POLICY_SLUG']:
            if not request.POST.get('privacy'):
                errors['privacy'] = True

        if not request.POST.get('name'):
            errors['name'] = True

        if not request.POST.get('email'):
            errors['email'] = True

        if not request.POST.get('subject'):
            errors['subject'] = True

        if not request.POST.get('message'):
            errors['message'] = True

        if not errors:
            success = send_mail(
                settings.SITE_SETTINGS['FROM_EMAIL'],
                settings.SITE_SETTINGS['CONTACT_EMAIL'],
                f"{request.POST.get('name')} - {request.POST.get('subject')}",
                f"{request.POST.get('message')}<hr>{request.POST.get('name')}<br>{request.POST.get('email')}"
            )
            if success:
                return redirect(f"{reverse('contact')}?success=true")
            else:
                errors['error'] = True

        return render(request, 'contact.html', context={'errors': errors})
    raise Http404
