-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
147 lines (125 loc) · 5.4 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
from fastapi import FastAPI, HTTPException, Response, UploadFile
from fastapi.responses import FileResponse
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from typing import Union, List
from t3dlitematica import LitimaticaToObj, Resolve, convert_texturepack, multiload
from contextlib import asynccontextmanager
import os
import re
import requests
def check():
if not os.path.exists("textures"):
os.mkdir("textures")
if not os.path.exists("obj"):
os.mkdir("obj")
if not os.path.exists("temp"):
os.mkdir("temp")
@asynccontextmanager
async def startup(app: FastAPI):
check()
yield
print("Shutting down")
app = FastAPI(lifespan=startup)
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
def read_root():
html = open("./public/index.html", "r").read()
return html
@app.get("/ping")
def ping():
return {"ping": "pong"}
@app.get("/status")
def status():
data = {
"litematicas": len(os.listdir("obj")),
"texturepacks": len(os.listdir("textures")),
}
return data
@app.post("/litematica/upload")
def upload_litematica(file: UploadFile | str, texturepack: Union[str, List[str]]) -> Response:
if isinstance(file, str):
try:
match = re.match(r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()!@:%_\+.~#?&\/\/=]*)\/([\w\-\.%]+\.litematic)\??.*", file)
if not match:
raise HTTPException(status_code=400, detail="Invalid URL")
infilename = match.group(3)
r = requests.get(file, stream=True)
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError):
raise HTTPException(status_code=400, detail="Invalid URL")
with open(os.path.join("temp", infilename), "wb") as f:
f.write(r.content)
else:
if not file.filename.endswith(".litematic"):
raise HTTPException(status_code=400, detail="File must be a .litematic file")
infilename = file.filename
with open(os.path.join("temp", infilename), "wb") as f:
f.write(file.file.read())
if isinstance(texturepack, list):
for tp in texturepack:
if not os.path.exists(os.path.join("textures", tp)):
raise HTTPException(
status_code=404, detail=f"{tp} Texturepack not found"
)
with multiload(texturepack) as texturepath:
filename = LitimaticaToObj(
Resolve(os.path.join("temp", infilename)),
texturepath,
os.path.join(os.getcwd(), "obj"),
)
else:
print(Resolve(os.path.join("temp", infilename)))
texturepath = os.path.join("textures", texturepack)
filename = LitimaticaToObj(
Resolve(os.path.join("temp", infilename)),
texturepath,
os.path.join(os.getcwd(), "obj"),
)
os.remove(os.path.join("temp", infilename))
return FileResponse(path=os.path.join("obj", str(filename)), filename=str(filename))
@app.post("/litematica/resolve")
def resolve_litematica(file: UploadFile | str):
if isinstance(file, str):
try:
match = re.match(r"https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()!@:%_\+.~#?&\/\/=]*)\/([\w\-\.%]+\.litematic)\??.*", file)
if not match:
return {"error": "Invalid URL"}
infilename = match.group(3)
r = requests.get(file, stream=True)
except (requests.exceptions.HTTPError, requests.exceptions.ConnectionError):
return {"error": "Invalid URL"}
with open(os.path.join("temp", infilename), "wb") as f:
f.write(r.content)
else:
if not file.filename.endswith(".litematic"):
return {"error": "File must be a .litematic file"}
infilename = file.filename
with open(os.path.join("temp", infilename), "wb") as f:
f.write(file.file.read())
data = Resolve(os.path.join("temp", infilename))
os.remove(os.path.join("temp", infilename))
return data
@app.post("/texturepack/upload")
def upload_texturepack(file: UploadFile, texturepackname: str):
if not file.filename.endswith(".zip"):
raise HTTPException(status_code=400, detail="File must be a .zip file")
if os.path.exists(os.path.join("textures", texturepackname)):
raise HTTPException(status_code=409, detail="Texturepack already exists")
with open(os.path.join(os.getcwd(), "temp", file.filename), "wb") as f:
f.write(file.file.read())
os.mkdir(os.path.join("textures", texturepackname))
convert_texturepack(
os.path.join("temp", file.filename), os.path.join("textures", texturepackname)
)
os.remove(os.path.join("temp", file.filename))
return {"message": "Upload Texturepack"}
@app.get("/texturepack/list")
def list_texturepack():
texturepacklist = os.listdir("textures")
if not texturepacklist:
raise HTTPException(status_code=404, detail="No texturepacks found")
return {"texturepacks": texturepacklist}
if __name__ == "__main__":
import uvicorn
check()
uvicorn.run(app, host="127.0.0.1", port=8000)