Dynastie/views.py

591 lines
18 KiB
Python

import os
from datetime import datetime, date, time
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.http import HttpResponseRedirect, HttpResponse, Http404
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from django.forms.models import inlineformset_factory
from dynastie.models import *
from dynastie.forms import *
from django.template.defaultfilters import register
from django.template import Variable, VariableDoesNotExist
@register.filter
def hash(object, attr):
pseudo_context = { 'object' : object }
try:
value = Variable('object.%s' % attr).resolve(pseudo_context)
except VariableDoesNotExist:
value = None
return value
def have_I_right(request, blog_id=None, post_id=None):
b = None
p = None
if not post_id is None:
p = Post.objects.filter(pk=post_id)
if p is None:
raise Http404
p = p[0]
blog_id = p.blog.id
if not blog_id is None:
if not request.user.is_superuser:
b = Blog.objects.filter(pk=blog_id).filter(writers=request.user.id)[0]
else:
b = Blog.objects.get(pk=post.blog.id)
if b is None:
raise Http404
b = b
return (b, p)
def index(request):
if request.user.is_authenticated():
return HttpResponseRedirect('/blog')
login_failed = False
if 'login' in request.POST:
user = authenticate(username=request.POST['login'], password=request.POST['password'])
if user is None:
login_failed = True
else:
login(request, user)
print request.GET
if 'next' in request.GET:
return HttpResponseRedirect(request.GET['next'])
else:
return HttpResponseRedirect('/blog')
c = {'auth_key': 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',\
'login_failed' : login_failed}
return render(request, 'templates/login.html', c)
def disconnect(request):
logout(request)
c = {'auth_key': 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA',\
'login_failed' : False}
return HttpResponseRedirect('/')
@login_required
def user(request):
users = User.objects.all()
c = {'users' : users}
return render(request, 'templates/user.html', c)
@login_required
def add_user(request):
if not request.user.is_superuser:
return HttpResponseRedirect('/user')
if request.method == 'POST': # If the form has been submitted...
if 'add' in request.POST:
form = UserForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form = form.save()
user = User.objects.get(pk=form.id)
user.set_password(request.POST['password'])
user.save()
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/user') # Redirect after POST
else:
return HttpResponseRedirect('/user') # Redirect after POST
else:
form = UserForm() # An unbound form
return render(request, 'add_user.html', {
'form': form,
})
@login_required
def edit_user(request, user_id):
user = User.objects.get(pk=user_id)
if user is None:
raise Http404
edited = False
if request.method == 'POST': # If the form has been submitted...
if int(user_id) != int(request.user.id) and (not request.user.is_superuser):
return HttpResponseRedirect('/user/' + str(user_id))
if 'edit' in request.POST:
form = UserForm(request.POST, instance=user, initial={'password':''}) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
if request.POST['password'] != '':
user.set_password(request.POST['password'])
user.save()
edited = True
else:
if 'delete' in request.POST and request.user.is_superuser:
User.objects.get(pk=user_id).delete()
return HttpResponseRedirect('/user')
if 'cancel' in request.POST:
return HttpResponseRedirect('/user')
else:
form = UserForm(instance=user, initial={'password':''}) # An unbound form
c = {'user_to_edit' : user, 'form' : form, 'edited' : edited}
return render(request, 'templates/edit_user.html', c)
@login_required
def category(request):
categories = Category.objects.all()
c = {'categories' : categories}
return render(request, 'templates/category.html', c)
@login_required
def add_category(request):
if not request.user.is_superuser:
return HttpResponseRedirect('/category')
if request.method == 'POST': # If the form has been submitted...
if 'add' in request.POST:
form = CategoryForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form = form.save()
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/category') # Redirect after POST
else:
return HttpResponseRedirect('/category') # Redirect after POST
else:
form = CategoryForm() # An unbound form
return render(request, 'add_category.html', {
'form': form,
})
@login_required
def edit_category(request, category_id):
category = Category.objects.get(pk=category_id)
if category is None:
raise Http404
if request.method == 'POST': # If the form has been submitted...
if 'cancel' in request.POST:
return HttpResponseRedirect('/category')
if 'edit' in request.POST and request.user.is_superuser:
name = category.name
form = CategoryForm(request.POST, instance=category) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
if request.POST['name'] != name:
category.remove()
form.save()
else:
form = CategoryForm(instance=category) # An unbound form
c = {'category' : category, 'form' : form}
return render(request, 'templates/edit_category.html', c)
@login_required
def delete_category(request, category_id):
if not request.user.is_superuser:
return HttpResponseRedirect('/category/' + str(category_id))
category = Category.objects.get(pk=category_id)
if category is None:
raise Http404
category.remove()
category.delete()
return HttpResponseRedirect('/category')
@login_required
def blog(request):
if request.user.is_superuser:
b = Blog.objects.all()
else:
b = Blog.objects.filter(writers=request.user.id)
c = {'blogs' : b}
return render(request, 'templates/blog.html', c)
@login_required
def add_blog(request):
if not request.user.is_superuser:
return HttpResponseRedirect('/blog')
if request.method == 'POST': # If the form has been submitted...
if 'add' in request.POST:
form = BlogForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form = form.save()
form.create()
return HttpResponseRedirect('/blog') # Redirect after POST
else:
return HttpResponseRedirect('/blog') # Redirect after POST
else:
form = BlogForm() # An unbound form
return render(request, 'add_blog.html', {
'form': form,
})
@login_required
def view_blog(request, blog_id):
if not request.user.is_superuser:
b = Blog.objects.filter(id=blog_id).filter(writers=request.user.id)
else:
b = Blog.objects.get(pk=blog_id)
if b is None:
raise Http404
posts = Post.objects.filter(blog=b).order_by('-creation_date')
b = Blog.objects.get(pk=blog_id)
form = BlogForm(instance=b)
comments = Comment.objects.all()
dict_comments = {}
for comment in comments:
if not str(comment.post.id) in dict_comments:
dict_comments[str(comment.post.id)] = 1
else:
dict_comments[str(comment.post.id)] = dict_comments[comment.post.id] + 1
c = {'blog' : b, 'posts' : posts, 'form' : form, 'comments' : dict_comments}
return render(request, 'templates/view_blog.html', c)
@login_required
def edit_blog(request, blog_id):
if not request.user.is_superuser:
return HttpResponseRedirect('/blog/' + str(blog_id))
b = Blog.objects.get(pk=blog_id)
if b is None:
raise Http404
if request.method == 'POST': # If the form has been submitted...
if 'edit' in request.POST:
form = BlogForm(request.POST, instance=b) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form.save()
else:
if 'delete' in request.POST:
b = Blog.objects.get(pk=blog_id)
b.delete()
return HttpResponseRedirect('/blog')
else:
form = BlogForm(instance=b) # An unbound form
posts = Post.objects.filter(blog=b).order_by('-creation_date')
c = {'blog' : b, 'posts' : posts, 'form' : form}
return render(request, 'templates/view_blog.html', c)
@login_required
def add_post(request, blog_id):
if not request.user.is_superuser:
(b,) = have_I_right(request, blog_id)
if request.method == 'POST': # If the form has been submitted...
if 'add' in request.POST:
post = Post(blog=Blog.objects.get(pk=blog_id), author=User.objects.get(pk=request.user.id), creation_date=datetime.now(), modification_date=datetime.now())
content = request.POST['content']
# del request.POST['content']
form = PostForm(request.POST, instance=post) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form = form.save()
form.createPost(content)
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/blog/' + blog_id) # Redirect after POST
else:
return HttpResponseRedirect('/blog/' + blog_id) # Redirect after POST
else:
form = PostForm() # An unbound form
return render(request, 'add_post.html', {
'form': form, 'blog_id' : blog_id
})
@login_required
def edit_post(request, post_id):
(b, post) = have_I_right(request, None, post_id)
post = Post.objects.get(pk=post_id)
title = post.title
blog_id = b.id
if request.method == 'POST': # If the form has been submitted...
if 'edit' in request.POST:
post.modification_date = datetime.now()
form = PostForm(request.POST, instance=post) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
if title != request.POST['title']:
post.remove()
post.createPost(request.POST['content'])
form.save()
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/blog/' + str(blog_id)) # Redirect after POST
else:
if 'cancel' in request.POST:
return HttpResponseRedirect('/blog/' + str(blog_id)) # Redirect after POST
else:
form = PostForm(instance=post) # An unbound form
b.create_paths()
filename = b.src_path + '/_post/' + str(post.pk)
if os.path.exists(filename):
f = open(filename, 'rb')
content = f.read()
f.close()
else:
content = 'Empty post'
comments = Comment.objects.filter(post=post).order_by('date')
comment_list_list = []
for comment in comments:
print comment.date
try:
if comment.parent.id is None:
comment_list_list.append([comment])
else:
for comment_list in comment_list_list:
if comment_list[0] == comment.parent:
comment_list[0].append(comment)
break
except Comment.DoesNotExist:
comment_list_list.append([comment])
return render(request, 'edit_post.html', {
'form': form, 'post_id' : post_id, 'content' : content,
'blog_id' : blog_id, 'comments' : comment_list_list
})
@login_required
def delete_post(request, post_id):
(b, post) = have_I_right(request, None, post_id)
blog_id = b.id
post.delete()
return HttpResponseRedirect('/blog/' + str(blog_id))
@login_required
def generate(request, blog_id):
(b, post) = have_I_right(request, blog_id)
b.create_paths()
report = b.generate()
posts = Post.objects.filter(blog=b).order_by('-creation_date')
b = Blog.objects.get(pk=blog_id)
form = BlogForm(instance=b)
c = {'blog' : b, 'posts' : posts, 'form' : form, 'report': report}
return render(request, 'templates/generate.html', c)
@login_required
def preview(request, blog_id):
from dynastie.generators import post
values = {'title' : request.POST['title'], \
'author' : request.user.first_name + ' ' + request.user.last_name, \
'content' : request.POST['content']
}
(b, ) = have_I_right(request, blog_id)
b.create_paths()
engine = globals()['post']
for name, obj in inspect.getmembers(engine):
if inspect.isclass(obj) and obj.__module__.startswith("dynastie") \
and obj.__module__.endswith("post"):
e = obj()
content = e.preview(b.src_path, values)
break
output = b.output_path
path = output + '/preview.html'
if os.path.exists(path):
os.unlink(path)
f = open(path, 'wb')
f.write(content)
f.close()
c = {'content' : content}
return HttpResponseRedirect('http://' + b.name + '/preview.html')
# return HttpResponseRedirect('http://' + 'localhost:8080' + '/preview.html')
def _tinymcelist(request, b, year, month):
ret = 'var tinyMCEImageList = new Array('
b.create_paths()
if month < 10:
suffix = '/images/' + str(year) + '/0' + str(month)
else:
suffix = '/images/' + str(year) + '/' + str(month)
path = b.src_path + '/' + suffix
# url = 'http://' + 'localhost:8080' + '/' + suffix + '/'
url = 'http://' + b.name + '/' + suffix + '/'
if os.path.exists(path):
files = ''
for p in os.listdir(path):
files += '["' + p + '", "' + url + p + '"],'
# Remove last comma
if len(files) != 0:
ret += files[:-1]
ret += ');'
return ret
@login_required
def tinymcelist_add(request, blog_id):
now = datetime.now()
year = now.year
month = now.month
try:
(b, ) = have_I_right(request, blog_id)
except Http404:
return HttpResponse('', content_type='application/x-javascript')
ret = _tinymcelist(request, b, year, month)
return HttpResponse(ret, content_type='application/x-javascript')
@login_required
def tinymcelist_edit(request, post_id):
try:
(b, post) = have_I_right(request, None, post_id)
except Http404:
return HttpResponse('', content_type='application/x-javascript')
year = post.creation_date.year()
month = post.creation_date.month()
ret = _tinymcelist(request, b, year, month)
return HttpResponse(ret, content_type='application/x-javascript')
@csrf_exempt
def add_comment(request, post_id, parent_id):
from dynastie.generators import post
ref = request.META['HTTP_REFERER']
post = Post(pk=post_id)
if post is None:
return HttpResponseRedirect(ref)
blog = post.blog
if parent_id != 0:
parentComment = Comment(pk=parent_id)
if parentComment is None:
return HttpResponseRedirect(ref)
else:
parentComment = None
if request.POST['author'] == '' or request.POST['the_comment'] == '':
print 'Error on author or the_comment'
return HttpResponseRedirect(ref)
comment = Comment(post=post, parent=parentComment, date=datetime.now(), author=request.POST['author'],\
email=request.POST['email'], the_comment=request.POST['the_comment'])
comment.save()
engine = globals()['post']
blog.create_paths()
for name, obj in inspect.getmembers(engine):
if inspect.isclass(obj) and obj.__module__.startswith("dynastie") \
and obj.__module__.endswith("post"):
e = obj()
content = e.generate(blog, b.src_path, b.output_path, post)
break
# Send emails
return HttpResponseRedirect(ref)
@login_required
def edit_comment(request, comment_id):
comment = Comment(pk=comment_id)
if comment is None:
return Http404
(b, post) = have_I_right(request, None, comment.post.id)
post_id = post.id
if request.method == 'POST': # If the form has been submitted...
if 'edit' in request.POST:
form = UserForm(request.POST) # A form bound to the POST data
if form.is_valid(): # All validation rules pass
form = form.save()
user = User.objects.get(pk=form.id)
user.set_password(request.POST['password'])
user.save()
# Process the data in form.cleaned_data
# ...
return HttpResponseRedirect('/post/edit/' + str(post_id))
else:
return HttpResponseRedirect('/post/edit/' + str(post_id))
else:
form = CommentForm() # An unbound form
return render(request, 'edit_comment.html', {
'form': form, 'comment':comment
})
@login_required
def delete_comment(request, comment_id):
comment = Comment(pk=comment_id)
if comment is None:
return Http404
(b, post) = have_I_right(request, None, comment.post.id)
post_id = post.id
childs = Comment.objects.filter(parent=comment)
for child in childs:
child.parent = comment.parent
child.save()
comment.delete()
return HttpResponseRedirect('/post/edit/' + str(post_id))