Esempio n. 1
0
def remove_asset(asset_id):
    asset = fetch_asset(asset_id)
    try:
        if asset["uri"].startswith(settings.get_asset_folder()):
            os.remove(asset["uri"])
    except OSError:
        pass
    delete_asset(asset_id)
    response.status = 204  # return an OK with no content
Esempio n. 2
0
def remove_asset(asset_id):
    asset = assets_helper.read(db_conn, asset_id)
    try:
        if asset['uri'].startswith(settings.get_asset_folder()):
            os.remove(asset['uri'])
    except OSError:
        pass
    assets_helper.delete(db_conn, asset_id)
    response.status = 204  # return an OK with no content
Esempio n. 3
0
def prepare_asset(request):

    data = request.POST or request.FORM or {}

    if "model" in data:
        data = json.loads(data["model"])

    def get(key):
        val = data.get(key, "")
        return val.strip() if isinstance(val, basestring) else val

    if all([get("name"), get("uri") or (request.files.file_upload != ""), get("mimetype")]):

        asset = {"name": get("name").decode("UTF-8"), "mimetype": get("mimetype"), "asset_id": get("asset_id")}

        uri = get("uri") or False

        if not asset["asset_id"]:
            asset["asset_id"] = uuid.uuid4().hex

        try:
            file_upload = request.files.file_upload
            filename = file_upload.filename
        except AttributeError:
            file_upload = None
            filename = None

        if filename and "web" in asset["mimetype"]:
            raise Exception("Invalid combination. Can't upload a web resource.")

        if uri and filename:
            raise Exception("Invalid combination. Can't select both URI and a file.")

        if uri and not uri.startswith("/"):
            if not validate_uri(uri):
                raise Exception("Invalid URL. Failed to add asset.")

            if "image" in asset["mimetype"]:
                file = req_get(uri, allow_redirects=True)
            else:
                file = req_head(uri, allow_redirects=True)

            if file.status_code == 200:
                asset["uri"] = uri
                # strict_uri = file.url

            else:
                raise Exception("Could not retrieve file. Check the asset URL.")
        else:
            asset["uri"] = uri

        if filename:
            asset["uri"] = path.join(settings.get_asset_folder(), asset["asset_id"])

            with open(asset["uri"], "w") as f:
                while True:
                    chunk = file_upload.file.read(1024)
                    if not chunk:
                        break
                    f.write(chunk)

        if "video" in asset["mimetype"]:
            asset["duration"] = "N/A"
        else:
            # crashes if it's not an int. we want that.
            asset["duration"] = int(get("duration"))

        if get("start_date"):
            asset["start_date"] = datetime.strptime(get("start_date").split(".")[0], "%Y-%m-%dT%H:%M:%S")
        else:
            asset["start_date"] = ""

        if get("end_date"):
            asset["end_date"] = datetime.strptime(get("end_date").split(".")[0], "%Y-%m-%dT%H:%M:%S")
        else:
            asset["end_date"] = ""

        if not asset["asset_id"]:
            raise Exception

        if not asset["uri"]:
            raise Exception

        return asset
    else:
        raise Exception("Not enough information provided. Please specify 'name', 'uri', and 'mimetype'.")
Esempio n. 4
0

@error(403)
def mistake403(code):
    return "The parameter you passed has the wrong format!"


@error(404)
def mistake404(code):
    return "Sorry, this page does not exist!"


################################
# Static
################################


@route("/static/:path#.+#", name="static")
def static(path):
    return static_file(path, root="static")


if __name__ == "__main__":
    # Make sure the asset folder exist. If not, create it
    if not path.isdir(settings.get_asset_folder()):
        mkdir(settings.get_asset_folder())

    initiate_db()

    run(host=settings.get_listen_ip(), port=settings.get_listen_port(), reloader=True)
Esempio n. 5
0
def prepare_asset(request):

    data = request.POST or request.FORM or {}

    if 'model' in data:
        data = json.loads(data['model'])

    def get(key):
        val = data.get(key, '')
        return val.strip() if isinstance(val, basestring) else val

    if all([
        get('name'),
        get('uri') or (request.files.file_upload != ""),
        get('mimetype')]):

        asset = {
            'name': get('name').decode('UTF-8'),
            'mimetype': get('mimetype'),
            'asset_id': get('asset_id'),
        }

        uri = get('uri') or False

        if not asset['asset_id']:
            asset['asset_id'] = uuid.uuid4().hex

        try:
            file_upload = request.files.file_upload
            filename = file_upload.filename
        except AttributeError:
            file_upload = None
            filename = None

        if filename and 'web' in asset['mimetype']:
            raise Exception("Invalid combination. Can't upload a web resource.")

        if uri and filename:
            raise Exception("Invalid combination. Can't select both URI and a file.")

        if uri and not uri.startswith('/'):
	    actual_uri = tok_replace(uri)	# [bknittel] Use actual_uri in tests below

            if not validate_uri(actual_uri):
                raise Exception("Invalid URL. Failed to add asset.")

            if "image" in asset['mimetype']:
                file = req_get(actual_uri, allow_redirects=True)
            else:
                file = req_head(actual_uri, allow_redirects=True)

            if file.status_code == 200:
                asset['uri'] = uri
                # strict_uri = file.url

            else:
                raise Exception("Could not retrieve file. Check the asset URL.")
        else:
            asset['uri'] = uri

        if filename:
            asset['uri'] = path.join(settings.get_asset_folder(), asset['asset_id'])

            with open(asset['uri'], 'w') as f:
                while True:
                    chunk = file_upload.file.read(1024)
                    if not chunk:
                        break
                    f.write(chunk)


        if "video" in asset['mimetype']:
            asset['duration'] = "N/A"
        else:
            # crashes if it's not an int. we want that.
            asset['duration'] = int(get('duration'))

        if get('start_date'):
            asset['start_date'] = datetime.strptime(get('start_date').split(".")[0], "%Y-%m-%dT%H:%M:%S")
        else:
            asset['start_date'] = ""

        if get('end_date'):
            asset['end_date'] = datetime.strptime(get('end_date').split(".")[0], "%Y-%m-%dT%H:%M:%S")
        else:
            asset['end_date'] = ""

        if not asset['asset_id']:
            raise Exception

        if not asset['uri']:
            raise Exception

        return asset
    else:
        raise Exception("Not enough information provided. Please specify 'name', 'uri', and 'mimetype'.")