Commit d7480f74 authored by Lukas Böhm's avatar Lukas Böhm
Browse files

moved file operations to models

now files and models appear as one
parent 0a2b503f
from app import db
import os
from flask import current_app
from app import db, app
class Share(db.Model):
......@@ -11,6 +13,45 @@ class Share(db.Model):
files = db.relationship('Attachment', backref='share')
def __repr__(self):
return f'<Share {self.id}>'
def __init__(self, name, expires, download_limit):
# with app.app_context():
# create id
import uuid
share_id = str(uuid.uuid4())
while Share.query.get(share_id) is not None:
share_id = str(uuid.uuid4())
# set attributes
self.id = share_id
self.name = name
self.expires = expires
self.download_limit = download_limit
# create folder
try:
os.makedirs(os.path.join(current_app.config['MEDIA_LOCATION'], share_id))
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
# wrap it up
# db.session.add(self)
# db.session.commit()
def delete(self):
with app.app_context():
# delete files
try:
from shutil import rmtree
rmtree(os.path.join(current_app.config['MEDIA_LOCATION'], self.id))
os.remove(os.path.join(current_app.config['MEDIA_LOCATION'], self.id + '.zip'))
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
# delete from database
for att in self.files:
db.session.delete(att)
db.session.delete(self)
db.session.commit()
class Attachment(db.Model):
__tablename__ = 'Attachment'
......@@ -18,3 +59,19 @@ class Attachment(db.Model):
id = db.Column('ID', db.INTEGER, primary_key=True, unique=True)
filename = db.Column('filename', db.String(), nullable=False)
share_id = db.Column('ShareID', db.String(64), db.ForeignKey('Share.ID'), nullable=False)
def __repr__(self):
return f'<Attachment {self.id}, {self.filename} for Share {self.share_id}>'
def __init__(self, share_id, file):
#with app.app_context():
# set attributes
self.share_id = share_id
self.filename = file.filename
# save file
from werkzeug.utils import secure_filename
fn = secure_filename(filename=file.filename)
file.save(os.path.join(current_app.config['MEDIA_LOCATION'], share_id, fn))
# wrap it up
# db.session.add(self)
# db.session.commit()
import uuid
import os
from datetime import datetime, timedelta
from werkzeug.exceptions import HTTPException
from werkzeug.utils import secure_filename
from app import app, db
from flask import redirect, url_for, render_template, send_from_directory, current_app, abort
from app.models import Share, Attachment
from app.forms import UploadForm
from shutil import rmtree, make_archive
from apscheduler.schedulers.background import BackgroundScheduler
import atexit
from shutil import make_archive
def remove_share(sh):
# delete files
try:
rmtree(os.path.join(current_app.config['MEDIA_LOCATION'], sh.id))
os.remove(os.path.join(current_app.config['MEDIA_LOCATION'], sh.id + '.zip'))
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
# delete from database
for att in sh.files:
db.session.delete(att)
db.session.delete(sh)
db.session.commit()
def remove_expired():
print('cleaning up!')
with app.app_context():
expired_shares = Share.query.filter(datetime.now() > Share.expires).all()
for sh in expired_shares:
remove_share(sh)
sched = BackgroundScheduler(daemon=True)
sched.add_job(remove_expired, 'interval', seconds=10)
sched.start()
atexit.register(lambda: sched.shutdown())
@app.route('/secret')
def secret():
return 'Max wird gecückd'
@app.route('/privacy')
......@@ -71,34 +44,26 @@ def upload():
form = UploadForm()
if form.validate_on_submit():
# generate unique uuid
share_id = str(uuid.uuid4())
while Share.query.get(share_id) is not None:
share_id = str(uuid.uuid4())
# create share object
up = Share(id=share_id, name=form.name.data, expires=datetime.now() + timedelta(minutes=float(form.timer.data)),
download_limit=form.download_limit.data)
db.session.add(up)
# create share folder
try:
os.makedirs(os.path.join(current_app.config['MEDIA_LOCATION'], share_id))
except OSError as e:
print("Error: %s - %s." % (e.filename, e.strerror))
# create attachments
# create share
share = Share(name=form.name.data,
expires=datetime.now() + timedelta(minutes=float(form.timer.data)),
download_limit=form.download_limit.data
)
db.session.add(share)
db.session.flush()
# files
for file in form.files.data:
fn = secure_filename(filename=file.filename)
file.save(os.path.join(current_app.config['MEDIA_LOCATION'], share_id, fn))
att = Attachment(filename=fn, share_id=share_id)
db.session.add(att)
db.session.add(Attachment(share_id=share.id, file=file))
db.session.commit()
# create zip
make_archive(
os.path.join(current_app.config['MEDIA_LOCATION'], up.id),
os.path.join(current_app.config['MEDIA_LOCATION'], share.id),
'zip',
os.path.join(current_app.config['MEDIA_LOCATION'], up.id)
os.path.join(current_app.config['MEDIA_LOCATION'], share.id)
)
# wrap it up
db.session.commit()
return url_for('shared', share_id=share_id)
return url_for('shared', share_id=share.id)
return render_template('Upload.html', form=form)
......@@ -112,34 +77,30 @@ def shared(share_id):
@app.route('/d/<string:share_id>', methods=['GET'])
def download(share_id):
share = Share.query.get_or_404(share_id)
if share.download_limit < 0:
remove_share(share)
return redirect(url_for('expired'))
else:
return render_template('Download.html', up=share)
return render_template('Download.html', up=share)
@app.route('/media/<string:share_id>/<string:filename>', methods=['GET'])
def media(share_id, filename):
share = Share.query.get_or_404(share_id)
share.download_limit -= 1
db.session.commit()
if share.download_limit < 0:
remove_share(share)
return redirect(url_for('expired'))
else:
return send_from_directory(os.path.join(current_app.config['MEDIA_LOCATION'], share_id), filename=filename,
as_attachment=True)
return send_from_directory(os.path.join(current_app.config['MEDIA_LOCATION'], share_id), filename=filename,
as_attachment=True)
@app.route('/zip/<string:share_id>')
def zip(share_id):
share = Share.query.get_or_404(share_id)
share.download_limit -= 1
db.session.commit()
if share.download_limit < 0:
remove_share(share)
return redirect(url_for('expired'))
else:
return send_from_directory(os.path.join(current_app.config['MEDIA_LOCATION']),
filename=str(share.id) + '.zip', as_attachment=True)
return send_from_directory(os.path.join(current_app.config['MEDIA_LOCATION']),
filename=str(share.id) + '.zip', as_attachment=True)
@app.route("/upload-test", methods=["GET", "POST"])
def upload_test():
form = UploadForm()
print(form.data.items())
if form.validate_on_submit():
print(form.files.data[0])
return url_for('expired')
return render_template("Upload.html", form=form)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment