aboutsummaryrefslogtreecommitdiff
path: root/scripts/chat.py
blob: e19fb6b76f20439cf04f575266a7f882169b4e13 (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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
#!/usr/bin/env python3
"""scripts/chat.py — read and reply to newOS4 chat threads as Hermes.

  chat.py list [--json]        # threads, counts, who spoke last
  chat.py show <thread>        # full transcript
  chat.py reply <thread> "…"   # append a Hermes reply (atomic, locked)

Store: data/chat/<thread>.json — contract: _docs/chat-contract.md
Thread id is 16 lowercase hex = sha256(browser token)[0:16].
"""
import json, sys, os, re, datetime, secrets, fcntl

CHAT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data', 'chat')
THREAD_RE = re.compile(r'^[a-f0-9]{16}$')


def utc_iso():
    # UTC, matching the PHP side. A local offset here breaks every comparison downstream.
    return datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%dT%H:%M:%S+00:00')


def now_ms():
    return int(datetime.datetime.now(datetime.timezone.utc).timestamp() * 1000)


def load(path):
    try:
        with open(path) as f:
            return json.load(f)
    except Exception:
        return []


def threads():
    out = []
    if not os.path.isdir(CHAT_DIR):
        return out
    for name in sorted(os.listdir(CHAT_DIR)):
        if not name.endswith('.json') or name.startswith('.'):
            continue
        msgs = load(os.path.join(CHAT_DIR, name))
        if not msgs:
            continue
        last = msgs[-1]
        out.append({
            'thread': name[:-5],
            'count': len(msgs),
            'last_ts': last.get('ts', ''),
            'last_author': last.get('author', ''),
            'awaiting': last.get('author') != 'hermes',
            'preview': (last.get('text') or '')[:100].replace('\n', ' '),
        })
    return out


def reply(thread, text):
    # A typo'd id must fail, not silently create a thread nobody reads.
    if not THREAD_RE.match(thread):
        raise SystemExit('invalid thread id (expected 16 lowercase hex chars)')
    path = os.path.join(CHAT_DIR, thread + '.json')
    if not os.path.exists(path):
        raise SystemExit('no such thread: ' + thread)
    lockpath = os.path.join(CHAT_DIR, '.lock-' + thread)
    with open(lockpath, 'a+') as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        try:
            msgs = load(path)
            msg = {
                'id': 'MSG-' + datetime.datetime.now().strftime('%Y%m%d-%H%M%S') + '-' + secrets.token_hex(3),
                'ts': utc_iso(),
                'epoch': now_ms(),
                'author': 'hermes',
                'text': text,
            }
            msgs.append(msg)
            msgs = msgs[-200:]
            tmp = path + '.tmp-' + secrets.token_hex(4)
            with open(tmp, 'w') as fh:
                json.dump(msgs, fh, ensure_ascii=False)
            os.chmod(tmp, 0o664)
        finally:
            fcntl.flock(lock, fcntl.LOCK_UN)
    os.replace(tmp, path)          # atomic: a poll never sees a half-written file
    return msg


def main():
    if len(sys.argv) < 2:
        print(__doc__)
        return 1
    cmd = sys.argv[1]

    if cmd == 'list':
        rows = threads()
        if '--json' in sys.argv:
            print(json.dumps(rows, indent=2))
            return 0
        if not rows:
            print('(no threads)')
            return 0
        for t in rows:
            flag = 'AWAITING' if t['awaiting'] else 'replied '
            print(f"{t['thread']}  {flag}  {t['count']:>3} msg  {t['last_ts']}  {t['preview']}")
        return 0

    if cmd == 'show' and len(sys.argv) >= 3:
        msgs = load(os.path.join(CHAT_DIR, sys.argv[2] + '.json'))
        if not msgs:
            print('(empty or unknown thread)')
            return 1
        for m in msgs:
            print(f"[{m.get('ts','')}] {m.get('author','')}: {m.get('text','')}")
        return 0

    if cmd == 'reply' and len(sys.argv) >= 4:
        msg = reply(sys.argv[2], ' '.join(sys.argv[3:]))
        print('replied', msg['id'])
        return 0

    print(__doc__)
    return 1


if __name__ == '__main__':
    sys.exit(main())