pycdn/server.py

106 lines
3.2 KiB
Python
Raw Normal View History

2023-10-30 02:29:47 +03:00
import pathlib
2023-03-21 23:58:22 +03:00
from typing import Union, Annotated
2023-03-22 18:22:43 +03:00
import uvicorn
2023-04-06 23:58:56 +03:00
from routes.user_routes import user_route
from bearer.routes.auth import auth
from db.DB import DBException
import mimetypes
from mime.mime import mime_content_type
2023-04-09 14:26:34 +03:00
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
2023-03-21 23:58:22 +03:00
2023-04-06 23:58:56 +03:00
from fastapi import FastAPI, File, UploadFile, Form, Response, status, HTTPException
2023-03-21 23:58:22 +03:00
import os
import magic
2023-04-09 14:26:34 +03:00
middleware = [
Middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=['*'],
allow_headers=['*']
)
]
app = FastAPI(middleware=middleware)
# app.add_middleware(
# CORSMiddleware,
# allow_origins=['*'],
# allow_credentials=True,
# allow_methods=['*'],
# allow_headers=['*'],
# max_age=3600
# )
2023-04-06 23:58:56 +03:00
app.include_router(user_route)
app.include_router(auth)
2023-03-21 23:58:22 +03:00
2023-04-07 16:57:00 +03:00
2023-03-21 23:58:22 +03:00
@app.get("/")
2023-04-09 14:26:34 +03:00
async def read_root():
2023-03-21 23:58:22 +03:00
return {"Hello": "World"}
2023-04-06 23:58:56 +03:00
@app.get("/items/{name}/{version}/{file}")
2023-04-09 14:26:34 +03:00
async def read_item(version: str, name: str, file: str = 'index.js'):
2023-03-21 23:58:22 +03:00
file_path = f"packages/{name}/{version}/{file}"
2023-04-06 23:58:56 +03:00
file_mime = mime_content_type(file_path)
print(file_mime)
2023-03-21 23:58:22 +03:00
if os.path.exists(file_path):
with open(file_path, 'rb') as f:
2023-04-09 14:26:34 +03:00
return Response(content=f.read(), media_type=file_mime, headers={"Access-Control-Allow-Origin": "*"})
2023-03-21 23:58:22 +03:00
return status.HTTP_404_NOT_FOUND
@app.post("/files/")
async def create_file(file: Annotated[bytes | None, File()] = None):
if not file:
return {"message": "No file sent"}
else:
return {"file_size": len(file)}
@app.post("/uploadfile/")
2023-04-09 14:26:34 +03:00
async def create_upload_file(file: UploadFile | None, package: Annotated[str, Form()], version: Annotated[str, Form()],
2023-04-13 12:47:46 +03:00
filename: Annotated[str, Form()], stable: Annotated[bool, Form()]):
2023-03-21 23:58:22 +03:00
try:
contents = file.file.read()
dir_file = "packages/{package}/{version}".format(package=package, version=version)
2023-04-06 23:58:56 +03:00
dir_last = "packages/{package}/latest".format(package=package)
dir_stable = "packages/{package}/stable".format(package=package)
2023-03-21 23:58:22 +03:00
if not os.path.exists(dir_file):
os.makedirs(dir_file)
2023-04-06 23:58:56 +03:00
if not os.path.exists(dir_last):
os.makedirs(dir_last)
if not os.path.exists(dir_stable):
os.makedirs(dir_stable)
2023-10-30 02:35:18 +03:00
if os.path.exists(f"{dir_file}/{filename}"):
os.remove(f"{dir_file}/{filename}")
2023-10-30 02:29:47 +03:00
with open(f"{dir_file}/{filename}", 'a') as f:
2023-10-30 02:15:27 +03:00
f.write(str(contents))
2023-10-30 02:35:18 +03:00
if os.path.exists(f"{dir_last}/{filename}"):
os.remove(f"{dir_last}/{filename}")
2023-10-30 02:29:47 +03:00
with open(f"{dir_last}/{filename}", 'a') as f:
2023-10-30 02:15:27 +03:00
f.write(str(contents))
2023-04-13 12:35:31 +03:00
if stable:
2023-10-30 02:35:18 +03:00
if os.path.exists(f"{dir_stable}/{filename}"):
os.remove(f"{dir_stable}/{filename}")
2023-10-30 02:29:47 +03:00
with open(f"{dir_stable}/{filename}", 'a') as f:
2023-10-30 02:15:27 +03:00
f.write(str(contents))
2023-03-23 00:36:10 +03:00
except Exception as err:
return {"message": "There was an error uploading the file, error {err}".format(err=err)}
2023-03-21 23:58:22 +03:00
finally:
file.file.close()
2023-03-22 18:22:43 +03:00
return {"message": f"Successfully uploaded {file.filename}"}
if __name__ == "__main__":
2023-04-09 14:26:34 +03:00
uvicorn.run("server:app", port=5044, log_level="info")