Ejemplo n.º 1
0
def prepare_asset_v1_2(request, asset_id=None):
    req = Request(request.environ)

    data = json.loads(req.data)

    def get(key):
        val = data.get(key, '')
        if isinstance(val, unicode):
            return val.strip()
        elif isinstance(val, basestring):
            return val.strip().decode('utf-8')
        else:
            return val

    if not all([
            get('name'),
            get('uri'),
            get('mimetype'),
            str(get('is_enabled')),
            get('start_date'),
            get('end_date')
    ]):
        raise Exception(
            "Not enough information provided. Please specify 'name', 'uri', 'mimetype', 'is_enabled', 'start_date' and 'end_date'."
        )

    asset = {
        'name': get('name'),
        'mimetype': get('mimetype'),
        'is_enabled': get('is_enabled'),
        'nocache': get('nocache')
    }

    uri = get('uri')

    if uri.startswith('/'):
        if not path.isfile(uri):
            raise Exception("Invalid file path. Failed to add asset.")
    else:
        if not validate_url(uri):
            raise Exception("Invalid URL. Failed to add asset.")

    if not asset_id:
        asset['asset_id'] = uuid.uuid4().hex
        if uri.startswith('/'):
            rename(uri, path.join(settings['assetdir'], asset['asset_id']))
            uri = path.join(settings['assetdir'], asset['asset_id'])

    if 'youtube_asset' in asset['mimetype']:
        uri, asset['name'], asset['duration'] = download_video_from_youtube(
            uri, asset['asset_id'])
        asset['mimetype'] = 'video'
        asset['is_processing'] = 1

    asset['uri'] = uri

    if "video" in asset['mimetype']:
        if get('duration') == 'N/A' or int(get('duration')) == 0:
            asset['duration'] = int(get_video_duration(uri).total_seconds())
    elif get('duration'):
        # Crashes if it's not an int. We want that.
        asset['duration'] = int(get('duration'))
    else:
        asset['duration'] = 10

    asset['play_order'] = get('play_order') if get('play_order') else 0

    # parse date via python-dateutil and remove timezone info
    asset['start_date'] = date_parser.parse(
        get('start_date')).replace(tzinfo=None)
    asset['end_date'] = date_parser.parse(get('end_date')).replace(tzinfo=None)

    return asset
Ejemplo n.º 2
0
def prepare_asset_v1_2(request_environ, asset_id=None, unique_name=False):
    data = json.loads(request_environ.data)

    def get(key):
        val = data.get(key, '')
        if isinstance(val, unicode):
            return val.strip()
        elif isinstance(val, basestring):
            return val.strip().decode('utf-8')
        else:
            return val

    if not all([get('name'),
                get('uri'),
                get('mimetype'),
                str(get('is_enabled')),
                get('start_date'),
                get('end_date')]):
        raise Exception(
            "Not enough information provided. Please specify 'name', 'uri', 'mimetype', 'is_enabled', 'start_date' and 'end_date'.")

    name = get('name')
    if unique_name:
        with db.conn(settings['database']) as conn:
            names = assets_helper.get_names_of_assets(conn)
        if name in names:
            i = 1
            while True:
                new_name = '%s-%i' % (name, i)
                if new_name in names:
                    i += 1
                else:
                    name = new_name
                    break

    asset = {
        'name': name,
        'mimetype': get('mimetype'),
        'is_enabled': get('is_enabled'),
        'nocache': get('nocache')
    }

    uri = get('uri')

    if uri.startswith('/'):
        if not path.isfile(uri):
            raise Exception("Invalid file path. Failed to add asset.")
    else:
        if not validate_url(uri):
            raise Exception("Invalid URL. Failed to add asset.")

    if not asset_id:
        asset['asset_id'] = uuid.uuid4().hex
        if uri.startswith('/'):
            rename(uri, path.join(settings['assetdir'], asset['asset_id']))
            uri = path.join(settings['assetdir'], asset['asset_id'])

    if 'youtube_asset' in asset['mimetype']:
        uri, asset['name'], asset['duration'] = download_video_from_youtube(uri, asset['asset_id'])
        asset['mimetype'] = 'video'
        asset['is_processing'] = 1

    asset['uri'] = uri

    if "video" in asset['mimetype']:
        if get('duration') == 'N/A' or int(get('duration')) == 0:
            asset['duration'] = int(get_video_duration(uri).total_seconds())
    elif get('duration'):
        # Crashes if it's not an int. We want that.
        asset['duration'] = int(get('duration'))
    else:
        asset['duration'] = 10

    asset['play_order'] = get('play_order') if get('play_order') else 0

    asset['skip_asset_check'] = int(get('skip_asset_check')) if int(get('skip_asset_check')) else 0

    # parse date via python-dateutil and remove timezone info
    asset['start_date'] = date_parser.parse(get('start_date')).replace(tzinfo=None)
    asset['end_date'] = date_parser.parse(get('end_date')).replace(tzinfo=None)

    return asset
Ejemplo n.º 3
0
def prepare_asset(request, unique_name=False):
    req = Request(request.environ)
    data = None

    # For backward compatibility
    try:
        data = json.loads(req.data)
    except ValueError:
        data = json.loads(req.form['model'])
    except TypeError:
        data = json.loads(req.form['model'])

    def get(key):
        val = data.get(key, '')
        if isinstance(val, unicode):
            return val.strip()
        elif isinstance(val, basestring):
            return val.strip().decode('utf-8')
        else:
            return val

    if not all([get('name'), get('uri'), get('mimetype')]):
        raise Exception(
            "Not enough information provided. Please specify 'name', 'uri', and 'mimetype'."
        )

    name = get('name')
    if unique_name:
        with db.conn(settings['database']) as conn:
            names = assets_helper.get_names_of_assets(conn)
        if name in names:
            i = 1
            while True:
                new_name = '%s-%i' % (name, i)
                if new_name in names:
                    i += 1
                else:
                    name = new_name
                    break

    asset = {
        'name': name,
        'mimetype': get('mimetype'),
        'asset_id': get('asset_id'),
        'is_enabled': get('is_enabled'),
        'is_processing': get('is_processing'),
        'nocache': get('nocache'),
    }

    uri = get('uri').encode('utf-8')

    if uri.startswith('/'):
        if not path.isfile(uri):
            raise Exception("Invalid file path. Failed to add asset.")
    else:
        if not validate_url(uri):
            raise Exception("Invalid URL. Failed to add asset.")

    if not asset['asset_id']:
        asset['asset_id'] = uuid.uuid4().hex
        if uri.startswith('/'):
            rename(uri, path.join(settings['assetdir'], asset['asset_id']))
            uri = path.join(settings['assetdir'], asset['asset_id'])

    if 'youtube_asset' in asset['mimetype']:
        uri, asset['name'], asset['duration'] = download_video_from_youtube(
            uri, asset['asset_id'])
        asset['mimetype'] = 'video'
        asset['is_processing'] = 1

    asset['uri'] = uri

    if "video" in asset['mimetype']:
        if get('duration') == 'N/A' or int(get('duration')) == 0:
            asset['duration'] = int(get_video_duration(uri).total_seconds())
    else:
        # Crashes if it's not an int. We want that.
        asset['duration'] = int(get('duration'))

    asset['skip_asset_check'] = int(get('skip_asset_check')) if int(
        get('skip_asset_check')) else 0

    # parse date via python-dateutil and remove timezone info
    if get('start_date'):
        asset['start_date'] = date_parser.parse(
            get('start_date')).replace(tzinfo=None)
    else:
        asset['start_date'] = ""

    if get('end_date'):
        asset['end_date'] = date_parser.parse(
            get('end_date')).replace(tzinfo=None)
    else:
        asset['end_date'] = ""

    return asset
Ejemplo n.º 4
0
def prepare_asset(request):

    req = Request(request.environ)
    data = None

    data = json.loads(req.form['model']) if 'model' in req.form else req.form

    def get(key):
        val = data.get(key, '')
        if isinstance(val, unicode):
            return val.strip()
        elif isinstance(val, basestring):
            return val.strip().decode('utf-8')
        else:
            return val

    if all([
            get('name'),
            get('uri') or req.files.get('file_upload'),
            get('mimetype')
    ]):

        asset = {
            'name': get('name'),
            'mimetype': get('mimetype'),
            'asset_id': get('asset_id'),
            'is_enabled': get('is_enabled'),
            'nocache': get('nocache'),
        }

        uri = get('uri') or False

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

        try:
            file_upload = req.files.get('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_url(uri):
                raise Exception("Invalid URL. Failed to add asset.")
            else:
                asset['uri'] = uri
        else:
            asset['uri'] = uri

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

            file_upload.save(asset['uri'])

        if "video" in asset['mimetype']:
            video_duration = get_video_duration(asset['uri'])
            if video_duration:
                asset['duration'] = int(video_duration.total_seconds())
            else:
                asset['duration'] = 'N/A'
        else:
            # Crashes if it's not an int. We want that.
            asset['duration'] = int(get('duration'))

        # parse date via python-dateutil and remove timezone info
        if get('start_date'):
            asset['start_date'] = date_parser.parse(
                get('start_date')).replace(tzinfo=None)
        else:
            asset['start_date'] = ""

        if get('end_date'):
            asset['end_date'] = date_parser.parse(
                get('end_date')).replace(tzinfo=None)
        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'."
        )
Ejemplo n.º 5
0
def prepare_asset(request):

    req = Request(request.environ)
    data = None

    data = json.loads(req.form['model']) if 'model' in req.form else req.form

    def get(key):
        val = data.get(key, '')
        if isinstance(val, unicode):
            return val.strip()
        elif isinstance(val, basestring):
            return val.strip().decode('utf-8')
        else:
            return val

    if all([get('name'),
            get('uri') or req.files.get('file_upload'),
            get('mimetype')]):

        asset = {
            'name': get('name'),
            'mimetype': get('mimetype'),
            'asset_id': get('asset_id'),
            'is_enabled': get('is_enabled'),
            'nocache': get('nocache'),
        }

        uri = get('uri') or False

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

        try:
            file_upload = req.files.get('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_url(uri):
                raise Exception("Invalid URL. Failed to add asset.")
            else:
                asset['uri'] = uri
        else:
            asset['uri'] = uri

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

            file_upload.save(asset['uri'])

        if "video" in asset['mimetype']:
            video_duration = get_video_duration(asset['uri'])
            if video_duration:
                asset['duration'] = int(video_duration.total_seconds())
            else:
                asset['duration'] = 'N/A'
        else:
            # Crashes if it's not an int. We want that.
            asset['duration'] = int(get('duration'))

        # parse date via python-dateutil and remove timezone info
        if get('start_date'):
            asset['start_date'] = date_parser.parse(get('start_date')).replace(tzinfo=None)
        else:
            asset['start_date'] = ""

        if get('end_date'):
            asset['end_date'] = date_parser.parse(get('end_date')).replace(tzinfo=None)
        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'.")
Ejemplo n.º 6
0
def prepare_asset(request):
    req = Request(request.environ)
    data = None

    # For backward compatibility
    try:
        data = json.loads(req.data)
    except ValueError:
        data = json.loads(req.form['model'])
    except TypeError:
        data = json.loads(req.form['model'])

    def get(key):
        val = data.get(key, '')
        if isinstance(val, unicode):
            return val.strip()
        elif isinstance(val, basestring):
            return val.strip().decode('utf-8')
        else:
            return val

    if not all([get('name'), get('uri'), get('mimetype')]):
        raise Exception("Not enough information provided. Please specify 'name', 'uri', and 'mimetype'.")

    asset = {
        'name': get('name'),
        'mimetype': get('mimetype'),
        'asset_id': get('asset_id'),
        'is_enabled': get('is_enabled'),
        'is_processing': get('is_processing'),
        'nocache': get('nocache'),
    }

    uri = get('uri')

    if uri.startswith('/'):
        if not path.isfile(uri):
            raise Exception("Invalid file path. Failed to add asset.")
    else:
        if not validate_url(uri):
            raise Exception("Invalid URL. Failed to add asset.")

    if not asset['asset_id']:
        asset['asset_id'] = uuid.uuid4().hex
        if uri.startswith('/'):
            rename(uri, path.join(settings['assetdir'], asset['asset_id']))
            uri = path.join(settings['assetdir'], asset['asset_id'])

    if 'youtube_asset' in asset['mimetype']:
        uri, asset['name'], asset['duration'] = download_video_from_youtube(uri, asset['asset_id'])
        asset['mimetype'] = 'video'
        asset['is_processing'] = 1

    asset['uri'] = uri

    if "video" in asset['mimetype']:
        if get('duration') == 'N/A' or int(get('duration')) == 0:
            asset['duration'] = int(get_video_duration(uri).total_seconds())
    else:
        # Crashes if it's not an int. We want that.
        asset['duration'] = int(get('duration'))

    # parse date via python-dateutil and remove timezone info
    if get('start_date'):
        asset['start_date'] = date_parser.parse(get('start_date')).replace(tzinfo=None)
    else:
        asset['start_date'] = ""

    if get('end_date'):
        asset['end_date'] = date_parser.parse(get('end_date')).replace(tzinfo=None)
    else:
        asset['end_date'] = ""

    return asset
Ejemplo n.º 7
0
def prepare_asset(request):
    req = Request(request.environ)
    data = None

    data = json.loads(req.form['model'])

    def get(key):
        val = data.get(key, '')
        if isinstance(val, unicode):
            return val.strip()
        elif isinstance(val, basestring):
            return val.strip().decode('utf-8')
        else:
            return val

    if not all([get('name'), get('uri'), get('mimetype')]):
        raise Exception("Not enough information provided. Please specify 'name', 'uri', and 'mimetype'.")

    asset = {
        'name': get('name'),
        'mimetype': get('mimetype'),
        'asset_id': get('asset_id'),
        'is_enabled': get('is_enabled'),
        'nocache': get('nocache'),
    }

    uri = get('uri')

    if uri.startswith('/'):
        if not path.isfile(uri):
            raise Exception("Invalid file path. Failed to add asset.")
    else:
        if not validate_url(uri):
            raise Exception("Invalid URL. Failed to add asset.")

    if not asset['asset_id']:
        asset['asset_id'] = uuid.uuid4().hex
        if uri.startswith('/'):
            os.rename(uri, path.join(settings['assetdir'], asset['asset_id']))
            uri = path.join(settings['assetdir'], asset['asset_id'])

    asset['uri'] = uri

    if "video" in asset['mimetype']:
        video_duration = get_video_duration(asset['uri'])
        if video_duration:
            asset['duration'] = int(video_duration.total_seconds())
        else:
            asset['duration'] = 'N/A'
    else:
        # Crashes if it's not an int. We want that.
        asset['duration'] = int(get('duration'))

    # parse date via python-dateutil and remove timezone info
    if get('start_date'):
        asset['start_date'] = date_parser.parse(get('start_date')).replace(tzinfo=None)
    else:
        asset['start_date'] = ""

    if get('end_date'):
        asset['end_date'] = date_parser.parse(get('end_date')).replace(tzinfo=None)
    else:
        asset['end_date'] = ""

    return asset
Ejemplo n.º 8
0
    def run(self):
        directory = self.entry.directory
        files = [
            path.join(directory, f) for f in os.listdir(directory)
            if path.isfile(path.join(directory, f))
        ]

        num_files = len(files)

        if num_files == 0:
            load_browser(url='http://{0}:{1}/splash_page'.format(
                settings.get_listen_ip(), settings.get_listen_port()
            ) if settings['show_splash'] else 'file://' + BLACK_PAGE)
            while not self.__stop.isSet():
                sleep(self.loopTime)
        else:
            num = 0
            currentEntryDuration = 0
            mime = None
            file = None
            isNew = True
            while not self.__stop.isSet():
                logging.info("worker still waiting %d seconds for %s" %
                             (currentEntryDuration, file))
                if currentEntryDuration <= 0:
                    kill_player()

                    file = files[num]
                    mime = get_mimetype(file)
                    num = (num + 1) % num_files
                    if mime is not None:
                        if 'image' in mime:
                            currentEntryDuration = get_setting(
                                'image_duration', DEFAULT_DURATION, cast=int)
                            view_image(file, force=isNew)
                            isNew = False
                        elif 'text' in mime:
                            currentEntryDuration = get_setting(
                                'webpage_duration', DEFAULT_DURATION, cast=int)
                            with open(file, 'r') as urlfile:
                                try:
                                    line = urlfile.readlines()[0].replace(
                                        '\n', '')
                                    prefix = line[:5]
                                    if prefix == "live:":
                                        currentEntryDuration = 24 * 60 * 60  # large number of seconds
                                        VideoThread(line[5:]).start()
                                    else:
                                        view_url(line, force=isNew)
                                except Exception as e:
                                    currentEntryDuration = 0
                                    logging.error(
                                        'cannot show text file: %s, error: %s'
                                        % (file, e))
                            isNew = False
                        elif 'video' in mime:
                            currentEntryDuration = get_video_duration(file)
                            VideoThread(file).start()
                        else:
                            # cannot show this entry, so skip
                            logging.info(
                                'mimetype (%s) of file (%s) not supported.' %
                                (mime, file))
                            mime = None
                            currentEntryDuration = 0
                    else:
                        logging.info('cannot show suspect file: %s' % file)

                sleep(self.loopTime)
                currentEntryDuration -= self.loopTime