This commit is contained in:
oitsjustjose 2023-04-20 23:53:45 -05:00
commit cde7194936
7 changed files with 14 additions and 1 deletions

8
api/.gitignore vendored Normal file
View file

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

14
api/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`

174
api/api.py Normal file
View file

@ -0,0 +1,174 @@
"""
The API endpoints for the proessor
Author: oitsjustjose @ modrinth/curseforge/twitter
"""
import json
from dataclasses import asdict, dataclass
from multiprocessing import Manager, Process
from os import environ as env
from os.path import exists
from time import sleep
from typing import List
from cryptography.fernet import Fernet
from flask import Flask, request
from shortuuid import ShortUUID
from processor import download, upload
@dataclass
class Job:
"""A single job"""
github_pat: str
curseforge_slug: str
modrinth_id: str
logs = []
job_id: str = ShortUUID().random(length=8)
delimiter: str = "-"
app = Flask(__name__)
fer = Fernet(env["key"])
manager = Manager()
active_jobs: List[Job] = manager.list()
jobs: List[Job] = manager.list()
completed: List[Job] = manager.list()
def job_processor():
print("Starting the job processor")
while True:
try:
sleep(1)
if not jobs:
continue
active_job = jobs[0]
active_jobs.append(active_job)
active_job.logs += download(active_job.curseforge_slug)
active_job.logs += upload(
active_job.github_pat,
active_job.curseforge_slug,
active_job.modrinth_id,
active_job.delimiter,
)
active_job.github_pat = ""
completed.append(active_job)
for idx, obj in enumerate(active_jobs):
if obj.job_id == active_job.job_id:
del active_jobs[idx]
for idx, obj in enumerate(jobs):
if obj.job_id == active_job.job_id:
del jobs[idx]
except KeyboardInterrupt:
break
def save():
"""Saves the current application state to an encrypted file"""
data = {
"jobs": [asdict(x) for x in active_jobs] + [asdict(x) for x in jobs],
"completed": dict(completed),
}
with open("./state.dat", "wb") as handle:
handle.write(fer.encrypt(json.dumps(data).encode()))
def load():
"""Loads the current application state from encrypted file"""
global active_job, jobs, completed
if not exists("./state.dat"):
return
with open("./state.dat", "rb") as handle:
data = json.loads(fer.decrypt(handle.read().decode()))
if "jobs" in data:
for job in data["jobs"]:
jobs.append(
Job(
github_pat=job["github_pat"],
curseforge_slug=job["curseforge_slug"],
modrinth_id=job["modrinth_id"],
job_id=job["job_id"],
delimiter=job["delimiter"],
)
)
if "completed" in data:
completed = data["completed"]
print(completed, jobs)
@app.route("/jobs/status/<uuid>", methods=["GET", "POST"])
def get_job_status(uuid: str) -> str:
"Gets the queue status for a given job"
for job in active_jobs:
if job.job_id == uuid:
return "Currently Processing", 200
for job in completed:
if job.job_id == uuid:
logs = "\\n".join(job.logs)
return f"Completed!\n{logs}", 200
for idx, job in enumerate(jobs):
if job.job_id == uuid:
return f"Enqueued: {idx+1} Job(s) Ahead In Queue", 200
return "Failed to find job", 404
@app.route("/jobs/info/<uuid>", methods=["GET", "POST"])
def get_job_info(uuid: str):
"""Gets the job info for a given uuid"""
for job in jobs:
if job.job_id == uuid:
data = asdict(job)
data.pop("github_pat")
return json.dumps(data), 200
return "Failed to find job", 404
@app.route("/jobs/new", methods=["POST"])
def new_job():
"""Creates a new job"""
try:
data = json.loads(request.data)
jobe = Job(
github_pat=data["githubPat"],
curseforge_slug=data["slug"],
modrinth_id=data["projId"],
delimiter=data["delimiter"] if "delimiter" in data else "-",
)
# Don't enqueue a task that already exists
for job in jobs:
if (
job.github_pat == jobe.github_pat
and job.curseforge_slug == jobe.curseforge_slug
and job.modrinth_id == jobe.modrinth_id
and job.delimiter == jobe.delimiter
):
return job.job_id, 200
jobs.append(jobe)
return jobe.job_id, 200
except:
return "Internal Server Error", 500
load()
proc = Process(target=job_processor)
proc.start()
app.run("0.0.0.0", 3000)
proc.join()
save()

152
api/processor.py Normal file
View file

@ -0,0 +1,152 @@
"""
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
import requests
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
def upload(api_key: str, slug: str, proj_id: str, delimeter: str) -> 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
"""
logs = []
if not os.path.exists(f"./out/{slug}"):
return logs
for fpath in os.listdir(f"./out/{slug}"):
with open(f"out/{slug}/{fpath}", "rb") as modfile:
data = modfile.read()
parts = fpath.split(delimeter)
if len(parts) != 3:
logs.append(
f"Failed to parse name/version info for file {fpath}, it will be skipped"
)
continue
version_title = " ".join(parts).replace(".jar", "")
# .x versions somehow were only ever for the .0, .1 and .2 game vers lol
if "x" in parts[1].lower():
root = parts[1].replace(".x", "").replace(".X", "")
game_versions = [root, f"{root}.1", f"{root}.2"]
else:
game_versions = [parts[1]]
version = parts[2].replace(".jar", "")
payload = json.dumps(
{
"name": version_title,
"version_number": f"{parts[1]}-{version}",
"changelog": "Migrated Automagically from CurseForge",
"dependencies": [],
"game_versions": 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}")
else:
logs.append("API Response from Modrinth Failed for {fpath}:")
logs.append(response.text)
logs.append(json.dumps(response.json(), indent=2))
rmtree(f"./out/{slug}")
return logs
def __get_mods_for_page(driver: webdriver.Chrome, root: str, page: int) -> List[str]:
"""EH"""
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 download(slug: str) -> List[str]:
"""Downloads all mod files for a given slug"""
logs = []
try:
root = f"https://legacy.curseforge.com/minecraft/mc-mods/{slug}/files/all"
os.makedirs(f"./out/{slug}", exist_ok=True)
page_num: int = 1
options = Options()
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
)
driver.get(f"{root}?page=1")
root_el = driver.page_source
root_el = BeautifulSoup(root_el, features="html.parser")
page_els = root_el.body.find_all("a", attrs={"class": "pagination-item"})
if page_els: # mods with only 1 page won't have a pagination item
page_el = page_els[-1]
page_el = page_el.find("span").text
page_num = int(page_el)
all_urls = []
for page in range(page_num):
all_urls += __get_mods_for_page(driver, root, page + 1)
for url in all_urls:
driver.get(url)
sleep(8)
except Exception as e:
logs.append(f"Download failed: {e}")
return logs

3
api/pyvenv.cfg Normal file
View file

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

61
api/requirements.txt Normal file
View file

@ -0,0 +1,61 @@
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
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
PySocks==1.7.1
python-dotenv==1.0.0
pytoolconfig==1.2.5
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