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
|
|
|
|
|
2021-02-02 01:07:41 +01:00
|
|
|
from app.logic.LogicError import LogicError
|
2021-01-30 19:25:00 +01:00
|
|
|
from app.models import *
|
2021-02-02 01:07:41 +01:00
|
|
|
from app.utils import randomString
|
2021-01-30 19:25:00 +01:00
|
|
|
|
|
|
|
|
2021-02-02 01:07:41 +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
|
|
|
|
|
2021-02-02 01:07:41 +01:00
|
|
|
def upload_file(file, fileType, fileTypeDesc):
|
2021-01-30 19:25:00 +01:00
|
|
|
if not file or file is None or file.filename == "":
|
2021-02-02 01:07:41 +01:00
|
|
|
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")
|
|
|
|
|
2021-02-02 01:07:41 +01:00
|
|
|
ext = get_extension(file.filename)
|
2021-01-30 19:25:00 +01:00
|
|
|
if ext is None or not ext in allowedExtensions:
|
2021-02-02 01:07:41 +01:00
|
|
|
raise LogicError(400, "Please upload " + fileTypeDesc)
|
2021-01-30 19:25:00 +01:00
|
|
|
|
|
|
|
if isImage and not isAllowedImage(file.stream.read()):
|
2021-02-02 01:07:41 +01:00
|
|
|
raise LogicError(400, "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-02-02 01:07:41 +01:00
|
|
|
|
2021-01-30 19:25:00 +01:00
|
|
|
return "/uploads/" + filename, filepath
|