|
|
|
|
|
|
|
|
|
|
|
import glob |
|
|
|
|
|
import mimetypes |
|
|
|
|
|
import random |
|
|
|
|
|
import string |
|
|
from http import HTTPStatus |
|
|
from http import HTTPStatus |
|
|
from pathlib import Path |
|
|
from pathlib import Path |
|
|
|
|
|
|
|
|
|
|
|
import filetype |
|
|
from roll import Roll |
|
|
from roll import Roll |
|
|
from roll.extensions import simple_server, static |
|
|
from roll.extensions import simple_server, static |
|
|
|
|
|
from wand.exceptions import MissingDelegateError |
|
|
|
|
|
from wand.image import Image |
|
|
|
|
|
|
|
|
app = Roll() |
|
|
app = Roll() |
|
|
static(app) |
|
|
static(app) |
|
|
|
|
|
upload_path = Path("uploaded_images") |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def _get_random_filename(): |
|
|
|
|
|
random_string = "".join( |
|
|
|
|
|
random.choices( |
|
|
|
|
|
string.ascii_lowercase + string.digits + string.ascii_uppercase, k=15 |
|
|
|
|
|
) |
|
|
|
|
|
) |
|
|
|
|
|
file_exists = len(glob.glob(f"{upload_path}/{random_string}.*")) > 0 |
|
|
|
|
|
if file_exists: |
|
|
|
|
|
return _get_random_filename() |
|
|
|
|
|
return random_string |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
@app.route("/") |
|
|
@app.route("/") |
|
|
|
|
|
|
|
|
async def upload_images(request, response): |
|
|
async def upload_images(request, response): |
|
|
images = request.files.list("images") |
|
|
images = request.files.list("images") |
|
|
for image in images: |
|
|
for image in images: |
|
|
filepath = Path("uploaded_images") / image.filename |
|
|
|
|
|
filepath.write_bytes(image.read()) |
|
|
|
|
|
|
|
|
random_string = _get_random_filename() |
|
|
|
|
|
tmp_filepath = Path("/tmp/") / random_string |
|
|
|
|
|
tmp_filepath.write_bytes(image.read()) |
|
|
|
|
|
output_type = filetype.guess_extension(str(tmp_filepath)) |
|
|
|
|
|
error = None |
|
|
|
|
|
|
|
|
|
|
|
try: |
|
|
|
|
|
with Image(filename=tmp_filepath) as img: |
|
|
|
|
|
img.strip() |
|
|
|
|
|
with img.convert(output_type) as converted: |
|
|
|
|
|
output_filename = f"{random_string}.{output_type}" |
|
|
|
|
|
output_path = upload_path / output_filename |
|
|
|
|
|
if output_type not in ["gif"]: |
|
|
|
|
|
converted.sequence = [converted.sequence[0]] |
|
|
|
|
|
converted.save(filename=str(output_path)) |
|
|
|
|
|
except MissingDelegateError: |
|
|
|
|
|
error = "Invalid Filetype" |
|
|
|
|
|
finally: |
|
|
|
|
|
if tmp_filepath.exists(): |
|
|
|
|
|
tmp_filepath.unlink() |
|
|
|
|
|
# TODO: deal with errors! |
|
|
response.status = HTTPStatus.FOUND |
|
|
response.status = HTTPStatus.FOUND |
|
|
response.headers["Location"] = "/" |
|
|
response.headers["Location"] = "/" |
|
|
|
|
|
|