"""Library to interact with the badge store""" ___license___ = "MIT" ___dependencies___ = ["http", "ospath"] from ospath import * from http import * import hashlib, binascii class BadgeStore: def __init__(self, url = "http://badge.marekventur.com", repo="emfcamp/Mk4-Apps", ref="master"): self.url = url self.repo = repo self.ref = ref self._apps = None def get_apps(self): if not self._apps: self._apps = self._call("apps") return self._apps def get_categories(self): return self.get_apps().keys() def get_app(self, app): return self._call("app", {"app": app}) def install(self, apps): files = self._call("install", {"apps": ",".join(apps)}) installers = [] url = "%s/download" % (self.url) for path, hash in files.items(): if self._is_file_up_to_date(path, hash): continue params = {"repo": self.repo, "ref": self.ref, "path": path} installers.append(Installer(path, url, params)) return installers def _call(self, command, params = {}): params["repo"] = self.repo params["ref"] = self.ref with get("%s/%s" % (self.url, command), params=params).raise_for_status() as response: return response.json() # todo: error handling def _is_file_up_to_date(self, path, hash): if not isfile(path): return False with open(path, "rb") as file: sha256 = hashlib.sha256() buf = file.read(128) while len(buf) > 0: sha256.update(buf) buf = file.read(128) current = str(binascii.hexlify(sha256.digest()), "utf8")[:10] return current == hash class Installer: def __init__(self, path, url, params): self.path = path self.url = url self.params = params def download(self): with get(self.url, params=self.params).raise_for_status() as response: response.download(path)