summaryrefslogtreecommitdiff
path: root/test/test_record_upload.py
blob: ae9f8cc2762c41a84265ea76ad1ffad857e9ae7d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#!/usr/bin/env python3
import include_homekit
import logging
import time

from homekit.api import WebApiClient, RequestParams
from homekit.config import config
from homekit.media import SoundRecordClient
from homekit.util import Addr

logger = logging.getLogger(__name__)


# record callbacks
# ----------------

def record_error(info: dict, userdata: dict):
    node = userdata['node']
    # TODO


def record_finished(info: dict, fn: str, userdata: dict):
    logger.info('record finished: ' + str(info))

    node = userdata['node']
    api.upload_recording(fn, node, info['id'], int(info['start_time']), int(info['stop_time']))


# api client callbacks
# --------------------

def api_error_handler(exc, name, req: RequestParams):
    if name == 'upload_recording':
        logger.error('failed to upload recording, exception below')
        logger.exception(exc)

    else:
        logger.error(f'api call ({name}, params={req.params}) failed, exception below')
        logger.exception(exc)


def api_success_handler(response, name, req: RequestParams):
    if name == 'upload_recording':
        node = req.params['node']
        rid = req.params['record_id']

        logger.debug(f'successfully uploaded recording (node={node}, record_id={rid}), api response:' + str(response))

        # deleting temp file
        try:
            os.unlink(req.files['file'])
        except OSError as exc:
            logger.error(f'error while deleting temp file:')
            logger.exception(exc)

        record.forget(node, rid)


if __name__ == '__main__':
    config.load_app('test_record_upload')

    nodes = {}
    for name, addr in config['nodes'].items():
        nodes[name] = Addr(addr)
    record = SoundRecordClient(nodes,
                               error_handler=record_error,
                               finished_handler=record_finished,
                               download_on_finish=True)

    api = WebApiClient()
    api.enable_async(error_handler=api_error_handler,
                     success_handler=api_success_handler)

    record_id = record.record('localhost', 3, {'node': 'localhost'})
    print(f'record_id: {record_id}')

    while True:
        try:
            time.sleep(0.1)
        except (KeyboardInterrupt, SystemExit):
            break