contentdb/app/logic/uploads.py

67 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
2023-06-19 20:32:36 +02:00
from app import app
from app.logic.LogicError import LogicError
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
2023-06-19 20:32:36 +02:00
2021-01-30 19:25:00 +01:00
ALLOWED_IMAGES = {"jpeg", "png"}
2023-06-19 20:32:36 +02:00
def is_allowed_image(data):
2021-01-30 19:25:00 +01:00
return imghdr.what(None, data) in ALLOWED_IMAGES
2023-06-19 20:32:36 +02:00
def upload_file(file, file_type, file_type_desc):
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"
2023-06-19 20:32:36 +02:00
is_image = False
if file_type == "image":
allowed_extensions = ["jpg", "jpeg", "png"]
is_image = True
elif file_type == "zip":
allowed_extensions = ["zip"]
2021-01-30 19:25:00 +01:00
else:
raise Exception("Invalid fileType")
ext = get_extension(file.filename)
2023-06-19 20:32:36 +02:00
if ext is None or ext not in allowed_extensions:
raise LogicError(400, lazy_gettext("Please upload %(file_desc)s", file_desc=file_type_desc))
2021-01-30 19:25:00 +01:00
2023-06-19 20:32:36 +02:00
if is_image and not is_allowed_image(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