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

@ -36,7 +36,6 @@ export default async (req: Request, res: Response) => {
githubPat: fern.encrypt(req.body.githubPat), githubPat: fern.encrypt(req.body.githubPat),
curseforgeSlug: req.body.curseforgeSlug, curseforgeSlug: req.body.curseforgeSlug,
modrinthId: req.body.modrinthId, modrinthId: req.body.modrinthId,
delimiter: req.body.delimiter || "-",
queuePlace: await getNextQueuePlace(), queuePlace: await getNextQueuePlace(),
}); });

View file

@ -7,7 +7,6 @@ export type JobType = Document & {
githubPat: string; githubPat: string;
curseforgeSlug: string; curseforgeSlug: string;
modrinthId: string; modrinthId: string;
delimiter: string;
logs: string; logs: string;
status: number; status: number;
queuePlace: number; queuePlace: number;
@ -31,10 +30,6 @@ const JobSchema = new Schema<JobType>({
type: String, type: String,
required: true, required: true,
}, },
delimiter: {
type: String,
required: true,
},
logs: { logs: {
type: String, type: String,
default: "", default: "",

View file

@ -1,41 +0,0 @@
import React from 'react';
import { Modal } from 'react-bootstrap';
export default ({ show, onHide }) => (
<Modal
centered
show={show}
onHide={onHide}
>
<Modal.Body>
<div>
<p>
This is the splitter between parts of the filename. Many mods use the format
{' '}
<code>MODNAME-MCVER-MAJOR.MINOR.PATCH</code>
, where
{' '}
<code>-</code>
{' '}
is the delimiter.
</p>
<p>
Using this logic, it is assumed that the Minecraft version for this
{' '}
<code>.jar</code>
-file is between the first and second delimiter, and that the mod version is between
the second and the end of the file. Formatting aside from this is not supported,
unfortunately, as I&apos;ve got a bit of trauma
{' '}
<sup>(/s)</sup>
{' '}
from
{' '}
<a href="https://dv2ls.com/code?id=lUY-c4A2H" target="_blank" rel="noreferrer">
this Regular Expression I wrote.
</a>
</p>
</div>
</Modal.Body>
</Modal>
);

View file

@ -3,10 +3,9 @@ import React, { useState, useEffect } from 'react';
import { import {
Form, Button, Container, Accordion, Image, Form, Button, Container, Accordion, Image,
} from 'react-bootstrap'; } from 'react-bootstrap';
import { TbInfoHexagon, TbHelp } from 'react-icons/tb'; import { TbInfoHexagon } from 'react-icons/tb';
import OutputLog from '../components/OutputLog'; import OutputLog from '../components/OutputLog';
import Info from '../components/Help/Info'; import Info from '../components/Help/Info';
import Delimiter from '../components/Help/Delimiter';
import HeaderImg from '../img/ctm.png'; import HeaderImg from '../img/ctm.png';
export default () => { export default () => {
@ -58,7 +57,6 @@ export default () => {
return ( return (
<div className="ctm-root"> <div className="ctm-root">
<Info override={modals.info} propagateOnHide={() => setModals({ ...modals, info: false })} /> <Info override={modals.info} propagateOnHide={() => setModals({ ...modals, info: false })} />
<Delimiter show={modals.delim} onHide={() => setModals({ ...modals, delim: false })} />
<Container style={{ margin: '1rem auto', maxWidth: '512px' }}> <Container style={{ margin: '1rem auto', maxWidth: '512px' }}>
<Image className="d-block mb-3 mx-auto w-50 headerimg" src={HeaderImg} /> <Image className="d-block mb-3 mx-auto w-50 headerimg" src={HeaderImg} />
@ -124,31 +122,6 @@ export default () => {
/> />
</Form.Group> </Form.Group>
<Form.Group className="mb-3" controlId="delimiter">
<Form.Label>
Delimiter (Optional)
{' '}
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
<a
onClick={() => setModals({ ...modals, delim: true })}
style={{ textDecoration: 'none', fontSize: '16px' }}
href="#"
label="delimiter_help"
>
<TbHelp />
</a>
</Form.Label>
<Form.Control
placeholder="Defaults to Hyphen (-)"
type="text"
value={formData.delimiter}
onChange={(x) => setFormData({
...formData,
delimiter: x.target.value,
})}
/>
</Form.Group>
<Button variant={dark ? 'light' : 'dark'} type="submit">Submit</Button> <Button variant={dark ? 'light' : 'dark'} type="submit">Submit</Button>
<Button <Button
className="info" className="info"

View file

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

View file

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

View file

@ -2,21 +2,49 @@
Downloads mod files from Curse Downloads mod files from Curse
Author: oitsjustjose @ modrinth/curseforge/twitter Author: oitsjustjose @ modrinth/curseforge/twitter
""" """
import json
import os import os
import re
from time import sleep from time import sleep
from typing import List from typing import List
import selenium.common.exceptions as selex import selenium.common.exceptions as selex
from bs4 import BeautifulSoup from bs4 import BeautifulSoup
from selenium import webdriver from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.options import Options from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service 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 webdriver_manager.chrome import ChromeDriverManager
from common import Job, Status from common import Job, Status
from mgmt_tools import MgmtApiHelper, MgmtApiLogger 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): class CurseDownloader(MgmtApiLogger):
""" """
The class for handling curse downloads The class for handling curse downloads
@ -72,6 +100,9 @@ class CurseDownloader(MgmtApiLogger):
) )
return Status.FAIL 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) statuses = self.__download_files(all_urls)
any_succ = len(list(filter(lambda x: x == Status.SUCCESS, statuses))) > 0 any_succ = len(list(filter(lambda x: x == Status.SUCCESS, statuses))) > 0
any_fail = 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 if any_succ and not any_fail
else Status.FAIL else Status.FAIL
) )
return status 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]: def __download_files(self, all_urls: List[str]) -> List[Status]:
""" """
Attempts to download jarfiles from the acquired list of urls Attempts to download jarfiles from the acquired list of urls
@ -100,7 +168,7 @@ class CurseDownloader(MgmtApiLogger):
for url in all_urls: for url in all_urls:
try: try:
self._driver.get(url) driver_get(self._driver, url)
sleep(8) sleep(8)
# Verify if/that file actually downloaded: # Verify if/that file actually downloaded:
new_file_cnt = len(os.listdir(f"./out/{self._slug}")) 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 root (str): the root url, i.e. https://legacy.curseforge.com/{slug}/files/all
Returns: (int): the number of pages for the mod Returns: (int): the number of pages for the mod
""" """
self._driver.get(f"{root}?page=1") driver_get(self._driver, f"{root}?page=1")
root = self._driver.page_source soup = BeautifulSoup(self._driver.page_source, features="html.parser")
root = BeautifulSoup(root, features="html.parser") soup = soup.body.find_all("a", attrs={"class": "pagination-item"})
root = root.body.find_all("a", attrs={"class": "pagination-item"}) if soup: # mods with only 1 page won't have a pagination item
if root: # mods with only 1 page won't have a pagination item soup = soup[-1]
root = root[-1] soup = soup.find("span").text
root = root.find("span").text return int(soup)
return int(root)
return 1 return 1
def __get_dl_urls_for_page(self, root: str, page: int) -> List[str]: def __get_dl_urls_for_page(self, root: str, page: int) -> List[str]:
@ -159,18 +226,12 @@ class CurseDownloader(MgmtApiLogger):
Returns: Returns:
(List[str]): a list of download urls for the mod files (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 soup = BeautifulSoup(self._driver.page_source, features="html.parser")
root_el = BeautifulSoup(root_el, 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 = root_el.body.find_all("a", attrs={"data-action": "file-link"}) file_links = list(
map(lambda x: f"https://legacy.curseforge.com{x}", file_links)
return list(
map(
lambda x: f"https://legacy.curseforge.com/{x['href']}".replace(
"files", "download"
),
file_links,
)
) )
return file_links

View file

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

View file

@ -3,6 +3,7 @@ Uploads mod files to Modrinth
Author: oitsjustjose @ modrinth/curseforge/twitter Author: oitsjustjose @ modrinth/curseforge/twitter
""" """
import json import json
import re
import os import os
from shutil import rmtree from shutil import rmtree
from typing import List, Union from typing import List, Union
@ -38,22 +39,32 @@ class ModrinthUploader(MgmtApiLogger):
return [root, f"{root}.1", f"{root}.2"] return [root, f"{root}.1", f"{root}.2"]
return [parts[1]] 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: Args:
filename (str): the name of the jarfile 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 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( return ModInfo(
name=parts[0], modrinth_name=name,
mod_version=parts[2], mod_version=mod_version,
modrinth_name=" ".join(parts), loaders=manifest[filename]["loaders"],
game_version=parts[1], game_version=manifest[filename]["version"],
game_versions=self.__get_versions(parts), game_versions=manifest[filename]["versions"],
) )
def upload(self) -> Status: def upload(self) -> Status:
@ -63,8 +74,6 @@ class ModrinthUploader(MgmtApiLogger):
api_key (str): the GitHub PAT for the associated Modrinth account api_key (str): the GitHub PAT for the associated Modrinth account
slug (str): the CurseForge slug, used to traverse the local filesystem slug (str): the CurseForge slug, used to traverse the local filesystem
proj_id (str): the Modrinth project id 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: Returns:
Tuple[Status, List[str]]: The overall status and any accompanying logs 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: with open(f"out/{self._job.curseforge_slug}/{fpath}", "rb") as modfile:
data = modfile.read() data = modfile.read()
mod_info = self.__extrapolate_mod(fpath) mod_info = self.__get_mod_info(fpath)
if not mod_info: if not mod_info:
self.logmsg(f"Couldn't parse name/version info for file {fpath}") self.logmsg(f"Couldn't parse name/version info for file {fpath}")
continue continue
@ -102,6 +111,7 @@ class ModrinthUploader(MgmtApiLogger):
"file_parts": [fpath], "file_parts": [fpath],
} }
) )
print(payload)
try: try:
response = requests.post( response = requests.post(