예제 #1
0
def generate_asset_list():
    logging.info('Generating asset-list...')
    c = connection.cursor()
    c.execute("SELECT asset_id, name, uri, md5, start_date, end_date, duration, mimetype FROM assets ORDER BY name")
    query = c.fetchall()

    playlist = []
    time_cur = datetime.utcnow()
    deadline = None
    for asset in query:
        asset_id = asset[0]
        name = asset[1].encode('ascii', 'ignore')
        uri = tok_replace(asset[2])		# [bknittel] call tok_replace on uri
        md5 = asset[3]
        start_date = asset[4]
        end_date = asset[5]
        duration = asset[6]
        mimetype = asset[7]

        logging.debug('generate_asset_list: %s: start (%s) end (%s)' % (name, start_date, end_date))
        if start_date and end_date:
            if start_date < time_cur and end_date > time_cur:
                playlist.append({"asset_id": asset_id, "name": name, "uri": uri, "duration": duration, "mimetype": mimetype})
                if not deadline or end_date < deadline:
                    deadline = end_date
            elif start_date >= time_cur and end_date > start_date:
                if not deadline or start_date < deadline:
                    deadline = start_date

    logging.debug('generate_asset_list deadline: %s' % deadline)

    if settings['shuffle_playlist']:
        shuffle(playlist)

    return (playlist, deadline)
예제 #2
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'.")