API w/ queueing surrounding upload/download proc
This commit is contained in:
parent
e2e511352b
commit
bdf811cc36
8 changed files with 360 additions and 146 deletions
9
.gitignore
vendored
9
.gitignore
vendored
|
|
@ -1 +1,8 @@
|
|||
out/
|
||||
/out/
|
||||
/lib/
|
||||
/lib64
|
||||
/bin/
|
||||
|
||||
state.dat
|
||||
filekey.key
|
||||
__pycache__
|
||||
10
.vscode/settings.json
vendored
Normal file
10
.vscode/settings.json
vendored
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"emeraldwalk.runonsave": {
|
||||
"commands": [
|
||||
{
|
||||
"match": "\\.py$",
|
||||
"cmd": "bin/isort \"${file}\""
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
174
api.py
Normal file
174
api.py
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
"""
|
||||
The API endpoints for the proessor
|
||||
Author: oitsjustjose @ modrinth/curseforge/twitter
|
||||
"""
|
||||
|
||||
import json
|
||||
from dataclasses import asdict, dataclass
|
||||
from multiprocessing import Manager, Process
|
||||
from os import environ as env
|
||||
from os.path import exists
|
||||
from time import sleep
|
||||
from typing import Dict, List, Union
|
||||
|
||||
from cryptography.fernet import Fernet
|
||||
from flask import Flask, request
|
||||
from shortuuid import ShortUUID
|
||||
|
||||
from processor import download, upload
|
||||
|
||||
|
||||
@dataclass
|
||||
class Job:
|
||||
"""A single job"""
|
||||
|
||||
github_pat: str
|
||||
curseforge_slug: str
|
||||
modrinth_id: str
|
||||
logs = []
|
||||
job_id: str = ShortUUID().random(length=8)
|
||||
delimiter: str = "-"
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
fer = Fernet(env["key"])
|
||||
|
||||
|
||||
manager = Manager()
|
||||
active_jobs: List[Job] = manager.list()
|
||||
jobs: List[Job] = manager.list()
|
||||
completed: List[Job] = manager.list()
|
||||
|
||||
|
||||
def job_processor():
|
||||
print("Starting the job processor")
|
||||
while True:
|
||||
try:
|
||||
sleep(1)
|
||||
if not jobs:
|
||||
continue
|
||||
active_job = jobs[0]
|
||||
active_jobs.append(active_job)
|
||||
|
||||
active_job.logs += download(active_job.curseforge_slug)
|
||||
active_job.logs += upload(
|
||||
active_job.github_pat,
|
||||
active_job.curseforge_slug,
|
||||
active_job.modrinth_id,
|
||||
active_job.delimiter,
|
||||
)
|
||||
|
||||
active_job.github_pat = ""
|
||||
completed.append(active_job)
|
||||
|
||||
for idx, obj in enumerate(active_jobs):
|
||||
if obj.job_id == active_job.job_id:
|
||||
del active_jobs[idx]
|
||||
for idx, obj in enumerate(jobs):
|
||||
if obj.job_id == active_job.job_id:
|
||||
del jobs[idx]
|
||||
|
||||
except KeyboardInterrupt:
|
||||
break
|
||||
|
||||
|
||||
def save():
|
||||
"""Saves the current application state to an encrypted file"""
|
||||
|
||||
data = {
|
||||
"jobs": [asdict(x) for x in active_jobs] + [asdict(x) for x in jobs],
|
||||
"completed": dict(completed),
|
||||
}
|
||||
with open("./state.dat", "wb") as handle:
|
||||
handle.write(fer.encrypt(json.dumps(data).encode()))
|
||||
|
||||
|
||||
def load():
|
||||
"""Loads the current application state from encrypted file"""
|
||||
global active_job, jobs, completed
|
||||
if not exists("./state.dat"):
|
||||
return
|
||||
with open("./state.dat", "rb") as handle:
|
||||
data = json.loads(fer.decrypt(handle.read().decode()))
|
||||
if "jobs" in data:
|
||||
for job in data["jobs"]:
|
||||
jobs.append(
|
||||
Job(
|
||||
github_pat=job["github_pat"],
|
||||
curseforge_slug=job["curseforge_slug"],
|
||||
modrinth_id=job["modrinth_id"],
|
||||
job_id=job["job_id"],
|
||||
delimiter=job["delimiter"],
|
||||
)
|
||||
)
|
||||
|
||||
if "completed" in data:
|
||||
completed = data["completed"]
|
||||
print(completed, jobs)
|
||||
|
||||
|
||||
@app.route("/jobs/status/<uuid>", methods=["GET", "POST"])
|
||||
def get_job_status(uuid: str) -> str:
|
||||
"Gets the queue status for a given job"
|
||||
for job in active_jobs:
|
||||
if job.job_id == uuid:
|
||||
return "Currently Processing", 200
|
||||
|
||||
for job in completed:
|
||||
if job.job_id == uuid:
|
||||
logs = "\\n".join(job.logs)
|
||||
return f"Completed!\n{logs}", 200
|
||||
|
||||
for idx, job in enumerate(jobs):
|
||||
if job.job_id == uuid:
|
||||
return f"Enqueued: {idx+1} Job(s) Ahead In Queue", 200
|
||||
|
||||
return "Failed to find job", 404
|
||||
|
||||
|
||||
@app.route("/jobs/info/<uuid>", methods=["GET", "POST"])
|
||||
def get_job_info(uuid: str):
|
||||
"""Gets the job info for a given uuid"""
|
||||
for job in jobs:
|
||||
if job.job_id == uuid:
|
||||
data = asdict(job)
|
||||
data.pop("github_pat")
|
||||
return json.dumps(data), 200
|
||||
return "Failed to find job", 404
|
||||
|
||||
|
||||
@app.route("/jobs/new", methods=["POST"])
|
||||
def new_job():
|
||||
"""Creates a new job"""
|
||||
try:
|
||||
data = json.loads(request.data)
|
||||
jobe = Job(
|
||||
github_pat=data["githubPat"],
|
||||
curseforge_slug=data["slug"],
|
||||
modrinth_id=data["projId"],
|
||||
delimiter=data["delimiter"] if "delimiter" in data else "-",
|
||||
)
|
||||
|
||||
# Don't enqueue a task that already exists
|
||||
for job in jobs:
|
||||
if (
|
||||
job.github_pat == jobe.github_pat
|
||||
and job.curseforge_slug == jobe.curseforge_slug
|
||||
and job.modrinth_id == jobe.modrinth_id
|
||||
and job.delimiter == jobe.delimiter
|
||||
):
|
||||
return job.job_id, 200
|
||||
|
||||
jobs.append(jobe)
|
||||
return jobe.job_id, 200
|
||||
except:
|
||||
return "Internal Server Error", 500
|
||||
|
||||
|
||||
load()
|
||||
proc = Process(target=job_processor)
|
||||
proc.start()
|
||||
|
||||
app.run("0.0.0.0", 3000)
|
||||
proc.join()
|
||||
save()
|
||||
73
download.py
73
download.py
|
|
@ -1,73 +0,0 @@
|
|||
"""**EH**"""
|
||||
from typing import List
|
||||
import os
|
||||
from time import sleep
|
||||
|
||||
from bs4 import BeautifulSoup
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
|
||||
|
||||
URL: str
|
||||
|
||||
|
||||
def get_mods_for_page(driver: webdriver.Chrome, page: int) -> List[str]:
|
||||
"""EH"""
|
||||
driver.get(f"{URL}?page={page}")
|
||||
|
||||
root = driver.page_source
|
||||
root = BeautifulSoup(root, features="html.parser")
|
||||
|
||||
file_links = root.body.find_all("a", attrs={"data-action": "file-link"})
|
||||
|
||||
return list(
|
||||
map(
|
||||
lambda x: f"https://legacy.curseforge.com/{x['href']}".replace(
|
||||
"files", "download"
|
||||
),
|
||||
file_links,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def mod_archive_all(modid: str) -> None:
|
||||
"""EH"""
|
||||
global URL
|
||||
URL = f"https://legacy.curseforge.com/minecraft/mc-mods/{modid}/files/all"
|
||||
os.makedirs(f"./out/{modid}", exist_ok=True)
|
||||
|
||||
page: int = 1
|
||||
page_num: int = 1
|
||||
|
||||
options = Options()
|
||||
options.add_experimental_option("excludeSwitches", ["enable-logging"])
|
||||
options.add_experimental_option(
|
||||
"prefs",
|
||||
{
|
||||
"download.default_directory": os.path.realpath(f"./out/{modid}/"),
|
||||
"download.prompt_for_download": False,
|
||||
"download.directory_upgrade": True,
|
||||
"safebrowsing.enabled": True,
|
||||
},
|
||||
)
|
||||
driver = webdriver.Chrome(options=options)
|
||||
driver.get(f"{URL}?page={page}")
|
||||
|
||||
root = driver.page_source
|
||||
root = BeautifulSoup(root, features="html.parser")
|
||||
page_els = root.body.find_all("a", attrs={"class": "pagination-item"})
|
||||
if page_els: # mods with only 1 page won't have a pagination item
|
||||
page_el = page_els[-1]
|
||||
page_el = page_el.find("span").text
|
||||
page_num = int(page_el)
|
||||
|
||||
all_urls = []
|
||||
for page in range(page_num):
|
||||
all_urls += get_mods_for_page(driver, page + 1)
|
||||
for url in all_urls:
|
||||
driver.get(url)
|
||||
sleep(8)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
mod_archive_all("YOUR_MODID")
|
||||
150
processor.py
Normal file
150
processor.py
Normal file
|
|
@ -0,0 +1,150 @@
|
|||
"""
|
||||
Performs upload/download operations
|
||||
Author: oitsjustjose @ modrinth/curseforge/twitter
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
from shutil import rmtree
|
||||
from time import sleep
|
||||
from typing import List
|
||||
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
from selenium import webdriver
|
||||
from selenium.webdriver.chrome.options import Options
|
||||
from selenium.webdriver.chrome.service import Service
|
||||
from webdriver_manager.chrome import ChromeDriverManager
|
||||
|
||||
|
||||
def upload(api_key: str, slug: str, proj_id: str, delimeter: str) -> List[str]:
|
||||
"""
|
||||
Uploads all downloaded files from CurseForge to Modrinth using the given API Key
|
||||
Args:
|
||||
api_key (str): the GitHub PAT for the associated Modrinth account
|
||||
slug (str): the CurseForge slug, used to traverse the local filesystem
|
||||
proj_id (str): the Modrinth project id
|
||||
delimiter (str): the splitter between parts of the filename. Geolosys uses format
|
||||
"MODNAME-MCVER-MAJOR.MINOR.PATCH", where '-' is the delimiter
|
||||
"""
|
||||
logs = []
|
||||
if not os.path.exists(f"./out/{slug}"):
|
||||
return logs
|
||||
|
||||
for fpath in os.listdir(f"./out/{slug}"):
|
||||
with open(f"out/{slug}/{fpath}", "rb") as modfile:
|
||||
data = modfile.read()
|
||||
|
||||
parts = fpath.split(delimeter)
|
||||
if len(parts) != 3:
|
||||
logs.append(
|
||||
f"Failed to parse name/version info for file {fpath}, it will be skipped"
|
||||
)
|
||||
continue
|
||||
|
||||
version_title = " ".join(parts).replace(".jar", "")
|
||||
# .x versions somehow were only ever for the .0, .1 and .2 game vers lol
|
||||
if "x" in parts[1].lower():
|
||||
root = parts[1].replace(".x", "").replace(".X", "")
|
||||
game_versions = [root, f"{root}.1", f"{root}.2"]
|
||||
else:
|
||||
game_versions = [parts[1]]
|
||||
version = parts[2].replace(".jar", "")
|
||||
|
||||
payload = json.dumps(
|
||||
{
|
||||
"name": version_title,
|
||||
"version_number": f"{parts[1]}-{version}",
|
||||
"changelog": "Migrated Automagically from CurseForge",
|
||||
"dependencies": [],
|
||||
"game_versions": game_versions,
|
||||
"loaders": ["forge"],
|
||||
"featured": False,
|
||||
"requested_status": "listed",
|
||||
"version_type": "release",
|
||||
"project_id": proj_id,
|
||||
"primary_file": fpath,
|
||||
"file_parts": [fpath],
|
||||
}
|
||||
)
|
||||
|
||||
response = requests.post(
|
||||
"https://api.modrinth.com/v2/version",
|
||||
timeout=30,
|
||||
headers={"Authorization": api_key},
|
||||
files=[
|
||||
("data", (None, payload, None)),
|
||||
("files", (fpath, data, "application/octet-stream")),
|
||||
],
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
logs.append(f"Successfully uploaded {fpath}")
|
||||
else:
|
||||
logs.append("API Response from Modrinth Failed for {fpath}:")
|
||||
logs.append(response.text)
|
||||
logs.append(json.dumps(response.json(), indent=2))
|
||||
|
||||
rmtree(f"./out/{slug}")
|
||||
return logs
|
||||
|
||||
|
||||
def __get_mods_for_page(driver: webdriver.Chrome, root: str, page: int) -> List[str]:
|
||||
"""EH"""
|
||||
driver.get(f"{root}?page={page}")
|
||||
|
||||
root_el = driver.page_source
|
||||
root_el = BeautifulSoup(root_el, features="html.parser")
|
||||
|
||||
file_links = root_el.body.find_all("a", attrs={"data-action": "file-link"})
|
||||
|
||||
return list(
|
||||
map(
|
||||
lambda x: f"https://legacy.curseforge.com/{x['href']}".replace(
|
||||
"files", "download"
|
||||
),
|
||||
file_links,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def download(slug: str) -> List[str]:
|
||||
"""Downloads all mod files for a given slug"""
|
||||
logs = []
|
||||
try:
|
||||
root = f"https://legacy.curseforge.com/minecraft/mc-mods/{slug}/files/all"
|
||||
os.makedirs(f"./out/{slug}", exist_ok=True)
|
||||
|
||||
page_num: int = 1
|
||||
|
||||
options = Options()
|
||||
options.add_experimental_option("excludeSwitches", ["enable-logging"])
|
||||
options.add_experimental_option(
|
||||
"prefs",
|
||||
{
|
||||
"download.default_directory": os.path.realpath(f"./out/{slug}/"),
|
||||
"download.prompt_for_download": False,
|
||||
"download.directory_upgrade": True,
|
||||
"safebrowsing.enabled": True,
|
||||
},
|
||||
)
|
||||
driver = webdriver.Chrome(
|
||||
service=Service(ChromeDriverManager().install()), options=options
|
||||
)
|
||||
driver.get(f"{root}?page=1")
|
||||
|
||||
root_el = driver.page_source
|
||||
root_el = BeautifulSoup(root_el, features="html.parser")
|
||||
page_els = root_el.body.find_all("a", attrs={"class": "pagination-item"})
|
||||
if page_els: # mods with only 1 page won't have a pagination item
|
||||
page_el = page_els[-1]
|
||||
page_el = page_el.find("span").text
|
||||
page_num = int(page_el)
|
||||
all_urls = []
|
||||
for page in range(page_num):
|
||||
all_urls += __get_mods_for_page(driver, root, page + 1)
|
||||
for url in all_urls:
|
||||
driver.get(url)
|
||||
sleep(8)
|
||||
except Exception as e:
|
||||
logs.append(f"Download failed: {e}")
|
||||
return logs
|
||||
3
pyvenv.cfg
Normal file
3
pyvenv.cfg
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
home = /usr/bin
|
||||
include-system-site-packages = false
|
||||
version = 3.10.11
|
||||
|
|
@ -1,34 +1,45 @@
|
|||
abstra==0.14.2
|
||||
abstra-cli==0.20.1
|
||||
abstra-runtimes==0.13.0
|
||||
astroid==2.15.3
|
||||
async-generator==1.10
|
||||
attrs==23.1.0
|
||||
beautifulsoup4==4.12.2
|
||||
black==23.3.0
|
||||
certifi==2022.12.7
|
||||
cffi==1.15.1
|
||||
charset-normalizer==3.1.0
|
||||
click==8.1.3
|
||||
colour==0.1.5
|
||||
crontab==1.0.1
|
||||
cryptography==40.0.2
|
||||
decorator==5.1.1
|
||||
dill==0.3.6
|
||||
exceptiongroup==1.1.1
|
||||
fire==0.5.0
|
||||
Flask==2.2.3
|
||||
h11==0.14.0
|
||||
idna==3.4
|
||||
isort==5.12.0
|
||||
itsdangerous==2.1.2
|
||||
jedi==0.18.2
|
||||
Jinja2==3.1.2
|
||||
lazy-object-proxy==1.9.0
|
||||
MarkupSafe==2.1.2
|
||||
mccabe==0.7.0
|
||||
mypy-extensions==1.0.0
|
||||
outcome==1.2.0
|
||||
packaging==23.1
|
||||
parso==0.8.3
|
||||
pathspec==0.11.1
|
||||
platformdirs==3.2.0
|
||||
progress==1.6
|
||||
pycparser==2.21
|
||||
pylint==2.17.2
|
||||
PySocks==1.7.1
|
||||
python-dotenv==1.0.0
|
||||
pytoolconfig==1.2.5
|
||||
requests==2.28.2
|
||||
rope==1.7.0
|
||||
selenium==4.8.3
|
||||
shortuuid==1.0.11
|
||||
simplejson==3.19.1
|
||||
six==1.16.0
|
||||
sniffio==1.3.0
|
||||
|
|
@ -45,5 +56,6 @@ urllib3==1.26.15
|
|||
validators==0.20.0
|
||||
webdriver-manager==3.8.6
|
||||
websocket-client==1.5.1
|
||||
Werkzeug==2.2.3
|
||||
wrapt==1.15.0
|
||||
wsproto==1.2.0
|
||||
|
|
|
|||
69
upload.py
69
upload.py
|
|
@ -1,69 +0,0 @@
|
|||
"""EH"""
|
||||
import os
|
||||
import json
|
||||
import requests
|
||||
|
||||
|
||||
MOD_OUTPUT_PATH = "./out/MODID" # CHANGE ME
|
||||
MODRINTH_PROJECT_ID = "" # CHANGE ME
|
||||
|
||||
|
||||
def main(api_key: str) -> None:
|
||||
"""EH"""
|
||||
for fpath in os.listdir(MOD_OUTPUT_PATH):
|
||||
with open(f"{MOD_OUTPUT_PATH}/{fpath}", "rb") as modfile:
|
||||
data = modfile.read()
|
||||
|
||||
parts = fpath.split("-")
|
||||
if len(parts) != 3:
|
||||
continue
|
||||
|
||||
version_title = " ".join(parts).replace(".jar", "")
|
||||
# .x versions somehow were only ever for the .0, .1 and .2 game vers lol
|
||||
if "x" in parts[1].lower():
|
||||
root = parts[1].replace(".x", "").replace(".X", "")
|
||||
game_versions = [root, f"{root}.1", f"{root}.2"]
|
||||
else:
|
||||
game_versions = [parts[1]]
|
||||
version = parts[2].replace(".jar", "")
|
||||
|
||||
payload = json.dumps(
|
||||
{
|
||||
"name": version_title,
|
||||
"version_number": f"{parts[1]}-{version}",
|
||||
"changelog": "Migrated Automagically from CurseForge",
|
||||
"dependencies": [],
|
||||
"game_versions": game_versions,
|
||||
"loaders": ["forge"],
|
||||
"featured": False,
|
||||
"requested_status": "listed",
|
||||
"version_type": "release",
|
||||
"project_id": MODRINTH_PROJECT_ID,
|
||||
"primary_file": fpath,
|
||||
"file_parts": [fpath],
|
||||
}
|
||||
)
|
||||
|
||||
response = requests.post(
|
||||
"https://api.modrinth.com/v2/version",
|
||||
headers={"Authorization": api_key},
|
||||
files=[
|
||||
("data", (None, payload, None)),
|
||||
("files", (fpath, data, "application/octet-stream")),
|
||||
],
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
print(f"Successfully uploaded {fpath} - deleting")
|
||||
os.unlink(f"{MOD_OUTPUT_PATH}/{fpath}")
|
||||
else:
|
||||
print(f"---------{fpath}---------")
|
||||
print(response.text)
|
||||
print(json.dumps(response.json(), indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if "github_token" in os.environ:
|
||||
main(os.environ["github_token"])
|
||||
else:
|
||||
print("`github_token` is not part of your PATH, add it and run again")
|
||||
Loading…
Reference in a new issue