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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
|
(ns frq.main
"The Flutter entry point: what `frq.cosmic` is to the jolt half.
Two jobs, and the first one is why `frq.io.dart` cannot install itself the
way `frq.io.jolt` does: the app's storage directory arrives from
path_provider as a Future, so `main` is async, awaits it, and installs the
host before a widget is built. Everything under ../common asks `frq.io` for
the filesystem, so nothing shared can run until that has happened.
`ensureInitialized` first, and not as a formality: path_provider is a
platform channel, and a channel used before the binding exists throws.
The screens themselves are not written. `frq.app` is 1,834 lines of hiccup
over glimmer's widget tags, and glimmer is not here — Flutter brings its own
reconciler, so those screens are a rewrite against cljd.flutter rather than a
port. What this paints is the proof the shared half is alive under a second
compiler: the clock and the saved session, read through exactly the
namespaces the desktop reads them through."
(:require ["dart:async" :as async]
["package:flutter/material.dart" :as m]
["package:path_provider/path_provider.dart" :as pp]
[cljd.flutter :as f]
[frq.hiccup :as h]
[frq.theme :as t]
[frq.io.dart :as host]
;; The seam, not the implementation above: `open-url!` is asked for
;; the same way the shared half asks for it.
[frq.io :as fio]
[frq.crypto.dart :as crypto-dart]
[frq.net.dart :as net]
[frq.atproto.dart :as atproto]
[frq.clock :as clock]
[frq.store :as store]
[frq.actions :as actions]
[frq.cells :as cells]
[frq.screens.connect :as connect]
[frq.screens.chats :as chats]
[frq.screens.chat :as chat]
[frq.screens.settings :as settings]
[frq.screens.app :as screens]
[frq.rooms :as rooms]
[frq.members :as members]
[frq.oauth.core :as oauth]
[frq.oauth.dart :as oauth-dart]
[frq.irc.parse :as irc]
[frq.irc.handshake :as handshake]))
(defonce ^:private lines (atom []))
(defonce ^:private conn (atom nil))
(defonce ^:private last-line (atom nil))
(def ^:private history-limit
"How many lines of backlog to ask a room for, as `frq.state` asks for them."
100)
(defn- room!
"The little of `frq.state/apply-msg!` the conversation list needs: the two
messages that make a room appear and give it a last line, and everything
that says who is in it.
The membership half is `frq.members`, unchanged from what the desktop folds
— the server is the one deciding who is in a room, and it tells both halves
in the same words."
[m]
(let [cmd (str (:command m))
params (vec (:params m))
who (irc/nick-of (:prefix m))
me? (= who (str @cells/form-nick))
ensure (fn [m name] (update m name #(merge {:name name :messages [] :unread 0} %)))]
(cond
(= "JOIN" cmd)
(let [name (first params)]
(swap! cells/channels
#(-> (ensure % name)
(members/add-user name who)
(cond-> me? (update name merge {:joined? true
:accessed (clock/now-ms)}))))
;; Only our own JOIN opens the room. Someone else arriving in a
;; channel used to move the reader into it.
(when me? (reset! cells/current name)))
;; 353 is the roll, in as many lines as it takes; 366 ends it.
(= "353" cmd)
(let [name (nth params 2 nil)]
(when name
(swap! cells/channels #(members/with-names (ensure % name) name (last params)))))
(= "366" cmd)
(let [name (nth params 1 nil)]
(when name
(swap! cells/channels members/names-done name)
;; End of NAMES, and the only moment this client knows a room is
;; fully arrived. freeq re-joins an authenticated user's channels at
;; registration and leaves the backlog for the client to ask for, so
;; a room that reaches here with an empty buffer has no history
;; coming unless we ask — which is why nothing but new lines ever
;; appeared here. Same request `frq.state` makes on 366, and the
;; replayed lines come back as ordinary PRIVMSGs the branch below
;; already folds.
(when (and @conn (empty? (get-in @cells/channels [name :messages])))
(net/send-line! @conn
(str "CHATHISTORY LATEST " name " * " history-limit)))))
(= "PART" cmd)
(swap! cells/channels members/remove-user (first params) who)
(= "KICK" cmd)
(swap! cells/channels members/remove-user (first params) (nth params 1 nil))
(= "QUIT" cmd)
(swap! cells/channels members/remove-everywhere who)
(= "NICK" cmd)
(do (swap! cells/channels members/rename-user who (last params))
;; Our own rename is the server settling what we are called — it
;; hands a guest a name of its choosing, so this is the usual way
;; the nick on screen becomes the real one.
(when me? (reset! cells/form-nick (last params))))
(= "MODE" cmd)
(swap! cells/channels members/with-mode
(first params) (nth params 1 "") (drop 2 params))
(= "PRIVMSG" cmd)
(let [target (first params)
text (last params)
name (if (rooms/dm? target) who target)]
(swap! cells/channels update name
#(-> (merge {:name name :messages [] :unread 0} %)
(update :messages conj {:from who :text text})))))))
(defn- note! [m]
(reset! last-line (str (:command m) " " (last (:params m))))
(swap! lines (fn [v] (vec (take-last 8 (conj v m))))))
(def ^:private registration-failed
"Numerics that mean registration will never complete.
Only 001 used to clear `connecting?`, so anything the server said instead of
it spun for ever with no message — and the likeliest of them is the dullest:
433, the nick is already in use, which is what a second phone or a session
left open elsewhere gets."
#{"431" ; no nickname given
"432" ; erroneous nickname
"433" ; nickname in use
"436" ; nick collision
"464" ; password incorrect
"465" ; banned
"ERROR"})
(defonce ^:private attempt (atom 0))
;; Ticked whenever any cell changes, so one `:watch` covers all of them.
;;
;; What this replaced was a list of cells named by hand in the widget below,
;; and everything not on it was a control that flipped its cell and repainted
;; nothing — People, Overview and hide join/part all did.
(defonce ^:private repaint (atom 0))
(defn- watch-cells!
"Every cell in `frq.cells` ticking `repaint` when it changes.
Called from `main` rather than run from a top-level `defonce`, and that is
not a style preference: ClojureDart compiles a `def` to a Dart top-level
variable, Dart initialises those on first read, and a `defonce` whose value
nothing ever reads simply never runs. The first attempt at this installed no
watches at all and printed nothing to say so."
[]
(doseq [c (cells/all-cells)]
(add-watch c ::repaint
(fn [_ _ old new]
(when (not= old new) (swap! repaint inc))
nil))))
(defonce ^:private caps
;; What the server has agreed to on this connection. `frq.irc.handshake`
;; holds none of it: it takes the set and hands a new one back, so the
;; desktop can keep it in an atom on the connection and the phone here.
(atom #{}))
(defonce ^:private closing?
;; Whether the close about to arrive is one we asked for. Without it a tap
;; on Disconnect comes back as "closed by the server", which is both untrue
;; and alarming.
(atom false))
(defn- fail! [why]
(reset! cells/connecting? false)
(reset! cells/status "Not connected")
(reset! cells/screen :connect)
(reset! cells/error why))
(defn ^:async bluesky-session!
"A web-token session from freeq's auth broker.
Only the half that needs no browser. A saved broker token is durable and the
web-token minted from it is single-use, so a return visit is one POST to
/session and `frq.oauth.core` already says what to send and what the answer
means. Getting the *first* broker token is the other half: the browser hands
it back to a loopback listener on the desktop, and a phone has nowhere for
that to land — it wants an Android app link, which is a decision about what
the broker will redirect to and not a porting problem. So that case says so
rather than quietly connecting as somebody else."
[]
(if-let [bt @cells/broker-token]
(do
(reset! cells/status "Resuming your session…")
(let [tokens (oauth/refresh-session-parse
bt
(await (atproto/fetch
(oauth/refresh-session-req oauth/default-broker bt))))]
(reset! cells/broker-token (:broker-token tokens))
;; On every sign-in and not only the first: /session can hand back a
;; rotated broker token, and the old one may stop working the moment
;; it does.
(store/save-session! tokens)
(assoc tokens :kind :web-token)))
;; No saved token: the browser leg. `frq.oauth.dart` binds the loopback,
;; and what comes back through it is the first broker token.
(let [tokens (await (oauth-dart/await-callback!
oauth/default-broker
(str @cells/form-handle)
(fn [url]
(reset! cells/login-url url)
(reset! cells/status
(if (fio/open-url! url)
"Waiting for the browser…"
"Open the sign-in link below to continue"))
nil)))]
(reset! cells/login-url nil)
(reset! cells/broker-token (:broker-token tokens))
(store/save-session! tokens)
(assoc tokens :kind :web-token))))
(defn ^:async sign-in!
"Fill `cells/session` for the mode that was chosen, or say why not.
True when the connection may go ahead. A guest carries no session, and must
not carry the last one either: a leftover would have `frq.irc.handshake` ask
for sasl and authenticate as whoever signed in before."
[]
(case @cells/auth-mode
:guest (do (reset! cells/session nil) true)
(try
(reset! cells/connecting? true)
(reset! cells/error nil)
(reset! cells/session
(await (if (= :bluesky @cells/auth-mode)
(bluesky-session!)
(do (reset! cells/status "Signing in…")
(atproto/create-session @cells/form-handle
@cells/form-app-password)))))
;; An authenticated connection still needs a nick — the DID is the
;; identity, the nick is only what the channel calls you. Same order the
;; desktop picks it in: what the broker said, else the first label of the
;; handle, else whatever is in the box.
(let [sess @cells/session
nick (or (:nick sess)
(first (.split (str (or (:handle sess) "")) "."))
nil)]
(when (seq (str (or (:handle sess) "")))
(reset! cells/form-handle (:handle sess)))
(when (seq (str (or nick "")))
(reset! cells/form-nick nick))
;; The password did its work at the PDS; do not keep it.
(reset! cells/form-app-password ""))
true
(catch Object e
(reset! cells/session nil)
;; The message, not the exception: `frq.atproto.core` puts the body it
;; could not read in the ex-data, and a PDS that answers a resolve with
;; an HTML error page puts the whole page there.
(fail! (str "Sign-in failed: " (or (ex-message e) e)))
false))))
(defn ^:async connect!
"What `frq.actions/connect!` is on the phone.
The desktop's is `frq.state/connect!` — jolt's TLS, SASL, a reader thread.
This is the dart:io one, and it reads the same cells the screen wrote: the
host, the port and the TLS tick are `frq.cells`, filled in by the entry and
the checkbutton on screen.
Guest and app-password both. The handshake itself is not here: it is
`frq.irc.handshake`, which answers each line with the lines to send back,
and all this does is write them."
[]
;; Close whatever was open first. Connecting twice left the old socket
;; holding the nick, so the second attempt got 433 from its own predecessor.
(when-let [c @conn]
(reset! closing? true)
(net/close! c)
(reset! conn nil))
;; Whatever identity was asked for, settled before the socket opens. Both
;; of the signed-in modes are an HTTPS round trip that has nothing to do
;; with IRC, and a failure in either must stop here: connecting anyway lands
;; us on the server as a guest, which looks like a success and is not the
;; one that was asked for. Bluesky did exactly that until it was asked.
(when (await (sign-in!))
(let [n (swap! attempt inc)]
(reset! caps #{})
(reset! cells/connecting? true)
(reset! cells/error nil)
(reset! cells/status (str "Connecting to " @cells/form-host "…"))
(reset! lines [])
;; A watchdog, because "no answer at all" is a real outcome: a TLS
;; handshake that hangs, or a server that accepts the socket and says
;; nothing, leaves every callback below unfired.
(.then (async/Future.delayed (Duration .seconds 20))
(fn [_]
(when (and @cells/connecting? (= n @attempt))
(fail! "No answer from the server after 20s"))))
(try
(let [sock (await (net/connect!
{:host @cells/form-host
;; The cell is a string, because it is what an
;; :entry holds.
:port (or (parse-long (str @cells/form-port)) 6697)
:tls? (boolean @cells/form-tls?)
:on-msg (fn [m]
(note! m)
(room! m)
;; Capability negotiation and SASL, out of
;; common/ — the same steps the desktop
;; takes, and all this does is write what
;; they answer with.
(let [{:keys [send] next-caps :caps}
(handshake/step {:session @cells/session
:caps @caps}
m)]
(reset! caps next-caps)
(doseq [line send]
(when-let [c @conn] (net/send-line! c line))))
(let [cmd (str (:command m))
text (str (last (:params m)))]
(cond
(= "001" cmd)
(do (reset! cells/connecting? false)
(reset! cells/error nil)
(reset! cells/status
(str "Connected as " @cells/form-nick))
;; Off the connect screen, as
;; frq.state does on 001. Without
;; this a successful connect just
;; puts the Connect button back
;; and looks exactly like a
;; failure.
(reset! cells/screen :chats)
(when-let [c @conn]
(net/send-line! c "JOIN #test")))
(contains? registration-failed cmd)
(fail! (if (= "433" cmd)
(str "Nick " @cells/form-nick
" is already in use — try another")
(str cmd " " text)))
;; Something is happening; say so
;; rather than sit on one message.
@cells/connecting?
(reset! cells/status (str "… " cmd)))))
:on-close (fn [why]
(reset! conn nil)
;; Say what the last thing seen was. A
;; connection that registers and then
;; drops is a different bug from one
;; that never registers, and only the
;; last line apart tells them.
(if @closing?
(reset! closing? false)
(fail! (str (or why "closed by the server")
" (after " (count @lines)
" lines, last: " @last-line ")"))))}))]
(reset! conn sock)
;; CAP first, then registration — the order the server expects, and the
;; order `frq.irc` uses.
(net/send-line! sock "CAP LS 302")
(let [nick (if-let [h (:handle @cells/session)] h @cells/form-nick)]
(net/send-line! sock (str "NICK " nick))
(net/send-line! sock (str "USER " nick " 0 * :frq"))))
;; Object, not Exception. Dart keeps Error and Exception in separate
;; hierarchies, so a TypeError is not an Exception and would leave
;; `connecting?` true for ever.
(catch Object e
(fail! (str e)))))))
(defn- disconnect! []
(reset! closing? true)
(when-let [c @conn] (net/close! c))
(reset! conn nil)
(reset! cells/connecting? false)
(reset! cells/status "Not connected")
(reset! cells/screen :connect))
(defonce ^:private handle (atom "nandi-test.bsky.social"))
(defonce ^:private identity-out (atom nil))
(defn ^:async resolve-identity! []
(reset! identity-out ["resolving…"])
(try
(let [h @handle
did (await (atproto/resolve-handle h))
pds (await (atproto/pds-endpoint did))]
(reset! identity-out [(str "did " did) (str "pds " pds)]))
(catch Exception e
(reset! identity-out [(str "failed: " e)]))))
(defn- connected-screen
"Where a connect lands, until `frq.app`'s chats screen is portable.
Not much, and honest about it: the status, what the server said, and the way
back. The desktop goes to :chats here — that screen reads rooms, messages,
avatars and the media plane, which is most of what is not ported yet."
[]
[:page {:max-width 520}
[:title {:label "frq"}]
[:status {:live true :label @cells/status}]
[:card {}
[:title-2 {:label "What the server said"}]
(if (empty? @lines)
[:dim-label {:label "nothing yet"}]
(for [[i m] (map-indexed vector @lines)]
[:label {:key i
:label (str (:command m)
(when-let [p (seq (:params m))]
(str " " (last p))))}]))]
[:hbox {:spacing 8}
[:button {:label "Disconnect" :destructive true :on-click #(disconnect!)}]]
[:dim-label {:label "The chats screen is next: it wants rooms, messages and avatars, none of which are ported yet."}]])
(defn- send-draft! []
(let [text (str @cells/draft)
room (str @cells/current)]
(when (and (seq text) (seq room) @conn)
(net/send-line! @conn (str "PRIVMSG " room " :" text))
;; Echoed locally only when the server will not echo it back. With
;; `echo-message` negotiated it does — that is what the cap is for, and
;; it is how a client learns the msgid of its own line — so adding one
;; here as well put every sent message in the room twice.
(when-not (handshake/acked? @caps "echo-message")
(swap! cells/channels update room
#(update % :messages conj {:from @cells/form-nick :text text})))
(reset! cells/draft ""))))
(defn ^:async main []
(m/WidgetsFlutterBinding.ensureInitialized)
;; Layout errors do not come back as exceptions — they happen after the
;; build, so nothing can catch them, and what they leave is a blank screen
;; and an empty log. Flutter routes them here instead.
(set! (.-onError m/FlutterError)
(fn [details]
(m/debugPrint (str "frq: FLUTTER ERROR " (.-exception details)))
(m/debugPrint (str "frq: LIBRARY " (.-library details)
" CONTEXT " (.-context details)))))
(let [dir (.-path (await (pp/getApplicationSupportDirectory)))]
(host/install! dir)
;; Ed25519 for the reactions freeq will not take on trust. Verified
;; against RFC 8032 test 1 on the device: the same public key and the
;; same signature OpenSSL gives on the desktop, so a signature minted
;; here verifies the same way at the server.
(crypto-dart/install!)
;; Before any widget is built: a cell that changes before its watch is on
;; is a change the screen never hears about.
(watch-cells!)
;; A sign-in that already happened. Only the durable broker token comes
;; back — the connection mints a fresh web-token from it — so this is not
;; a session, it is the means to ask for one.
(when-let [saved (store/load-session)]
(reset! cells/broker-token (:broker-token saved))
(when (seq (str (or (:handle saved) "")))
(reset! cells/form-handle (:handle saved)))
(when (seq (str (or (:nick saved) "")))
(reset! cells/form-nick (:nick saved)))
(reset! cells/auth-mode :bluesky)
(reset! cells/status (str "Signed in as " (:handle saved) " — Connect to resume")))
;; What the shared screen calls. The desktop installs frq.state's
;; reducers here; this installs the phone's.
(actions/install!
{:connect! connect!
:disconnect! disconnect!
:connected? (fn [] (some? @conn))
:join! (fn [name]
(when-let [c @conn]
(when (seq (str name))
(net/send-line! c (str "JOIN " name)))))
:leave-channel! (fn [name]
(when-let [c @conn] (net/send-line! c (str "PART " name)))
(swap! cells/channels dissoc name))
:send-draft! send-draft!
:wide? (fn [] false)
:desktop? (fn [] false)
:mine? (fn [from] (= (str from) (str @cells/form-nick)))
:message-by-id (fn [room id]
(->> (get-in @cells/channels [room :messages])
(filter #(= id (:id %)))
first))
:member-count (fn [room] (members/member-count @cells/channels room))
:member-list (fn [room] (members/member-list @cells/channels room))
:toggle-users! (fn [] (swap! cells/show-users? not))
:toggle-overview! (fn [] (swap! cells/overview? not))
:toggle-chat-list! (fn [] (swap! cells/hide-chat-list? not))
:toggle-hide-join-part! (fn [] (swap! cells/hide-join-part? not))
:quit! (fn [] nil)
:forget-session! (fn []
(reset! cells/broker-token nil)
(reset! cells/session nil))
:jump-to-present! (fn [] (reset! cells/at-present? true))
:open-channel! (fn [name]
(reset! cells/current name)
;; `frq.state/open-channel!` does this and more: it
;; marks the buffer read, remembers the room list and
;; asks for NAMES. What it also does, and what made
;; Open look like a no-op here, is go to the
;; conversation — and join it on the way, because a row
;; can outlive the membership behind it.
(swap! cells/channels update name
#(merge {:name name :messages [] :unread 0} %))
(reset! cells/screen :chat)
(let [buffer (get @cells/channels name)]
(when (and @conn
(.startsWith (str name) "#")
(not (:joined? buffer)))
(net/send-line! @conn (str "JOIN " name)))))})
(f/run
(m/MaterialApp .title "frq" .theme (t/app-theme))
.home
;; No AppBar. `connect-screen` opens with [:title {:label "frq"}] — the
;; desktop has no bar above it either, the window's title is the
;; window's — so a bar here says "frq" twice.
(m/Scaffold)
.body
m/SafeArea
(f/widget
;; One watch, not twenty. `lines` is a local atom and not a cell, so it
;; is named beside the tick; everything under `frq.cells` arrives
;; through `repaint`.
:watch [tick repaint ls lines]
(h/render
;; `frq.screens.app` decides which screen shows, the same way it does
;; on the desktop. The phone was switching by hand until this moved.
[screens/app])))))
|