#! -*- coding:utf-8 -*-
# Created by F1renze on 2018/3/18 13:54
__author__ = 'F1renze'
__time__ = '2018/3/18 13:54'
from . import home
from flask import render_template, flash, current_app, redirect, url_for, request, \
abort
from flask_login import login_required, current_user
from app.home.forms import VideoUpload, CommentForm, SearchForm, EditProfileForm
from werkzeug.utils import secure_filename
from app.models import Video, Comment, User, UserLog, VideoTag, Admin
from app import db, cache
import os, uuid, stat
from datetime import datetime
from app import videos, images
from PIL import Image
from app.decorators import admin_required
@home.route('/')
# @cache.cached(30)
def index():
# flash('欢迎!')
page = request.args.get('page', 1, type=int)
if Video.query.all() == None:
pagination = None
videos = None
else:
pagination = Video.query.order_by(Video.add_time.desc()).\
paginate(page, per_page=current_app.config['INDEX_VIDEO_PER_PAGE'], error_out=False)
videos = pagination.items
tags = VideoTag.query.all()
return render_template('home/index.html',
pagination=pagination, videos=videos, tags=tags)
@home.route('/tag/<tagname>')
@cache.cached()
def show_tag(tagname):
page = request.args.get('page', 1, type=int)
tag = VideoTag.query.filter_by(name=tagname).first()
pagination = Video.query.filter_by(tag_id=tag.id).order_by(Video.add_time.desc())\
.paginate(page, per_page=current_app.config['INDEX_VIDEO_PER_PAGE'], error_out=False)
videos = pagination.items
tags = VideoTag.query.all()
return render_template('home/index.html', pagination=pagination,
videos=videos, tags=tags, active=tagname)
@home.route('/user/<username>')
def user(username):
user = User.query.filter_by(username=username).first()
if user is None:
abort(404)
newest_comments = user.comments[-2:]
page = request.args.get('page', 1, type=int)
if page == -1:
page = (user.videos.count() - 1) // current_app.config['SEARCH_PER_PAGE'] + 1
pagination = user.videos.paginate(page,
per_page=current_app.config['SEARCH_PER_PAGE'],
error_out=False)
return render_template('home/user.html', user=user, comments=newest_comments, pagination=pagination)
@home.route('/user/edit-profile', methods=['GET', 'POST'])
@login_required
def edit_profile():
form = EditProfileForm(user=current_user)
if form.validate_on_submit():
if not os.path.exists(current_app.config['UPLOADS_DEFAULT_DEST']):
os.makedirs(current_app.config['UPLOADS_DEFAULT_DEST'])
os.chmod(current_app.config['UPLOADS_DEFAULT_DEST'],
stat.S_IRWXU + stat.S_IRGRP + stat.S_IWGRP + stat.S_IROTH)
elif not os.path.exists(current_app.config['IMG_THUMB_DEST']):
os.makedirs(current_app.config['IMG_THUMB_DEST'])
os.chmod(current_app.config['IMG_THUMB_DEST'],
stat.S_IRWXU + stat.S_IRGRP + stat.S_IWGRP + stat.S_IROTH)
if form.avatar.data:
avatar_filename = images.save(form.avatar.data)
size = 50, 50
im = Image.open(os.path.join(current_app.config['UPLOADS_DEFAULT_DEST'], 'images/', avatar_filename))
im.thumbnail(size)
file_split_name = os.path.splitext(avatar_filename)
img_thumb = file_split_name[0] + '_thumbnail' + file_split_name[-1]
im.save(os.path.join(current_app.config['IMG_THUMB_DEST'], img_thumb))
current_user.thumb_head_img = url_for('static', filename='uploads/thumbnails/' + img_thumb)
current_user.head_img = images.url(avatar_filename)
if form.location.data:
current_user.location = form.location.data
if form.phone.data:
current_user.phone = form.phone.data
if form.intro.data:
current_user.info = form.intro.data
current_user.username = form.username.data
db.session.add(current_user)
try:
db.session.commit()
flash('个人资料已经更新!')
except:
flash('未知错误!请重试或联系管理员')
db.session.rollback()
return redirect(url_for('.user', username=current_user.username))
form.username.data = current_user.username
form.phone.data = current_user.phone
form.intro.data = current_user.info
form.location.data = current_user.location
return render_template('home/edit_profile.html', form=form, user=current_user)
@home.route('/user/collections/<username>')
@login_required
def display_collections(username):
if current_user.username != username:
abort(403)
user = User.query.filter_by(username=username).first()
if user is None:
abort(404)
page = request.args.get('page', 1, type=int)
if page == -1:
page = (user.collect_videos.count() - 1) // current_app.config['SEARCH_PER_PAGE'] + 1
pagination = user.collect_videos.paginate(page,
per_page=current_app.config['SEARCH_PER_PAGE'],
error_out=False)
return render_template('home/video_collections.html', user=user, pagination=pagination)
@home.route('/user/collections/uncollect/<int:id>')
@login_required
def user_uncollect(id):
video = Video.query.get_or_404(id)
current_user.uncollect(video)
return redirect(url_for('home.display_collections', username=current_user.username))
@home.route('/video/delete/<int:id>')
@login_required
def delete_video(id):
video = Video.query.get_or_404(id)
name = video.title
if current_user != video.uploader:
abort(403)
db.session.delete(video)
video_file = os.path.join(current_app.config['UPLOADS_DEFAULT_DEST'], 'videos/', video.url)
cover_file = os.path.join(current_app.config['UPLOADS_DEFAULT_DEST'], 'images/', video.cover)
extension = os.path.splitext(video.cover)
thumbnail_name = extension[0] + '_thumbnail' + extension[-1]
thumbnail_file = os.path.join(current_app.config['IMG_THUMB_DEST'], thumbnail_name)
try:
if os.path.exists(video_file):
os.remove(video_file)
if os.path.exists(cover_file):
os.remove(cover_file)
if os.path.exists(thumbnail_file):
os.remove(thumbnail_file)
except:
error_log = UserLog(user=current_user, ip=request.remote_addr, info='删除视频文件失败!')
db.session.add(error_log)
try:
user_log = UserLog(user=current_user, ip=request.remote_addr, info='删除 '+video.title)
db.session.add(user_log)
db.session.commit()
flash('视频[ ' + name + ' ]已经删除')
except:
flash('未知错误!请重试或联系管理员')
db.session.rollback()
return redirect(url_for('.user', username=current_user.username))
@home.route('/comment/delete/<int:id>')
@login_required
def delete_comment(id):
comment = Comment.query.get_or_404(id)
video_id = comment.video_id
if current_user != comment.author:
abort(403)
db.session.delete(comment)
try:
db.session.commit()
flash('评论删除成功')
except:
flash('未知错误!请重试或联系管理员')
db.session.rollback()
finally:
return redirect(url_for('.video', id=video_id))
@home.route('/comment/disable/<int:id>')
@admin_required
def disable_comment(id):
comment = Comment.query.get_or_404(id)
video_id = comment.video_id
comment.disabled = True
db.session.add(comment)
try:
db.session.commit()
flash('已经屏蔽此评论')
except:
flash('未知错误!')
db.session.rollback()
finally:
return redirect(url_for('.video', id=video_id))
@home.route('/comment/enable/