add types and decouple packs functions from flask

This commit is contained in:
Kentai Radiquum 2025-05-14 23:49:01 +05:00
parent ee133e9111
commit f4d15c5eaf
Signed by: Radiquum
GPG key ID: 858E8EE696525EED
7 changed files with 174 additions and 48 deletions

View file

@ -1,70 +1,37 @@
import os
from . import apiPacks from . import apiPacks
from flask import request, jsonify from flask import request, jsonify
from config import PACKS_FOLDER from shared.packs import getPacks, createPack, deletePack
import json
import shutil
@apiPacks.route("/all", methods=["GET"]) @apiPacks.route("/all", methods=["GET"])
def getPacks(): def getPacksEndpoint():
packs = [] return jsonify(getPacks())
if not os.path.exists(f"{PACKS_FOLDER}"):
os.makedirs(f"{PACKS_FOLDER}", exist_ok=True)
return jsonify(packs)
pack_folders = [f.name for f in os.scandir(PACKS_FOLDER) if f.is_dir()]
for pack_folder in pack_folders:
if not os.path.exists(f"{PACKS_FOLDER}/{pack_folder}/packfile.json"):
continue
with open(f"{PACKS_FOLDER}/{pack_folder}/packfile.json") as fp:
pack = json.load(fp)
pack["_id"] = pack_folder
packs.append(pack)
fp.close()
return jsonify(packs)
@apiPacks.route("/new", methods=["POST"]) @apiPacks.route("/new", methods=["POST"])
def createPack(): def createPackEndpoint():
pack = { pack, is_exists = createPack(
"formatVersion": 0, request.json.get("title"),
"modpackVersion": 0, request.json.get("author"),
"title": request.json.get("title"), request.json.get("version"),
"author": request.json.get("author"), request.json.get("modloader"),
"version": request.json.get("version"), )
"modloader": request.json.get("modloader"),
"updateURL": "",
"mods": [],
}
title = pack.get("title").replace(" ", "_")
if os.path.exists(f"{PACKS_FOLDER}/{title}"): if is_exists:
return jsonify({"status": "error", "message": "pack already exists"}) return jsonify({"status": "error", "message": "pack already exists"})
os.makedirs(f"{PACKS_FOLDER}/{title}", exist_ok=True)
with open(
os.path.abspath(f"{PACKS_FOLDER}/{title}/packfile.json"),
mode="w",
encoding="utf-8",
) as fp:
json.dump(pack, fp)
fp.close()
return jsonify( return jsonify(
{ {
"status": "ok", "status": "ok",
"message": f"pack {pack.get('title')} created", "message": f"pack {pack.title} created",
"id": title, "id": pack._id,
} }
) )
@apiPacks.route("/<id>/delete", methods=["GET"]) @apiPacks.route("/<id>/delete", methods=["GET"])
def deletePack(id): def deletePackEndpoint(id):
shutil.rmtree(f"{PACKS_FOLDER}/{id}") deletePack(id)
return jsonify( return jsonify(
{ {
"status": "ok", "status": "ok",

0
src/shared/__init__.py Normal file
View file

61
src/shared/packs.py Normal file
View file

@ -0,0 +1,61 @@
import os
from config import PACKS_FOLDER
import json
import shutil
from type.pack import Pack
def getPacks() -> list[Pack]:
"""
Lists and returns all available packs from PACKS_FOLDER directory defined in config.py
"""
packs: list[Pack] = []
if not os.path.exists(f"{PACKS_FOLDER}"):
os.makedirs(f"{PACKS_FOLDER}", exist_ok=True)
return packs
pack_folders = [f.name for f in os.scandir(PACKS_FOLDER) if f.is_dir()]
for pack_folder in pack_folders:
if not os.path.exists(f"{PACKS_FOLDER}/{pack_folder}/packfile.json"):
continue
with open(f"{PACKS_FOLDER}/{pack_folder}/packfile.json") as fp:
pack = json.load(fp)
pack["_id"] = pack_folder
packs.append(pack)
fp.close()
return packs
def createPack(
title: str, author: str, game_version: str, mod_loader: str
) -> Pack | bool:
"""
Creates a new pack.
If pack exists returns tuple[Pack, True], if pack was created returns tuple[Pack, False]
"""
pack = Pack(
title.replace(" ", "_"), title, author, game_version, mod_loader, "", [], 0, 0
)
if os.path.exists(f"{PACKS_FOLDER}/{pack._id}"):
return pack, True
os.makedirs(f"{PACKS_FOLDER}/{pack._id}", exist_ok=True)
with open(
os.path.abspath(f"{PACKS_FOLDER}/{pack._id}/packfile.json"),
mode="w",
encoding="utf-8",
) as fp:
json.dump(pack.json(), fp)
fp.close()
return pack, False
def deletePack(id):
shutil.rmtree(f"{PACKS_FOLDER}/{id}")
return True

0
src/type/__init__.py Normal file
View file

21
src/type/file.py Normal file
View file

@ -0,0 +1,21 @@
import json
class ModFile:
def __init__(
self, version: str, hashes: dict[str, str], url: str, filename: str, size: int
):
self.version = version
self.hashes = hashes
self.url = url
self.filename = filename
self.size = size
def json(self):
return {
"version": self.version,
"hashes": self.hashes,
"url": self.url,
"filename": self.filename,
"size": self.size,
}

39
src/type/mod.py Normal file
View file

@ -0,0 +1,39 @@
import json
from .file import ModFile
class Mod:
def __init__(
self,
slug: str,
project_id: str,
icon: str,
title: str,
developers: list[str],
source: str,
environment: dict[str, bool],
dependencies: list,
file: ModFile,
):
self.slug = slug
self.project_id = project_id
self.icon = icon
self.title = title
self.developers = developers
self.source = source
self.environment = environment
self.dependencies = dependencies
self.file = file
def json(self):
return {
"slug": self.slug,
"project_id": self.project_id,
"icon": self.icon,
"title": self.title,
"developers": self.developers,
"source": self.source,
"environment": self.environment,
"dependencies": self.dependencies,
"file": self.file,
}

38
src/type/pack.py Normal file
View file

@ -0,0 +1,38 @@
import json
from .mod import Mod
class Pack:
def __init__(
self,
_id: str,
title: str,
author: str,
version: str,
modloader: str,
updateURL: str,
mods: list[Mod],
modpackVersion: int = 0,
formatVersion: int = 0,
):
self._id = _id
self.title = title
self.author = author
self.version = version
self.modloader = modloader
self.updateURL = updateURL
self.mods = mods
self.modpackVersion = modpackVersion
self.formatVersion = formatVersion
def json(self):
return {
"title": self.title,
"author": self.author,
"version": self.version,
"modloader": self.modloader,
"updateURL": self.updateURL,
"mods": self.mods,
"modpackVersion": self.modpackVersion,
"formatVersion": self.formatVersion,
}