Beispiel #1
0
def stream_or_delete_media(media_id):
    """
    This route can be used to stream active media points or unregister
    a mounted media stream
    """

    # Remove the extension
    media_id = '.'.join(media_id.split('.')[:-1])

    try:
        if request.method == 'GET':
            if media_id is None:
                return jsonify([dict(media) for media in media_map.values()])
            else:
                return stream_media(media_id, request)
        else:
            media_info = unregister_media(media_id)
            return jsonify(media_info)
    except (AttributeError, FileNotFoundError) as e:
        abort(404, str(e))
    except KeyError as e:
        abort(400, str(e))
    except Exception as e:
        logger().exception(e)
        abort(500, str(e))
Beispiel #2
0
def add_media():
    """
    This route can be used by the `media` plugin to add streaming content over HTTP
    """

    args = {}
    try:
        args = json.loads(request.data.decode('utf-8'))
    except:
        abort(400, 'Invalid JSON request')

    source = args.get('source')
    if not source:
        abort(400, 'The request does not contain any source')

    subtitles = args.get('subtitles')
    try:
        media_hndl = register_media(source, subtitles)
        ret = dict(media_hndl)
        if media_hndl.subtitles:
            ret['subtitles_url'] = get_remote_base_url() + \
                '/media/subtitles/' + media_hndl.media_id + '.vtt'
        return jsonify(ret)
    except FileNotFoundError as e:
        abort(404, str(e))
    except AttributeError as e:
        abort(400, str(e))
    except Exception as e:
        logger().exception(e)
        abort(500, str(e))
Beispiel #3
0
def register_media(source, subtitles=None):
    global media_map, media_map_lock

    media_id = get_media_id(source)
    media_url = get_media_url(media_id)

    with media_map_lock:
        if media_id in media_map:
            return media_map[media_id]

    subfile = None
    if subtitles:
        req = {
            'type': 'request',
            'action': 'media.subtitles.download',
            'args': {
                'link': subtitles,
                'convert_to_vtt': True,
            }
        }

        try:
            subfile = (send_message(req).output or {}).get('filename')
        except Exception as e:
            logger().warning('Unable to load subtitle {}: {}'
                             .format(subtitles, str(e)))

    with media_map_lock:
        media_hndl = MediaHandler.build(source, url=media_url, subtitles=subfile)
        media_map[media_id] = media_hndl
        media_hndl.media_id = media_id

    logger().info('Streaming "{}" on {}'.format(source, media_url))
    return media_hndl
Beispiel #4
0
def _hook(hook_name):
    """ Endpoint for custom webhooks """

    event_args = {
        'hook': hook_name,
        'method': request.method,
        'args': dict(request.args or {}),
        'data': request.data.decode(),
    }

    if event_args['data']:
        # noinspection PyBroadException
        try:
            event_args['data'] = json.loads(event_args['data'])
        except:
            pass

    event = WebhookEvent(**event_args)

    try:
        send_message(event)
        return Response(json.dumps({
            'status': 'ok',
            **event_args
        }),
                        mimetype='application/json')
    except Exception as e:
        logger().exception(e)
        logger().error('Error while dispatching webhook event {}: {}'.format(
            event, str(e)))
        abort(500, str(e))
Beispiel #5
0
def unregister_media(source):
    global media_map, media_map_lock

    if source is None:
        raise KeyError('No media_id specified')

    media_id = get_media_id(source)
    media_info = {}

    with media_map_lock:
        if media_id not in media_map:
            raise FileNotFoundError('{} is not a registered media_id'.
                                    format(source))
        media_info = media_map.pop(media_id)

    logger().info('Unregistered {} from {}'.format(source, media_info.get('url')))
    return media_info
Beispiel #6
0
def execute():
    """ Endpoint to execute commands """
    try:
        msg = json.loads(request.data.decode('utf-8'))
    except Exception as e:
        logger().error('Unable to parse JSON from request {}: {}'.format(request.data, str(e)))
        return abort(400, str(e))

    logger().info('Received message on the HTTP backend: {}'.format(msg))

    try:
        response = send_message(msg)
        return Response(str(response or {}), mimetype='application/json')
    except Exception as e:
        logger().error('Error while running HTTP action: {}. Request: {}'.format(str(e), msg))
        return abort(500, str(e))