contentdb/app/logic/uploads.py

64 lines
2.0 KiB
Python
Raw Normal View History

2021-01-30 19:25:00 +01:00
# ContentDB
# Copyright (C) 2018-21 rubenwardy
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import imghdr
import os
2022-01-14 19:25:28 +01:00
from flask_babel import lazy_gettext
from app.logic.LogicError import LogicError
2021-01-30 19:25:00 +01:00
from app.models import *
from app.utils import randomString
2021-01-30 19:25:00 +01:00
def get_extension(filename):
2021-01-30 19:25:00 +01:00
return filename.rsplit(".", 1)[1].lower() if "." in filename else None
ALLOWED_IMAGES = {"jpeg", "png"}
def isAllowedImage(data):
return imghdr.what(None, data) in ALLOWED_IMAGES
def upload_file(file, fileType, fileTypeDesc):
2021-01-30 19:25:00 +01:00
if not file or file is None or file.filename == "":
raise LogicError(400, "Expected file")
2021-01-30 19:25:00 +01:00
assert os.path.isdir(app.config["UPLOAD_DIR"]), "UPLOAD_DIR must exist"
isImage = False
if fileType == "image":
allowedExtensions = ["jpg", "jpeg", "png"]
isImage = True
elif fileType == "zip":
allowedExtensions = ["zip"]
else:
raise Exception("Invalid fileType")
ext = get_extension(file.filename)
2021-01-30 19:25:00 +01:00
if ext is None or not ext in allowedExtensions:
2022-01-14 19:25:28 +01:00
raise LogicError(400, lazy_gettext("Please upload %(file_desc)s", file_desc=fileTypeDesc))
2021-01-30 19:25:00 +01:00
if isImage and not isAllowedImage(file.stream.read()):
2022-01-14 19:25:28 +01:00
raise LogicError(400, lazy_gettext("Uploaded image isn't actually an image"))
2021-01-30 19:25:00 +01:00
file.stream.seek(0)
filename = randomString(10) + "." + ext
filepath = os.path.join(app.config["UPLOAD_DIR"], filename)
file.save(filepath)
2021-01-30 19:25:00 +01:00
return "/uploads/" + filename, filepath