def inject(): return { 'root': _cfg("protocol") + "://" + _cfg("domain"), 'domain': _cfg("domain"), 'len': len, 'any': any, 'request': request, 'locale': locale, 'url_for': url_for, 'user': current_user }
def send_confirmation(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/confirm-account") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.confirmation }))) message['X-MC-Important'] = "true" message['X-MC-PreserveRecipients'] = "false" message['Subject'] = "Confirm your account on the KnightOS Package Index" message['From'] = "*****@*****.**" message['To'] = user.email smtp.sendmail("*****@*****.**", [ user.email ], message.as_string()) smtp.quit()
def download(repo, name): p = Package.query.filter(Package.name == name and Package.repo == repo).first() if not p: abort(404) if p.downloads == None: p.downloads = 0 p.downloads += 1 db.commit() return send_file(os.path.join(_cfg("storage"), p.repo, "{0}-{1}.pkg".format(p.name, p.version)), as_attachment=True)
def remove_package(repo, name): package = Package.query.filter(Package.name == name).filter(Package.repo == repo).first() if not package: return { 'success': False, 'error': 'Package not found.' }, 404 if not current_user or not current_user.admin: return { 'success': False, 'error': 'You do not have permission to remove this package.' }, 403 packagePath = os.path.join(_cfg("storage"), package.repo, "{0}-{1}.pkg".format(package.name, package.version)) os.remove(packagePath) db.delete(package) db.commit() return { 'success': True }
def package(repo, name): p = Package.query.filter(Package.name == name).filter(Package.repo == repo).first() if not p: abort(404) if p.contents == None: packagePath = os.path.join(_cfg("storage"), p.repo, "{0}-{1}.pkg".format(p.name, p.version)) packageDict = PackageInfo.get_package_contents(packagePath) p.contents = json.dumps(packageDict) db.commit() packageContents = json.loads(p.contents) if p.downloads == None: p.downloads = 0 return render_template("package.html", package=p, packageContents = packageContents)
def send_new_pacakge_email(package): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/new-package") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'url': _cfg("protocol") + "://" + _cfg("domain") + url_for("html.package", name=package.name, repo=package.repo) }))) targets = [u.email for u in User.query.filter(User.admin == True)] message['Subject'] = "New package pending approval" message['From'] = _cfg("smtp-user") message['To'] = ';'.join(targets) smtp.sendmail(_cfg("smtp-user"), targets, message.as_string()) smtp.quit()
def hook_publish(): allow = False for ip in _cfg("hook_ips").split(","): parts = ip.split("/") range = 32 if len(parts) != 1: range = int(parts[1]) addr = networkMask(parts[0], range) if addressInNetwork(dottedQuadToNum(request.remote_addr), addr): allow = True if not allow: return "unauthorized", 403 # Pull and restart site event = json.loads(request.data.decode("utf-8")) if not _cfg("hook_repository") == "%s/%s" % (event["repository"]["owner"]["name"], event["repository"]["name"]): return "ignored" if any("[noupdate]" in c["message"] for c in event["commits"]): return "ignored" if "refs/heads/" + _cfg("hook_branch") == event["ref"]: subprocess.call(["git", "pull", "origin", "master"]) subprocess.Popen(_cfg("restart_command").split()) return "thanks" return "ignored"
def hook_publish(): allow = False for ip in _cfg("hook_ips").split(","): parts = ip.split("/") range = 32 if len(parts) != 1: range = int(parts[1]) addr = networkMask(parts[0], range) if addressInNetwork(dottedQuadToNum(request.remote_addr), addr): allow = True if not allow: return "unauthorized", 403 # Pull and restart site event = json.loads(request.data.decode("utf-8")) if not _cfg("hook_repository") == "%s/%s" % ( event["repository"]["owner"]["name"], event["repository"]["name"]): return "ignored" if any("[noupdate]" in c["message"] for c in event["commits"]): return "ignored" if "refs/heads/" + _cfg("hook_branch") == event["ref"]: subprocess.call(["git", "pull", "origin", "master"]) subprocess.Popen(_cfg("restart_command").split()) return "thanks" return "ignored"
def remove_package(repo, name): package = Package.query.filter(Package.name == name).filter( Package.repo == repo).first() if not package: return {'success': False, 'error': 'Package not found.'}, 404 if not current_user or not current_user.admin: return { 'success': False, 'error': 'You do not have permission to remove this package.' }, 403 packagePath = os.path.join( _cfg("storage"), package.repo, "{0}-{1}.pkg".format(package.name, package.version)) os.remove(packagePath) db.delete(package) db.commit() return {'success': True}
def send_reset(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/password-reset") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.passwordReset }))) message['Subject'] = "Reset your password for the KnightOS Package Index" message['From'] = _cfg("smtp-user") message['To'] = user.email smtp.sendmail(_cfg("smtp-user"), [user.email], message.as_string()) smtp.quit()
def send_reset(user): if _cfg("smtp-host") == "": return smtp = smtplib.SMTP(_cfg("smtp-host"), _cfgi("smtp-port")) smtp.ehlo() smtp.starttls() smtp.login(_cfg("smtp-user"), _cfg("smtp-password")) with open("emails/password-reset") as f: message = MIMEText(html.parser.HTMLParser().unescape(\ pystache.render(f.read(), { 'user': user, "domain": _cfg("domain"), 'confirmation': user.passwordReset }))) message['Subject'] = "Reset your password for the KnightOS Package Index" message['From'] = _cfg("smtp-user") message['To'] = user.email smtp.sendmail(_cfg("smtp-user"), [ user.email ], message.as_string()) smtp.quit()
def compile_if_debug(): if app.debug and _cfg("debug-static-recompile").lower() in ['true','yes']: prepare()
# TODO: Bug the slimit guys to support python 3 #if not app.debug: # javascript = minify(javascript) with open(os.path.join(app.static_folder, output), "w") as w: w.write(javascript) w.flush() except: pass try: d = os.walk('images') for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('images', f) copyfile(inputpath, outputpath) except: pass @app.before_first_request def compile_first(): prepare() @app.before_request def compile_if_debug(): if app.debug and _cfg("debug-static-recompile").lower() in ['true','yes']: prepare() if __name__ == '__main__': app.run(host=_cfg("debug-host"), port=_cfgi('debug-port'), debug=True)
with open(os.path.join(app.static_folder, output), "w") as w: w.write(javascript) w.flush() except: pass try: d = os.walk('images') for f in list(d)[0][2]: outputpath = os.path.join(app.static_folder, os.path.basename(f)) inputpath = os.path.join('images', f) copyfile(inputpath, outputpath) except: pass @app.before_first_request def compile_first(): prepare() @app.before_request def compile_if_debug(): if app.debug and _cfg("debug-static-recompile").lower() in ['true', 'yes']: prepare() if __name__ == '__main__': app.run(host=_cfg("debug-host"), port=_cfgi('debug-port'), debug=True)
import zipfile import locale import traceback import xml.etree.ElementTree as ET from packages.config import _cfg, _cfgi from packages.database import db, init_db from packages.objects import User from packages.common import * from packages.network import * from packages.blueprints.api import api from packages.blueprints.html import html app = Flask(__name__) app.secret_key = _cfg("secret-key") app.jinja_env.cache = None init_db() login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(username): return User.query.filter(User.username == username).first() login_manager.anonymous_user = lambda: None app.register_blueprint(api) app.register_blueprint(html) try:
def compile_if_debug(): if app.debug and _cfg("debug-static-recompile").lower() in ['true', 'yes']: prepare()
import zipfile import locale import traceback import xml.etree.ElementTree as ET from packages.config import _cfg, _cfgi from packages.database import db, init_db from packages.objects import User from packages.common import * from packages.network import * from packages.blueprints.api import api from packages.blueprints.html import html app = Flask(__name__) app.secret_key = _cfg("secret-key") app.jinja_env.cache = None init_db() login_manager = LoginManager() login_manager.init_app(app) @login_manager.user_loader def load_user(username): return User.query.filter(User.username == username).first() login_manager.anonymous_user = lambda: None app.register_blueprint(api) app.register_blueprint(html)
def upload_package(): package_file = request.files.get('package') if not package_file: return {'success': False, 'error': 'You must include a package file.'} f, path = tempfile.mkstemp() package_file.save(path) info = None try: info = PackageInfo.read_package(path) if info.repo == None or info.name == None or info.version == None: return { 'success': False, 'error': 'This is not a valid KnightOS package.' }, 400 if not info.repo in ['core', 'extra', 'community', 'ports', 'nonfree']: return { 'success': False, 'error': '{0} is not an acceptable package repository.'.format( info.repo) }, 400 if '/' in info.name: return { 'success': False, 'error': '{0} is not an acceptable package name.'.format(info.name) }, 400 except: return { 'success': False, 'error': 'This is not a valid KnightOS package.' }, 400 package = Package() existing = Package.query.filter(Package.name == info.name).first() if existing: if existing.repo != info.repo: return { 'success': False, 'error': 'This name conflicts with {0}/{1}.'.format( existing.repo, existing.name) }, 403 if existing.user.username != current_user.username and not current_user.admin: return { 'success': False, 'error': 'You do not have permission to update {0}/{1}.'.format( existing.repo, existing.name) }, 403 package = existing package.updated = datetime.now() else: package.user = current_user package.name = info.name package.repo = info.repo package.approved = False package.version = '{0}.{1}.{2}'.format(info.version[0], info.version[1], info.version[2]) package.description = info.description package.author = info.author package.maintainer = info.maintainer package.infourl = info.infourl package.copyright = info.copyright package.capabilities = ' '.join(info.capabilities) package.contents = None package.dependencies = list() for dep in info.dependencies: try: repo = dep.split('/')[0] name = dep.split('/')[1] db_dep = Package.query.filter(Package.repo == repo).filter( Package.name == name).first() if not db_dep: raise Exception() package.dependencies.append(db_dep) print('appended ' + db_dep.name) except: return { 'success': False, 'error': '{0} is not a known dependency. Did you upload it first?'. format(dep) }, 400 storage_dir = os.path.join(_cfg("storage"), package.repo) if not os.path.exists(storage_dir): os.makedirs(storage_dir) final_path = os.path.join( storage_dir, "{0}-{1}.pkg".format(package.name, package.version)) move(path, final_path) if not existing: db.add(package) send_new_pacakge_email(package) db.commit() return { 'success': True, 'url': '/{0}/{1}'.format(package.repo, package.name) }, 200
def upload_package(): package_file = request.files.get('package') if not package_file: return { 'success': False, 'error': 'You must include a package file.' } f, path = tempfile.mkstemp() package_file.save(path) info = None try: info = PackageInfo.read_package(path) if info.repo == None or info.name == None or info.version == None: return { 'success': False, 'error': 'This is not a valid KnightOS package.' }, 400 if not info.repo in ['core', 'extra', 'community', 'ports', 'nonfree']: return { 'success': False, 'error': '{0} is not an acceptable package repository.'.format(info.repo) }, 400 if '/' in info.name: return { 'success': False, 'error': '{0} is not an acceptable package name.'.format(info.name) }, 400 except: return { 'success': False, 'error': 'This is not a valid KnightOS package.' }, 400 package = Package() existing = Package.query.filter(Package.name == info.name).first() if existing: if existing.repo != info.repo: return { 'success': False, 'error': 'This name conflicts with {0}/{1}.'.format(existing.repo, existing.name) }, 403 if existing.user.username != current_user.username and not current_user.admin: return { 'success': False, 'error': 'You do not have permission to update {0}/{1}.'.format(existing.repo, existing.name) }, 403 package = existing package.updated = datetime.now() else: package.user = current_user package.name = info.name package.repo = info.repo package.approved = False package.version = '{0}.{1}.{2}'.format(info.version[0], info.version[1], info.version[2]) package.description = info.description package.author = info.author package.maintainer = info.maintainer package.infourl = info.infourl package.copyright = info.copyright package.capabilities = ' '.join(info.capabilities) package.contents = None package.dependencies = list() for dep in info.dependencies: try: repo = dep.split('/')[0] name = dep.split('/')[1] db_dep = Package.query.filter(Package.repo == repo).filter(Package.name == name).first() if not db_dep: raise Exception() package.dependencies.append(db_dep) print('appended ' + db_dep.name) except: return { 'success': False, 'error': '{0} is not a known dependency. Did you upload it first?'.format(dep) }, 400 storage_dir = os.path.join(_cfg("storage"), package.repo) if not os.path.exists(storage_dir): os.makedirs(storage_dir) final_path = os.path.join(storage_dir, "{0}-{1}.pkg".format(package.name, package.version)) move(path, final_path) if not existing: db.add(package) send_new_pacakge_email(package) db.commit() return { 'success': True, 'url': '/{0}/{1}'.format(package.repo, package.name) }, 200