contentmatcher/upload.py

78 lines
2.9 KiB
Python
Raw Normal View History

2022-06-08 19:51:55 +02:00
import tempfile
import os
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
2022-06-08 19:51:55 +02:00
from werkzeug.utils import secure_filename
from auth import login_required
from config import CONFIG
2022-06-14 14:47:12 +02:00
from create_db import User, Card, get_session
import nextcloud_client
import magic
2022-06-08 19:51:55 +02:00
bp = Blueprint('upload', __name__, url_prefix='/upload')
nc = nextcloud_client.Client('https://obzorje.kompot.si')
#print("Loggin in", CONFIG['NC_USER'], CONFIG['NC_PASSWORD'])
nc.login(CONFIG['NC_USER'],CONFIG['NC_PASSWORD'])
2022-06-08 19:51:55 +02:00
@bp.route("/", methods=["GET", "POST"])
def index():
2022-06-07 18:58:57 +02:00
username = session["username"]
2022-08-12 19:51:55 +02:00
return render_template("upload.html", username=username)
2022-06-08 19:51:55 +02:00
@bp.route('/uploader', methods = ('GET', 'POST'))
def upload_file():
2022-06-14 14:47:12 +02:00
dbsession = get_session()
2022-06-07 18:58:57 +02:00
user_id = session["user_id"]
2022-06-08 19:51:55 +02:00
username = session["username"]
if request.method == 'POST':
#@TODO ta forloop bi lahko flashal postopoma
for upload in request.files.getlist("file"):
filename = secure_filename(upload.filename)
# Is there really a file?
if not filename:
flash('There is no file. Try again?')
2022-08-12 19:51:55 +02:00
return render_template("upload.html", username=username)
#prevent duplicate filenames
print(filename)
if dbsession.query(Card).filter(Card.title == filename).first() != None:
flash("Filename already in database, please rename if you want to upload: " + filename, 'error')
continue
script_path = os.path.dirname(os.path.abspath(__file__)) #where are we
temp_path = os.path.join(script_path, "temp") #where is the temp file
# a lot of stuff can wrong here and nobody may know
with tempfile.NamedTemporaryFile(dir=temp_path, delete=False) as fp:
fp.write(upload.stream.read())
path = fp.name
fp.close()
if magic.from_file(path, mime=True) == "application/pdf":
nc.put_file("/GIA CLOUD/" + filename, path)
#get public link
public_link = nc.share_file_with_link("/GIA CLOUD/" + filename).get_link()+"/download/"+filename
#add card
card = Card(title=filename, interest_rate=-1.0, owner_id=user_id, item_location=public_link, last_review=None, share_id=0)
flash(f"{filename} uploaded successfully")
dbsession.add(card)
dbsession.commit()
dbsession.close()
else:
flash("Please insert a PDF file, support for other formats comming soon...")
2022-08-12 19:51:55 +02:00
#return render_template("upload.html", user_id=user_id, username=username)
os.remove(path)
2022-06-08 19:51:55 +02:00
2022-06-08 20:54:50 +02:00
2022-08-12 19:51:55 +02:00
return render_template("upload.html", user_id=user_id, username=username)