2 from flask.ext.sqlalchemy import SQLAlchemy
3 from urllib.error import HTTPError
5 from urllib.parse import urlparse, quote_plus
7 from app.models import *
8 from app.tasks import celery, TaskError
9 from app.utils import randomString
12 def __init__(self, url):
15 m = re.search("^\/([^\/]+)\/([^\/]+)\/?$", url.path)
21 self.baseUrl = "https://raw.githubusercontent.com/{}/{}/master" \
22 .format(user, repo.replace(".git", ""))
27 return self.baseUrl is not None
30 return "https://github.com/{}/{}".format(self.user, self.repo)
32 def getIssueTrackerURL(self):
33 return "https://github.com/{}/{}/issues/".format(self.user, self.repo)
35 def getModConfURL(self):
36 return self.baseUrl + "/mod.conf"
39 return self.baseUrl + "/description.txt"
41 def getScreenshotURL(self):
42 return self.baseUrl + "/screenshot.png"
44 def getCommitsURL(self, branch):
45 return "https://api.github.com/repos/{}/{}/commits?sha={}" \
46 .format(self.user, self.repo, urllib.parse.quote_plus(branch))
48 def getCommitDownload(self, commit):
49 return "https://github.com/{}/{}/archive/{}.zip" \
50 .format(self.user, self.repo, commit)
53 krock_list_cache = None
54 krock_list_cache_by_name = None
56 global krock_list_cache
57 global krock_list_cache_by_name
59 if krock_list_cache is None:
60 contents = urllib.request.urlopen("http://krock-works.16mb.com/MTstuff/modList.php").read().decode("utf-8")
61 list = json.loads(contents)
64 if not ("title" in x and "author" in x and \
65 "topicId" in x and "link" in x and x["link"] != ""):
69 m = re.search("\[([A-Za-z0-9_]+)\]", x["title"])
73 x["name"] = m.group(1)
79 "author": x["author"],
81 "topicId": x["topicId"],
85 krock_list_cache = [g(x) for x in list if h(x)]
86 krock_list_cache_by_name = {}
87 for x in krock_list_cache:
88 if not x["name"] in krock_list_cache_by_name:
89 krock_list_cache_by_name[x["name"]] = []
91 krock_list_cache_by_name[x["name"]].append(x)
93 return krock_list_cache, krock_list_cache_by_name
95 def findModInfo(author, name, link):
96 list, lookup = getKrockList()
98 if name is not None and name in lookup:
99 if len(lookup[name]) == 1:
100 return lookup[name][0]
102 for x in lookup[name]:
103 if x["author"] == author:
106 if link is not None and len(link) > 15:
108 if link in x["link"]:
114 def parseConf(string):
116 for line in string.split("\n"):
119 key = line[:idx].strip()
120 value = line[idx+1:].strip()
127 def getMeta(urlstr, author):
128 url = urlparse(urlstr)
131 if url.netloc == "github.com":
132 urlmaker = GithubURLMaker(url)
134 raise TaskError("Unsupported repo")
136 if not urlmaker.isValid():
137 raise TaskError("Error! Url maker not valid")
141 result["repo"] = urlmaker.getRepoURL()
142 result["issueTracker"] = urlmaker.getIssueTrackerURL()
145 contents = urllib.request.urlopen(urlmaker.getModConfURL()).read().decode("utf-8")
146 conf = parseConf(contents)
147 for key in ["name", "description", "title"]:
149 result[key] = conf[key]
153 print("mod.conf does not exist")
156 result["title"] = result["name"].replace("_", " ").title()
158 if not "description" in result:
160 contents = urllib.request.urlopen(urlmaker.getDescURL()).read().decode("utf-8")
161 result["description"] = contents.strip()
163 print("description.txt does not exist!")
165 if "description" in result:
166 desc = result["description"]
167 idx = desc.find(".") + 1
168 cutIdx = min(len(desc), 200 if idx < 5 else idx)
169 result["short_description"] = desc[:cutIdx]
171 info = findModInfo(author, result.get("name"), result["repo"])
173 result["forumId"] = info.get("topicId")
179 def makeVCSRelease(id, branch):
180 release = PackageRelease.query.get(id)
183 raise TaskError("No such release!")
185 if release.package is None:
186 raise TaskError("No package attached to release")
188 url = urlparse(release.package.repo)
191 if url.netloc == "github.com":
192 urlmaker = GithubURLMaker(url)
194 raise TaskError("Unsupported repo")
196 if not urlmaker.isValid():
197 raise TaskError("Invalid github repo URL")
199 contents = urllib.request.urlopen(urlmaker.getCommitsURL(branch)).read().decode("utf-8")
200 commits = json.loads(contents)
202 if len(commits) == 0:
203 raise TaskError("No commits found")
205 release.url = urlmaker.getCommitDownload(commits[0]["sha"])
206 release.task_id = None
213 def importRepoScreenshot(id):
214 package = Package.query.get(id)
216 raise Exception("Unexpected none package")
219 url = urlparse(package.repo)
221 if url.netloc == "github.com":
222 urlmaker = GithubURLMaker(url)
224 raise TaskError("Unsupported repo")
226 if not urlmaker.isValid():
227 raise TaskError("Error! Url maker not valid")
230 filename = randomString(10) + ".png"
231 imagePath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
233 urllib.request.urlretrieve(urlmaker.getScreenshotURL(), imagePath)
235 ss = PackageScreenshot()
237 ss.title = "screenshot.png"
238 ss.url = "/uploads/" + filename
242 return "/uploads/" + filename
244 print("screenshot.png does not exist")