Beispiel #1
0
 def get_track_and_queued_dict(id):
     track = cache.get_or_create("track_dict:{0}".format(id), lambda: get_track_dict(id))
     if not track:
         return cache_none
     log.debug('cache gen - track_queue_dict for {0}'.format(id))
     def queue_item_list_to_dict(queue_items):
         return [queue_item.to_dict('full', exclude_fields='track_id,session_owner') for queue_item in queue_items]
     queue_item_for_track_dict = subdict(queue_item_for_track(request, DBSession, track['id']), {'played', 'pending'})
     track['queue'] = {k: queue_item_list_to_dict(v) for k, v in queue_item_for_track_dict.items()}
     return track
Beispiel #2
0
    def get_track_and_queued_dict(id):
        track = cache.get_or_create("track_dict:{0}".format(id),
                                    lambda: get_track_dict(id))
        if not track:
            return cache_none
        log.debug('cache gen - track_queue_dict for {0}'.format(id))

        def queue_item_list_to_dict(queue_items):
            return [
                queue_item.to_dict('full',
                                   exclude_fields='track_id,session_owner')
                for queue_item in queue_items
            ]

        queue_item_for_track_dict = subdict(
            queue_item_for_track(request, DBSession, track['id']),
            {'played', 'pending'})
        track['queue'] = {
            k: queue_item_list_to_dict(v)
            for k, v in queue_item_for_track_dict.items()
        }
        return track
Beispiel #3
0
    def get_track_and_queued_dict(id):
        track = cache_manager.get(
            f'''track_dict-{id}-{request.registry.settings['karakara.tracks.version']}'''
        ).get_or_create(lambda: get_track_dict(id))
        if not track:
            return cache_none
        log.debug(f'cache gen - track_queue_dict for {id}')

        def queue_item_list_to_dict(queue_items):
            return [
                queue_item.to_dict('full',
                                   exclude_fields='track_id,session_owner')
                for queue_item in queue_items
            ]

        queue_item_for_track_dict = subdict(
            request.queue.for_track(track['id']), {'played', 'pending'})
        track['queue'] = {
            k: queue_item_list_to_dict(v)
            for k, v in queue_item_for_track_dict.items()
        }
        return track
Beispiel #4
0
def queue_item_add(request):
    """
    Add items to end of queue
    """
    _ = request.translate
    _log_event = partial(request.log_event, method='add')

    # Validation
    for field in ['track_id', 'performer_name']:
        if not request.params.get(field):
            raise action_error(message='no {0}'.format(field), code=400)
    track_id = request.params.get('track_id')
    try:
        track = DBSession.query(Track).get(track_id)
        assert track
    except AssertionError:
        raise action_error(message=_(
            'view.queue_item.add.error.track_id ${track_id}',
            mapping={'track_id': track_id}),
                           code=400)

    # If not admin, check additional restrictions
    if not is_admin(request):
        performer_name = request.params.get('performer_name').strip(
        )  # TODO: It would be good to ensure this value is writen to the db. However we cant modify the request.param dict directly. See creation of queueitem below

        # Valid performer name
        valid_performer_names = request.queue.settings.get(
            'karakara.queue.add.valid_performer_names')
        if valid_performer_names and performer_name.lower() not in map(
                lambda name: name.lower(), valid_performer_names):
            message = _(
                'view.queue_item.add.invalid_performer_name ${performer_name}',
                mapping=dict(performer_name=performer_name))
            raise action_error(message, code=400)

        # TODO: Unify and tidy this shit .. Duplicate messages are very similat and can offload they db access to the model_logic.

        # Duplicate performer retractions
        queue_item_performed_tracks = request.queue.for_performer(
            performer_name)
        if queue_item_performed_tracks[
                'performer_status'] == QUEUE_DUPLICATE.THRESHOLD:
            try:
                latest_track_title = get_track(
                    queue_item_performed_tracks['queue_items']
                    [0].track_id).title
            except Exception:
                latest_track_title = ''
            message = _(
                'view.queue_item.add.dupicate_performer_limit ${performer_name} ${estimated_next_add_time} ${track_count} ${latest_queue_item_title}',
                mapping=dict(performer_name=performer_name,
                             latest_queue_item_title=latest_track_title,
                             **subdict(queue_item_performed_tracks, {
                                 'estimated_next_add_time',
                                 'track_count',
                             })))
            _log_event(status='reject',
                       reason='dupicate.performer',
                       message=message)
            raise action_error(message=message, code=400)

        # Duplicate Addition Restrictions
        queue_item_tracks_queued = request.queue.for_track(track.id)
        if queue_item_tracks_queued[
                'track_status'] == QUEUE_DUPLICATE.THRESHOLD:
            try:
                latest_track_title = get_track(
                    queue_item_tracks_queued['queue_items'][0].track_id).title
            except Exception:
                latest_track_title = ''
            message = _(
                'view.queue_item.add.dupicate_track_limit ${track_id} ${estimated_next_add_time} ${track_count} ${latest_queue_item_title}',
                mapping=dict(track_id=track.id,
                             latest_queue_item_title=latest_track_title,
                             **subdict(queue_item_tracks_queued, {
                                 'estimated_next_add_time',
                                 'track_count',
                             })))
            _log_event(status='reject',
                       reason='duplicate.track',
                       message=message)
            raise action_error(message=message, code=400)

        # Event end time
        event_end = request.queue.settings.get('karakara.event.end')
        if event_end and now() + request.queue.duration > event_end:
            log.debug('event end restricted')
            _log_event(status='reject', reason='event_end')
            raise action_error(message=_(
                'view.queue_item.add.event_end ${event_end}',
                mapping={'event_end': event_end}),
                               code=400)

        # Queue time limit
        queue_limit = request.queue.settings.get('karakara.queue.add.limit')
        if queue_limit and request.queue.duration > queue_limit:
            # If no device priority token - issue token and abort
            # else consume the token and proceed with addition
            priority_token_manager = PriorityTokenManager(request)
            if not priority_token_manager.consume():
                # Issue a priority token
                priority_token = priority_token_manager.issue()
                if isinstance(priority_token, PriorityToken):
                    _log_event(status='reject', reason='token.issued')
                    raise action_error(
                        message=_('view.queue_item.add.priority_token_issued'),
                        code=400)
                if priority_token == TOKEN_ISSUE_ERROR.EVENT_END:
                    _log_event(status='reject', reason='event_end')
                    raise action_error(message=_(
                        'view.queue_item.add.event_end ${event_end}',
                        mapping={'event_end': event_end}),
                                       code=400)
                if priority_token == TOKEN_ISSUE_ERROR.TOKEN_ISSUED:
                    _log_event(status='reject', reason='token.already_issued')
                    raise action_error(message=_(
                        'view.queue_item.add.priority_token_already_issued'),
                                       code=400)
                _log_event(status='reject', reason='token.limit')
                raise action_error(
                    message=_('view.queue_item.add.token_limit'), code=400)

    queue_item = QueueItem()
    for key, value in request.params.items(
    ):  # TODO: strip() the performer_name?
        if hasattr(queue_item, key):
            setattr(queue_item, key, value)
    queue_item.queue_id = request.context.queue_id

    # Set session owner - if admin allow manual setting of session_owner via params
    if is_admin(request) and queue_item.session_owner:
        pass
    else:
        queue_item.session_owner = request.session['id']

    DBSession.add(queue_item)
    _log_event(status='ok',
               queue_id=queue_item.queue_id,
               track_id=queue_item.track_id,
               performer_name=queue_item.performer_name)
    #log.info('add - %s to queue by %s' % (queue_item.track_id, queue_item.performer_name))

    message_data = {
        'track_id': queue_item.track_id,
        'performer_name': queue_item.performer_name
    }
    invalidate_cache(request, track_id)

    return action_ok(
        message=_('view.queue_item.add.ok ${track_id} ${performer_name}',
                  mapping=message_data),
        data={'queue_item.id': ''},
        code=201,
    )  # TODO: should return 201 and have id of newly created object. data={'track':{'id':}}
Beispiel #5
0
def queue_add(request):
    """
    Add items to end of queue
    """
    _ = request.translate
    _log_event = partial(log_event, request, method='add')

    # Validation
    for field in ['track_id', 'performer_name']:
        if not request.params.get(field):
            raise action_error(message='no {0}'.format(field), code=400)
    track_id = request.params.get('track_id')
    try:
        track = DBSession.query(Track).get(track_id)
        assert track
    except AssertionError:
        raise action_error(message=_('view.queue.add.error.track_id ${track_id}', mapping={'track_id': track_id}), code=400)

    # If not admin, check additional restrictions
    if not is_admin(request):

        performer_name = request.params.get('performer_name').strip()  # TODO: It would be good to ensure this value is writen to the db. However we cant modify the request.param dict directly. See creation of queueitem below

        # Valid performer name
        valid_performer_names = request.registry.settings.get('karakara.queue.add.valid_performer_names')
        if valid_performer_names and performer_name.lower() not in map(lambda name: name.lower(), valid_performer_names):
            message = _('view.queue.add.invalid_performer_name ${performer_name}', mapping=dict(
                performer_name=performer_name
            ))
            raise action_error(message, code=400)

        # Duplucate performer resrictions
        queue_item_performed_tracks = _logic.queue_item_for_performer(request, DBSession, request.params.get('performer_name'))
        if queue_item_performed_tracks['performer_status'] == _logic.QUEUE_DUPLICATE.THRESHOLD:
            try:
                latest_track_title = get_track(queue_item_performed_tracks['queue_items'][0].track_id).title
            except Exception:
                latest_track_title = ''
            message = _('view.queue.add.dupicate_performer_limit ${performer_name} ${estimated_next_add_time} ${track_count} ${latest_queue_item_title}', mapping=dict(
                performer_name=performer_name,
                latest_queue_item_title=latest_track_title,
                **subdict(queue_item_performed_tracks, {
                    'estimated_next_add_time',
                    'track_count',
                })
            ))
            _log_event(status='reject', reason='dupicate.performer', message=message)
            raise action_error(message=message, code=400)

        # Duplicate Addition Restrictions
        queue_item_tracks_queued = _logic.queue_item_for_track(request, DBSession, track.id)
        if queue_item_tracks_queued['track_status'] == _logic.QUEUE_DUPLICATE.THRESHOLD:
            message = _('view.queue.add.dupicate_track_limit ${track_id} ${estimated_next_add_time} ${track_count}', mapping=dict(
                track_id=track.id,
                **subdict(queue_item_performed_tracks, {
                    'estimated_next_add_time',
                    'track_count',
                })
            ))
            _log_event(status='reject', reason='duplicate.track', message=message)
            raise action_error(message=message, code=400)

        # Max queue length restrictions
        queue_duration = _logic.get_queue_duration(request)

        # Event end time
        event_end = request.registry.settings.get('karakara.event.end')
        if event_end and now()+queue_duration > event_end:
            log.debug('event end restricted')
            _log_event(status='reject', reason='event_end')
            raise action_error(message=_('view.queue.add.event_end ${event_end}', mapping={'event_end': event_end}), code=400)

        # Queue time limit
        queue_limit = request.registry.settings.get('karakara.queue.add.limit')
        if queue_limit and queue_duration > queue_limit:
            # If no device priority token - issue token and abort
            # else consume the token and proceed with addition
            if not _logic.consume_priority_token(request, DBSession):
                # Issue a priority token
                priority_token = _logic.issue_priority_token(request, DBSession)
                if isinstance(priority_token, PriorityToken):
                    _log_event(status='reject', reason='token.issued')
                    raise action_error(message=_('view.queue.add.priority_token_issued'), code=400)
                if priority_token == _logic.TOKEN_ISSUE_ERROR.EVENT_END:
                    _log_event(status='reject', reason='event_end')
                    raise action_error(message=_('view.queue.add.event_end ${event_end}', mapping={'event_end': event_end}), code=400)
                if priority_token == _logic.TOKEN_ISSUE_ERROR.TOKEN_ISSUED:
                    _log_event(status='reject', reason='token.already_issued')
                    raise action_error(message=_('view.queue.add.priority_token_already_issued'), code=400)
                _log_event(status='reject', reason='token.limit')
                raise action_error(message=_('view.queue.add.token_limit'), code=400)

    queue_item = QueueItem()
    for key, value in request.params.items():
        if hasattr(queue_item, key):
            setattr(queue_item, key, value)

    # Set session owner - if admin allow manual setting of session_owner via params
    if is_admin(request) and queue_item.session_owner:
        pass
    else:
        queue_item.session_owner = request.session['id']

    DBSession.add(queue_item)
    _log_event(status='ok', track_id=queue_item.track_id, performer_name=queue_item.performer_name)
    #log.info('add - %s to queue by %s' % (queue_item.track_id, queue_item.performer_name))

    invalidate_queue(request)  # Invalidate Cache
    invalidate_track(track_id)

    return action_ok(message='track queued', data={'queue_item.id': ''}, code=201)  # TODO: should return 201 and have id of newly created object. data={'track':{'id':}}