You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

340 lines
12 KiB
Python

"""
Flask Documentation: http://flask.pocoo.org/docs/
Jinja2 Documentation: http://jinja.pocoo.org/2/documentation/
Werkzeug Documentation: http://werkzeug.pocoo.org/documentation/
This file creates your application.
"""
from app import app, db, socketio, DOMAIN, light
from flask import Flask, Response, session, render_template, request, redirect, url_for, flash, send_from_directory, jsonify, abort
import json
from functools import wraps
import os
from sqlalchemy.sql.expression import func, select
from sqlalchemy.sql import except_
from sqlalchemy.ext.serializer import loads, dumps
# from app.forms import UploadForm, EditForm, SearchForm, ChatForm, StackForm, AddtoStackForm, EditStackForm
from app.forms import UploadText, UploadAudio, UploadLocation
from app.models import Location, LocationSchema
from app.cover import get_cover
from app.getannot import get_annotations, get_annot_results, get_annot_book
from urllib.parse import quote as urlquote
from app.extractText import extract_text
from os import environ
from flask_socketio import SocketIO, emit
from datetime import datetime
import time
from csv import DictWriter, DictReader
import io
from sqlalchemy.inspection import inspect
import sys
from werkzeug.utils import secure_filename
# import sqlite3
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'epub', 'chm', 'mobi', "png", "mp3"])
location_schema = LocationSchema()
locations_schema = LocationSchema(many=True)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
###
# Routing for your application.
###
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'],
filename)
@app.route('/', methods= ['POST','GET'])
def home():
server = request.host
locations = db.session.query(Location).all()
serialized = [location_schema.dump(location) for location in locations]
return render_template('home.html',domain=DOMAIN, server=server, locations = locations, data_locations = serialized)
@app.route('/listlocations', methods= ['POST','GET'])
def list_locations():
locations = db.session.query(Location).all()
serialized = [location_schema.dump(location) for location in locations]
return render_template('list.html',domain=DOMAIN, locations = locations, data_locations = serialized)
@app.route('/hello/<name>')
def hello(name):
return "Hello " + name
@app.route('/test/<lng>/<lat>/', methods=['POST', 'GET'])
def test(lng, lat):
return lng +" " +lat
@app.route('/addhangout/<float:lng>/<float:lat>/', methods=['POST', 'GET'])
def add_hangout(lng, lat):
upload_form = UploadLocation()
longitude =lng
latitude = lat
if request.method == 'POST':
if upload_form.validate_on_submit():
longitude = upload_form.longitude.data
latitude = upload_form.latitude.data
location = Location(longitude,latitude, "hangout", "", "");
db.session.add(location)
db.session.commit()
return redirect(url_for('home'))
flash_errors(upload_form)
return render_template('addhangout.html', form=upload_form, longitude=longitude, latitude=latitude)
@app.route('/addmosquito/<float:lng>/<float:lat>/', methods=['POST', 'GET'])
def add_mosquito(lng, lat):
upload_form = UploadLocation()
longitude =lng
latitude = lat
if request.method == 'POST':
if upload_form.validate_on_submit():
longitude = upload_form.longitude.data
latitude = upload_form.latitude.data
location = Location(longitude,latitude, "mosquito", "", "");
db.session.add(location)
db.session.commit()
return redirect(url_for('home'))
flash_errors(upload_form)
return render_template('addmosquito.html', form=upload_form, longitude=longitude, latitude=latitude)
@app.route('/addtext/<float:lng>/<float:lat>/', methods=['POST', 'GET'])
def addtext(lng, lat):
upload_form = UploadText()
longitude = lng
latitude = lat
print(longitude)
print(latitude)
if request.method == 'POST':
if upload_form.validate_on_submit():
#get data from form
message = upload_form.message.data
longitude = upload_form.longitude.data
latitude = upload_form.latitude.data
location = Location(longitude,latitude, "message", message, "");
db.session.add(location)
db.session.commit()
return redirect(url_for('home'))
flash_errors(upload_form)
return render_template('addtext.html', form=upload_form, longitude=longitude, latitude=latitude)
@app.route('/addaudio/<float:lng>/<float:lat>/', methods=['POST', 'GET'])
def addaudio(lng, lat):
upload_form = UploadAudio()
if request.method == 'GET':
longitude = lng
latitude = lat
if request.method == 'POST':
if upload_form.validate_on_submit():
#get data from form
message = upload_form.message.data
longitude = upload_form.longitude.data
latitude = upload_form.latitude.data
file = request.files['file']
print(file.filename)
locations = db.session.query(Location).all()
id = len(locations)+1
# Getting the current date and time
dt = datetime.now()
# getting the timestamp
ts = datetime.timestamp(dt)
filename = secure_filename(str(id) + "_" + file.filename) # + str(int(ts))
fullpath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(fullpath)
#add to database
location = Location(longitude,latitude, "audio", message, filename);
db.session.add(location)
db.session.commit()
return redirect(url_for('home'))
flash_errors(upload_form)
return render_template('addaudio.html', form=upload_form, longitude=longitude, latitude=latitude)
@app.route('/privacy/')
def privacy():
"""Render the website's about page."""
return render_template('privacy.html')
@app.route('/questions/')
def questions():
"""Render the website's about page."""
return render_template('questions.html')
@app.route('/about/')
def about():
"""Render the website's about page."""
return render_template('about.html')
@app.route('/location/<int:id>/delete', methods=['POST', 'GET'])
def delete_location(id):
if request.method == 'GET':
Location.query.filter_by(id=id).delete()
db.session.commit()
return redirect(url_for('list_locations'))
@app.route('/books/<int:id>')
def show_book_by_id(id):
book = Book.query.get(id)
all_instances = db.session.query(Instance).all()
previousbook = Book.query.filter_by(id=id - 1).first()
nextbook = Book.query.filter_by(id=id + 1).first()
allbooks = db.session.query(Book).all()
edge = len(allbooks)
if id == 1:
previousbook = None
if id == edge:
nextbook = None
name= book.file
annot = get_annotations()
res = get_annot_book(annot,name)
userin = UserIns.query.filter_by(title="lastViewed").first()
if userin != None:
userin.info = book.title
db.session.commit()
else:
user_info = UserIns("lastViewed", book.title)
db.session.add(user_info)
db.session.commit()
if not book:
return render_template('red_link.html', id=id, light=light)
else:
return render_template('show_book_detail.html', book=book, previousbook = previousbook, nextbook = nextbook, all_instances=all_instances, name=name, annot=annot, res=res, light=light)
@app.route('/add-book', methods=['POST', 'GET'])
def add_book():
upload_form = UploadForm()
allbooks = db.session.query(Book).all()
books_all = len(allbooks)
allauthors = db.session.query(Author).all()
authors_all = len(allauthors)
stacks_all = [s.stack_name for s in db.session.query(Stack.stack_name)]
categories = [r.category for r in db.session.query(Book.category).distinct()]
allpotential = db.session.query(Book).filter(Book.file.contains('potential.pdf')).all()
books_potential = len(allpotential)
earliest = db.session.query(func.min(Book.year_published)).scalar()
latest = db.session.query(func.max(Book.year_published)).scalar()
if request.method == 'POST':
if upload_form.validate_on_submit():
#get data from form
title = upload_form.title.data
authors = upload_form.author.data
category = upload_form.category.data
message = upload_form.message.data
year_published = upload_form.year_published.data
sameness = upload_form.sameness.data
gender = upload_form.gender.data
diversity = upload_form.diversity.data
who = upload_form.who.data
if year_published=="":
year_published = None
#if upload with file
if upload_form.upload.data:
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']
# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)
if file and allowed_file(file.filename):
allbooks = db.session.query(Book).all()
id = len(allbooks)+1
filename = str(id) + "_" + secure_filename(file.filename)
fullpath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
name, file_extension = os.path.splitext(filename)
file.save(fullpath)
cover = get_cover(fullpath, name)
extract_text(fullpath, name)
else:
flash('allowed file formats: %s' % ALLOWED_EXTENSIONS)
#if upload without file -> wishform, with potential PDF
if upload_form.wish.data:
#pdf generator
filename = 'potential.pdf'
file_extension = '.pdf'
cover= 'default_cover.gif'
ptitle = upload_form.title.data
pbook = Potential(ptitle)
db.session.add(pbook)
db.session.commit()
pbooks = Potential.query.all()
template = 'app/templates/potential_pdf.html'
html_string = render_template('potential_pdf.html', pbooks = pbooks)
html = HTML(string=html_string)
html.write_pdf(target='app/uploads/potential.pdf');
book = Book(title, filename, cover, file_extension, category, year_published, message, sameness, diversity, gender, who)
db.session.add(book)
for author in authors:
author_name = author.get("author_name")
if author_name:
a = db.session.query(Author).filter_by(author_name=author_name).first()
if a == None:
a = Author(author_name=author_name)
db.session.add(a)
book.authors.append(a)
i = Instance(request.host, "add")
existing_ip = db.session.query(Instance).filter_by(ip=request.host).first()
if existing_ip:
i.name = existing_ip.name
book.instances.append(i)
db.session.commit()
flash("%s added to the library" % (title))
return redirect(url_for('show_books'))
flash_errors(upload_form)
return render_template('add_book.html', form=upload_form, books_all=books_all, authors_all=authors_all, categories=categories, stacks_all=stacks_all, books_potential=books_potential, earliest=earliest, latest=latest, light=light)
# Flash errors from the form if validation fails
def flash_errors(form):
for field, errors in form.errors.items():
for error in errors:
flash(u"Error in the %s field - %s" % (
getattr(form, field).label.text,
error
))
if __name__ == '__main__':
# socketio.run(app)
app.run(debug=True,host="0.0.0.0",port="8080")