2 # Copyright (C) 2018 rubenwardy
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <https://www.gnu.org/licenses/>.
18 import flask, json, os, git, tempfile, shutil
19 from git import GitCommandError
20 from flask.ext.sqlalchemy import SQLAlchemy
21 from urllib.error import HTTPError
23 from urllib.parse import urlparse, quote_plus, urlsplit
25 from app.models import *
26 from app.tasks import celery, TaskError
27 from app.utils import randomString
31 def __init__(self, url):
34 m = re.search("^\/([^\/]+)\/([^\/]+)\/?$", url.path)
39 repo = m.group(2).replace(".git", "")
40 self.baseUrl = "https://raw.githubusercontent.com/{}/{}/master" \
46 return self.baseUrl is not None
49 return "https://github.com/{}/{}".format(self.user, self.repo)
51 def getScreenshotURL(self):
52 return self.baseUrl + "/screenshot.png"
54 def getCommitsURL(self, branch):
55 return "https://api.github.com/repos/{}/{}/commits?sha={}" \
56 .format(self.user, self.repo, urllib.parse.quote_plus(branch))
58 def getCommitDownload(self, commit):
59 return "https://github.com/{}/{}/archive/{}.zip" \
60 .format(self.user, self.repo, commit)
62 krock_list_cache = None
63 krock_list_cache_by_name = None
65 global krock_list_cache
66 global krock_list_cache_by_name
68 if krock_list_cache is None:
69 contents = urllib.request.urlopen("http://krock-works.16mb.com/MTstuff/modList.php").read().decode("utf-8")
70 list = json.loads(contents)
73 if not ("title" in x and "author" in x and \
74 "topicId" in x and "link" in x and x["link"] != ""):
78 m = re.search("\[([A-Za-z0-9_]+)\]", x["title"])
82 x["name"] = m.group(1)
88 "author": x["author"],
90 "topicId": x["topicId"],
94 krock_list_cache = [g(x) for x in list if h(x)]
95 krock_list_cache_by_name = {}
96 for x in krock_list_cache:
97 if not x["name"] in krock_list_cache_by_name:
98 krock_list_cache_by_name[x["name"]] = []
100 krock_list_cache_by_name[x["name"]].append(x)
102 return krock_list_cache, krock_list_cache_by_name
104 def findModInfo(author, name, link):
105 list, lookup = getKrockList()
107 if name is not None and name in lookup:
108 if len(lookup[name]) == 1:
109 return lookup[name][0]
111 for x in lookup[name]:
112 if x["author"] == author:
115 if link is not None and len(link) > 15:
117 if link in x["link"]:
123 def parseConf(string):
125 for line in string.split("\n"):
128 key = line[:idx].strip()
129 value = line[idx+1:].strip()
135 class PackageTreeNode:
136 def __init__(self, baseDir, author=None, repo=None, name=None):
137 print("Scanning " + baseDir)
138 self.baseDir = baseDir
148 if os.path.isfile(baseDir + "/game.conf"):
149 type = PackageType.GAME
150 elif os.path.isfile(baseDir + "/init.lua"):
151 type = PackageType.MOD
152 elif os.path.isfile(baseDir + "/modpack.txt"):
153 type = PackageType.MOD
155 elif os.path.isdir(baseDir + "/mods"):
156 type = PackageType.GAME
157 elif os.listdir(baseDir) == []:
158 # probably a submodule
161 raise TaskError("Unable to detect package type!")
166 if self.type == PackageType.GAME:
167 self.addChildrenFromModDir(baseDir + "/mods")
169 self.addChildrenFromModDir(baseDir)
172 def readMetaFiles(self):
177 with open(self.baseDir + "/mod.conf", "r") as myfile:
178 conf = parseConf(myfile.read())
179 for key in ["name", "description", "title", "depends", "optional_depends"]:
181 result[key] = conf[key]
185 print("description.txt does not exist!")
188 if not "description" in result:
190 with open(self.baseDir + "/description.txt", "r") as myfile:
191 result["description"] = myfile.read()
193 print("description.txt does not exist!")
197 pattern = re.compile("^([a-z0-9_]+)\??$")
198 if not "depends" in result and not "optional_depends" in result:
200 with open(self.baseDir + "/depends.txt", "r") as myfile:
201 contents = myfile.read()
204 for line in contents.split("\n"):
206 if pattern.match(line):
207 if line[len(line) - 1] == "?":
208 soft.append( line[:-1])
212 result["depends"] = hard
213 result["optional_depends"] = soft
216 print("depends.txt does not exist!")
219 if "depends" in result:
220 result["depends"] = [x.strip() for x in result["depends"].split(",")]
221 if "optional_depends" in result:
222 result["optional_depends"] = [x.strip() for x in result["optional_depends"].split(",")]
226 if "name" in result and not "title" in result:
227 result["title"] = result["name"].replace("_", " ").title()
229 # Calculate short description
230 if "description" in result:
231 desc = result["description"]
232 idx = desc.find(".") + 1
233 cutIdx = min(len(desc), 200 if idx < 5 else idx)
234 result["short_description"] = desc[:cutIdx]
237 info = findModInfo(self.author, result.get("name"), self.repo)
239 result["forumId"] = info.get("topicId")
242 self.name = result["name"]
247 def addChildrenFromModDir(self, dir):
248 for entry in next(os.walk(dir))[1]:
249 path = dir + "/" + entry
250 if not entry.startswith('.') and os.path.isdir(path):
251 self.children.append(PackageTreeNode(path, name=entry))
254 def fold(self, attr, key=None, acc=None):
258 if self.meta is None:
261 at = getattr(self, attr)
262 value = at if key is None else at.get(key)
264 if isinstance(value, list):
266 elif value is not None:
269 for child in self.children:
270 child.fold(attr, key, acc)
275 return self.meta.get(key)
277 def generateGitURL(urlstr):
278 scheme, netloc, path, query, frag = urlsplit(urlstr)
280 return "http://:@" + netloc + path + query
282 # Clones a repo from an unvalidated URL.
283 # Returns a tuple of path and repo on sucess.
284 # Throws `TaskError` on failure.
285 # Caller is responsible for deleting returned directory.
286 def cloneRepo(urlstr, ref=None, recursive=False):
287 gitDir = tempfile.gettempdir() + "/" + randomString(10)
291 gitUrl = generateGitURL(urlstr)
292 print("Cloning from " + gitUrl)
293 repo = git.Repo.clone_from(gitUrl, gitDir, \
294 progress=None, env=None, depth=1, recursive=recursive, kill_after_timeout=15)
297 repo.create_head("myhead", ref).checkout()
299 except GitCommandError as e:
300 # This is needed to stop the backtrace being weird
303 raise TaskError(err.replace("stderr: ", "") \
304 .replace("Cloning into '" + gitDir + "'...", "") \
308 def getMeta(urlstr, author):
309 gitDir, _ = cloneRepo(urlstr, recursive=True)
310 tree = PackageTreeNode(gitDir, author=author, repo=urlstr)
311 shutil.rmtree(gitDir)
314 result["name"] = tree.name
315 result["provides"] = tree.fold("name")
316 result["type"] = tree.type.name
318 for key in ["depends", "optional_depends"]:
319 result[key] = tree.fold("meta", key)
321 for key in ["title", "repo", "issueTracker", "forumId", "description", "short_description"]:
322 result[key] = tree.get(key)
324 for mod in result["provides"]:
325 result["depends"].discard(mod)
326 result["optional_depends"].discard(mod)
328 for key, value in result.items():
329 if isinstance(value, set):
330 result[key] = list(value)
335 def makeVCSReleaseFromGithub(id, branch, release, url):
336 urlmaker = GithubURLMaker(url)
337 if not urlmaker.isValid():
338 raise TaskError("Invalid github repo URL")
340 commitsURL = urlmaker.getCommitsURL(branch)
341 contents = urllib.request.urlopen(commitsURL).read().decode("utf-8")
342 commits = json.loads(contents)
344 if len(commits) == 0 or not "sha" in commits[0]:
345 raise TaskError("No commits found")
347 release.url = urlmaker.getCommitDownload(commits[0]["sha"])
349 release.task_id = None
357 def makeVCSRelease(id, branch):
358 release = PackageRelease.query.get(id)
360 raise TaskError("No such release!")
361 elif release.package is None:
362 raise TaskError("No package attached to release")
365 url = urlparse(release.package.repo)
366 if url.netloc == "github.com":
367 return makeVCSReleaseFromGithub(id, branch, release, url)
369 gitDir, repo = cloneRepo(release.package.repo, ref=branch, recursive=True)
372 filename = randomString(10) + ".zip"
373 destPath = os.path.join("app/public/uploads", filename)
374 with open(destPath, "wb") as fp:
377 release.url = "/uploads/" + filename
379 release.task_id = None
384 shutil.rmtree(gitDir)
387 def importRepoScreenshot(id):
388 package = Package.query.get(id)
389 if package is None or package.soft_deleted:
390 raise Exception("Unexpected none package")
394 gitDir, _ = cloneRepo(package.repo)
395 except TaskError as e:
396 # ignore download errors
400 # Find and import screenshot
402 for ext in ["png", "jpg", "jpeg"]:
403 sourcePath = gitDir + "/screenshot." + ext
404 if os.path.isfile(sourcePath):
405 filename = randomString(10) + "." + ext
406 destPath = os.path.join("app/public/uploads", filename)
407 shutil.copyfile(sourcePath, destPath)
409 ss = PackageScreenshot()
412 ss.title = "screenshot.png"
413 ss.url = "/uploads/" + filename
417 return "/uploads/" + filename
419 shutil.rmtree(gitDir)
421 print("screenshot.png does not exist")
426 def getDepends(package):
427 url = urlparse(package.repo)
429 if url.netloc == "github.com":
430 urlmaker = GithubURLMaker(url)
435 if not urlmaker.isValid():
439 # Try getting depends on mod.conf
442 contents = urllib.request.urlopen(urlmaker.getModConfURL()).read().decode("utf-8")
443 conf = parseConf(contents)
444 for key in ["depends", "optional_depends"]:
446 result[key] = conf[key]
451 print("mod.conf does not exist")
453 if "depends" in result or "optional_depends" in result:
461 pattern = re.compile("^([a-z0-9_]+)\??$")
463 contents = urllib.request.urlopen(urlmaker.getDependsURL()).read().decode("utf-8")
466 for line in contents.split("\n"):
468 if pattern.match(line):
469 if line[len(line) - 1] == "?":
470 soft.append( line[:-1])
474 result["depends"] = ",".join(hard)
475 result["optional_depends"] = ",".join(soft)
477 print("depends.txt does not exist")
482 def importDependencies(package, mpackage_cache):
483 if Dependency.query.filter_by(depender=package).count() != 0:
486 result = getDepends(package)
488 if "depends" in result:
489 deps = Dependency.SpecToList(package, result["depends"], mpackage_cache)
490 print("{} hard: {}".format(len(deps), result["depends"]))
495 if "optional_depends" in result:
496 deps = Dependency.SpecToList(package, result["optional_depends"], mpackage_cache)
497 print("{} soft: {}".format(len(deps), result["optional_depends"]))
503 def importAllDependencies():
504 Dependency.query.delete()
506 packages = Package.query.filter_by(type=PackageType.MOD).all()
507 for i, p in enumerate(packages):
508 print("============= {} ({}/{}) =============".format(p.name, i, len(packages)))
509 importDependencies(p, mpackage_cache)