Separate API, proc

This commit is contained in:
oitsjustjose 2023-04-22 23:46:37 -05:00
commit 6a3f531527
27 changed files with 334 additions and 104 deletions

9
processor/.dockerignore Normal file
View file

@ -0,0 +1,9 @@
/out/
/lib/
/lib64
/bin/
state.dat
filekey.key
__pycache__
.envrc

9
processor/.gitignore vendored Normal file
View file

@ -0,0 +1,9 @@
/out/
/lib/
/lib64
/bin/
state.dat
filekey.key
__pycache__
.envrc

33
processor/Dockerfile Normal file
View file

@ -0,0 +1,33 @@
FROM python:3.10-buster
RUN apt-get update && apt-get upgrade -y
RUN apt-get install -y libasound2 \
libnspr4 \
libnss3 \
libxss1 \
xdg-utils \
unzip \
libappindicator1 \
fonts-liberation \
xvfb \
libatk-bridge2.0-0 \
libatspi2.0-0 \
libgbm1 \
libgtk-3-0 \
libu2f-udev \
libvulkan1 \
libxkbcommon0
RUN apt-get -f install
RUN wget http://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
RUN dpkg -i google-chrome*.deb && rm google-chrome*.deb
# Patch to make XVFB actually work
RUN mkdir /tmp/.X11-unix
RUN chmod 1777 /tmp/.X11-unix
RUN chown root /tmp/.X11-unix/
COPY . .
RUN pip install -r requirements.txt
CMD ["python", "src/__main__.py"]

14
processor/README.md Normal file
View file

@ -0,0 +1,14 @@
# Curse to Modrinth Migrator
## REQUIRES CHROME TO BE INSTALLED
This project only handles copying files from Curse to Modrinth - nothing else. It's pretty crude but great if you want to catch up your Modrinth mod with CurseForge's versions.
## Steps
1. Install Python 3.10 from [here](https://www.python.org/downloads/release/python-3100) - scroll down to files
2. Run `pip[3][.exe] install -r requirements.txt`
3. Open `download.py`, scroll all the way to the bottom and insert a `mod_archive_all` for each mod's slug you want to automatically fully archive. One has been included by default, but you can repeat `mod_archive_all("YOURMODSLUG")` as many times as you wish. This process takes a while.
4. Run `python[3][.exe] download.py`
5. For each mod you just downloaded, modify `upload.py` at the very top to include your newly created Modrinth project ID, and the folder with all files for the mod you just downloaded from Curseforge in step 4.
6. Run `python[3][.exe] upload.py`

3
processor/pyvenv.cfg Normal file
View file

@ -0,0 +1,3 @@
home = /usr/bin
include-system-site-packages = false
version = 3.10.11

View file

@ -0,0 +1,64 @@
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
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

81
processor/src/__main__.py Normal file
View file

@ -0,0 +1,81 @@
"""
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

46
processor/src/data.py Normal file
View file

@ -0,0 +1,46 @@
"""
Houses data classes
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
from dataclasses import dataclass
from enum import Enum
from typing import List
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

View file

@ -0,0 +1,118 @@
"""
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 cryptography.fernet import Fernet
from pymongo import ASCENDING, DESCENDING, MongoClient
from pymongo.collection import Collection
from pymongo.database import Database
from shortuuid import ShortUUID
from data import Job, Status
class JobDb:
"""A database for the job queue"""
def __init__(self, host: str, port: int):
self._client: MongoClient = MongoClient(host, port)
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"""
data: List[Union[dict, None]] = list(
self._coll.find({"status": Status.ENQUEUED.value})
.sort("queuePlace", ASCENDING)
.limit(1)
)
if data:
return self._dict_to_job(data[0])
return None
def get_active_jobs(self) -> List[Job]:
"""Gets all active jobs - only used for resuming between restarts"""
data: List[Union[dict, None]] = list(
self._coll.find({"status": Status.PROCESSING.value}).sort(
"queuePlace", ASCENDING
)
)
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:
"""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})
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 get_existing_queued_job(self, slug: str, proj_id: str) -> Union[str, None]:
"""Gets the existing job ID if it exists"""
data: Union[dict, None] = self._coll.find_one(
{
"status": Status.ENQUEUED.value,
"curseforgeSlug": slug,
"modrinthId": proj_id,
}
)
print(data)
if not data:
return None
return data["jobId"]
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()),
curseforge_slug=data["curseforgeSlug"],
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

@ -0,0 +1,285 @@
"""
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