moodle-import-worker/worker.py

55 lines
1.6 KiB
Python
Raw Normal View History

2022-08-20 05:58:22 +00:00
from pathlib import Path
from configparser import ConfigParser
import re
import subprocess
import shutil
config = ConfigParser()
config.read("config.ini")
source = Path(config["IMPORTER"]["SourcePath"])
completed = source / "completed"
completed.mkdir(exist_ok=True)
courses = dict()
mbzre = re.compile(r"course_(?P<courseid>\d+)_(?P<categoryid>\d+)_(?P<timestamp>\d+).mbz")
def call_php(courseid: int, categoryid: int, timestamp: int):
try:
subprocess.run(["php", config["IMPORTER"]["PHPScript"], f"--courseid={courseid}", f"--categoryid={categoryid}", f"--timestamp={timestamp}"], cwd=Path(config["IMPORTER"]["PHPScript"]).parent, check=True)
return True
except subprocess.CalledProcessError:
return False
for mbz in source.glob("course_*_*_*.mbz"):
2022-08-22 09:58:41 +00:00
meta = mbzre.search(str(mbz)).groupdict()
2022-08-20 05:58:22 +00:00
if not meta["courseid"] in courses.keys():
courses[int(meta["courseid"])] = list()
courses[int(meta["courseid"])].append((int(meta["categoryid"]), int(meta["timestamp"])))
for course, data in sorted(courses.items(), key = lambda x: x[0]):
current = config.getint("STATUS", str(course), fallback=0)
byage = sorted(data, key = lambda x: -x[1])
if byage[0][1] > current:
if not call_php(course, byage[0][0], byage[0][1]):
2022-08-22 09:58:41 +00:00
print(f"Something went wrong while importing {course}.")
2022-08-20 05:58:22 +00:00
continue
config["STATUS"][str(course)] = str(byage[0][1])
for categoryid, timestamp in byage:
shutil.move(source / f"course_{course}_{categoryid}_{timestamp}.mbz", completed)
with open("config.ini", "w") as configfile:
2022-08-22 09:58:41 +00:00
config.write(configfile)