briar-cli.py 2.18 KB
Newer Older
Torsten Grote's avatar
Torsten Grote committed
1 2 3 4
#!/usr/bin/env python3

import asyncio
import json
5
import sys
Torsten Grote's avatar
Torsten Grote committed
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
import threading
from datetime import datetime

import requests
import websockets

HOST = 'localhost:7000'
CONTACT_ID = '1'

URL = 'http://%s/v1/messages/%s' % (HOST, CONTACT_ID)
URL_WS = 'ws://%s/v1/ws' % HOST

PROMPT = '$> '


def main():
22 23 24
    if len(sys.argv) != 2:
        print("Please provide auth token: %s <token>" % sys.argv[0])
        sys.exit(1)
Torsten Grote's avatar
Torsten Grote committed
25

26 27 28
    auth_token = sys.argv[1]
    load_history(auth_token)
    threading.Thread(target=get_message_stdin, args=[auth_token]).start()
Torsten Grote's avatar
Torsten Grote committed
29 30

    loop = asyncio.get_event_loop()
31
    loop.create_task(connect_websocket(auth_token))
Torsten Grote's avatar
Torsten Grote committed
32 33 34 35
    loop.run_forever()
    loop.close()


36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
async def connect_websocket(token):
    async with websockets.connect(URL_WS) as ws:
        await ws.send(token)
        await get_message_websocket(ws)


async def get_message_websocket(ws):
    while not ws.closed and not asyncio.get_event_loop().is_closed():
        message = await ws.recv()
        m = json.loads(message)
        if m['name'] == 'ConversationMessageReceivedEvent':
            print()  # line-break
            print_message(m['data'])
            print(PROMPT, end='', flush=True)
    if not asyncio.get_event_loop().is_closed():
        asyncio.get_event_loop().create_task(get_message_websocket(ws))
Torsten Grote's avatar
Torsten Grote committed
52 53


54
def get_message_stdin(token):
Torsten Grote's avatar
Torsten Grote committed
55 56 57
    while True:
        body = input(PROMPT)
        if len(body) > 0:
58 59 60 61 62
            res = requests.post(URL, headers=get_auth_header(token), json={'text': body})
            if res.status_code == 200:
                print_message(res.json())
            else:
                print("Error: %d" % res.status_code)
Torsten Grote's avatar
Torsten Grote committed
63 64 65 66 67


def print_message(message):
    prefix = '>' if message['local'] else '<'
    time = get_timestamp(datetime.fromtimestamp(message['timestamp'] / 1000))
68 69
    if 'text' in message:
        print(f"{time} {prefix} {message['text']}")
Torsten Grote's avatar
Torsten Grote committed
70 71 72 73 74 75


def get_timestamp(date):
    return date.strftime('%Y-%m-%dT%H:%M:%S')


76 77
def load_history(token):
    history = requests.get(URL, headers=get_auth_header(token)).json()
Torsten Grote's avatar
Torsten Grote committed
78 79 80 81
    for message in history:
        print_message(message)


82 83 84 85
def get_auth_header(token):
    return {'Authorization': 'Bearer %s' % token}


Torsten Grote's avatar
Torsten Grote committed
86 87
if __name__ == "__main__":
    main()