Rearchitect

This commit is contained in:
oitsjustjose 2023-04-23 15:41:40 -05:00
commit 825d7c7246
13 changed files with 444 additions and 467 deletions

View file

@ -9,15 +9,17 @@ RUN apt-get install -y libasound2 \
unzip \
libappindicator1 \
fonts-liberation \
xvfb \
libatk-bridge2.0-0 \
libatspi2.0-0 \
libgbm1 \
libgtk-3-0 \
libu2f-udev \
libvulkan1 \
libxkbcommon0
libxkbcommon0 \
xvfb
RUN apt-get -f install
# # Install Google Chrome
RUN wget http://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
RUN dpkg -i google-chrome*.deb && rm google-chrome*.deb
@ -30,4 +32,8 @@ COPY . .
RUN pip install -r requirements.txt
CMD ["python", "src/__main__.py"]
ENV MONGO_URI ""
ENV MONGO_PORT 0
ENV SECRET ""
CMD ["python", "./src/main.py"]

View file

@ -1,64 +1,28 @@
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
dnspython==2.3.0
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
pymongo==4.3.3
PySocks==1.7.1
python-dotenv==1.0.0
pytoolconfig==1.2.5
PyVirtualDisplay==3.0
requests==2.28.2
rope==1.7.0
selenium==4.8.3
shortuuid==1.0.11
simplejson==3.19.1
six==1.16.0
selenium==4.9.0
sniffio==1.3.0
sortedcontainers==2.4.0
soupsieve==2.4.1
termcolor==2.2.0
tomli==2.0.1
tomlkit==0.11.7
tqdm==4.65.0
trio==0.22.0
trio-websocket==0.10.2
typing_extensions==4.5.0
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

View file

@ -1,81 +0,0 @@
"""
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
job_db = JobDb(env["MONGO_URI"], int(env["MONGO_PORT"]))
def _resume():
"""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() -> 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
if __name__ == "__main__":
print("Starting the job processor")
_resume()
while True:
try:
if _work():
sleep(1)
else:
sleep(5)
except KeyboardInterrupt:
print("Quitting..")
break

View file

@ -4,8 +4,6 @@ Author: oitsjustjose @ modrinth/curseforge/twitter
"""
from dataclasses import dataclass
from enum import Enum
from typing import List
@ -44,3 +42,23 @@ class ModInfo:
modrinth_name: str
game_version: str # representative game ver
game_versions: List[str] # actual game vers
class DbLogger:
"""
A base class for Upload and Download that indicates how to log
Args:
db (JobDb): the job database
job_id (str): the job id for the given job
"""
def __init__(self, db, job_id: str):
self._db = db
self._job_id = job_id
def logmsg(self, msg: str) -> None:
"""
Logs a message to the database
Args: msg(str): the message to log
"""
self._db.append_job_log(self._job_id, msg)

View file

@ -0,0 +1,174 @@
import os
from time import sleep
from typing import List
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 common import DbLogger, Job, Status
from job_database import JobDb
class CurseDownloader(DbLogger):
"""
The class for handling curse downloads
Args:
db (JobDb): the job database
job_id (str): the job id for the given job
"""
def __init__(self, db: JobDb, job: Job):
super().__init__(db, job.job_id)
self._slug = job.curseforge_slug
self._job_db = db
self._job_id = job.job_id
# REGION CHROME DRIVER AND OPTIONS
options = Options()
options.add_argument("--no-sandbox")
options.add_argument("--ignore-ssl-errors=yes")
options.add_argument("--ignore-certificate-errors")
options.add_argument("--disable-dev-shm-usage")
options.add_experimental_option("excludeSwitches", ["enable-logging"])
options.add_experimental_option(
"prefs",
{
"download.default_directory": os.path.realpath(f"./out/{self._slug}/"),
"download.prompt_for_download": False,
"download.directory_upgrade": True,
"safebrowsing.enabled": True,
},
)
self._driver = webdriver.Chrome(
service=Service(ChromeDriverManager().install()), options=options
)
# ENDREGION CHROME DRIVER AND OPTIONS
def download(self) -> Status:
"""
Downloads all mod files for a given slug
Returns: (Tuple[Status, List[str]]): The status and logs, if any
"""
root = f"https://legacy.curseforge.com/minecraft/mc-mods/{self._slug}/files/all"
os.makedirs(f"./out/{self._slug}", exist_ok=True)
self.logmsg("Populating list of mod download urls")
all_urls: List[str] = []
for page in range(self.__get_page_count(root)):
all_urls += self.__get_dl_urls_for_page(root, page + 1)
if all_urls:
self.logmsg(f"Found {len(all_urls)} Mod files to Download")
else:
self.logmsg(
f"Failed to find any files for CurseForge Project with Slug '{self._slug}' - was this spelled correctly?"
)
return Status.FAIL
statuses = self.__download_files(all_urls)
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
)
self._driver.close()
self._driver.quit()
return status
def __download_files(self, all_urls: List[str]) -> List[Status]:
"""
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
"""
statuses: List[Status] = []
file_cnt = len(os.listdir(f"./out/{self._slug}"))
for url in all_urls:
try:
self._driver.get(url)
sleep(8)
# Verify if/that file actually downloaded:
new_file_cnt = len(os.listdir(f"./out/{self._slug}"))
if new_file_cnt == file_cnt + 1: # this should work
file_cnt = new_file_cnt
statuses.append(Status.SUCCESS)
self.logmsg(f"Successfully downloaded {url}")
else:
self.logmsg(
f"Could not download jarfile from {url}. This file will need manual migration."
)
statuses.append(Status.FAIL)
except selex.TimeoutException:
self.logmsg(
f"Timed out while reaching {url}. This file will need manual migration."
)
statuses.append(Status.FAIL)
continue
except selex.WebDriverException as exception:
self.logmsg(
f"Could not download jarfile from {url}. RAW ERR: {exception}. 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(5)
return statuses
def __get_page_count(self, 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
"""
self._driver.get(f"{root}?page=1")
root = self._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 __get_dl_urls_for_page(self, 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
"""
self._driver.get(f"{root}?page={page}")
root_el = self._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,
)
)

View file

@ -3,35 +3,25 @@ DB Handling for Jobs
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
from dataclasses import asdict
from os import environ as env
from typing import Dict, List, Tuple, Union
from typing import Dict, List, Union
from cryptography.fernet import Fernet
from pymongo import ASCENDING, DESCENDING, MongoClient
from pymongo import ASCENDING, MongoClient
from pymongo.collection import Collection
from pymongo.database import Database
from shortuuid import ShortUUID
from data import Job, Status
from common import Job, Status
class JobDb:
"""A database for the job queue"""
def __init__(self, host: str, port: int):
self._client: MongoClient = MongoClient(host, port)
def __init__(self, host: str = "", port: int = 0):
self._client: MongoClient = MongoClient(host or "localhost", port or 27017)
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"""
data: Union[dict, None] = self._coll.find_one({"jobId": job_id})
if not data:
return None
return self._dict_to_job(data)
def get_next_job(self) -> Union[Job, None]:
"""Gets the next job to do, if any"""
@ -53,41 +43,15 @@ class JobDb:
)
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": Status.ENQUEUED.value})
.sort("queuePlace", DESCENDING)
.limit(1)
)
if data:
queue_place = data[0]["queuePlace"] + 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
def update_job_status(
self, job_id: str, status: Status, logs: Union[str, None] = None
) -> None:
def update_job_status(self, job_id: str, status: Status) -> None:
"""Updates the status of a job, and logs, if applicable"""
update = {"status": status.value}
if logs:
update["logs"] = logs
self._coll.update_one({"jobId": job_id}, {"$set": update})
self._coll.update_one({"jobId": job_id}, {"$set": {"status": status.value}})
def get_job_status(self, job_id: str) -> Tuple[Status, str, int]:
"""Gets the status of a job, including queue place and logs"""
data: Union[dict, None] = self._coll.find_one({"jobId": job_id})
if not data:
return (Status.NOTFOUND, [], -1)
return (
Status(data["status"]),
data["logs"],
data["queuePlace"],
def append_job_log(self, job_id: str, newlog: str) -> None:
"""Updates the status of a job, and logs, if applicable"""
job = self._coll.find_one({"jobId": job_id})
self._coll.update_one(
{"jobId": job_id}, {"$set": {"logs": f"{newlog}\n{job['logs']}"}}
)
def get_existing_queued_job(self, slug: str, proj_id: str) -> Union[str, None]:
@ -107,7 +71,7 @@ class JobDb:
def _dict_to_job(self, data: Dict) -> Job:
"""Converts a dictionary (from mongo) into a Job"""
return Job(
github_pat=self._fernet.decrypt(data["githubPat"].decode()),
github_pat=self._fernet.decrypt(data["githubPat"]),
curseforge_slug=data["curseforgeSlug"],
modrinth_id=data["modrinthId"],
logs=data["logs"] if "logs" in data else [],

82
processor/src/main.py Normal file
View file

@ -0,0 +1,82 @@
"""
Does the actual work behind the scenes
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
from os import environ as env
from os import system as run
from time import sleep
from common import Job, Status
from curse_downloader import CurseDownloader
from job_database import JobDb
from modrinth_uploader import ModrinthUploader
def _process(job_db: JobDb, job: Job):
"""Handles the download and upload process for a single job"""
job_db.update_job_status(job.job_id, Status.PROCESSING)
downloader = CurseDownloader(job_db, job)
dls = downloader.download()
if dls == Status.FAIL:
job_db.update_job_status(job.job_id, Status.COMPLETE)
job_db.append_job_log(job.job_id, "***FAILED***")
return
uploader = ModrinthUploader(job_db, job)
uls = uploader.upload()
stat = Status(max(dls.value, uls.value)).name
job_db.update_job_status(job.job_id, Status.COMPLETE)
job_db.append_job_log(job.job_id, f"***{stat}***")
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}")
_process(job_db, job)
def _work(job_db: JobDb) -> bool:
"""Does the actual lifting"""
job: Job = job_db.get_next_job()
if not job:
return False
_process(job_db, job)
return True
def main_loop():
"""The main process loop"""
print("Init DB connection")
job_db = JobDb(
env["MONGO_URI"] if "MONGO_URI" in env else "localhost",
int(env["MONGO_PORT"]) if "MONGO_PORT" in env else 27017,
)
print("DB Connected")
print("Starting virtual display")
run("Xvfb -ac :99 -screen 0 1280x1024x16 &")
env["DISPLAY"] = ":99"
print("Done initializing VDisplay")
print("Starting the job processor")
_resume(job_db)
while True:
try:
if _work(job_db):
sleep(1)
else:
sleep(5)
except KeyboardInterrupt:
run("pkill -9 Xvfb")
print("Quitting")
break
if __name__ == "__main__":
main_loop()

View file

@ -0,0 +1,135 @@
"""
Performs upload/download operations
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
import json
import os
from shutil import rmtree
from typing import List, Union
import requests
from common import DbLogger, Job, ModInfo, Status
from job_database import JobDb
class ModrinthUploader(DbLogger):
def __init__(self, job_db: JobDb, job: Job):
super().__init__(job_db, job.job_id)
self._job = job
def __get_versions(self, 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]]
def __extrapolate_mod(self, filename: 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
"""
parts = filename.replace(".jar", "").split(self._job.delimiter)
return ModInfo(
name=parts[0],
mod_version=parts[2],
modrinth_name=" ".join(parts),
game_version=parts[1],
game_versions=self.__get_versions(parts),
)
def upload(self) -> Status:
"""
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/{self._job.curseforge_slug}"):
self.logmsg(
f"CurseForge Slug {self._job.curseforge_slug} was not valid and therefore didn't download from Curse"
)
return Status.FAIL
statuses = []
for fpath in os.listdir(f"./out/{self._job.curseforge_slug}"):
with open(f"out/{self._job.curseforge_slug}/{fpath}", "rb") as modfile:
data = modfile.read()
mod_info = self.__extrapolate_mod(fpath)
if not mod_info:
self.logmsg(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": self._job.modrinth_id,
"primary_file": fpath,
"file_parts": [fpath],
}
)
try:
response = requests.post(
"https://api.modrinth.com/v2/version",
timeout=30,
headers={"Authorization": self._job.github_pat},
files=[
("data", (None, payload, None)),
("files", (fpath, data, "application/octet-stream")),
],
)
except TimeoutError:
self.logmsg(f"Timed out uploading {fpath}. Manual upload required")
if response.status_code == 200:
self.logmsg(f"Successfully uploaded {fpath}")
statuses.append(Status.SUCCESS)
else:
statuses.append(Status.FAIL)
self.logmsg("----- FILE {fpath} -----")
self.logmsg("API Response from Modrinth FAIL for {fpath}:")
if response.text: # Add text if exists
self.logmsg(response.text)
data = response.json()
if data: # Add json response if exists
self.logmsg(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/{self._job.github_pat}")
return status

View file

@ -1,285 +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, 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 pyvirtualdisplay import Display
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
display = Display(visible=0, size=(1366, 768))
display.start()
options = Options()
options.add_argument("--no-sandbox")
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
)
display.stop()
driver.close()
return status, logs