mirror of
https://github.com/flibusta-apps/fb2converter_server.git
synced 2025-12-06 06:55:36 +01:00
Add converter files exists checking
This commit is contained in:
49
app/main.py
49
app/main.py
@@ -1,27 +1,40 @@
|
||||
import uuid
|
||||
import asyncio
|
||||
import os
|
||||
import uuid
|
||||
|
||||
from fastapi import FastAPI, APIRouter, File, UploadFile, Form, HTTPException, BackgroundTasks, status
|
||||
from fastapi import (
|
||||
FastAPI,
|
||||
APIRouter,
|
||||
File,
|
||||
UploadFile,
|
||||
Form,
|
||||
HTTPException,
|
||||
BackgroundTasks,
|
||||
status,
|
||||
)
|
||||
from fastapi.responses import FileResponse
|
||||
|
||||
from starlette.background import BackgroundTask
|
||||
|
||||
import aiofiles
|
||||
import aiofiles.ospath
|
||||
|
||||
|
||||
router = APIRouter(
|
||||
tags=["converter"]
|
||||
)
|
||||
router = APIRouter(tags=["converter"])
|
||||
|
||||
|
||||
@router.post("/")
|
||||
async def convert(background_tasks: BackgroundTasks, file: UploadFile = File({}), format: str = Form({})):
|
||||
async def convert(
|
||||
background_tasks: BackgroundTasks,
|
||||
file: UploadFile = File({}),
|
||||
format: str = Form({}),
|
||||
):
|
||||
temp_uuid = uuid.uuid1()
|
||||
|
||||
temp_filename = str(temp_uuid) + '.fb2'
|
||||
converted_temp_filename = str(temp_uuid) + '.' + format
|
||||
temp_filename = str(temp_uuid) + ".fb2"
|
||||
converted_temp_filename = str(temp_uuid) + "." + format
|
||||
|
||||
async with aiofiles.open(temp_filename, 'wb') as f:
|
||||
async with aiofiles.open(temp_filename, "wb") as f:
|
||||
content = await file.read()
|
||||
|
||||
if isinstance(content, str):
|
||||
@@ -30,21 +43,27 @@ async def convert(background_tasks: BackgroundTasks, file: UploadFile = File({})
|
||||
await f.write(content)
|
||||
|
||||
proc = await asyncio.create_subprocess_exec(
|
||||
'./bin/fb2c', 'convert', '--to', format, temp_filename,
|
||||
"./bin/fb2c",
|
||||
"convert",
|
||||
"--to",
|
||||
format,
|
||||
temp_filename,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=asyncio.subprocess.PIPE
|
||||
stderr=asyncio.subprocess.PIPE,
|
||||
)
|
||||
|
||||
await proc.communicate()
|
||||
_, stderr = await proc.communicate()
|
||||
|
||||
background_tasks.add_task(os.remove, temp_filename)
|
||||
|
||||
if proc.returncode != 0:
|
||||
return HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Can't convert!")
|
||||
if proc.returncode != 0 or len(stderr) != 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST, detail="Can't convert!"
|
||||
)
|
||||
|
||||
return FileResponse(
|
||||
converted_temp_filename,
|
||||
background=BackgroundTask(lambda: os.remove(converted_temp_filename))
|
||||
background=BackgroundTask(lambda: os.remove(converted_temp_filename)),
|
||||
)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user