def compile_ai(id):
    ai = AI.query.get(id)
    if not ai:
        abort(404)
    if not current_user.can_access(ai):
        abort(401)
    return render_template("compile_ai.html", ai=ai)
Exemple #2
0
def ai_qualify_blocking(id):
    ai = AI.query.get(id)
    if not ai:
        return (CommonErrors.INVALID_ID[0]["error"], "error")
    if not current_user.can_access(ai):
        return (CommonErrors.NO_ACCESS[0]["error"], "error")

    if not ai.latest_version().compiled:
        return {"error": "AI_Version isnt compiled."}, 400
    if ai.latest_version().frozen:
        return {"error": "AI_Version is frozen."}, 400

    reqid = backend.request_qualify(ai)
    for data, event in backend.inprogress_log(reqid):
        if event == "success":
            d = backend.request(reqid)
            if "position" in d:
                if d["position"][str(ai.id) + "v" + str(ai.latest_version(
                ).version_id)] > d["position"][str(-ai.type.id) + "v1"]:
                    yield "", "qualified"
                    ai.latest_version().compiled = True
                    ai.latest_version().qualified = True
                else:
                    logger.info("AI " + str(ai.id) + " '" + str(ai.name) +
                                "' failed its qualification")
                    yield "", "failed"
                    ai.latest_version().qualified = False
            else:
                logger.warning("no position in finished ai_qualify_blocking")
            db.session.commit()
        elif event == "crash":
            return False
Exemple #3
0
def start_game():
    if not 'ai[]' in request.form:
        return CommonErrors.INVALID_ID

    ais = request.form.getlist("ai[]")
    logger.debug(ais)
    for i1, ai1 in enumerate(ais):
        for i2, ai2 in enumerate(ais):
            if i1 != i2 and ai1 == ai2:
                logger.warning("Nen Gegen die selben KIs")
                logger.warning(str(ais))
                return {"error": "No duplicate AIs allowed."}, 400

    ais = [AI.query.get(ai) for ai in ais]
    logger.debug(ais)
    if not all(ais):
        return CommonErrors.INVALID_ID

    if not any([current_user.can_access(ai) for ai in ais]):
        return CommonErrors.NO_ACCESS

    if not all([ai.latest_frozen_version() for ai in ais]):
        return {"error": "All AIs have to be frozen"}, 400

    return {"error": False, "inprogress_id": backend.request_game(ais)}
Exemple #4
0
def ai_delete_file(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    if not ("path" in request.form and "filename" in request.form):
        return CommonErrors.BAD_REQUEST

    path = request.form["path"]
    if path.startswith("/") or ".." in path:
        return CommonErrors.BAD_REQUEST
    if not path.endswith("/"):
        path += "/"
    path = "AIs/{}/v{}/{}".format(id, ai.latest_version().version_id, path)
    filename = secure_filename(request.form["filename"])

    @ftp.safe
    def f():
        if not ftp.ftp_host.path.isdir(path):
            return ({"error": "Invalid path."}, 400)

        if ftp.ftp_host.path.isfile(path + filename):
            ftp.ftp_host.remove(path + filename)
        else:
            ftp.ftp_host.rmtree(path + filename)
        return ({"error": False}, 200)

    try:
        return f()
    except ftp.err:
        return CommonErrors.FTP_ERROR
def qualify_ai(id):
    ai = AI.query.get(id)
    if not ai:
        abort(404)
    if not current_user.can_access(ai):
        abort(401)

    #quali_ai = AI.query.get(-ai.type.id)
    quali_ai = mock.Mock()
    quali_ai.id = -ai.type.id
    version = quali_ai.active_version()
    version.compiled, version.qualified, version.frozen = True, True, True
    version.version_id = 1
    quali_ai.name = "QualiKI"
    quali_ai.user = User.query.filter(User.admin == True).first()
    quali_ai.lang = Lang.query.first()

    stream = url_for("api.ai_qualify", id=id)

    return render_template(ai.type.viz,
                           qualify=True,
                           ai0=ai,
                           ai1=quali_ai,
                           inprogress=True,
                           stream=stream)
Exemple #6
0
def ai_enter_tournament(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    if UserTournamentAi.query.filter(UserTournamentAi.ai == ai).first():
        return {"error": "AI already entered"}, 400

        ## vllt doch nicht auf nur eine KI pro User pro Spieltyp limitieren
    if (
        UserTournamentAi.query.filter(UserTournamentAi.user == current_user)
        .filter(UserTournamentAi.type == ai.type)
        .first()
    ):
        return {"error": "You can only enter with one AI"}, 400

    if not ai.active_version():
        return {"error": "Ai isnt active"}, 400

    o = UserTournamentAi.from_ai(ai)
    db.session.add(o)
    db.session.commit()
    logger.info(str(current_user) + " entered a tournament w/ " + str(o))

    return {"error": False}, 200
Exemple #7
0
def ai_new_version_from_zip(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    if any([not v.frozen for v in ai.version_list]):
        return {
            "error":
            "You need to freeze all prior versions to create a new one."
        }, 400

    tmpdir = tempfile.mkdtemp()
    _, tmpzip = tempfile.mkstemp()
    with open(tmpzip, "wb") as f:
        f.write(request.data)

    try:
        with zipfile.ZipFile(tmpzip) as z:
            z.extractall(tmpdir)
    except zipfile.BadZipFile:
        return {"error": "Bad zip file."}, 400

    ai.new_version()

    if not ftp.upload_tree(
            tmpdir, "AIs/{}/v{}".format(ai.id,
                                        ai.latest_version().version_id)):
        return CommonErrors.FTP_ERROR

    return {"error": False}, 200
Exemple #8
0
def ai_enter_tournament(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    if UserTournamentAi.query.filter(UserTournamentAi.ai == ai).first():
        return {"error": "AI already entered"}, 400

    ## vllt doch nicht auf nur eine KI pro User pro Spieltyp limitieren
    if UserTournamentAi.query.filter(
            UserTournamentAi.user == current_user).filter(
                UserTournamentAi.type == ai.type).first():
        return {"error": "You can only enter with one AI"}, 400

    if not ai.active_version():
        return {"error": "Ai isnt active"}, 400

    o = UserTournamentAi.from_ai(ai)
    db.session.add(o)
    db.session.commit()
    logger.info(str(current_user) + " entered a tournament w/ " + str(o))

    return {"error": False}, 200
Exemple #9
0
def download_zip(id, version_id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    version = AI_Version.query.filter(AI_Version.ai_id == id).filter(
        AI_Version.version_id == version_id).first()
    if not version:
        return CommonErrors.INVALID_ID

    tmpdir = tempfile.mkdtemp()
    _, tmpzip = tempfile.mkstemp()

    if not ftp.download_tree(version.path, tmpdir):
        return CommonErrors.FTP_ERROR

    currdir = os.getcwd()
    os.chdir(tmpdir)
    zipf = zipfile.ZipFile(tmpzip, 'w')
    zipdir(".", zipf)
    zipf.close()
    os.chdir(currdir)
    return send_file(tmpzip,
                     as_attachment=True,
                     attachment_filename="{}_v{}.zip".format(
                         ai.name, version_id))
Exemple #10
0
def ai_create_folder(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    if not ('path' in request.form and 'name' in request.form):
        return CommonErrors.BAD_REQUEST

    path = request.form['path']
    if path.startswith("/") or ".." in path:
        return CommonErrors.BAD_REQUEST
    if not path.endswith("/"):
        path += "/"
    path = "AIs/{}/v{}/{}".format(id, ai.latest_version().version_id, path)
    name = secure_filename(request.form['name'])
    if not len(name):
        return ({"error": "Missing name."}, 400)

    @ftp.safe
    def f():
        if not ftp.ftp_host.path.isdir(path):
            return ({'error': 'Invalid path.'}, 400)

        ftp.ftp_host.mkdir(path + name)
        return ({"error": False}, 200)

    try:
        return f()
    except ftp.err:
        return CommonErrors.FTP_ERROR
Exemple #11
0
def ai_qualify_blocking(id):
	ai = AI.query.get(id)
	if not ai:
		return (CommonErrors.INVALID_ID[0]["error"], "error")
	if not current_user.can_access(ai):
		return (CommonErrors.NO_ACCESS[0]["error"], "error")


	if not ai.latest_version().compiled:
		return ("AI_Version isnt compiled.", "error")
	if ai.latest_version().frozen:
		return ("AI_Version is frozen.", "error")

	reqid = backend.request_qualify(ai)
	for data, event in backend.inprogress_log(reqid):
		if event == "success":
			d = backend.request(reqid)
			if "position" in d:
				if d["position"][str(ai.id) + "v" + str(ai.latest_version().version_id)] > d["position"][str(-ai.type.id) + "v1"]:
					yield "", "qualified"
					ai.latest_version().compiled = True
					ai.latest_version().qualified = True
				else:
					logger.info("AI " + str(ai.id) + " '" + str(ai.name) + "' failed its qualification")
					yield "", "failed"
					ai.latest_version().qualified = False
			else:
				logger.warning("no position in finished ai_qualify_blocking")
			db.session.commit()
		elif event == "crash":
			return ("ai crashed", "error")
Exemple #12
0
def start_game():
	if not 'ai[]' in request.form:
		return CommonErrors.INVALID_ID

	ais = request.form.getlist("ai[]")
	logger.debug(ais)
	for i1, ai1 in enumerate(ais):
		for i2, ai2 in enumerate(ais):
			if i1 != i2 and ai1 == ai2:
				logger.warning("Nen Gegen die selben KIs")
				logger.warning(str(ais))
				return {"error": "No duplicate AIs allowed."}, 400

	ais = [AI.query.get(ai) for ai in ais]
	logger.debug(ais)
	if not all(ais):
		return CommonErrors.INVALID_ID

	if not any([current_user.can_access(ai) for ai in ais]):
		return CommonErrors.NO_ACCESS

	if not all([ai.latest_frozen_version() for ai in ais]):
		return {"error": "All AIs have to be frozen"}, 400

	return {"error": False, "inprogress_id": backend.request_game(ais)}
Exemple #13
0
def ai_new_version_from_zip(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	if any([not v.frozen for v in ai.version_list]):
		return {"error": "You need to freeze all prior versions to create a new one."}, 400

	tmpdir = tempfile.mkdtemp()
	_, tmpzip = tempfile.mkstemp()
	with open(tmpzip, "wb") as f:
		f.write(request.data)

	try:
		with zipfile.ZipFile(tmpzip) as z:
			z.extractall(tmpdir)
	except zipfile.BadZipFile:
		return {"error": "Bad zip file."}, 400

	ai.new_version()

	if not ftp.upload_tree(tmpdir, "AIs/{}/v{}".format(ai.id, ai.latest_version().version_id)):
		return CommonErrors.FTP_ERROR

	return {"error": False}, 200
def compile_ai(id):
    ai = AI.query.get(id)
    if not ai:
        abort(404)
    if not current_user.can_access(ai):
        abort(401)
    return render_template("compile_ai.html", ai=ai)
Exemple #15
0
def ai_create_folder(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	if not ('path' in request.form and 'name' in request.form):
		return CommonErrors.BAD_REQUEST

	path = request.form['path']
	if path.startswith("/") or ".." in path:
		return CommonErrors.BAD_REQUEST
	if not path.endswith("/"):
		path += "/"
	path = "AIs/{}/v{}/{}".format(id, ai.latest_version().version_id, path)
	name = secure_filename(request.form['name'])
	if not len(name):
		return ({"error": "Missing name."}, 400)

	@ftp.safe
	def f():
		if not ftp.ftp_host.path.isdir(path):
			return ({'error': 'Invalid path.'}, 400)

		ftp.ftp_host.mkdir(path + name)
		return ({"error": False}, 200)

	try:
		return f()
	except ftp.err:
		return CommonErrors.FTP_ERROR
Exemple #16
0
 def filter_output(cls, chunk):
     ## TODO: kein lookup jedes mal
     for ai in chunk["output"]:
         ai_id = ai.split("v")[0]
         if not (current_user and current_user.is_authenticated
                 and current_user.can_access(AI.query.get(ai_id))):
             chunk["output"][ai] = ""
def file_browser(id, path=""):

    if ".." in path or path.startswith("/"):
        abort(404)

    ai = AI.query.get(id)
    if not ai:
        abort(404)
    if not current_user.can_access(ai):
        abort(401)

        ## cleanup?

    curr_url = url_for("authenticated.file_browser", id=id, path=path)
    if not curr_url.endswith("/"):
        curr_url += "/"

    ftp_url = "AIs/{}/v{}/{}".format(id, ai.latest_version().version_id, path)

    root_url = url_for("authenticated.file_browser", id=id, path="")
    path_url = [(ai.name, url_for("authenticated.edit_ai", id=id)), ("(root)", root_url)]
    url = root_url[:-1]
    for p in path.split("/"):
        url += "/" + p
        path_url.append((p, url))

    @ftp.safe
    def f():
        if ftp.ftp_host.path.isfile(ftp_url):
            submit_path = "/".join(path.split("/")[:-1])
            submit_name = path.split("/")[-1]
            with ftp.ftp_host.open(ftp_url, "r") as remote_obj:
                code = remote_obj.read()
                return render_template(
                    "ai_file_editor.html",
                    path=path_url,
                    code=code,
                    ai=ai,
                    is_libs=submit_name == "libraries.txt",
                    submit_name=submit_name,
                    submit_path=submit_path,
                )

        objs = []
        files = ftp.ftp_host.listdir(ftp_url)
        for f in files:
            tmps = int(ftp.ftp_host.path.getmtime(ftp_url + "/" + f))
            objs.append(
                dict(name=f, isfile=ftp.ftp_host.path.isfile(ftp_url + "/" + f), url=curr_url + f, timestamp=tmps)
            )
        return render_template(
            "ai_file_browser.html", ai=ai, objs=objs, path=path_url, connected=True, submit_path=path
        )

    try:
        return f()
    except ftp.err:
        logger.warning("err")
        return render_template("ai_file_browser.html", connected=False, ai=ai)
Exemple #18
0
	def filter_crash(cls, data):
		ai = AI.query.get(int(data["id"].split("v")[0]))
		if not ai:
			logger.error("crash on nonexistant ai")
			return False, None
		data.pop("isCrash", None)
		data.pop("requestid", None)
		if current_user and current_user.is_authenticated and current_user.can_access(ai):
			return True, data
		return False, None
def profile_id(id):
    user = User.query.get(id)
    if not user:
        abort(404)
    if not current_user.can_access(user):
        abort(403)

    ais = AI.filtered().filter(AI.user == user).all()
    columns = [ais[i : i + 3] for i in range(0, len(ais), 3)]
    return render_template("profile.html", columns=columns, user=user, gametype=GameType.selected())
Exemple #20
0
def ai_new_version(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	if any([not v.frozen for v in ai.version_list]):
		return {"error": "You need to freeze all prior versions to create a new one."}, 400
	ai.new_version()
	return {"error": False}, 200
Exemple #21
0
def api_user_delete(id):
	user = User.query.get(id)
	if not user:
		return CommonErrors.INVALID_ID

	if not current_user.can_access(user):
		return CommonErrors.NO_ACCESS

	logger.info("User " + user.name + " von " + current_user.name + " geloescht!")
	user.delete()
	return {"error": False}
Exemple #22
0
def api_ai_delete(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID

	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	logger.info("AI " + ai.name + " von " + current_user.name + " geloescht!")
	ai.delete()
	return ({"error": False}, 200)
def qualify_ai(id):
	ai = AI.query.get(id)
	if not ai:
		abort(404)
	if not current_user.can_access(ai):
		abort(401)

	quali_ai = QualiAI(ai.type, ai.lang)
	stream = url_for("api.ai_qualify", id=id)

	return render_template(ai.type.viz, qualify=True, ai0=ai, ai1=quali_ai, inprogress=True, stream=stream)
Exemple #24
0
def api_ai_delete(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID

    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    logger.info("AI " + ai.name + " von " + current_user.name + " geloescht!")
    ai.delete()
    return ({"error": False}, 200)
Exemple #25
0
 def filter_crash(cls, data):
     ai = AI.query.get(int(data["id"].split("v")[0]))
     if not ai:
         logger.error("crash on nonexistant ai")
         return False, None
     data.pop("isCrash", None)
     data.pop("requestid", None)
     if current_user and current_user.is_authenticated and current_user.can_access(
             ai):
         return True, data
     return False, None
Exemple #26
0
def api_user_delete(id):
    user = User.query.get(id)
    if not user:
        return CommonErrors.INVALID_ID

    if not current_user.can_access(user):
        return CommonErrors.NO_ACCESS

    logger.info("User " + user.name + " von " + current_user.name +
                " geloescht!")
    user.delete()
    return {"error": False}
Exemple #27
0
def ai_freeze(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	for version in ai.version_list:
		if version.compiled and version.qualified:
			version.frozen = True

	db.session.commit()
	return {"error": False}, 200
Exemple #28
0
def ai_freeze(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    for version in ai.version_list:
        if version.compiled and version.qualified:
            version.frozen = True

    db.session.commit()
    return {"error": False}, 200
def profile_id(id):
    user = User.query.get(id)
    if not user:
        abort(404)
    if not current_user.can_access(user):
        abort(403)

    ais = AI.filtered().filter(AI.user == user).all()
    columns = [ais[i:i + 3] for i in range(0, len(ais), 3)]
    return render_template("profile.html",
                           columns=columns,
                           user=user,
                           gametype=GameType.selected())
def edit_ai(id):
    ai = AI.query.get(id)
    if not ai:
        abort(404)
    if not current_user.can_access(ai):
        abort(401)
    t = UserTournamentAi.query.filter(UserTournamentAi.user == current_user)\
        .filter(UserTournamentAi.type == ai.type).first() is None
    t = t and ai.active_version()
    return render_template("edit_ai.html",
                           ai=ai,
                           langs=Lang.query.all(),
                           can_enter_tournament=t)
Exemple #31
0
def api_ai_compile(id):
	ai = AI.query.get(id)
	if not ai:
		return (CommonErrors.INVALID_ID[0]["error"], "error")
	if not current_user.can_access(ai):
		return (CommonErrors.NO_ACCESS[0]["error"], "error")

	if ai.latest_version().frozen:
		return ("AI_Version is frozen", "error")
	ai.latest_version().compiled = True
	ai.latest_version().qualified = False
	db.session.commit()

	yield from backend.compile(ai)
def edit_ai(id):
    ai = AI.query.get(id)
    if not ai:
        abort(404)
    if not current_user.can_access(ai):
        abort(401)
    t = (
        UserTournamentAi.query.filter(UserTournamentAi.user == current_user)
        .filter(UserTournamentAi.type == ai.type)
        .first()
        is None
    )
    t = t and ai.active_version()
    return render_template("edit_ai.html", ai=ai, langs=Lang.query.all(), can_enter_tournament=t)
Exemple #33
0
def api_ai_compile(id):
    ai = AI.query.get(id)
    if not ai:
        return (CommonErrors.INVALID_ID[0]["error"], "error")
    if not current_user.can_access(ai):
        return (CommonErrors.NO_ACCESS[0]["error"], "error")

    if ai.latest_version().frozen:
        return {"error": "AI_Version is frozen"}, 400
    ai.latest_version().compiled = True
    ai.latest_version().qualified = False
    db.session.commit()

    yield from backend.compile(ai)
Exemple #34
0
def ai_new_version(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    if any([not v.frozen for v in ai.version_list]):
        return {
            "error":
            "You need to freeze all prior versions to create a new one."
        }, 400
    ai.new_version()
    return {"error": False}, 200
def edit_ai(id):
	ai = AI.query.get(id)
	if not ai:
		abort(404)
	if not current_user.can_access(ai):
		abort(401)
	t = UserTournamentAi.query.filter(UserTournamentAi.user == ai.user) \
	    .filter(UserTournamentAi.type == ai.type).first() is None
	t = t and ai.active_version()
	t = t and Tournament.query.first()
	current_download = None
	if len(ai.version_list) > 0:
		current_download = url_for('api.download_zip', id=ai.id, version_id=ai.version_list[-1].version_id)
	return render_template("edit_ai.html", ai=ai, langs=Lang.query.all(), can_enter_tournament=t, current_download=current_download)
Exemple #36
0
def api_ai_copy_example_code(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    try:
        ai.ftp_sync()
    except ftp.err:
        return CommonErrors.FTP_ERROR

    if not ai.copy_example_code():
        return CommonErrors.FTP_ERROR

    return ({"error": False}, 200)
Exemple #37
0
def ai_exit_tournament(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    o = UserTournamentAi.query.filter(UserTournamentAi.ai == ai).first()
    if not o:
        return {"error": "AI isnt in any tournament"}, 400

    o.delete()

    logger.info(str(current_user) + " exited a tournament")

    return {"error": False}, 200
Exemple #38
0
def ai_exit_tournament(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	o = UserTournamentAi.query.filter(UserTournamentAi.ai == ai).first()
	if not o:
		return {"error": "AI isnt in any tournament"}, 400

	o.delete()

	logger.info(str(current_user) + " exited a tournament")

	return {"error": False}, 200
Exemple #39
0
def api_ai_copy_example_code(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    try:
        ai.ftp_sync()
    except ftp.err:
        return CommonErrors.FTP_ERROR

    if not ai.copy_example_code():
        return CommonErrors.FTP_ERROR

    return ({"error": False}, 200)
Exemple #40
0
def ai_upload_zip(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    if any([not v.frozen for v in ai.version_list]):
        ai.new_version(copy_prev=False)

    if request.mimetype == "multipart/form-data":
        if len(request.files) != 1:
            return {"error": "Invalid number of files attached."}, 400
        content = list(request.files.values())[0].read()
    else:
        content = request.data

    mime = magic.from_buffer(content, mime=True).decode("ascii")
    if mime != "application/zip":
        return {
            "error": "Invalid mimetype for an ZIP-File.",
            "mimetype": mime
        }, 400

    tmpdir = tempfile.mkdtemp()
    _, tmpzip = tempfile.mkstemp()
    with open(tmpzip, "wb") as f:
        f.write(content)

    try:
        with zipfile.ZipFile(tmpzip) as z:
            z.extractall(tmpdir)
    except zipfile.BadZipFile:
        return {"error": "Bad zip file."}, 400

    version = ai.latest_version()
    if version.frozen:
        version = ai.new_version(copy=False)

    if not ftp.upload_tree(tmpdir, "AIs/{}/v{}".format(ai.id,
                                                       version.version_id)):
        return CommonErrors.FTP_ERROR

    version.compiled, version.qualified, version.frozen = False, False, False

    return {"error": False}, 200
Exemple #41
0
def ai_activate_version(id, version_id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	version = AI_Version.query.filter(AI_Version.ai == ai).filter(AI_Version.version_id == version_id).first()
	if not version:
		return CommonErrors.INVALID_ID
	if not version.compiled or not version.qualified or not version.frozen:
		return {"error": "New version isnt frozen"}, 400

	ai._active_version_id = version.id
	db.session.commit()

	return {"error": False}, 200
Exemple #42
0
def ai_upload(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    if not ('path' in request.form and 'filename' in request.form
            and 'data' in request.form):
        return CommonErrors.BAD_REQUEST

    path = request.form['path']
    if path.startswith("/") or ".." in path:
        return CommonErrors.BAD_REQUEST
    if not path.endswith("/"):
        path += "/"
    path = "AIs/{}/v{}/{}".format(id, ai.latest_version().version_id, path)
    filename = secure_filename(request.form['filename'])
    if not len(filename):
        return ({"error": "Missing filename."}, 400)
    data = request.form["data"]

    if ai.latest_version().frozen:
        return {
            "error": "AI is frozen, you need to create a new version."
        }, 400

    @ftp.safe
    def f():
        if not ftp.ftp_host.path.isdir(path):
            return ({'error': 'Invalid path.'}, 400)

        with open("tmpfile", "w") as f:
            f.write(data)

        ftp.ftp_host.upload("tmpfile", path + filename)
        ai.latest_version().compiled = False
        ai.latest_version().qualified = False
        db.session.commit()
        return ({"error": False}, 200)

    try:
        return f()
    except ftp.err:
        return CommonErrors.FTP_ERROR
Exemple #43
0
def api_ai_update(id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID

    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    logger.info("AI " + ai.name + " geaendert")

    ai.set_name(request.form.get('name', ai.name))
    ai.desc = request.form.get('description', ai.desc)
    if 'lang' in request.form:
        l = Lang.query.get(request.form.get('lang'))
        if l and l is not ai.lang:
            logger.warning("Sprache von AI geändert")
            ai.lang = l
            ai.ftp_sync()
            ai.copy_example_code()
            for version in ai.version_list:
                if not any(
                    [version.frozen, version.qualified, version.compiled]):
                    version.lang = ai.lang
            ai.latest_version().lang = ai.lang
    if 'extra[]' in request.form:
        extras = request.form.getlist("extra[]")
        logger.info(str(extras))
        lib_objs = [
            ai.available_extras().filter(Library.name == extra).first()
            for extra in extras
        ]
        lib_objs = [o for o in lib_objs if o is not None]
        ai.latest_version().extras = lib_objs
        ai.latest_version().sync_extras()
    elif 'extra' in request.form:
        # das Web-Interface schickt bei nem leeren Feld statt 'extra[]' 'extra'
        ai.latest_version().extras = []
        ai.latest_version().sync_extras()

    # es muss zur Datenbank geschrieben werden, um die aktuellen Infos zu bekommen
    db.session.commit()

    ai.updated()

    return ai.info()
Exemple #44
0
def ai_activate_version(id, version_id):
    ai = AI.query.get(id)
    if not ai:
        return CommonErrors.INVALID_ID
    if not current_user.can_access(ai):
        return CommonErrors.NO_ACCESS

    version = AI_Version.query.filter(AI_Version.ai == ai).filter(
        AI_Version.version_id == version_id).first()
    if not version:
        return CommonErrors.INVALID_ID
    if not version.compiled or not version.qualified or not version.frozen:
        return {"error": "New version isnt frozen"}, 400

    ai._active_version_id = version.id
    db.session.commit()

    return {"error": False}, 200
Exemple #45
0
def ai_upload(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	if not ('path' in request.form and 'filename' in request.form and 'data' in request.form):
		return CommonErrors.BAD_REQUEST

	path = request.form['path']
	if path.startswith("/") or ".." in path:
		return CommonErrors.BAD_REQUEST
	if not path.endswith("/"):
		path += "/"
	path = "AIs/{}/v{}/{}".format(id, ai.latest_version().version_id, path)
	filename = secure_filename(request.form['filename'])
	if not len(filename):
		return ({"error": "Missing filename."}, 400)
	data = request.form["data"]

	if ai.latest_version().frozen:
		return {"error": "AI is frozen, you need to create a new version."}, 400

	@ftp.safe
	def f():
		if not ftp.ftp_host.path.isdir(path):
			return ({'error': 'Invalid path.'}, 400)

		with open("tmpfile", "w") as f:
			f.write(data)

		ftp.ftp_host.upload("tmpfile", path + filename)
		ai.latest_version().compiled = False
		ai.latest_version().qualified = False
		db.session.commit()
		return ({"error": False}, 200)

	try:
		return f()
	except ftp.err:
		return CommonErrors.FTP_ERROR
Exemple #46
0
def ai_upload_zip(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	if any([not v.frozen for v in ai.version_list]):
		ai.new_version(copy_prev=False)

	if request.mimetype == "multipart/form-data":
		if len(request.files) != 1:
			return {"error": "Invalid number of files attached."}, 400
		content = list(request.files.values())[0].read()
	else:
		content = request.data

	mime = magic.from_buffer(content, mime=True).decode("ascii")
	if mime != "application/zip":
		return {"error": "Invalid mimetype for an ZIP-File.", "mimetype": mime}, 400

	tmpdir = tempfile.mkdtemp()
	_, tmpzip = tempfile.mkstemp()
	with open(tmpzip, "wb") as f:
		f.write(content)

	try:
		with zipfile.ZipFile(tmpzip) as z:
			z.extractall(tmpdir)
	except zipfile.BadZipFile:
		return {"error": "Bad zip file."}, 400

	version = ai.latest_version()
	if version.frozen:
		version = ai.new_version(copy=False)

	if not ftp.upload_tree(tmpdir, "AIs/{}/v{}".format(ai.id, version.version_id)):
		return CommonErrors.FTP_ERROR

	version.compiled, version.qualified, version.frozen = False, False, False

	return {"error": False}, 200
def qualify_ai(id):
    ai = AI.query.get(id)
    if not ai:
        abort(404)
    if not current_user.can_access(ai):
        abort(401)

        # quali_ai = AI.query.get(-ai.type.id)
    quali_ai = mock.Mock()
    quali_ai.id = -ai.type.id
    version = quali_ai.active_version()
    version.compiled, version.qualified, version.frozen = True, True, True
    version.version_id = 1
    quali_ai.name = "QualiKI"
    quali_ai.user = User.query.filter(User.admin == True).first()
    quali_ai.lang = Lang.query.first()

    stream = url_for("api.ai_qualify", id=id)

    return render_template(ai.type.viz, qualify=True, ai0=ai, ai1=quali_ai, inprogress=True, stream=stream)
Exemple #48
0
def api_ai_update(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID

	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	logger.info("AI " + ai.name + " geaendert")

	ai.set_name(request.form.get('name', ai.name))
	ai.desc = request.form.get('description', ai.desc)
	if 'lang' in request.form:
		l = Lang.query.get(request.form.get('lang'))
		if l and l is not ai.lang:
			logger.warning("Sprache von AI geändert")
			ai.lang = l
			ai.ftp_sync()
			ai.copy_example_code()
			for version in ai.version_list:
				if not any([version.frozen, version.qualified, version.compiled]):
					version.lang = ai.lang
			ai.latest_version().lang = ai.lang
	if 'extra[]' in request.form:
		extras = request.form.getlist("extra[]")
		logger.info(str(extras))
		lib_objs = [ai.available_extras().filter(Library.name == extra).first() for extra in extras]
		lib_objs = [o for o in lib_objs if o is not None]
		ai.latest_version().extras = lib_objs
		ai.latest_version().sync_extras()
	elif 'extra' in request.form:
		# das Web-Interface schickt bei nem leeren Feld statt 'extra[]' 'extra'
		ai.latest_version().extras = []
		ai.latest_version().sync_extras()

	# es muss zur Datenbank geschrieben werden, um die aktuellen Infos zu bekommen
	db.session.commit()

	ai.updated()

	return ai.info()
Exemple #49
0
def api_ai_compile_blocking(id):
    ai = AI.query.get(id)
    if not ai:
        return (CommonErrors.INVALID_ID[0]["error"], "error")
    if not current_user.can_access(ai):
        return (CommonErrors.NO_ACCESS[0]["error"], "error")

    if ai.latest_version().frozen:
        return {"error": "AI_Version is frozen"}, 400
    ai.latest_version().compiled = True
    ai.latest_version().qualified = False
    db.session.commit()

    compile_log = ""

    for data, event in backend.compile(ai):
        if event == "log":
            compile_log += data
        if event == "error":
            return {"error": data, "compilelog": compile_log}

    return {"error": None, "compilelog": compile_log}, 200
Exemple #50
0
def api_ai_compile_blocking(id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	if ai.latest_version().frozen:
		return {"error": "AI_Version is frozen"}, 400
	ai.latest_version().compiled = True
	ai.latest_version().qualified = False
	db.session.commit()

	compile_log = ""

	for data, event in backend.compile(ai):
		if event == "log":
			compile_log += data
		if event == "error":
			return {"error": data, "compilelog": compile_log}, 200

	return {"error": None, "compilelog": compile_log}, 200
Exemple #51
0
def api_user_update(id):
	user = User.query.get(id)
	if not user:
		return CommonErrors.INVALID_ID

	if not current_user.can_access(user):
		return CommonErrors.NO_ACCESS

	user.firstname = request.form.get('firstname', user.firstname)
	user.lastname = request.form.get('lastname', user.lastname)
	user.email = request.form.get('email', user.email)
	if "name_public" in request.form:
		user.name_public = request.form["name_public"] in ["true", "True", "1"]
	if "password" in request.form:
		user.set_pw(request.form["password"])

	# es muss zur Datenbank geschrieben werden, um die aktuellen Infos zu bekommen
	db.session.commit()

	logger.info("User '" + user.name + "' geaendert")
	flash("Änderungen gespeichert.", "info")

	return {"error": False, "user": user.info()}, 200
Exemple #52
0
def api_user_update(id):
    user = User.query.get(id)
    if not user:
        return CommonErrors.INVALID_ID

    if not current_user.can_access(user):
        return CommonErrors.NO_ACCESS

    user.firstname = request.form.get('firstname', user.firstname)
    user.lastname = request.form.get('lastname', user.lastname)
    user.email = request.form.get('email', user.email)
    if "name_public" in request.form:
        user.name_public = request.form["name_public"] in ["true", "True", "1"]
    if "password" in request.form:
        user.set_pw(request.form["password"])

    # es muss zur Datenbank geschrieben werden, um die aktuellen Infos zu bekommen
    db.session.commit()

    logger.info("User '" + user.name + "' geaendert")
    flash("Änderungen gespeichert.", "info")

    return {"error": False, "user": user.info()}, 200
Exemple #53
0
def download_zip(id, version_id):
	ai = AI.query.get(id)
	if not ai:
		return CommonErrors.INVALID_ID
	if not current_user.can_access(ai):
		return CommonErrors.NO_ACCESS

	version = AI_Version.query.filter(AI_Version.ai_id == id).filter(AI_Version.version_id == version_id).first()
	if not version:
		return CommonErrors.INVALID_ID

	tmpdir = tempfile.mkdtemp()
	_, tmpzip = tempfile.mkstemp()

	if not ftp.download_tree(version.path, tmpdir):
		return CommonErrors.FTP_ERROR

	currdir = os.getcwd()
	os.chdir(tmpdir)
	zipf = zipfile.ZipFile(tmpzip, 'w')
	zipdir(".", zipf)
	zipf.close()
	os.chdir(currdir)
	return send_file(tmpzip, as_attachment=True, attachment_filename="{}_v{}.zip".format(ai.name, version_id))
def file_browser(id, path=""):

    if '..' in path or path.startswith('/'):
        abort(404)

    ai = AI.query.get(id)
    if not ai:
        abort(404)
    if not current_user.can_access(ai):
        abort(401)

    ## cleanup?

    curr_url = url_for("authenticated.file_browser", id=id, path=path)
    if not curr_url.endswith("/"):
        curr_url += "/"

    ftp_url = "AIs/{}/v{}/{}".format(id, ai.latest_version().version_id, path)

    root_url = url_for("authenticated.file_browser", id=id, path="")
    path_url = [(ai.name, url_for("authenticated.edit_ai", id=id)),
                ("(root)", root_url)]
    url = root_url[:-1]
    for p in path.split("/"):
        url += "/" + p
        path_url.append((p, url))

    @ftp.safe
    def f():
        if ftp.ftp_host.path.isfile(ftp_url):
            submit_path = "/".join(path.split("/")[:-1])
            submit_name = path.split("/")[-1]
            with ftp.ftp_host.open(ftp_url, "r") as remote_obj:
                code = remote_obj.read()
                return render_template("ai_file_editor.html",
                                       path=path_url,
                                       code=code,
                                       ai=ai,
                                       is_libs=submit_name == "libraries.txt",
                                       submit_name=submit_name,
                                       submit_path=submit_path)

        objs = []
        files = ftp.ftp_host.listdir(ftp_url)
        for f in files:
            tmps = int(ftp.ftp_host.path.getmtime(ftp_url + "/" + f))
            objs.append(
                dict(name=f,
                     isfile=ftp.ftp_host.path.isfile(ftp_url + "/" + f),
                     url=curr_url + f,
                     timestamp=tmps))
        return render_template("ai_file_browser.html",
                               ai=ai,
                               objs=objs,
                               path=path_url,
                               connected=True,
                               submit_path=path)

    try:
        return f()
    except ftp.err:
        logger.warning("err")
        return render_template("ai_file_browser.html", connected=False, ai=ai)
 def inner():
     return [
         app for app in get_apps_handler()
         if current_user.can_access(app['name'])
     ]
Exemple #56
0
	def filter_output(cls, chunk):
		## TODO: kein lookup jedes mal
		for ai in chunk["output"]:
			ai_id = ai.split("v")[0]
			if not (current_user and current_user.is_authenticated and current_user.can_access(AI.query.get(ai_id))):
				chunk["output"][ai] = ""
 def inner():
     return [app for app in get_apps_handler() if
             current_user.can_access(app['name'])]