This commit is contained in:
oitsjustjose 2023-04-29 20:35:37 -05:00
commit f112cf0912
9 changed files with 160 additions and 132 deletions

View file

@ -12,50 +12,83 @@ from mgmt_tools import MgmtApiHelper
from modrinth_uploader import ModrinthUploader
def _process(helper: MgmtApiHelper, job: Job):
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
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)
downloader = CurseDownloader(helper, job)
dls = downloader.download()
if dls == Status.FAIL:
helper.update_job_status(job.job_id, Status.COMPLETE)
helper.append_job_log(job.job_id, "***FAILED***")
download_status = _download(helper, job)
if download_status == Status.FAIL:
return
uploader = ModrinthUploader(helper, job)
uls = uploader.upload()
upload_status = _upload(helper, job)
stat = Status(max(dls.value, uls.value)).name
status = Status(max(download_status.value, upload_status.value)).name
helper.update_job_status(job.job_id, Status.COMPLETE)
helper.append_job_log(job.job_id, f"***{stat}***")
helper.append_job_log(job.job_id, f"***{status}***")
def _resume(helper: MgmtApiHelper):
def resume(helper: MgmtApiHelper):
"""Resumes processing jobs on server restart"""
print("Resuming jobs from last run")
for job in helper.get_resumable_jobs():
print(f"Resuming job {job.job_id}")
_process(helper, job)
process_job(helper, job)
def _work(helper: MgmtApiHelper) -> bool:
def work(helper: MgmtApiHelper) -> bool:
"""Does the actual lifting"""
sleep(2) # Sleep to make sure DB processing is done
job: Job = helper.get_next_job()
if not job:
return False
_process(helper, job)
process_job(helper, job)
return True
def main_loop():
"""The main process loop"""
print("Init DB connection")
helper = MgmtApiHelper()
print("DB Connected")
print("Starting virtual display")
run("Xvfb -ac :99 -screen 0 1280x1024x16 &")
@ -63,10 +96,10 @@ def main_loop():
print("Done initializing VDisplay")
print("Starting the job processor")
_resume(helper)
resume(helper)
while True:
try:
if _work(helper):
if work(helper):
sleep(1)
else:
sleep(5)

View file

@ -27,7 +27,6 @@ class Job:
curseforge_slug: str
modrinth_id: str
job_id: str = ""
delimiter: str = "-"
logs: str = ""
status: Status = Status.ENQUEUED
queue_place: int = 0
@ -37,8 +36,8 @@ class Job:
class ModInfo:
"""Stores metadata about a jarfile to be extrapolated"""
name: str
mod_version: str
modrinth_name: str
loaders: List[str]
game_version: str # representative game ver
game_versions: List[str] # actual game vers

View file

@ -2,21 +2,49 @@
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
@ -72,6 +100,9 @@ class CurseDownloader(MgmtApiLogger):
)
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
@ -82,9 +113,46 @@ class CurseDownloader(MgmtApiLogger):
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
@ -100,7 +168,7 @@ class CurseDownloader(MgmtApiLogger):
for url in all_urls:
try:
self._driver.get(url)
driver_get(self._driver, url)
sleep(8)
# Verify if/that file actually downloaded:
new_file_cnt = len(os.listdir(f"./out/{self._slug}"))
@ -139,14 +207,13 @@ class CurseDownloader(MgmtApiLogger):
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)
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]:
@ -159,18 +226,12 @@ class CurseDownloader(MgmtApiLogger):
Returns:
(List[str]): a list of download urls for the mod files
"""
self._driver.get(f"{root}?page={page}")
driver_get(self._driver, 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,
)
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

@ -59,7 +59,6 @@ class MgmtApiHelper:
modrinth_id=data["modrinthId"],
logs=data["logs"] if "logs" in data else [],
job_id=data["jobId"],
delimiter=data["delimiter"] if "delimiter" in data else "-",
status=data["status"],
queue_place=data["queuePlace"],
)

View file

@ -3,6 +3,7 @@ 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
@ -38,22 +39,32 @@ class ModrinthUploader(MgmtApiLogger):
return [root, f"{root}.1", f"{root}.2"]
return [parts[1]]
def __extrapolate_mod(self, filename: str) -> Union[ModInfo, None]:
def __get_mod_info(self, filename: str) -> Union[ModInfo, None]:
"""
Extrapolates mod info from a given jarfile name
Loads mod info from the manifest generated during download
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
"""
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())
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),
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:
@ -63,8 +74,6 @@ class ModrinthUploader(MgmtApiLogger):
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
"""
@ -81,7 +90,7 @@ class ModrinthUploader(MgmtApiLogger):
with open(f"out/{self._job.curseforge_slug}/{fpath}", "rb") as modfile:
data = modfile.read()
mod_info = self.__extrapolate_mod(fpath)
mod_info = self.__get_mod_info(fpath)
if not mod_info:
self.logmsg(f"Couldn't parse name/version info for file {fpath}")
continue
@ -102,6 +111,7 @@ class ModrinthUploader(MgmtApiLogger):
"file_parts": [fpath],
}
)
print(payload)
try:
response = requests.post(