Major cleanup, fix shortids, and more
This commit is contained in:
parent
d9411642b6
commit
f74d0ee58a
9 changed files with 436 additions and 249 deletions
3
api/.gitignore
vendored
3
api/.gitignore
vendored
|
|
@ -5,4 +5,5 @@
|
|||
|
||||
state.dat
|
||||
filekey.key
|
||||
__pycache__
|
||||
__pycache__
|
||||
.envrc
|
||||
|
|
@ -1,61 +0,0 @@
|
|||
"""Does the actual work behind the scenes"""
|
||||
from os import environ as env
|
||||
from time import sleep
|
||||
|
||||
from db import Job, JobDb, Status
|
||||
from processor import download, upload
|
||||
|
||||
|
||||
def resume(job_db: JobDb):
|
||||
"""Resumes processing jobs on server restart"""
|
||||
print("Resuming jobs from last run")
|
||||
|
||||
for job in job_db.get_active_jobs():
|
||||
sleep(1)
|
||||
job: Job = job_db.get_next_job()
|
||||
if not job:
|
||||
sleep(5)
|
||||
continue
|
||||
job_db.update_job_status(job.job_id, Status.PROCESSING)
|
||||
logs = download(job.curseforge_slug)
|
||||
job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(logs))
|
||||
logs += upload(
|
||||
job.github_pat,
|
||||
job.curseforge_slug,
|
||||
job.modrinth_id,
|
||||
job.delimiter,
|
||||
)
|
||||
job_db.update_job_status(job.job_id, Status.COMPLETED, "\n".join(logs))
|
||||
|
||||
|
||||
def work(job_db: JobDb) -> bool:
|
||||
"""Does the actual lifting"""
|
||||
job: Job = job_db.get_next_job()
|
||||
if not job:
|
||||
return False
|
||||
job_db.update_job_status(job.job_id, Status.PROCESSING)
|
||||
logs = download(job.curseforge_slug)
|
||||
job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(logs))
|
||||
logs += upload(
|
||||
job.github_pat,
|
||||
job.curseforge_slug,
|
||||
job.modrinth_id,
|
||||
job.delimiter,
|
||||
)
|
||||
job_db.update_job_status(job.job_id, Status.COMPLETED, "\n".join(logs))
|
||||
return True
|
||||
|
||||
|
||||
def worker():
|
||||
"""A worker thread function for processing jobs in the job db"""
|
||||
print("Starting the job processor")
|
||||
job_db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"]))
|
||||
resume(job_db)
|
||||
while True:
|
||||
try:
|
||||
if work(job_db):
|
||||
sleep(1)
|
||||
else:
|
||||
sleep(5)
|
||||
except KeyboardInterrupt:
|
||||
break
|
||||
152
api/processor.py
152
api/processor.py
|
|
@ -1,152 +0,0 @@
|
|||
"""
|
||||
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_argument("--ignore-ssl-errors=yes")
|
||||
options.add_argument("--ignore-certificate-errors")
|
||||
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
|
||||
|
|
@ -10,10 +10,10 @@ from os import environ as env
|
|||
|
||||
from flask import Flask, request
|
||||
|
||||
from db import Job, JobDb, Status
|
||||
from data import Status
|
||||
from job_database import Job, JobDb, Status
|
||||
from job_processor import worker
|
||||
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"]))
|
||||
|
|
@ -27,9 +27,9 @@ def get_job_status(job_id: str) -> str:
|
|||
if status == Status.ENQUEUED:
|
||||
return f"Enqueued: {queue} Job(s) Ahead In Queue", 200
|
||||
if status == Status.PROCESSING:
|
||||
return f"Currently Processing!\n{logs}", 200
|
||||
if status == Status.COMPLETED:
|
||||
return f"Completed!\n{logs}", 200
|
||||
return f"Currently Processing\n{logs}", 200
|
||||
if status == Status.COMPLETE:
|
||||
return logs, 200
|
||||
return "Failed to find job", 404
|
||||
|
||||
|
||||
44
api/src/data.py
Normal file
44
api/src/data.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"""
|
||||
Houses data classes
|
||||
Author: oitsjustjose @ modrinth/curseforge/twitter
|
||||
"""
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import List, Union
|
||||
|
||||
|
||||
class Status(Enum):
|
||||
"""Job Status"""
|
||||
|
||||
ENQUEUED = 0
|
||||
PROCESSING = 1
|
||||
COMPLETE = 2
|
||||
SUCCESS = 3
|
||||
PARTIAL_FAIL = 4
|
||||
FAIL = 5
|
||||
NOTFOUND = -1
|
||||
|
||||
|
||||
@dataclass
|
||||
class Job:
|
||||
"""A single job"""
|
||||
|
||||
github_pat: str
|
||||
curseforge_slug: str
|
||||
modrinth_id: str
|
||||
job_id: str = ""
|
||||
delimiter: str = "-"
|
||||
logs: str = ""
|
||||
status: Status = Status.ENQUEUED
|
||||
queue_place: int = 0
|
||||
|
||||
|
||||
@dataclass
|
||||
class ModInfo:
|
||||
"""Stores metadata about a jarfile to be extrapolated"""
|
||||
|
||||
name: str
|
||||
mod_version: str
|
||||
modrinth_name: str
|
||||
game_version: str # representative game ver
|
||||
game_versions: List[str] # actual game vers
|
||||
|
|
@ -1,7 +1,9 @@
|
|||
"""DB Handling for Jobs"""
|
||||
"""
|
||||
DB Handling for Jobs
|
||||
Author: oitsjustjose @ modrinth/curseforge/twitter
|
||||
"""
|
||||
|
||||
from dataclasses import asdict, dataclass
|
||||
from enum import Enum
|
||||
from dataclasses import asdict
|
||||
from os import environ as env
|
||||
from typing import Dict, List, Tuple, Union
|
||||
|
||||
|
|
@ -11,28 +13,7 @@ from pymongo.collection import Collection
|
|||
from pymongo.database import Database
|
||||
from shortuuid import ShortUUID
|
||||
|
||||
|
||||
class Status(Enum):
|
||||
"""Job Status"""
|
||||
|
||||
ENQUEUED = 0
|
||||
PROCESSING = 1
|
||||
COMPLETED = 2
|
||||
NOTFOUND = -1
|
||||
|
||||
|
||||
@dataclass
|
||||
class Job:
|
||||
"""A single job"""
|
||||
|
||||
github_pat: str
|
||||
curseforge_slug: str
|
||||
modrinth_id: str
|
||||
job_id: str = ShortUUID().random(length=8)
|
||||
delimiter: str = "-"
|
||||
logs: str = ""
|
||||
status: Status = Status.ENQUEUED
|
||||
queue_place: int = 0
|
||||
from data import Job, Status
|
||||
|
||||
|
||||
class JobDb:
|
||||
|
|
@ -43,6 +24,7 @@ class JobDb:
|
|||
self._db: Database = self._client["ctmmm"]
|
||||
self._coll: Collection = self._db["jobs"]
|
||||
self._fernet = Fernet(env["SECRET"])
|
||||
self._shrt = ShortUUID()
|
||||
|
||||
def get_job(self, job_id: str) -> Union[Job, None]:
|
||||
"""Gets a job by the job's short ID"""
|
||||
|
|
@ -54,7 +36,9 @@ class JobDb:
|
|||
def get_next_job(self) -> Union[Job, None]:
|
||||
"""Gets the next job to do, if any"""
|
||||
data: List[Union[dict, None]] = list(
|
||||
self._coll.find({"status": 0}).sort("queue_place", ASCENDING).limit(1)
|
||||
self._coll.find({"status": Status.ENQUEUED.value})
|
||||
.sort("queue_place", ASCENDING)
|
||||
.limit(1)
|
||||
)
|
||||
if data:
|
||||
return self._dict_to_job(data[0])
|
||||
|
|
@ -62,21 +46,26 @@ class JobDb:
|
|||
|
||||
def get_active_jobs(self) -> List[Job]:
|
||||
data: List[Union[dict, None]] = list(
|
||||
self._coll.find({"status": 0}).sort("queue_place", ASCENDING).limit(1)
|
||||
self._coll.find({"status": Status.PROCESSING.value})
|
||||
.sort("queue_place", ASCENDING)
|
||||
.limit(1)
|
||||
)
|
||||
return data
|
||||
return [self._dict_to_job(x) for x in data]
|
||||
|
||||
def enqueue_job(self, job: Job) -> str:
|
||||
"""Inserts the job, with corrected Queue Place and encrypted PAT"""
|
||||
queue_place = 0
|
||||
data: List[Union[dict, None]] = list(
|
||||
self._coll.find({"status": 0}).sort("queue_place", DESCENDING).limit(1)
|
||||
self._coll.find({"status": Status.ENQUEUED.value})
|
||||
.sort("queue_place", DESCENDING)
|
||||
.limit(1)
|
||||
)
|
||||
if data:
|
||||
queue_place = data[0]["queue_place"] + 1
|
||||
job.queue_place = queue_place
|
||||
job.github_pat = self._fernet.encrypt(job.github_pat.encode())
|
||||
job.status = job.status.value
|
||||
job.job_id = self._shrt.random(length=8)
|
||||
self._coll.insert_one(asdict(job))
|
||||
return job.job_id
|
||||
|
||||
|
|
@ -109,6 +98,7 @@ class JobDb:
|
|||
"modrinth_id": proj_id,
|
||||
}
|
||||
)
|
||||
print(data)
|
||||
if not data:
|
||||
return None
|
||||
return data["job_id"]
|
||||
80
api/src/job_processor.py
Normal file
80
api/src/job_processor.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
"""
|
||||
Does the actual work behind the scenes
|
||||
Author: oitsjustjose @ modrinth/curseforge/twitter
|
||||
"""
|
||||
from os import environ as env
|
||||
from time import sleep
|
||||
|
||||
from data import Job, Status
|
||||
from job_database import JobDb
|
||||
from netio_processor import download, upload
|
||||
|
||||
|
||||
def _resume(job_db: JobDb):
|
||||
"""Resumes processing jobs on server restart"""
|
||||
print("Resuming jobs from last run")
|
||||
|
||||
for job in job_db.get_active_jobs():
|
||||
print(f"Resuming job {job.job_id}")
|
||||
job_db.update_job_status(job.job_id, Status.PROCESSING)
|
||||
dl_status, dl_logs = download(job.curseforge_slug)
|
||||
if dl_status == Status.FAIL: # Failed - early exit, update DB for user
|
||||
job_db.update_job_status(
|
||||
job.job_id, Status.COMPLETE, "\n".join(["**FAILED**"] + dl_logs)
|
||||
)
|
||||
continue
|
||||
# Didn't fail, update DB with latest logs and same status
|
||||
job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(dl_logs))
|
||||
ul_status, ul_logs = upload(
|
||||
job.github_pat, job.curseforge_slug, job.modrinth_id, job.delimiter
|
||||
)
|
||||
# Take the higher severity - it would only be
|
||||
text_status = Status(max(dl_status.value, ul_status.value)).name
|
||||
job_db.update_job_status(
|
||||
job.job_id,
|
||||
Status.COMPLETE,
|
||||
"\n".join([f"**{text_status}**"] + ul_logs + dl_logs),
|
||||
)
|
||||
|
||||
|
||||
def _work(job_db: JobDb) -> bool:
|
||||
"""Does the actual lifting"""
|
||||
job: Job = job_db.get_next_job()
|
||||
if not job:
|
||||
return False
|
||||
|
||||
job_db.update_job_status(job.job_id, Status.PROCESSING)
|
||||
dl_status, dl_logs = download(job.curseforge_slug)
|
||||
if dl_status == Status.FAIL: # Failed - early exit, update DB for user
|
||||
job_db.update_job_status(
|
||||
job.job_id, Status.COMPLETE, "\n".join(["**FAILED**"] + dl_logs)
|
||||
)
|
||||
return True
|
||||
# Didn't fail, update DB with latest logs and same status
|
||||
job_db.update_job_status(job.job_id, Status.PROCESSING, "\n".join(dl_logs))
|
||||
ul_status, ul_logs = upload(
|
||||
job.github_pat, job.curseforge_slug, job.modrinth_id, job.delimiter
|
||||
)
|
||||
# Take the higher severity - it would only be
|
||||
text_status = Status(max(dl_status.value, ul_status.value)).name
|
||||
job_db.update_job_status(
|
||||
job.job_id,
|
||||
Status.COMPLETE,
|
||||
"\n".join([f"**{text_status}**"] + ul_logs + dl_logs),
|
||||
)
|
||||
return True
|
||||
|
||||
|
||||
def worker():
|
||||
"""A worker thread function for processing jobs in the job db"""
|
||||
print("Starting the job processor")
|
||||
job_db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"]))
|
||||
_resume(job_db)
|
||||
while True:
|
||||
try:
|
||||
if _work(job_db):
|
||||
sleep(1)
|
||||
else:
|
||||
sleep(5)
|
||||
except KeyboardInterrupt:
|
||||
break
|
||||
279
api/src/netio_processor.py
Normal file
279
api/src/netio_processor.py
Normal file
|
|
@ -0,0 +1,279 @@
|
|||
"""
|
||||
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, Tuple, Union
|
||||
|
||||
import requests
|
||||
import selenium.common.exceptions as selex
|
||||
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
|
||||
|
||||
from data import ModInfo, Status
|
||||
|
||||
|
||||
def __extrapolate_mod(filename: str, delimiter: str) -> Union[ModInfo, None]:
|
||||
"""
|
||||
Extrapolates mod info from a given jarfile name
|
||||
Args:
|
||||
filename (str): the name of the jarfile
|
||||
delimiter (str): the splitter between parts of the filename
|
||||
Returns: (ModInfo|None): the extraploted mod info, None if extrap failed
|
||||
"""
|
||||
|
||||
def get_versions(parts: List[str]) -> List[str]:
|
||||
"""
|
||||
Most of the patches that we modders labeled as ".x" (i.e. 1.18.x) were
|
||||
specifically for .0, .1, .2 patches. This is presumptuous, but it's
|
||||
not that terrible to fix.
|
||||
Args: parts (List[str]): the split jarfile string
|
||||
Returns: (List[str]) a list of assumed supported MC versions
|
||||
"""
|
||||
#
|
||||
if "x" in parts[1].lower():
|
||||
root = parts[1].replace(".x", "").replace(".X", "")
|
||||
return [root, f"{root}.1", f"{root}.2"]
|
||||
return [parts[1]]
|
||||
|
||||
parts = filename.replace(".jar", "").split(delimiter)
|
||||
return ModInfo(
|
||||
name=parts[0],
|
||||
mod_version=parts[2],
|
||||
modrinth_name=" ".join(parts),
|
||||
game_version=parts[1],
|
||||
game_versions=get_versions(parts),
|
||||
)
|
||||
|
||||
|
||||
def __get_mods_for_page(driver: webdriver.Chrome, root: str, page: int) -> List[str]:
|
||||
"""
|
||||
Gets all mod download URLs for a given page
|
||||
Args:
|
||||
driver (webdriver.Chrome): the chrome driver
|
||||
root (str): the root url, i.e. https://legacy.curseforge.com/{slug}/files/all
|
||||
page (int): the page number, added as a query to the query str
|
||||
Returns:
|
||||
(List[str]): a list of download urls for the mod files
|
||||
"""
|
||||
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 __get_page_count(driver: webdriver.Chrome, root: str) -> int:
|
||||
"""
|
||||
Gets the page count for a given mod slug
|
||||
Args:
|
||||
driver (webdriver.Chrome): the chrome driver
|
||||
root (str): the root url, i.e. https://legacy.curseforge.com/{slug}/files/all
|
||||
Returns: (int): the number of pages for the mod
|
||||
"""
|
||||
driver.get(f"{root}?page=1")
|
||||
root = driver.page_source
|
||||
root = BeautifulSoup(root, features="html.parser")
|
||||
root = root.body.find_all("a", attrs={"class": "pagination-item"})
|
||||
if root: # mods with only 1 page won't have a pagination item
|
||||
root = root[-1]
|
||||
root = root.find("span").text
|
||||
return int(root)
|
||||
return 1
|
||||
|
||||
|
||||
def __download_files(
|
||||
driver: webdriver.Chrome, all_urls: List[str], slug: str
|
||||
) -> Tuple[List[Status], List[str]]:
|
||||
"""
|
||||
Attempts to download jarfiles from the acquired list of urls
|
||||
Args:
|
||||
driver (webdriver.Chrome): the chrome driver
|
||||
all_urls (List[str]): a list of download urls for the mod files
|
||||
slug (str): the CurseForge slug, used to traverse the local filesystem
|
||||
Returns:
|
||||
(Tuple[List[Status], List[str]]) A list of statuses and logs
|
||||
"""
|
||||
logs: List[str] = []
|
||||
statuses: List[Status] = []
|
||||
file_cnt = len(os.listdir(f"./out/{slug}"))
|
||||
|
||||
for url in all_urls:
|
||||
try:
|
||||
driver.get(url)
|
||||
sleep(8)
|
||||
# Verify if/that file actually downloaded:
|
||||
new_file_cnt = len(os.listdir(f"./out/{slug}"))
|
||||
if new_file_cnt == file_cnt + 1: # this should work
|
||||
file_cnt = new_file_cnt
|
||||
statuses.append(Status.SUCCESS)
|
||||
else:
|
||||
logs.append(f"Could not download jarfile from {url}")
|
||||
logs.append("This file will need manual migration")
|
||||
statuses.append(Status.FAIL)
|
||||
except selex.TimeoutException:
|
||||
logs.append(f"Timed out while reaching {url}.")
|
||||
logs.append("This file will need manual migration")
|
||||
statuses.append(Status.FAIL)
|
||||
continue
|
||||
except selex.WebDriverException as exception:
|
||||
logs.append(f"Could not download jarfile from {url}. RAW ERR: {exception}")
|
||||
logs.append("This file will need manual migration")
|
||||
statuses.append(Status.FAIL)
|
||||
continue
|
||||
|
||||
# Yes, this could also be true if a download failed... oh well
|
||||
if file_cnt != len(all_urls):
|
||||
sleep(15)
|
||||
return statuses, logs
|
||||
|
||||
|
||||
def upload(
|
||||
api_key: str, slug: str, proj_id: str, delimiter: str
|
||||
) -> Tuple[Status, 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
|
||||
Returns:
|
||||
Tuple[Status, List[str]]: The overall status and any accompanying logs
|
||||
"""
|
||||
|
||||
if not os.path.exists(f"./out/{slug}"):
|
||||
return Status.FAIL, [
|
||||
f"CurseForge Slug {slug} was not valid and therefore didn't download from Curse"
|
||||
]
|
||||
|
||||
logs = []
|
||||
statuses = []
|
||||
|
||||
for fpath in os.listdir(f"./out/{slug}"):
|
||||
with open(f"out/{slug}/{fpath}", "rb") as modfile:
|
||||
data = modfile.read()
|
||||
|
||||
mod_info = __extrapolate_mod(fpath, delimiter)
|
||||
if not mod_info:
|
||||
logs.append(f"Couldn't parse name/version info for file {fpath}")
|
||||
continue
|
||||
|
||||
payload = json.dumps(
|
||||
{
|
||||
"name": mod_info.name,
|
||||
"version_number": mod_info.modrinth_name,
|
||||
"changelog": "Migrated Automagically from CurseForge",
|
||||
"dependencies": [],
|
||||
"game_versions": mod_info.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}")
|
||||
statuses.append(Status.SUCCESS)
|
||||
else:
|
||||
statuses.append(Status.FAIL)
|
||||
logs.append("----- FILE {fpath} -----")
|
||||
logs.append("API Response from Modrinth FAIL for {fpath}:")
|
||||
if response.text: # Add text if exists
|
||||
logs.append(response.text)
|
||||
data = response.json(indent=2)
|
||||
if data: # Add json response if exists
|
||||
logs.append(data)
|
||||
|
||||
any_succ = len(list(filter(lambda x: x == Status.SUCCESS, statuses))) > 0
|
||||
any_fail = len(list(filter(lambda x: x == Status.SUCCESS, statuses))) > 0
|
||||
status = (
|
||||
Status.PARTIAL_FAIL
|
||||
if any_succ and any_fail
|
||||
else Status.SUCCESS
|
||||
if any_succ and not any_fail
|
||||
else Status.FAIL
|
||||
)
|
||||
rmtree(f"./out/{slug}")
|
||||
return status, logs
|
||||
|
||||
|
||||
def download(slug: str) -> Tuple[Status, List[str]]:
|
||||
"""
|
||||
Downloads all mod files for a given slug
|
||||
Args: slug (str): the slug for the given Curse Mod Project
|
||||
Returns: (Tuple[Status, List[str]]): The status and logs, if any
|
||||
"""
|
||||
root = f"https://legacy.curseforge.com/minecraft/mc-mods/{slug}/files/all"
|
||||
os.makedirs(f"./out/{slug}", exist_ok=True)
|
||||
|
||||
# REGION CHROME DRIVER AND OPTIONS
|
||||
options = Options()
|
||||
options.add_argument("--ignore-ssl-errors=yes")
|
||||
options.add_argument("--ignore-certificate-errors")
|
||||
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
|
||||
)
|
||||
# ENDREGION CHROME DRIVER AND OPTIONS
|
||||
|
||||
all_urls: List[str] = []
|
||||
for page in range(__get_page_count(driver, root)):
|
||||
all_urls += __get_mods_for_page(driver, root, page + 1)
|
||||
if not all_urls:
|
||||
return Status.FAIL, [
|
||||
f"Failed to find any files for CurseForge Project with Slug '{slug}' - was this spelled correctly?"
|
||||
]
|
||||
statuses, logs = __download_files(driver, all_urls, slug)
|
||||
|
||||
any_succ = len(list(filter(lambda x: x == Status.SUCCESS, statuses))) > 0
|
||||
any_fail = len(list(filter(lambda x: x == Status.SUCCESS, statuses))) > 0
|
||||
status = (
|
||||
Status.PARTIAL_FAIL
|
||||
if any_succ and any_fail
|
||||
else Status.SUCCESS
|
||||
if any_succ and not any_fail
|
||||
else Status.FAIL
|
||||
)
|
||||
|
||||
return status, logs
|
||||
|
|
@ -15,5 +15,11 @@ export default ({ id }) => {
|
|||
return () => clearInterval(handle);
|
||||
}, [setLogs, id]);
|
||||
|
||||
return (<code>{logs}</code>);
|
||||
return (
|
||||
<code>
|
||||
{logs.split('\n').map((log) => (
|
||||
<p>{log}</p>
|
||||
))}
|
||||
</code>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
Loading…
Reference in a new issue