예제 #1
0
파일: mopidy.py 프로젝트: k3an3/home
def mopidy_ws(data, **kwargs):
    mopidy = get_device(data.pop('device')).dev
    auth = kwargs.pop('auth', False)
    action = data.pop('action')
    if not auth and action not in UNAUTH_COMMANDS:
        print(
            "Disconnected client from Mopidy endpoint, not authorized/invalid command"
        )
        disconnect()
    if action == 'search':
        results = mopidy.search(**data)
        try:
            results = results['result'][0]['tracks']
            emit('search results', json.dumps(results))
        except Exception as e:
            pass
    elif action == 'add_track':
        r = mopidy.add_track(**data)
    elif action == 'get_current_track':
        track = mopidy.get_current_track()
        emit(
            'track',
            json.dumps({
                'title':
                track['name'],
                'artists':
                ', '.join(artist['name'] for artist in track['artists']),
                'album':
                track['album']['name'],
                'art':
                track['art']
            }))
예제 #2
0
        def wrapped(*args, **kwargs):
            if has_permission and check_device:
                raise AuthPluginMisuseError(
                    "Cannot provide both `has_permission` and `check_device` to decorator."
                )
            # noinspection PyBroadException
            try:
                if request.is_json:
                    data = request.get_json()
                    kwargs['data'] = data
                    device = data.get('device')
                else:
                    device = request.values.get('device')

                if request.headers.get('X-Gogs-Signature'):
                    client = APIClient.get(name='gogs-update')
                    secret = bytes(client.token.encode())
                    mac = hmac.new(secret,
                                   msg=request.get_data(),
                                   digestmod=hashlib.sha256)
                    if not hmac.compare_digest(
                            mac.hexdigest(),
                            request.headers['X-Gogs-Signature']):
                        abort(403)
                elif request.headers.get('X-Auth-Token'):
                    client = APIClient.get(
                        token=request.headers['X-Auth-Token'])
                elif request.is_json:
                    client = APIClient.get(token=data['key'])
                else:
                    client = APIClient.get(token=request.values.get('key'))

                if client:
                    kwargs['client'] = client
                    if has_permission and not client.has_permission(
                            has_permission):
                        abort(403)
                    elif check_device:
                        device = get_device(device.replace('-', ' '))
                        if client.has_permission(device.group):
                            kwargs['device'] = device
                            return f(*args, **kwargs)
                    else:
                        return f(*args, **kwargs)
                else:
                    # Should not happen
                    from home.web.web import app
                    app.logger.warning("API auth hit else block")
                    abort(403)
            except DoesNotExist:
                if DEBUG:
                    kwargs['client'] = APIClient.get()
                    return f(*args, **kwargs)
                else:
                    from home.web.web import app
                    app.logger.warning("No API client exists for the request.")
                    abort(403)
            app.logger.warning("API auth fell through")
예제 #3
0
def motd(client):
    data = dict(request.values)
    try:
        speech = get_device(data.pop('device'))
    except StopIteration:
        abort(404)
    if not speech.driver.klass == Speech:
        raise NotImplementedError
    if not client.has_permission(speech.group):
        abort(403)
    speech = speech.dev
    data.pop('key')
    weather = speech.weather.get(**data)
    forecast = speech.weather.get(**data, mode='forecast')
    return format_weather(weather, forecast, speech)
예제 #4
0
파일: motion.py 프로젝트: k3an3/home
def stream(camera):
    """
    Requires nginx to be configured properly
    :param camera: 
    :return: 
    """
    try:
        camera = get_device(camera)
    except StopIteration:
        abort(404)
    if not camera.driver.klass == MotionController:
        raise NotImplementedError
    if current_user.has_permission(camera):
        response = make_response()
        response.headers['X-Accel-Redirect'] = '/stream/' + camera.name
        return response
예제 #5
0
def request_change_color(message):
    """
    Change the bulb's color.
    """
    device = get_device(message['device'].replace('-', ' '))
    if not current_user.has_permission(device):
        disconnect()
        return
    emit('push color', {
        "device": message['device'],
        "color": message['color']
    },
         broadcast=True)
    device.dev.change_color(*utils.RGBfromhex(message['color']),
                            utils.to_int(message.get('white', 0)),
                            message.get('bright', 100), '41')
예제 #6
0
 def wrapped(*args, **kwargs):
     if has_permission and check_device:
         raise AuthPluginMisuseError(
             "Cannot provide both `has_permission` and `check_device` to decorator."
         )
     if current_user.is_authenticated:
         if has_permission and current_user.has_permission(
                 group=has_permission):
             return f(*args, **kwargs)
         elif check_device:
             device = get_device(args[0]['device'].replace('-', ' '))
             if current_user.has_permission(device):
                 kwargs['device'] = device
                 return f(*args, **kwargs)
         elif not has_permission and not check_device:
             return f(*args, **kwargs)
     disconnect()
예제 #7
0
def handle_task(post: dict, client: APIClient) -> bool:
    try:
        device = get_device(post.pop('device').strip())
        method = method_from_name(device.dev, post.pop('method'))
    except StopIteration:
        return False
    from home.web.web import app
    if not client.has_permission(device.group):
        app.logger.warning(
            "({}) Insufficient API permissions to execute '{}' on '{}' with config {}"
            .format(client.name, method.__name__, device.name, post))
        return False
    app.logger.info("({}) Execute '{}' on '{}' with config {}".format(
        client.name, method.__name__, device.name, post))
    if device.driver.noserialize or type(device) is MultiDevice:
        method(**post)
    else:
        device.last_task = run(method, **post)
    return True
예제 #8
0
파일: speech.py 프로젝트: k3an3/home
 def __init__(self, name, weather):
     self.name = name
     self.weather = get_device(weather).dev
예제 #9
0
def next_bus():
    nb = get_device('nextbus').dev
    if (datetime.datetime.now() - nb.data_time).total_seconds() / 60 >= 5:
        nb.get_predictions()
    emit('next bus data', nb.data)
예제 #10
0
def get_presence_api():
    dd = get_device('router').dev
    users = dd.clients_to_users()
    return json.dumps(users)
예제 #11
0
def get_presence():
    dd = get_device('router').dev
    users = dd.clients_to_users()
    emit('presence data', users)
예제 #12
0
 def wrapped(*args, **kwargs):
     t = get_device('android')
     t.dev.sid = request.sid
     if DEBUG:
         return f(*args, **kwargs)
     abort(403)