New ultra-fast provider who dis

This commit is contained in:
oitsjustjose 2023-04-30 01:52:06 -05:00
commit 993fef81dc
7 changed files with 590 additions and 442 deletions

View file

@ -7,64 +7,36 @@ from os import system as run
from time import sleep
from common import Job, Status
from curse_downloader import CurseDownloader
from mgmt_tools import MgmtApiHelper
from modrinth_uploader import ModrinthUploader
def _download(helper: MgmtApiHelper, job: Job, retries=0) -> Status:
"""Performs function - returns True if success, False otherwise"""
try:
downloader = CurseDownloader(helper, job)
status = downloader.download()
if status == Status.FAIL:
helper.update_job_status(job.job_id, Status.COMPLETE)
helper.append_job_log(job.job_id, "***FAILED***")
return status
except Exception as exc:
helper.update_job_status(job, Status.ENQUEUED)
helper.append_job_log(
job,
f"Download Error: {exc}. Restarting Download.. ({3-retries} retries left)",
)
print(exc)
if retries <= 3:
sleep(10)
return _download(helper, job, retries=retries + 1)
return Status.FAIL
def _upload(helper: MgmtApiHelper, job: Job, retries=0) -> Status:
"""Performs function - returns True if success, False otherwise"""
try:
uploader = ModrinthUploader(helper, job)
status = uploader.upload()
return status
except Exception as exc:
helper.update_job_status(job, Status.ENQUEUED)
helper.append_job_log(
job,
f"Upload Error: {exc}. Restarting Upload.. ({3-retries} retries left)",
)
if retries <= 3:
sleep(10)
return _upload(helper, job, retries=retries + 1)
return Status.FAIL
from x_fast_provider import FastProvider
from x_slow_provider import SlowProvider
def process_job(helper: MgmtApiHelper, job: Job):
"""Handles the download and upload process for a single job"""
helper.update_job_status(job.job_id, Status.PROCESSING)
download_status = _download(helper, job)
if download_status == Status.FAIL:
# Try to use the fast provider first
fast_prov = FastProvider(helper, job)
if fast_prov.supports_downloads():
helper.append_job_log(
job.job_id,
f"ℹ️ Mod {job.curseforge_slug} supports third-party launchers, migration will be quick 🙂",
)
status = fast_prov.process()
helper.update_job_status(job.job_id, Status.COMPLETE)
helper.append_job_log(job.job_id, f"***{status.name}***")
return
upload_status = _upload(helper, job)
status = Status(max(download_status.value, upload_status.value)).name
# Otherwise use the slow provider since you're a goblin 👺
slow_prov = SlowProvider(helper, job)
helper.append_job_log(
job.job_id,
f"ℹ️ Mod {job.curseforge_slug} does not support third-party launchers, migration will be slowed by workarounds 😭",
)
status = slow_prov.process()
helper.update_job_status(job.job_id, Status.COMPLETE)
helper.append_job_log(job.job_id, f"***{status}***")
helper.append_job_log(job.job_id, f"***{status.name}***")
def resume(helper: MgmtApiHelper):

111
processor/src/curse_api.py Normal file
View file

@ -0,0 +1,111 @@
"""
@author: oitsjustjose @ github / twitter / modrinth
@license: MIT
@description: Common core CurseAPI utils
"""
import re
from os import environ as env
from typing import Callable, List, Tuple, Union
import requests
def get_modid(slug: str, logmsg: Callable[[str], None]) -> Union[str, None]:
"""
Gets the ModID for this job
Returns (str): the mod name if any
"""
try:
response = requests.get(
f"https://api.curseforge.com/v1/mods/search?gameId=432&slug={slug}",
headers={"x-api-key": env["CURSE_API_KEY"]},
timeout=30,
)
if not response.ok:
logmsg(f"🔥 Failed to get mod_id for {slug}.")
return None
mod_id = response.json()["data"][0]["id"]
return mod_id
except TimeoutError:
logmsg("🕜 Timed out getting mod_id from slug")
return None
def get_pages(mod_id: str, logmsg: Callable[[str], None]) -> Tuple[int, int]:
"""
Gets the number of pages and the item count of the final page for the mod
Returns (Tuple[int, int]): (-1,-1) on failure, values above otherwise
"""
try:
response = requests.get(
f"https://api.curseforge.com/v1/mods/{mod_id}/files",
headers={"x-api-key": env["CURSE_API_KEY"]},
timeout=30,
)
data = response.json()["pagination"]
num_pages = data["totalCount"] // data["pageSize"]
last_page_size = data["totalCount"] % data["pageSize"]
return num_pages, last_page_size
except TimeoutError:
logmsg("🕜 Timed out getting mod list")
return -1, -1
def get_changelog(mod_id: str, file_id: str) -> str:
"""
Gets the changelog from Curse for a given File ID.
Args: file_id (str): the File ID in question
Returns: (str): the changelog or a reasonable fallback
"""
try:
response = requests.get(
f"https://api.curseforge.com/v1/mods/{mod_id}/files/{file_id}/changelog",
headers={"x-api-key": env["CURSE_API_KEY"]},
timeout=30,
)
return response.json()["data"]
except TimeoutError:
return "Automagically migrated from CurseForge via https://ctm.oitsjustjose.com"
# region NON-API-CALL FUNCTIONS
def get_loader_info(game_versions: List[str]) -> Tuple[List[str], List[str]]:
"""
Gets the game version(s) and loader(s) for the mod given the mod's `gameVersions` attr
Args: game_versions (List[str]): the list of game versions
Returns: (Tuple[List[str], List[str]]): the minecraft versions and the loader(s), respectively
"""
print(game_versions)
mc_versions = list(
filter(lambda x: re.match(r"^1.[0-9].*.[0-9]?", x), game_versions)
)
loaders = list(
filter(lambda x: x.lower() in ["forge", "quilt", "fabric"], game_versions)
)
return mc_versions, [x.lower() for x in loaders] or ["forge"]
def get_version(file_name: str) -> str:
"""
Gets the version string to be used in Modrinth only, by removing everything but
numbers and concatenating with a hyphen ("-")
Args: file_name (str): the file's display name
Returns: (str): a Modrinth RegEx friendly version number
"""
ver = re.sub(r"[^0-9.-]", "-", file_name)
while "--" in ver:
ver = ver.replace("--", "-")
while (
ver.startswith(".")
or ver.startswith("-")
or ver.endswith("-")
or ver.endswith(".")
):
ver = ver.strip(".")
ver = ver.strip("-")
return ver
# endregion NON-API-CALL FUNCTIONS

View file

@ -1,237 +0,0 @@
"""
Downloads mod files from Curse
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
import json
import os
import re
from time import sleep
from typing import List
import selenium.common.exceptions as selex
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
from common import Job, Status
from mgmt_tools import MgmtApiHelper, MgmtApiLogger
def driver_get(driver: webdriver, url: str, timeout=30) -> bool:
"""
Attempts to get a URL with a given webdriver with a timeout
Args:
driver (webdriver): the webdriver
url (str): the url to navigate to
timeout (int) = 30: the time to wait before quitting
Returns:
(bool): True if successfully navigated, False otherwise
"""
try:
print(f"Attempting to get URL {url}")
driver.get(url)
WebDriverWait(driver, timeout).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
return True
except TimeoutException:
print(f"Failed to get {url}")
return False
class CurseDownloader(MgmtApiLogger):
"""
The class for handling curse downloads
Args:
helper (MgmtApiHelper): the job database
job_id (str): the job id for the given job
"""
def __init__(self, helper: MgmtApiHelper, job: Job):
super().__init__(helper, job.job_id)
self._slug = job.curseforge_slug
self._helper = helper
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: (Status): The status of the download
"""
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
self.__build_manifest(all_urls)
# Convert to DL links AFTER building mf.json
all_urls = list(map(lambda x: x.replace("files", "download"), all_urls))
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
)
return status
def __build_manifest(self, all_urls: List[str]) -> None:
"""Builds the manifest with important metadata"""
self.logmsg("Building Manifest")
manifest = {}
all_loaders = ["forge", "fabric", "quilt"]
for url in all_urls:
driver_get(self._driver, url)
soup = BeautifulSoup(self._driver.page_source, features="html.parser")
# REGION GET FILE NAME
header = soup.find_all(
"span", attrs={"class": "font-bold text-sm leading-loose"}
)
header = list(filter(lambda x: x.text == "Filename", header))[0]
file_name = header.parent()[-1].text
# ENDREGION GET FILE NAME
# REGION GET VERSIONS
vers = soup.find_all("span", attrs={"class": "tag"})
vers = list(filter(lambda x: re.match(r"^[0-9.]", x.text), vers))
vers = list(map(lambda x: re.sub(r"[^0-9.]", "", x.text), vers))
vers.sort()
# ENDREGION GET VERSIONS
# REGION GET LOADER
loaders = soup.find_all("span", attrs={"class": "tag"})
loaders = list(filter(lambda x: x.text.lower() in all_loaders, loaders))
loaders = list(map(lambda x: x.text.lower(), loaders))
# ENDREGION GET LOADER
manifest[file_name] = {
"versions": vers,
"version": vers[-1],
"loaders": loaders or ["forge"],
}
with open(f"./out/{self._slug}.mf.json", "w", encoding="utf-8") as handle:
handle.write(json.dumps(manifest))
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:
driver_get(self._driver, 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
"""
driver_get(self._driver, f"{root}?page=1")
soup = BeautifulSoup(self._driver.page_source, features="html.parser")
soup = soup.body.find_all("a", attrs={"class": "pagination-item"})
if soup: # mods with only 1 page won't have a pagination item
soup = soup[-1]
soup = soup.find("span").text
return int(soup)
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
"""
driver_get(self._driver, f"{root}?page={page}")
soup = BeautifulSoup(self._driver.page_source, features="html.parser")
file_links = soup.find_all("a", attrs={"data-action": "file-link"})
file_links = list(map(lambda x: x["href"], file_links))
file_links = list(
map(lambda x: f"https://legacy.curseforge.com{x}", file_links)
)
return file_links

View file

@ -15,12 +15,12 @@ class MgmtApiHelper:
"""An API Helper for the Job API"""
def __init__(self):
self._mgmt_timeout = 30
self._mgmt_timeout = 5
self._mgmt_host = env["MGMT_HOST"]
self._mgmt_key = env["MGMT_KEY"]
self._fernet = Fernet(env["SECRET"])
# REGION NON JOB-SPECIFIC METHODS
# region NON JOB-SPECIFIC METHODS
def get_next_job(self) -> Union[Job, None]:
"""Gets the next job to do, if any"""
@ -63,7 +63,7 @@ class MgmtApiHelper:
queue_place=data["queuePlace"],
)
# ENDREGION NON JOB-SPECIFIC METHODS
# endregion NON JOB-SPECIFIC METHODS
def update_job_status(self, job_id: str, status: Status) -> None:
"""Updates the status of a job"""
@ -85,9 +85,10 @@ class MgmtApiHelper:
timeout=self._mgmt_timeout,
data={"log": newlog},
)
except requests.exceptions.ReadTimeout as exc:
print(f"Timed out updating the status of job {job_id}:\n{exc}")
except requests.exceptions.ConnectionError as exc:
print(f"Failed to update the status of job {job_id}:")
print(exc)
print(f"Failed to update the status of job {job_id}:\n{exc}")
class MgmtApiLogger:

View file

@ -1,152 +0,0 @@
"""
Uploads mod files to Modrinth
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
import json
import re
import os
from shutil import rmtree
from typing import List, Union
import requests
from common import Job, ModInfo, Status
from mgmt_tools import MgmtApiHelper, MgmtApiLogger
class ModrinthUploader(MgmtApiLogger):
"""
Handles uploading jar files to Modrinth
Args:
helper (MgmtApiHelper): the current mongo instance for the Job DB
job (Job): the job to process
"""
def __init__(self, helper: MgmtApiHelper, job: Job):
super().__init__(helper, 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 __get_mod_info(self, filename: str) -> Union[ModInfo, None]:
"""
Loads mod info from the manifest generated during download
Args:
filename (str): the name of the jarfile
Returns: (ModInfo|None): the extraploted mod info, None if extrap failed
"""
name = filename.replace(".jar", "")
# Finds the versioning (like 1.19.2-1.2.3, 1.2.3) in the name
# TODO: more robust to grab from jar metadata, but sometimes it isn't there?
search = re.search(r"([0-9.].*)", name)
if not search:
return None
mod_version = name[search.start() : search.end()]
manifest_path = f"./out/{self._job.curseforge_slug}.mf.json"
with open(manifest_path, "r", encoding="utf-8") as handle:
manifest = json.loads(handle.read())
return ModInfo(
modrinth_name=name,
mod_version=mod_version,
loaders=manifest[filename]["loaders"],
game_version=manifest[filename]["version"],
game_versions=manifest[filename]["versions"],
)
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
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.__get_mod_info(fpath)
if not mod_info:
self.logmsg(f"Couldn't parse name/version info for file {fpath}")
continue
payload = json.dumps(
{
"name": mod_info.modrinth_name,
"version_number": mod_info.mod_version,
"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],
}
)
print(payload)
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(f"----- FILE {fpath} -----")
self.logmsg(f"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.curseforge_slug}")
return status

View file

@ -0,0 +1,193 @@
"""
@author: oitsjustjose @ github / twitter / modrinth
@license: MIT
@description: A fast working mod migrator from Curse to Modrinth
Use the other one for worse performance >:[
"""
import json
from os import environ as env
from os import unlink as rm
from textwrap import dedent
from typing import List
import requests
import curse_api as cf
from common import Job, Status
from mgmt_tools import MgmtApiHelper, MgmtApiLogger
class FastProvider(MgmtApiLogger):
"""
The class for handling curse downloads
Args:
helper (MgmtApiHelper): the job database
job_id (str): the job id for the given job
"""
def __init__(self, helper: MgmtApiHelper, job: Job):
super().__init__(helper, job.job_id)
self._helper = helper
self._job = job
self._modid = cf.get_modid(job.curseforge_slug, self.logmsg)
self._rel_map = {1: "release", 2: "beta", 3: "alpha"}
def _process_all_mods(self, mods: dict) -> List[Status]:
"""
Downloads and then uploads all mods from a given page of mods from /list
Args: mods (dict): the JSON payload from /list
Returns: (List[Status]): a list of statuses for each mod
"""
statuses = []
for mod in mods:
if (
not mod["isAvailable"]
or "downloadUrl" not in mod
or not mod["downloadUrl"]
):
continue
jar_fn = mod["fileName"]
display_nm = mod["displayName"]
game_versions, loaders = cf.get_loader_info(mod["gameVersions"])
# region DOWNLOAD JAR FILE
try:
with requests.get(mod["downloadUrl"], stream=True, timeout=30) as strm:
strm.raise_for_status()
with open(jar_fn, "wb") as jar:
for chunk in strm.iter_content(chunk_size=8192):
jar.write(chunk)
except TimeoutError:
self.logmsg(f"🕜 Timed out downloading {display_nm}, skipping..")
statuses.append(Status.FAIL)
continue
# endregion DOWNLOAD JAR FILE
# region UPLOAD JAR FILE
with open(jar_fn, "rb") as modfile:
jar_data = modfile.read()
payload = json.dumps(
{
"name": display_nm,
"version_number": cf.get_version(display_nm),
"changelog": cf.get_changelog(self._modid, mod["id"]),
"dependencies": [], # Dependencies need to be manually included
"game_versions": game_versions,
"loaders": loaders,
"featured": False,
"version_type": self._rel_map[mod["releaseType"]],
"requested_status": "listed",
"project_id": self._job.modrinth_id,
"primary_file": jar_fn,
"file_parts": [jar_fn],
}
)
print(payload)
try:
response = requests.post(
"https://api.modrinth.com/v2/version",
timeout=30,
headers={"Authorization": self._job.github_pat},
files=[
("data", (None, payload, None)),
("files", (jar_fn, jar_data, "application/octet-stream")),
],
)
if response.status_code == 200:
statuses.append(Status.SUCCESS)
self.logmsg(f"✅ {display_nm}")
else:
print(response.json()["description"])
statuses.append(Status.FAIL)
self.logmsg(
dedent(
f"""----- 🔥 {display_nm} -----
API Response from Modrinth FAIL for {display_nm}:
{response.json()["description"]}
"""
).strip("\n")
)
rm(jar_fn)
except TimeoutError:
self.logmsg(f"🕜 Timed out uploading {jar_fn}. Manual upload required")
statuses.append(Status.FAIL)
# endregion UPLOAD JAR FILE
return statuses
def process(self) -> Status:
"""Returns: (status): the status of the procedure"""
self.logmsg("ℹ️ Retrieving Curse ModID from Slug")
if not self._modid:
return Status.FAIL
self.logmsg("ℹ️ Enumerating Curse API Pages")
pages, last_size = cf.get_pages(self._modid, self.logmsg)
if pages == -1 and last_size == -1:
return Status.FAIL
self.logmsg(f"ℹ️ Processing {(pages*50)+last_size} files")
statuses: List[Status] = []
try:
for idx in range(pages):
response = requests.get(
f"https://api.curseforge.com/v1/mods/{self._modid}/files?index={idx}",
headers={"x-api-key": env["CURSE_API_KEY"]},
timeout=30,
)
statuses += self._process_all_mods(response.json()["data"])
self.logmsg(f"ℹ️ Processed {((idx+1)*50)} files")
if last_size != 0: # Handle the last, possibly incomplete page of mods
response = requests.get(
f"https://api.curseforge.com/v1/mods/{self._modid}/files?index={pages}&pageSize={last_size}",
headers={"x-api-key": env["CURSE_API_KEY"]},
timeout=30,
)
statuses += self._process_all_mods(response.json()["data"])
self.logmsg(f"ℹ️ Processed {last_size} files")
except TimeoutError:
statuses = [Status.FAIL]
self.logmsg(
f"🕜 Timed out enumerating files for {self._job.curseforge_slug} ({self._modid})"
)
any_succ = len(list(filter(lambda x: x == Status.SUCCESS, statuses))) > 0
any_fail = len(list(filter(lambda x: x == Status.FAIL, 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
def supports_downloads(self) -> bool:
"""
Determines if the mod even allows for third party launcher downloads
Returns (bool): True if it does, False otherwise
"""
try:
modid = cf.get_modid(self._job.curseforge_slug, self.logmsg)
if not modid:
return False
response = requests.get(
f"https://api.curseforge.com/v1/mods/{modid}/files",
headers={"x-api-key": env["CURSE_API_KEY"]},
timeout=30,
)
if response.ok:
data = response.json()["data"]
return "downloadUrl" in data[0]
return False
except TimeoutError:
self.logmsg("🕜 Timed out determining if Mod supports third party downloads")
return False

View file

@ -0,0 +1,260 @@
"""
@author: oitsjustjose @ github / twitter / modrinth
@license: MIT
@description: A SLOW working mod migrator from Curse to Modrinth
This one is used if you're a jerk and disable third party launchers
"""
import json
from os import environ as env
from os import makedirs, path
from os import unlink as rm
from shutil import rmtree as rmdir
from textwrap import dedent
from time import sleep
from typing import List, Union
import requests
import selenium.common.exceptions as selex
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from webdriver_manager.chrome import ChromeDriverManager
import curse_api as cf
from common import Job, Status
from mgmt_tools import MgmtApiHelper, MgmtApiLogger
def driver_get(driver: webdriver, url: str, timeout=30) -> bool:
"""
Attempts to get a URL with a given webdriver with a timeout
Args:
driver (webdriver): the webdriver
url (str): the url to navigate to
timeout (int) = 30: the time to wait before quitting
Returns:
(bool): True if successfully navigated, False otherwise
"""
try:
print(f"Attempting to get URL {url}")
driver.get(url)
WebDriverWait(driver, timeout).until(
EC.presence_of_element_located((By.TAG_NAME, "body"))
)
return True
except TimeoutException:
print(f"Failed to get {url}")
return False
class SlowProvider(MgmtApiLogger):
"""
The class for handling slow downloads
Args:
helper (MgmtApiHelper): the job database
job_id (str): the job id for the given job
"""
def __init__(self, helper: MgmtApiHelper, job: Job):
super().__init__(helper, job.job_id)
self._helper = helper
self._job = job
self._modid = cf.get_modid(job.curseforge_slug, self.logmsg)
self._rel_map = {1: "release", 2: "beta", 3: "alpha"}
# 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": path.realpath(
f"./out/{self._job.curseforge_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 _build_manifest(self) -> Union[dict, None]:
"""
Builds a manifest JSON to be used during Modrinth upload
"""
self.logmsg("ℹ️ Building Manifest for Jar Info")
manifest = {}
self.logmsg("ℹ️ Retrieving Curse ModID from Slug")
if not self._modid:
return None
self.logmsg("ℹ️ Enumerating Curse API Pages")
pages, last_size = cf.get_pages(self._modid, self.logmsg)
if pages == -1 and last_size == -1:
return None
# region ITERATE OVER PAGES AND DOWNLOAD MOD INFO
self.logmsg(f"ℹ️ Building manifest for {(pages*50)+last_size} files")
for idx in range(pages):
try:
response = requests.get(
f"https://api.curseforge.com/v1/mods/{self._modid}/files?index={idx}",
headers={"x-api-key": env["CURSE_API_KEY"]},
timeout=30,
)
for mod in response.json()["data"]:
manifest[mod["fileName"]] = mod
except TimeoutError:
self.logmsg(
f"🕜 Timed out enumerating files for {self._job.curseforge_slug} ({self._modid})"
)
continue
if last_size != 0:
try:
response = requests.get(
f"https://api.curseforge.com/v1/mods/{self._modid}/files?index={pages}&pageSize={last_size}",
headers={"x-api-key": env["CURSE_API_KEY"]},
timeout=30,
)
for mod in response.json()["data"]:
manifest[mod["fileName"]] = mod
except TimeoutError:
self.logmsg(
f"🕜 Timed out enumerating files for {self._job.curseforge_slug} ({self._modid})"
)
# endregion ITERATE OVER PAGES AND DOWNLOAD MOD INFO
for val in manifest.values():
url = f"https://legacy.curseforge.com/minecraft/mc-mods/{self._job.curseforge_slug}/download/{val['id']}"
val["downloadUrl"] = url
self.logmsg(f"ℹ️ Manifest Built! {len(manifest.keys())} Mods Found")
return manifest
def process(self) -> Status:
"""Returns: (status): the status of the procedure"""
self.logmsg("ℹ️ Retrieving Curse ModID from Slug")
if not self._modid:
return Status.FAIL
mods = self._build_manifest()
if not mods:
self.logmsg("🔥 Failed to create Manifest, see logs for info")
return Status.FAIL
makedirs(f"./out/{self._job.curseforge_slug}", exist_ok=True)
statuses: List[Status] = []
for fpath, mod in mods.items():
if (
not mod["isAvailable"]
or "downloadUrl" not in mod
or not mod["downloadUrl"]
):
continue
display_nm = mod["displayName"]
# region DOWNLOAD THE MOD
success = False
try:
driver_get(self._driver, mod["downloadUrl"])
sleep(8)
success = True
except selex.TimeoutException:
self.logmsg(
f"🕜 Timed out while downloading {display_nm}. This file will need manual migration."
)
statuses.append(Status.FAIL)
continue
except selex.WebDriverException as exception:
self.logmsg(
f"🔥 Could not download {display_nm}. RAW ERR: {exception}. This file will need manual migration"
)
statuses.append(Status.FAIL)
continue
# endregion DOWNLOAD THE MOD
if not success:
continue
# region UPLOAD THE MOD
with open(f"./out/{self._job.curseforge_slug}/{fpath}", "rb") as jar_file:
jar_data = jar_file.read()
game_versions, loaders = cf.get_loader_info(mod["gameVersions"])
payload = json.dumps(
{
"name": display_nm,
"version_number": cf.get_version(display_nm),
"changelog": cf.get_changelog(self._modid, mod["id"]),
"dependencies": [], # Dependencies need to be manually included
"game_versions": game_versions,
"loaders": loaders,
"featured": False,
"version_type": self._rel_map[mod["releaseType"]],
"requested_status": "listed",
"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, jar_data, "application/octet-stream")),
],
)
if response.status_code == 200:
statuses.append(Status.SUCCESS)
self.logmsg(f"✅ {display_nm}")
print(f"✅ {display_nm}")
else:
print(response.text)
print(response.json())
statuses.append(Status.FAIL)
self.logmsg(
dedent(
f"""----- 🔥 {display_nm} -----
API Response from Modrinth FAIL for {display_nm}:
{response.json()["description"]}
"""
).strip("\n")
)
rm(f"./out/{self._job.curseforge_slug}/{fpath}")
except TimeoutError:
self.logmsg(f"🕜 Timed out uploading {fpath}. Manual upload required")
statuses.append(Status.FAIL)
# endregion UPLOAD THE MOD
any_succ = len(list(filter(lambda x: x == Status.SUCCESS, statuses))) > 0
any_fail = len(list(filter(lambda x: x == Status.FAIL, 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
)
rmdir(f"./out/{self._job.curseforge_slug}")
return status