contentmatcher/upload.py

70 lines
2.2 KiB
Python

import tempfile
import os
from flask import (
Blueprint, flash, g, redirect, render_template, request, session, url_for
)
from werkzeug.utils import secure_filename
from auth import login_required
from config import CONFIG
from create_db import User, Card, get_session
import nextcloud_client
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'])
@bp.route("/", methods=["GET", "POST"])
def index():
username = session["username"]
return render_template("menu/upload.html", username=username)
@bp.route('/uploader', methods = ('GET', 'POST'))
def upload_file():
dbsession = get_session()
user_id = session["user_id"]
username = session["username"]
message = ""
if request.method == 'POST':
#flask gets the file
upload = request.files["file"]
filename = secure_filename(upload.filename)
# Is there really a file?
if not filename:
flash('There is no file. Try again?')
return render_template("menu/upload.html", username=username)
script_path = os.path.dirname(os.path.abspath(__file__))
temp_path = os.path.join(script_path, "temp")
# @TODO ne dela za več fajlov
# 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()
nc.put_file("/GIA CLOUD/" + filename, path)
os.remove(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()
return render_template("menu/upload.html", message=message, user_id=user_id, username=username)