aboutsummaryrefslogtreecommitdiffstats
path: root/alfred/twt.py
blob: 97bf5df5a3a7b62b00790e48af3249821dcc55e7 (plain) (blame)
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
"""
Sopel plugin: twtxt feed

Commands (owner only):
  !twt                       - show usage
  !twt last [n]              - show last n twts, most recent first (default 5)
  !twt count                 - total number of twts
  !twt delete                - delete the most recent twt (asks yes/no)
  !twt yes / !twt no         - confirm or cancel a pending delete
  !twt <message>             - post a twt

Config ([twt] section in sopel config):
  twtxt_path  - path to twtxt.txt (default /var/www/twt.gumx.cc/twtxt.txt)
  timezone    - timezone name for timestamps (default UTC)
  nick        - nick value written in file header (default gumx)
  url         - url value written in file header
"""

import glob
import os
from datetime import datetime, timezone
from pathlib import Path
from zoneinfo import ZoneInfo

from sopel import plugin
from sopel.config.types import FilenameAttribute, StaticSection, ValidatedAttribute

import os as _os, sys as _sys
_alfred_dir = _os.path.dirname(_os.path.abspath(__file__))
if _alfred_dir not in _sys.path:
    _sys.path.insert(0, _alfred_dir)
import helpstrings as h

_pending_delete = {}

_SUBCOMMANDS = {"last", "count", "delete", "yes", "no", "add", "users", "rm"}

WKFO_TOKENS = '/etc/nginx/twt-tokens.map'
WKFO_TWR    = '/var/www/wk.fo/twt'


def _load_twt_tokens():
    tokens = {}
    try:
        with open(WKFO_TOKENS) as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('#') or not line.startswith('"'):
                    continue
                end = line.index('"', 1)
                tok = line[1:end]
                rest = line[end+1:].strip().rstrip(';').split('#')[0].strip()
                if rest:
                    tokens[tok] = rest
    except FileNotFoundError:
        pass
    return tokens


def _save_twt_tokens(tokens):
    with open(WKFO_TOKENS, 'w') as f:
        for tok, user in tokens.items():
            f.write(f'"{tok}" {user};\n')


def _esc(s):
    return s.replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;').replace('"', '&quot;')


def _load_twtxt(path):
    twts = []
    try:
        with open(path) as f:
            for line in f:
                line = line.strip()
                if not line or line.startswith('#'):
                    continue
                parts = line.split('\t', 1)
                if len(parts) == 2:
                    try:
                        dt = datetime.fromisoformat(parts[0].replace('Z', '+00:00'))
                    except ValueError:
                        dt = datetime.min.replace(tzinfo=timezone.utc)
                    twts.append((dt, parts[1]))
    except FileNotFoundError:
        pass
    return twts


_WKFO_HEAD = """\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>{title}</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<style>
@font-face {{ font-family: "Kawkab Mono"; src: url(/fonts/KawkabMono-Regular.woff2); font-weight: normal; }}
@font-face {{ font-family: "Kawkab Mono"; src: url(/fonts/KawkabMono-Bold.woff2); font-weight: bold; }}
* {{ unicode-bidi: plaintext; box-sizing: border-box; }}
html {{ color: black; background-color: white; }}
body {{ font-family: "Kawkab Mono", monospace; font-size: 16px; line-height: 1.4; margin: 0; padding: 4rem 0; min-height: 100%; overflow-wrap: break-word; }}
main, header, footer {{ max-width: 800px; margin-inline: auto; padding: 0 2rem; }}
h1, footer {{ text-align: center; }}
p, h2, h3 {{ margin: 1em 0 0 0; }}
header {{ margin-bottom: 1em; }}
footer {{ margin-top: 3em; }}
hr {{ border: none; border-top: thin solid; margin: 1.25rem 0; }}
form {{ margin: 1em 0; }}
textarea, input[type=password] {{ font-family: inherit; font-size: inherit; width: 100%; border: thin solid; padding: 0.4em; box-sizing: border-box; }}
textarea {{ height: 5em; resize: vertical; }}
input[type=submit] {{ font-family: inherit; font-size: inherit; border: thin solid; padding: 0.3em 1em; cursor: pointer; background: transparent; margin-top: 0.5em; }}
ul {{ padding: 0 0 0 1.5em; margin: 1em 0; }}
li {{ margin: 0.5em 0; }}
.msg {{ min-height: 1.4em; }}
@media (max-width: 600px) {{ body {{ font-size: 0.9em; }} h1 {{ font-size: 1.8em; }} }}
@media (prefers-color-scheme: dark) {{ html {{ filter: invert(1); }} img {{ filter: invert(1); }} }}
</style>
</head>
<body>"""

_WKFO_FOOTER = """\
<footer>
<hr>
<a href="https://twt.gumx.cc">twt</a> /
<a href="https://feed.gumx.cc">feed</a> /
<a href="https://git.gumx.cc">git</a> /
<a href="https://mail.gumx.cc">mail</a> /
<a href="https://list.gumx.cc">list</a> /
<a href="https://irc.gumx.cc">irc</a> /
<a href="https://files.gumx.cc">files</a> /
<a href="https://vpn.gumx.cc">vpn</a> /
<a href="https://pgp.gumx.cc">pgp</a> /
<a href="https://demo.gumx.cc">demo</a> /
<a href="https://wk.fo">wk.fo</a>
<br>
<a href="https://git.gumx.cc/portal">source</a> /
<a href="https://gumx.cc/license">license</a>
</footer>
</body>
</html>"""


def _build_user_page(username):
    twts  = _load_twtxt(f'{WKFO_TWR}/~{username}/twtxt.txt')
    items = '\n'.join(
        f'<li>[{dt.strftime("%Y-%m-%d")}] {_esc(text)}</li>'
        for dt, text in reversed(sorted(twts))
    ) or '<li>(no twts yet)</li>'

    return (
        _WKFO_HEAD.format(title=f'wk.fo / twt / ~{_esc(username)}') + '\n'
        '<header>\n'
        f'<nav><strong><a href="https://wk.fo">wk.fo</a></strong> / '
        f'<a href="/twt/">twt</a> / ~{_esc(username)}</nav>\n'
        '</header>\n'
        '<main>\n'
        f'<h1>~{_esc(username)}</h1>\n'
        f'<p><a href="/twt/~{_esc(username)}/twtxt.txt">twtxt feed</a></p>\n'
        '<form method="post" action="/twt/submit">\n'
        '<p><input type="password" name="token" placeholder="token" autocomplete="off"></p>\n'
        '<p><textarea name="twt" placeholder="say something"></textarea></p>\n'
        '<p><input type="submit" value="post"></p>\n'
        '<p class="msg" id="msg"></p>\n'
        '</form>\n'
        '<script>\n'
        'document.querySelector("form").addEventListener("submit", async e => {\n'
        '  e.preventDefault();\n'
        '  const msg = document.getElementById("msg");\n'
        '  msg.textContent = "";\n'
        '  const r = await fetch("/twt/submit", {method: "POST", body: new URLSearchParams(new FormData(e.target))});\n'
        '  const j = await r.json();\n'
        '  if (j.ok) { location.reload(); } else { msg.textContent = j.error; }\n'
        '});\n'
        '</script>\n'
        '<hr>\n'
        '<ul>\n'
        + items + '\n'
        '</ul>\n'
        '</main>\n'
        + _WKFO_FOOTER
    )


def _build_index_page():
    users = sorted(
        os.path.basename(d)[1:]
        for d in glob.glob(f'{WKFO_TWR}/~*')
        if os.path.isdir(d)
    )

    all_twts = []
    for u in users:
        for dt, text in _load_twtxt(f'{WKFO_TWR}/~{u}/twtxt.txt'):
            all_twts.append((dt, u, text))
    all_twts.sort(reverse=True)

    feed_items = '\n'.join(
        f'<li>[{dt.strftime("%Y-%m-%d")}] '
        f'<a href="/twt/~{_esc(u)}/">~{_esc(u)}</a>: {_esc(text)}</li>'
        for dt, u, text in all_twts[:50]
    ) or '<li>(nothing yet)</li>'

    user_items = '\n'.join(
        f'<li><a href="/twt/~{_esc(u)}/">~{_esc(u)}</a> '
        f'(<a href="/twt/~{_esc(u)}/twtxt.txt">twtxt</a>)</li>'
        for u in users
    ) or '<li>(no users yet)</li>'

    return (
        _WKFO_HEAD.format(title='wk.fo / twt') + '\n'
        '<header>\n'
        '<nav><strong><a href="https://wk.fo">wk.fo</a></strong> / twt</nav>\n'
        '</header>\n'
        '<main>\n'
        '<h1>twt</h1>\n'
        '<p>Hosted <a href="https://twtxt.readthedocs.io/">twtxt</a>. Short messages from friends.</p>\n'
        '<h2>feed</h2>\n'
        '<ul>\n' + feed_items + '\n</ul>\n'
        '<h2>users</h2>\n'
        '<ul>\n' + user_items + '\n</ul>\n'
        '</main>\n'
        + _WKFO_FOOTER
    )


def _wkfo_regen(bot, username=None):
    try:
        root = Path(WKFO_TWR)
        root.mkdir(parents=True, exist_ok=True)
        if username:
            Path(f'{WKFO_TWR}/~{username}/index.html').write_text(
                _build_user_page(username), encoding='utf-8')
        Path(f'{WKFO_TWR}/index.html').write_text(
            _build_index_page(), encoding='utf-8')
    except Exception as e:
        bot.say(f'regen error: {e}')


class TwtSection(StaticSection):
    twtxt_path = FilenameAttribute("twtxt_path", relative=False,
                                   default="/var/www/twt.gumx.cc/twtxt.txt")
    timezone   = ValidatedAttribute("timezone", default="UTC")
    nick       = ValidatedAttribute("nick", default="gumx")
    url        = ValidatedAttribute("url", default="https://twt.gumx.cc/twtxt.txt")


def setup(bot):
    bot.settings.define_section("twt", TwtSection)


def _is_owner(bot, trigger):
    return trigger.nick == bot.settings.core.owner


def _path(bot):
    return bot.settings.twt.twtxt_path


def _read(bot):
    p = _path(bot)
    if not os.path.exists(p):
        return []
    with open(p) as f:
        lines = f.readlines()
    twts = []
    for line in lines:
        line = line.rstrip("\n")
        if not line or line.startswith("#"):
            continue
        tab = line.find("\t")
        if tab == -1:
            continue
        twts.append((line[:tab], line[tab + 1:]))
    return twts


def _write(bot, twts):
    p = _path(bot)
    nick = bot.settings.twt.nick
    url  = bot.settings.twt.url
    with open(p, "w") as f:
        f.write(f"# nick = {nick}\n")
        f.write(f"# url  = {url}\n")
        for ts, text in twts:
            f.write(f"{ts}\t{text}\n")


def _append(bot, text):
    tz = ZoneInfo(bot.settings.twt.timezone)
    now = datetime.now(tz)
    offset = now.strftime("%z")
    offset = offset[:3] + ":" + offset[3:]
    ts = now.strftime("%Y-%m-%dT%H:%M:%S") + offset

    p = _path(bot)
    nick = bot.settings.twt.nick
    url  = bot.settings.twt.url
    if not os.path.exists(p):
        os.makedirs(os.path.dirname(p), exist_ok=True)
        with open(p, "w") as f:
            f.write(f"# nick = {nick}\n")
            f.write(f"# url  = {url}\n")
    with open(p, "a") as f:
        f.write(f"{ts}\t{text}\n")
    return ts


@plugin.commands("twt")
def cmd_twt(bot, trigger):
    if not _is_owner(bot, trigger):
        return

    raw  = (trigger.group(2) or "").strip()
    args = raw.split()
    sub  = args[0].lower() if args else ""

    if not sub:
        bot.say(h.TWF_TOPIC)
        return

    # --- last ---
    if sub == "last":
        try:
            n = int(args[1]) if len(args) > 1 else 5
            n = max(1, min(n, 10))
        except ValueError:
            bot.say("usage: !twt last [n]")
            return
        twts = _read(bot)
        if not twts:
            bot.say("no twts yet.")
            return
        for ts, text in reversed(twts[-n:]):
            bot.say(f"[{ts[:10]}] {text}")
        return

    # --- count ---
    if sub == "count":
        n = len(_read(bot))
        bot.say(f"{n} twt{'s' if n != 1 else ''}")
        return

    # --- delete ---
    if sub == "delete":
        twts = _read(bot)
        if not twts:
            bot.say("nothing to delete.")
            return
        ts, text = twts[-1]
        _pending_delete[trigger.nick] = True
        bot.say(f"delete [{ts[:10]}] {text!r}? !twt yes / !twt no")
        return

    # --- yes/no (confirm delete) ---
    if sub == "yes":
        if not _pending_delete.pop(trigger.nick, False):
            bot.say("nothing pending.")
            return
        twts = _read(bot)
        if not twts:
            bot.say("nothing to delete.")
            return
        removed = twts.pop()
        _write(bot, twts)
        bot.say(f"deleted [{removed[0][:10]}] {removed[1]!r}")
        return

    if sub == "no":
        if _pending_delete.pop(trigger.nick, False):
            bot.say("cancelled.")
        return

    # --- wk.fo/twt user management ---
    if sub == "users":
        tokens = _load_twt_tokens()
        if not tokens:
            bot.say("no wk.fo/twt users")
            return
        users = sorted(set(tokens.values()))
        bot.say(", ".join(users))
        return

    if sub == "add":
        if len(args) < 3:
            bot.say("usage: !twt add <username> <token>")
            return
        username = args[1]
        token    = args[2]
        tokens   = _load_twt_tokens()
        if token in tokens:
            bot.say(f"token already exists for {tokens[token]}")
            return
        user_dir = Path(f'{WKFO_TWR}/~{username}')
        user_dir.mkdir(parents=True, exist_ok=True)
        twtxt = user_dir / 'twtxt.txt'
        if not twtxt.exists():
            twtxt.write_text(f'# nick = {username}\n# url  = https://wk.fo/twt/~{username}/twtxt.txt\n')
        tokens[token] = username
        _save_twt_tokens(tokens)
        _wkfo_regen(bot, username)
        bot.say(f"added {username}")
        return

    if sub == "rm":
        if len(args) < 2:
            bot.say("usage: !twt rm <username>")
            return
        target = args[1]
        tokens = _load_twt_tokens()
        before = len(tokens)
        tokens = {t: u for t, u in tokens.items() if u != target}
        if len(tokens) == before:
            bot.say(f"not found: {target}")
            return
        _save_twt_tokens(tokens)
        _wkfo_regen(bot)
        bot.say(f"removed {target} (feed files kept)")
        return

    # --- post (anything that's not a subcommand) ---
    ts = _append(bot, raw)
    bot.say(f"twted [{ts[:10]}]: {raw}")