Files
WattpadDownloader/src/api/main.py
T

61 lines
1.6 KiB
Python
Raw Normal View History

2023-12-29 02:57:37 +00:00
from pathlib import Path
2023-12-29 02:21:45 +00:00
from fastapi import FastAPI
2023-12-29 02:57:37 +00:00
from fastapi.responses import FileResponse, StreamingResponse
2023-12-29 02:21:45 +00:00
from ebooklib import epub
2023-12-29 02:57:37 +00:00
from create_book import retrieve_story, set_cover, set_metadata, add_chapters, slugify
2023-12-29 02:21:45 +00:00
import tempfile
from io import BytesIO
2023-12-29 02:57:37 +00:00
from fastapi.staticfiles import StaticFiles
2023-12-29 02:21:45 +00:00
app = FastAPI()
2023-12-29 02:57:37 +00:00
BUILD_PATH = Path(__file__).parent / "build"
@app.get("/")
def home():
return FileResponse(BUILD_PATH / "index.html")
2023-12-29 02:21:45 +00:00
@app.get("/download/{story_id}")
async def download_book(story_id: int):
data = await retrieve_story(story_id)
book = epub.EpubBook()
# Metadata and Cover are updated
set_metadata(book, data)
await set_cover(book, data)
# print("Metadata Downloaded")
# Chapters are downloaded
async for title in add_chapters(book, data):
# print(f"Part ({title}) downloaded")
...
# Book is compiled
temp_file = tempfile.NamedTemporaryFile(
dir=".", suffix=".epub", delete=True
) # Thanks https://stackoverflow.com/a/75398222
# create epub file
epub.write_epub(temp_file, book, {})
temp_file.file.seek(0)
book_data = temp_file.file.read()
return StreamingResponse(
BytesIO(book_data),
media_type="application/epub+zip",
2023-12-29 02:57:37 +00:00
headers={
"Content-Disposition": f'attachment; filename="{slugify(data["title"])}_{story_id}.epub"' # Thanks https://stackoverflow.com/a/72729058
},
2023-12-29 02:21:45 +00:00
)
2023-12-29 02:57:37 +00:00
app.mount("/", StaticFiles(directory=BUILD_PATH), "static")
2023-12-29 02:21:45 +00:00
if __name__ == "__main__":
import uvicorn
2023-12-29 02:57:37 +00:00
uvicorn.run(app, host="0.0.0.0", port=8084)