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.

337 lines
12 KiB
Python

7 years ago
"""
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
7 years ago
import json
from functools import wraps
import os
7 years ago
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
7 years ago
from urllib.parse import quote as urlquote
from app.extractText import extract_text
7 years ago
from os import environ
from flask_socketio import SocketIO, emit
from datetime import datetime
7 years ago
import time
from csv import DictWriter, DictReader
import io
from sqlalchemy.inspection import inspect
import sys
7 years ago
from werkzeug.utils import secure_filename
7 years ago
# import sqlite3
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'epub', 'chm', 'mobi', "png", "mp3"])
7 years ago
location_schema = LocationSchema()
locations_schema = LocationSchema(many=True)
7 years ago
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)
7 years ago
@app.route('/', methods= ['POST','GET'])
7 years ago
def home():
server = request.host
2 years ago
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)
7 years ago
2 years ago
@app.route('/listlocations', methods= ['POST','GET'])
def list_locations():
locations = db.session.query(Location).all()
serialized = [location_schema.dump(location) for location in locations]
2 years ago
return render_template('list.html',domain=DOMAIN, locations = locations, data_locations = serialized)
@app.route('/hello/<name>')
def hello(name):
return "Hello " + name
7 years ago
@app.route('/test/<lng>/<lat>/', methods=['POST', 'GET'])
def test(lng, lat):
return lng +" " +lat
7 years ago
@app.route('/addhangout/<float:lng>/<float:lat>/', methods=['POST', 'GET'])
def add_hangout(lng, lat):
upload_form = UploadLocation()
longitude =lng
latitude = lat
2 years ago
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)
2 years ago
@app.route('/addmosquito/<float:lng>/<float:lat>/', methods=['POST', 'GET'])
def add_mosquito(lng, lat):
upload_form = UploadLocation()
longitude =lng
latitude = lat
7 years ago
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)
7 years ago
@app.route('/addtext/<float:lng>/<float:lat>/', methods=['POST', 'GET'])
def addtext(lng, lat):
upload_form = UploadText()
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
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']
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')
2 years ago
@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'))
7 years ago
@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)
7 years ago
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()
7 years ago
if not book:
return render_template('red_link.html', id=id, light=light)
7 years ago
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)
7 years ago
7 years ago
@app.route('/add-book', methods=['POST', 'GET'])
def add_book():
7 years ago
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()
7 years ago
7 years ago
if request.method == 'POST':
7 years ago
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
7 years ago
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):
7 years ago
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)
7 years ago
file.save(fullpath)
cover = get_cover(fullpath, name)
extract_text(fullpath, name)
7 years ago
else:
flash('allowed file formats: %s' % ALLOWED_EXTENSIONS)
#if upload without file -> wishform, with potential PDF
7 years ago
if upload_form.wish.data:
7 years ago
#pdf generator
filename = 'potential.pdf'
file_extension = '.pdf'
cover= 'default_cover.gif'
7 years ago
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()
7 years ago
flash("%s added to the library" % (title))
return redirect(url_for('show_books'))
7 years ago
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)
7 years ago
7 years ago
# 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
))
7 years ago
7 years ago
if __name__ == '__main__':
# socketio.run(app)
app.run(debug=True,host="0.0.0.0",port="8080")