Use group-by from stdlib
[tt.git] / tt.rkt
CommitLineData
cd541405 1#lang typed/racket/no-check
4764ff89 2
1d753430 3(require openssl/sha1)
4764ff89 4(require racket/date)
9c464d95 5(require
d718efc4 6 net/head
edadb804 7 net/uri-codec
8da029e4 8 net/url)
4764ff89 9
3c9c8266
SK
10(require (prefix-in info: "info.rkt"))
11
78398948 12(module+ test
de3ff448 13 (require rackunit))
78398948 14
98529d3d
SK
15(define-type Url
16 net/url-structs:url)
17
18(define-type Out-Format
19 (U 'single-line
20 'multi-line))
21
22(define-type Timeline-Order
23 (U 'old->new
24 'new->old))
25
7fd20778
SK
26(define-type Result
27 (∀ (α β) (U (cons 'ok α)
28 (cons 'error β))))
29
63805738
SK
30(define-type Download-Result
31 (Result (U 'skipped-cached 'downloaded-new)
32 (U 'timeout
33 (Pair 'unsupported-url-scheme String)
34 (Pair 'http-not-ok Positive-Integer)
35 (Pair 'net-error Any)
36 (Pair 'other Any))))
37
651cf37d
SK
38(struct Hist
39 ([freq : Nonnegative-Integer]
40 [last : Nonnegative-Integer])
41 #:transparent)
42
5fef9856 43(define-type Url-Nick-Hist
651cf37d
SK
44 (Immutable-HashTable Url (Immutable-HashTable (Option String) Hist)))
45
7296ed94 46(struct User
1ecda371 47 ([url : Url]
3dc554da 48 [nick : (Option String)]))
7296ed94
SK
49
50(struct User-Agent
3dc554da
SK
51 ([user : User]
52 [prog : Prog]))
7296ed94
SK
53
54(struct Prog
3dc554da
SK
55 ([name : String]
56 [version : String]))
7296ed94 57
b0ff061a 58(struct Msg
78142acb 59 ([ts-epoch : Integer]
3877a0c4 60 [ts-orig : String]
0cb1ae9c 61 [from : Peer]
13c11724 62 [text : String]
b0ff061a 63 [mentions : (Listof Peer)]))
9c464d95 64
dbc26280 65(struct Peer
b056019b 66 ([nick : (Option String)]
1ecda371
SK
67 [url : Url]
68 [url-str : String]
b056019b 69 [comment : (Option String)])
d0a0e073 70 #:transparent)
4764ff89 71
7296ed94
SK
72(: prog Prog)
73(define prog
74 (Prog "tt" (info:#%info-lookup 'version)))
75
76(: user-default User)
77(define user-default
ab7bf8d5 78 (User (string->url "https://github.com/xandkar/tt") #f))
7296ed94
SK
79
80(: user->str (-> User String))
81(define (user->str user)
ab7bf8d5
SK
82 (match-define (User u0 n) user)
83 (define u (url->string u0))
7296ed94 84 (if n
3dc554da
SK
85 (format "+~a; @~a" u n)
86 (format "+~a" u )))
7296ed94
SK
87
88(: user-agent->str (-> User-Agent String))
89(define (user-agent->str ua)
90 (match-define (User-Agent u p) ua)
91 (format "~a/~a (~a)" (Prog-name p) (Prog-version p) (user->str u)))
92
93(: user->user-agent User)
94(define (user->user-agent user)
95 (User-Agent user prog))
96
97(: user-agent-str String)
98(define user-agent-str
99 (user-agent->str (user->user-agent user-default)))
100
101(: set-user-agent-str (-> Path-String Void))
102(define (set-user-agent-str filename)
103 (set! user-agent-str (user-agent->str (user->user-agent (file->user filename))))
104 (log-info "User-Agent string is now set to: ~v" user-agent-str))
105
106(: file->user (-> Path-String User))
107(define (file->user filename)
108 (if (file-exists? filename)
dd098ae3 109 (match (file->peers filename)
7296ed94
SK
110 [(list p)
111 (log-info
112 "User-Agent. Found one peer in file: ~v. Using the found peer: ~a"
113 filename
114 (peer->str p))
115 (peer->user p)]
116 [(list* p _)
117 (log-warning
118 "User-Agent. Multiple peers in file: ~v. Picking arbitrary: ~a"
119 filename
120 (peer->str p))
121 (peer->user p)]
122 ['()
123 (log-warning
124 "User-Agent. No peers found in file: ~v. Using the default user: ~a"
125 filename
126 user-default)
127 user-default])
128 (begin
129 (log-warning
130 "User-Agent. File doesn't exist: ~v. Using the default user: ~a"
131 filename
132 user-default)
133 user-default)))
134
ab7bf8d5 135(: peer->user (-> Peer User))
7296ed94 136(define (peer->user p)
ab7bf8d5 137 (match-define (Peer n u _ _) p)
7296ed94
SK
138 (User u n))
139
0cb1ae9c
SK
140(: peers-equal? (-> Peer Peer Boolean))
141(define (peers-equal? p1 p2)
1ecda371
SK
142 (equal? (Peer-url-str p1)
143 (Peer-url-str p2)))
0cb1ae9c
SK
144
145(: peer-hash (-> Peer Fixnum))
146(define (peer-hash p)
1ecda371 147 (equal-hash-code (Peer-url-str p)))
0cb1ae9c 148
e2840743
SK
149(define-custom-set-types peers
150 #:elem? Peer?
0cb1ae9c
SK
151 peers-equal?
152 peer-hash)
e2840743
SK
153; XXX Without supplying above explicit hash procedure, we INTERMITTENTLY get
154; the following contract violations:
155;
156; custom-elem-contents: contract violation
157; expected: custom-elem?
158; given: #f
159; context...:
160; /usr/share/racket/collects/racket/private/set-types.rkt:104:0: custom-set->list
161; /home/siraaj/proj/pub/tt/tt.rkt:716:0: crawl
162; /usr/share/racket/collects/racket/cmdline.rkt:191:51
163; body of (submod "/home/siraaj/proj/pub/tt/tt.rkt" main)
164;
165; TODO Investigate why and make a minimal reproducible test case.
166
dd098ae3
SK
167(: peers-merge (-> (Listof Peer) * (Listof Peer)))
168(define (peers-merge . peer-sets)
50f0609d
SK
169 (define (merge peers)
170 (match peers
171 ['() (raise 'impossible)]
172 [(list p) p]
173 [(list* p1 p2 ps)
174 (let* ([n1 (Peer-nick p1)]
175 [n2 (Peer-nick p2)]
176 [p (cond
5272d418 177 ; TODO Try to pick from nicks db: preferred, otherwise seen
651cf37d
SK
178 [(and (not n1) (not n2)) p1] ; TODO update with most-common nick
179 [(and n1 n2 ) p1] ; TODO compare which is more-common
50f0609d
SK
180 [(and n1 (not n2)) p1]
181 [(and (not n1) n2) p2]
182 [else
183 (raise 'impossible)])])
184 (merge (cons p ps)))]))
38ff609b 185 (sort (map merge (group-by Peer-url-str (append* peer-sets)))
dd098ae3
SK
186 (match-lambda**
187 [((Peer _ _ u1 _) (Peer _ _ u2 _)) (string<? u1 u2)])))
50f0609d
SK
188
189(module+ test
190 (let* ([u1 "http://foo/bar"]
191 [u2 "http://baz/quux"]
192 [p1 (Peer #f (string->url u1) u1 #f)]
193 [p2 (Peer "a" (string->url u1) u1 #f)]
194 [p3 (Peer "b" (string->url u2) u2 #f)]
dd098ae3
SK
195 [s1 (list p1)]
196 [s2 (list p2 p3)])
197 (check-equal? (list p3 p2) (peers-merge s1 s2))
198 (check-equal? (list p3 p2) (peers-merge s2 s1))))
50f0609d 199
edadb804
SK
200(: tt-home-dir Path-String)
201(define tt-home-dir (build-path (expand-user-path "~") ".tt"))
202
96412b0a
SK
203(: pub-peers-dir Path-String)
204(define pub-peers-dir (build-path tt-home-dir "peers"))
205
9a346534 206(: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α) (Listof β))))
78142acb 207(define (concurrent-filter-map num-workers f xs)
dad4504d 208 ; TODO preserve order of elements OR communicate that reorder is expected
a239a233 209 ; TODO switch from mailboxes to channels
895a32cf
SK
210 (define (make-worker id f)
211 (define parent (current-thread))
212 (λ ()
a9511f7c
SK
213 (define self : Thread (current-thread))
214 (: work (∀ (α) (-> α)))
895a32cf
SK
215 (define (work)
216 (thread-send parent (cons 'next self))
217 (match (thread-receive)
c562bea3
SK
218 ['done (thread-send parent (cons 'exit id))]
219 [(cons 'unit x) (begin
220 (define y (f x))
221 (when y (thread-send parent (cons 'result y)))
222 (work))]))
895a32cf 223 (work)))
a9511f7c 224 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
895a32cf
SK
225 (define (dispatch ws xs ys)
226 (if (empty? ws)
f1493e49
SK
227 ys
228 (match (thread-receive)
c562bea3
SK
229 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
230 [(cons 'result y) (dispatch ws xs (cons y ys))]
231 [(cons 'next thd) (match xs
232 ['() (begin
233 (thread-send thd 'done)
234 (dispatch ws xs ys))]
235 [(cons x xs) (begin
236 (thread-send thd (cons 'unit x))
237 (dispatch ws xs ys))])])))
78142acb 238 (define workers (range num-workers))
9926c9a9
SK
239 (define threads (map (λ (id) (thread (make-worker id f))) workers))
240 (define results (dispatch workers xs '()))
895a32cf
SK
241 (for-each thread-wait threads)
242 results)
243
dad4504d 244(module+ test
de3ff448
SK
245 (let* ([f (λ (x) (if (even? x) x #f))]
246 [xs (range 11)]
247 [actual (sort (concurrent-filter-map 10 f xs) <)]
248 [expected (sort ( filter-map f xs) <)])
c562bea3 249 (check-equal? actual expected "concurrent-filter-map")))
dad4504d 250
98529d3d 251(: msg-print (-> Out-Format Integer Msg Void))
3d042e75
SK
252(define msg-print
253 (let* ([colors (vector 36 33)]
254 [n (vector-length colors)])
255 (λ (out-format color-i msg)
01e4c499 256 (let ([color (vector-ref colors (modulo color-i n))]
0cb1ae9c 257 [nick (Peer-nick (Msg-from msg))]
1ecda371 258 [url (Peer-url-str (Msg-from msg))]
0cb1ae9c 259 [text (Msg-text msg)])
3d042e75 260 (match out-format
01e4c499 261 ['single-line
1ecda371 262 (let ([nick (if nick nick url)])
13c11724
SK
263 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
264 (parameterize
265 ([date-display-format 'iso-8601])
b0ff061a 266 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
13c11724 267 nick color text))]
01e4c499 268 ['multi-line
13c11724
SK
269 (let ([nick (if nick (string-append nick " ") "")])
270 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
271 (parameterize
272 ([date-display-format 'rfc2822])
b0ff061a
SK
273 (date->string (seconds->date (Msg-ts-epoch msg)) #t))
274 (Msg-ts-orig msg)
1ecda371 275 nick url color text))])))))
e96264cc 276
3877a0c4
SK
277(: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
278(define rfc3339->epoch
279 (let ([re (pregexp "^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2})(:([0-9]{2}))?(\\.[0-9]+)?(Z|([+-])([0-9]{1,2}):?([0-9]{2}))?$")])
280 (λ (ts)
281 (match (regexp-match re ts)
282 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
283 (let*
284 ([tz-offset
285 (match* (tz-whole tz-sign tz-HH tz-MM)
286 [("Z" #f #f #f)
287 0]
288 [(_ (or "-" "+") (? identity h) (? identity m))
289 (let ([h (string->number h)]
290 [m (string->number m)]
291 ; Reverse to get back to UTC:
292 [op (match tz-sign ["+" -] ["-" +])])
293 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
294 [(a b c d)
295 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
296 0])]
297 [ts-orig ts]
298 [local-time? #f]
299 [ts-epoch (find-seconds (if SS (string->number SS) 0)
300 (string->number MM)
301 (string->number HH)
302 (string->number dd)
303 (string->number mm)
304 (string->number yyyy)
305 local-time?)])
306 (+ ts-epoch tz-offset))]
307 [_
b8b29fbb 308 (log-debug "Invalid timestamp: ~v" ts)
3877a0c4
SK
309 #f]))))
310
0cb1ae9c 311(: str->msg (-> Peer String (Option Msg)))
b4689464 312(define str->msg
3877a0c4 313 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
0cb1ae9c
SK
314 (λ (from str)
315 (define from-str (peer->str from))
d3ac9e11 316 (define str-head (substring str 0 (min 100 (string-length str))))
b4689464
SK
317 (with-handlers*
318 ([exn:fail?
319 (λ (e)
b8b29fbb 320 (log-debug
9c464d95 321 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
0cb1ae9c 322 str-head from-str e)
b4689464
SK
323 #f)])
324 (match (regexp-match re str)
3877a0c4
SK
325 [(list _wholething ts-orig text)
326 (let ([ts-epoch (rfc3339->epoch ts-orig)])
327 (if ts-epoch
13c11724
SK
328 (let ([mentions
329 (filter-map
330 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
1ecda371
SK
331 [(list _wholething nick-url)
332 (str->peer nick-url)]))
13c11724 333 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
0cb1ae9c 334 (Msg ts-epoch ts-orig from text mentions))
3877a0c4 335 (begin
b8b29fbb 336 (log-debug
0cb1ae9c
SK
337 "Msg rejected due to invalid timestamp. From:~v. Line:~v"
338 from-str str-head)
3877a0c4 339 #f)))]
b4689464 340 [_
0cb1ae9c 341 (log-debug "Non-msg line. From:~v. Line:~v" from-str str-head)
b4689464 342 #f])))))
88d50b3e 343
63afa259 344(module+ test
13c11724 345 ; TODO Test for when missing-nick case
b4689464
SK
346 (let* ([tzs (for*/list ([d '("-" "+")]
347 [h '("5" "05")]
348 [m '("00" ":00" "57" ":57")])
349 (string-append d h m))]
350 [tzs (list* "" "Z" tzs)])
351 (for* ([n '("fake-nick")]
1ecda371 352 [u '("http://fake-url")]
50f0609d 353 [p (list (Peer n (string->url u) u #f))]
b4689464
SK
354 [s '("" ":10")]
355 [f '("" ".1337")]
356 [z tzs]
357 [sep (list "\t" " ")]
358 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
359 (let* ([ts (string-append "2020-11-18T22:22"
360 (if (non-empty-string? s) s ":00")
361 z)]
0cb1ae9c 362 [m (str->msg p (string-append ts sep txt))])
b4689464 363 (check-not-false m)
0cb1ae9c 364 (check-equal? (Msg-from m) p)
b0ff061a
SK
365 (check-equal? (Msg-text m) txt)
366 (check-equal? (Msg-ts-orig m) ts (format "Given: ~v" ts))
b4689464
SK
367 )))
368
de3ff448
SK
369 (let* ([ts "2020-11-18T22:22:09-0500"]
370 [tab " "]
371 [text "Lorem ipsum"]
372 [nick "foo"]
1ecda371
SK
373 [url "http://bar/"]
374 [peer (Peer nick (string->url url) url #f)]
0cb1ae9c
SK
375 [actual (str->msg peer (string-append ts tab text))]
376 [expected (Msg 1605756129 ts peer text '())])
c562bea3 377 (check-equal?
b0ff061a
SK
378 (Msg-ts-epoch actual)
379 (Msg-ts-epoch expected)
78142acb 380 "str->msg ts-epoch")
3877a0c4 381 (check-equal?
b0ff061a
SK
382 (Msg-ts-orig actual)
383 (Msg-ts-orig expected)
3877a0c4 384 "str->msg ts-orig")
c562bea3 385 (check-equal?
0cb1ae9c
SK
386 (Peer-nick (Msg-from actual))
387 (Peer-nick (Msg-from expected))
c562bea3
SK
388 "str->msg nick")
389 (check-equal?
1ecda371
SK
390 (Peer-url (Msg-from actual))
391 (Peer-url (Msg-from expected))
392 "str->msg url")
0cb1ae9c 393 (check-equal?
1ecda371
SK
394 (Peer-url-str (Msg-from actual))
395 (Peer-url-str (Msg-from expected))
396 "str->msg url-str")
c562bea3 397 (check-equal?
b0ff061a
SK
398 (Msg-text actual)
399 (Msg-text expected)
c562bea3 400 "str->msg text")))
63afa259 401
98529d3d 402(: str->lines (-> String (Listof String)))
e96264cc
SK
403(define (str->lines str)
404 (string-split str (regexp "[\r\n]+")))
405
63afa259 406(module+ test
de3ff448 407 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
63afa259 408
cd868590
SK
409; TODO Should return 2 things: 1) msgs; 2) metadata parsed from comments
410; TODO Update peer nick based on metadata?
0cb1ae9c
SK
411(: str->msgs (-> Peer String (Listof Msg)))
412(define (str->msgs peer str)
413 (filter-map (λ (line) (str->msg peer line))
414 (filter-comments (str->lines str))))
4764ff89 415
edadb804
SK
416(: cache-dir Path-String)
417(define cache-dir (build-path tt-home-dir "cache"))
418
d718efc4
SK
419(define cache-object-dir (build-path cache-dir "objects"))
420
edadb804 421(: url->cache-file-path-v1 (-> Url Path-String))
1ecda371 422(define (url->cache-file-path-v1 url)
edadb804
SK
423 (define (hash-sha1 str) : (-> String String)
424 (define in (open-input-string str))
425 (define digest (sha1 in))
426 (close-input-port in)
427 digest)
1ecda371 428 (build-path cache-object-dir (hash-sha1 (url->string url))))
edadb804
SK
429
430(: url->cache-file-path-v2 (-> Url Path-String))
1ecda371
SK
431(define (url->cache-file-path-v2 url)
432 (build-path cache-object-dir (uri-encode (url->string url))))
d718efc4 433
0cb1ae9c
SK
434(define url->cache-object-path
435 url->cache-file-path-v2)
d3ac9e11 436
1ecda371
SK
437(define (url->cache-etag-path url)
438 (build-path cache-dir "etags" (uri-encode (url->string url))))
d718efc4 439
1ecda371
SK
440(define (url->cache-lmod-path url)
441 (build-path cache-dir "lmods" (uri-encode (url->string url))))
9c464d95 442
1ecda371
SK
443(: url-read-cached (-> Url (Option String)))
444(define (url-read-cached url)
445 (define path-v1 (url->cache-file-path-v1 url))
446 (define path-v2 (url->cache-file-path-v2 url))
edadb804
SK
447 (when (file-exists? path-v1)
448 (rename-file-or-directory path-v1 path-v2 #t))
449 (if (file-exists? path-v2)
450 (file->string path-v2)
0e16a46c 451 (begin
1ecda371 452 (log-debug "Cache file not found for URL: ~a" (url->string url))
fee11be9 453 #f)))
4214c0f3 454
b056019b
SK
455(: str->url (-> String (Option String)))
456(define (str->url s)
457 (with-handlers*
458 ([exn:fail? (λ (e) #f)])
459 (string->url s)))
a60c484e 460
0cb1ae9c
SK
461(: peer->str (-> Peer String))
462(define (peer->str peer)
463 (match-define (Peer n _ u c) peer)
464 (format "~a~a~a"
465 (if n (format "~a " n) "")
466 u
467 (if c (format " # ~a" c) "")))
468
469(: str->peer (-> String (Option Peer)))
dbc26280
SK
470(define (str->peer str)
471 (log-debug "Parsing peer string: ~v" str)
b056019b
SK
472 (match
473 (regexp-match
474 #px"(([^\\s\t]+)[\\s\t]+)?([a-zA-Z]+://[^\\s\t]*)[\\s\t]*(#\\s*(.*))?"
475 str)
476 [(list _wholething
477 _nick-with-space
478 nick
479 url
480 _comment-with-hash
481 comment)
482 (match (str->url url)
483 [#f
1ecda371 484 (log-error "Invalid URL in peer string: ~v" str)
b056019b 485 #f]
e2840743
SK
486 [url
487 (Peer nick url (url->string url) comment)])]
b056019b 488 [_
b8b29fbb 489 (log-debug "Invalid peer string: ~v" str)
b056019b 490 #f]))
13c11724 491
b056019b
SK
492(module+ test
493 (check-equal?
494 (str->peer "foo http://bar/file.txt # some rando")
e2840743 495 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
b056019b
SK
496 (check-equal?
497 (str->peer "http://bar/file.txt # some rando")
e2840743 498 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" "some rando"))
b056019b
SK
499 (check-equal?
500 (str->peer "http://bar/file.txt #")
e2840743 501 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" ""))
b056019b
SK
502 (check-equal?
503 (str->peer "http://bar/file.txt#") ; XXX URLs can have #s
e2840743 504 (Peer #f (str->url "http://bar/file.txt#") "http://bar/file.txt#" #f))
b056019b
SK
505 (check-equal?
506 (str->peer "http://bar/file.txt")
e2840743 507 (Peer #f (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
b056019b
SK
508 (check-equal?
509 (str->peer "foo http://bar/file.txt")
e2840743 510 (Peer "foo" (str->url "http://bar/file.txt") "http://bar/file.txt" #f))
b056019b
SK
511 (check-equal?
512 (str->peer "foo bar # baz")
513 #f)
514 (check-equal?
515 (str->peer "foo bar://baz # quux")
e2840743 516 (Peer "foo" (str->url "bar://baz") "bar://baz" "quux"))
b056019b
SK
517 (check-equal?
518 (str->peer "foo bar//baz # quux")
519 #f))
9c464d95 520
98529d3d 521(: filter-comments (-> (Listof String) (Listof String)))
9c464d95
SK
522(define (filter-comments lines)
523 (filter-not (λ (line) (string-prefix? line "#")) lines))
524
dd098ae3 525(: str->peers (-> String (Listof Peer)))
dbc26280 526(define (str->peers str)
dd098ae3 527 (filter-map str->peer (filter-comments (str->lines str))))
9c464d95 528
dd098ae3 529(: peers->file (-> (Listof Peers) Path-String Void))
a60c484e 530(define (peers->file peers path)
96412b0a 531 (make-parent-directory* path)
a60c484e 532 (display-lines-to-file
0cb1ae9c 533 (map peer->str
dd098ae3 534 (sort peers
e2840743
SK
535 (match-lambda**
536 [((Peer n1 _ _ _) (Peer n2 _ _ _))
537 (string<? (if n1 n1 "")
538 (if n2 n2 ""))])))
a60c484e
SK
539 path
540 #:exists 'replace))
541
dd098ae3 542(: file->peers (-> Path-String (Listof Peer)))
d0a0e073
SK
543(define (file->peers file-path)
544 (if (file-exists? file-path)
545 (str->peers (file->string file-path))
546 (begin
a60c484e 547 (log-warning "File does not exist: ~v" (path->string file-path))
dd098ae3 548 '())))
9c464d95 549
9c5e4499
SK
550(define re-rfc2822
551 #px"^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), ([0-9]{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ([0-9]{4}) ([0-2][0-9]):([0-6][0-9]):([0-6][0-9]) GMT")
552
553(: b->n (-> Bytes (Option Number)))
554(define (b->n b)
555 (string->number (bytes->string/utf-8 b)))
556
557(: mon->num (-> Bytes Natural))
558(define/match (mon->num mon)
559 [(#"Jan") 1]
560 [(#"Feb") 2]
561 [(#"Mar") 3]
562 [(#"Apr") 4]
563 [(#"May") 5]
564 [(#"Jun") 6]
565 [(#"Jul") 7]
566 [(#"Aug") 8]
567 [(#"Sep") 9]
568 [(#"Oct") 10]
569 [(#"Nov") 11]
570 [(#"Dec") 12])
571
572(: rfc2822->epoch (-> Bytes (Option Nonnegative-Integer)))
573(define (rfc2822->epoch timestamp)
574 (match (regexp-match re-rfc2822 timestamp)
575 [(list _ _ dd mo yyyy HH MM SS)
576 #:when (and dd mo yyyy HH MM SS)
577 (find-seconds (b->n SS)
578 (b->n MM)
579 (b->n HH)
580 (b->n dd)
581 (mon->num mo)
582 (b->n yyyy)
583 #f)]
584 [_
585 #f]))
586
d718efc4
SK
587(: header-get (-> (Listof Bytes) Bytes (Option Bytes)))
588(define (header-get headers name)
589 (match (filter-map (curry extract-field name) headers)
590 [(list val) val]
591 [_ #f]))
592
1ecda371 593(: url-download-http-from-port
7fd20778
SK
594 (-> Url (Listof (U Bytes String)) Input-Port
595 (U 'skipped-cached 'downloaded-new))) ; TODO 'ok|'error ?
1ecda371 596(define (url-download-http-from-port u headers body-input)
bb208ad5
SK
597 ; TODO Update message db from here? or where?
598 ; - 1st try can just be an in-memory set that gets written-to
599 ; and read-from disk as a whole.
7fd20778 600 (define u-str (url->string u))
1ecda371 601 (log-debug "url-download-http-from-port ~v into ~v" u-str cached-object-path)
d718efc4
SK
602 (define cached-object-path (url->cache-object-path u))
603 (define cached-etag-path (url->cache-etag-path u))
604 (define cached-lmod-path (url->cache-lmod-path u))
7fd20778
SK
605 (define etag (header-get headers #"ETag"))
606 (define lmod (header-get headers #"Last-Modified"))
607 (define lmod-curr (if lmod (rfc2822->epoch lmod) #f))
608 (define lmod-prev (if (file-exists? cached-lmod-path)
609 (rfc2822->epoch (file->bytes cached-lmod-path))
610 #f))
611 (log-debug "lmod-curr:~v lmod-prev:~v" lmod-curr lmod-prev)
612 (define cached?
613 (or (and etag
614 (file-exists? cached-etag-path)
615 (bytes=? etag (file->bytes cached-etag-path))
616 (begin
617 (log-debug "ETags match, skipping the rest of ~v" u-str)
618 #t))
619 (and lmod-curr
620 lmod-prev
621 (<= lmod-curr lmod-prev)
622 (begin
623 (log-debug "Last-Modified <= current skipping the rest of ~v" u-str)
624 #t))))
625 (if (not cached?)
68bbd2e9
SK
626 (begin
627 (log-debug
628 "Downloading the rest of ~v. ETag: ~a, Last-Modified: ~v"
629 u-str etag lmod)
630 (make-parent-directory* cached-object-path)
631 (make-parent-directory* cached-etag-path)
632 (make-parent-directory* cached-lmod-path)
633 (call-with-output-file cached-object-path
634 (curry copy-port body-input)
635 #:exists 'replace)
636 (when etag
637 (display-to-file etag cached-etag-path #:exists 'replace))
638 (when lmod
639 (display-to-file lmod cached-lmod-path #:exists 'replace))
640 'downloaded-new)
641 'skipped-cached))
7fd20778 642
1ecda371
SK
643(: url-download-http (-> Positive-Float Url Download-Result))
644(define (url-download-http timeout u)
f65d6338 645 (define u-str (url->string u))
f65d6338
SK
646 (define timeout-chan (make-channel))
647 (define result-chan (make-channel))
648 (define timeout-thread
649 (thread (λ ()
650 ; Doing this instead of sync/timeout to distinguish error values,
651 ; rather than just have #f to work with.
652 (sleep timeout)
7fd20778 653 (channel-put timeout-chan '(error . timeout)))))
f65d6338
SK
654 (define result-thread
655 (thread (λ ()
f65d6338
SK
656 (define result
657 (with-handlers
7fd20778
SK
658 ; TODO Maybe name each known errno? (exn:fail:network:errno-errno e)
659 ([exn:fail:network?
660 (λ (e) `(error . (net-error . ,e)))]
661 [exn?
662 (λ (e) `(error . (other . ,e)))])
f65d6338
SK
663 (define-values (status-line headers body-input)
664 (http-sendrecv/url
665 u
7296ed94 666 #:headers (list (format "User-Agent: ~a" user-agent-str))))
bb208ad5
SK
667 (log-debug "headers: ~v" headers)
668 (log-debug "status-line: ~v" status-line)
669 (define status
670 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
671 (log-debug "status: ~v" status)
672 (let ([result
673 ; TODO Handle redirects.
674 ; TODO Should a redirect update a peer URL?
675 (match status
676 [200
1ecda371 677 `(ok . ,(url-download-http-from-port u headers body-input))]
bb208ad5
SK
678 [_
679 `(error . (http-not-ok . ,status))])])
680 (close-input-port body-input)
681 result)))
f65d6338 682 (channel-put result-chan result))))
bb208ad5 683 (define result (sync timeout-chan result-chan))
f65d6338
SK
684 (kill-thread result-thread)
685 (kill-thread timeout-thread)
bb208ad5 686 result)
4764ff89 687
1ecda371
SK
688(: url-download (-> Positive-Float Url Download-Result))
689(define (url-download timeout u)
63805738
SK
690 (match (url-scheme u)
691 ; TODO Support Gopher.
692 [(or "http" "https")
1ecda371 693 (url-download-http timeout u)]
63805738
SK
694 [scheme
695 `(error . (unsupported-url-scheme . ,scheme))]))
696
98529d3d 697(: timeline-print (-> Out-Format (Listof Msg) Void))
b201e854 698(define (timeline-print out-format timeline)
0cb1ae9c
SK
699 (match timeline
700 ['()
701 (void)]
702 [(cons first-msg _)
703 (void (foldl (match-lambda**
704 [((and m (Msg _ _ from _ _)) (cons prev-from i))
705 (let ([i (if (peers-equal? prev-from from) i (+ 1 i))])
706 (msg-print out-format i m)
707 (cons from i))])
708 (cons (Msg-from first-msg) 0)
709 timeline))]))
4764ff89 710
dbc26280 711(: peer->msgs (-> Peer (Listof Msg)))
b056019b 712(define (peer->msgs peer)
1ecda371
SK
713 (match-define (Peer nick url url-str _) peer)
714 (log-debug "Reading peer nick:~v url:~v" nick url-str)
715 (define msgs-data (url-read-cached url))
4a23fd99 716 ; TODO Expire cache
fee11be9 717 (if msgs-data
0cb1ae9c 718 (str->msgs peer msgs-data)
fee11be9 719 '()))
4214c0f3 720
7fd20778
SK
721(: peer-download
722 (-> Positive-Float Peer
723 (Result (U 'skipped-cached 'downloaded-new)
724 Any)))
f65d6338 725(define (peer-download timeout peer)
1ecda371 726 (match-define (Peer nick url u _) peer)
7fd20778
SK
727 (log-info "Download BEGIN URL:~a" u)
728 (define-values (results _tm-cpu-ms tm-real-ms _tm-gc-ms)
1ecda371 729 (time-apply url-download (list timeout url)))
7fd20778
SK
730 (define result (car results))
731 (log-info "Download END in ~a seconds, URL:~a, result:~s"
732 (/ tm-real-ms 1000.0)
733 u
734 result)
735 result)
4214c0f3 736
dd098ae3 737(: timeline-download (-> Integer Positive-Float (Listof Peer) Void))
f65d6338 738(define (timeline-download num-workers timeout peers)
7fd20778
SK
739 (define results
740 (concurrent-filter-map num-workers
741 (λ (p) (cons p (peer-download timeout p)))
dd098ae3 742 peers))
d54812ea
SK
743 (define peers-ok
744 (filter-map (match-lambda
745 [(cons p (cons 'ok _)) p]
746 [(cons _ (cons 'error e)) #f])
747 results))
748 (define peers-err
749 (filter-map (match-lambda
750 [(cons _ (cons 'ok _))
751 #f]
752 [(cons p (cons 'error e))
753 (struct-copy Peer p [comment (format "~s" e)])])
754 results))
96412b0a
SK
755 (peers->file peers-ok (build-path tt-home-dir "peers-last-downloaded-ok.txt"))
756 (peers->file peers-err (build-path tt-home-dir "peers-last-downloaded-err.txt")))
9a6a9f9a 757
dd098ae3 758(: peers->timeline (-> (Listof Peer) (Listof Msg)))
a60c484e 759(define (peers->timeline peers)
dd098ae3 760 (append* (filter-map peer->msgs peers)))
a60c484e 761
e2840743 762(: timeline-sort (-> (Listof Msg) timeline-order (Listof Msgs)))
a60c484e 763(define (timeline-sort msgs order)
a4899240
SK
764 (define cmp (match order
765 ['old->new <]
766 ['new->old >]))
a60c484e
SK
767 (sort msgs (λ (a b) (cmp (Msg-ts-epoch a)
768 (Msg-ts-epoch b)))))
4764ff89 769
dd098ae3 770(: paths->peers (-> (Listof String) (Listof Peer)))
d0a0e073
SK
771(define (paths->peers paths)
772 (let* ([paths (match paths
773 ['()
96412b0a 774 (let ([peer-refs-file (build-path tt-home-dir "following.txt")])
d0a0e073
SK
775 (log-debug
776 "No peer ref file paths provided, defaulting to ~v"
777 (path->string peer-refs-file))
778 (list peer-refs-file))]
779 [paths
780 (log-debug "Peer ref file paths provided: ~v" paths)
781 (map string->path paths)])]
dd098ae3
SK
782 [peers (apply peers-merge (map file->peers paths))])
783 (log-info "Read-in ~a peers." (length peers))
e2840743 784 peers))
d0a0e073 785
50f0609d
SK
786(: cache-filename->peer (-> Path-String (Option Peer)))
787(define (cache-filename->peer filename)
788 (define nick #f) ; TODO Look it up in the nick-db when it exists.
789 (define url-str (uri-decode (path->string filename))) ; TODO Can these crash?
790 (match (str->url url-str)
791 [#f #f]
792 [url (Peer nick url url-str #f)]))
793
dd098ae3 794(: peers-cached (-> (Listof Peer)))
50f0609d
SK
795(define (peers-cached)
796 ; TODO Expire cache?
dd098ae3 797 (filter-map cache-filename->peer (directory-list cache-object-dir)))
50f0609d 798
dd098ae3 799(: peers-mentioned (-> (Listof Msg) (Listof Peer)))
50f0609d 800(define (peers-mentioned msgs)
dd098ae3 801 (append* (map Msg-mentions msgs)))
d3ac9e11 802
432a72b0
SK
803(: peers-filter-denied-domains (-> (Listof Peer) (Listof Peer)))
804(define (peers-filter-denied-domains peers)
805 (define deny-file (build-path tt-home-dir "domains-deny.txt"))
806 (define denied-hosts
807 (list->set (map string-trim (filter-comments (file->lines deny-file)))))
808 (define denied-domain-patterns
809 (set-map denied-hosts (λ (h) (pregexp (string-append "\\." h "$")))))
810 (filter
811 (λ (p)
1ecda371 812 (define host (url-host (Peer-url p)))
432a72b0
SK
813 (not (or (set-member? denied-hosts host)
814 (ormap (λ (d) (regexp-match? d host)) denied-domain-patterns))))
815 peers))
816
56de6228
SK
817(: log-writer-stop (-> Thread Void))
818(define (log-writer-stop log-writer)
819 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
820 (thread-wait log-writer))
821
0d3f753c
SK
822(: log-writer-start (-> Log-Level Thread))
823(define (log-writer-start level)
56de6228
SK
824 (let* ([logger
825 (make-logger #f #f level #f)]
826 [log-receiver
827 (make-log-receiver logger level)]
828 [log-writer
829 (thread
830 (λ ()
831 (parameterize
832 ([date-display-format 'iso-8601])
833 (let loop ()
834 (match-define (vector level msg _ topic) (sync log-receiver))
835 (unless (equal? topic 'stop)
836 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
837 (loop))))))])
838 (current-logger logger)
839 log-writer))
01e4c499 840
5fef9856 841(: msgs->nick-hist (-> (Listof Msg) Url-Nick-Hist))
651cf37d 842(define (msgs->nick-hist msgs)
5272d418 843 (foldl
651cf37d
SK
844 (λ (msg url->nick->hist)
845 (match-define (Msg curr _ from _ mentions) msg)
846 (foldl
847 (λ (peer url->nick->hist)
848 (match-define (Peer nick url _ _) peer)
849 (if nick
850 (hash-update url->nick->hist
851 url
852 (λ (nick->hist)
853 (hash-update nick->hist
854 nick
855 (match-lambda
856 [(Hist freq prev)
857 (Hist (+ 1 freq) (max prev curr))])
858 (Hist 0 0)))
859 (hash))
860 url->nick->hist))
861 url->nick->hist
862 (cons from mentions)))
5272d418 863 (hash)
651cf37d 864 msgs))
5272d418 865
5fef9856
SK
866(: url-nick-hist->file (-> Url-Nick-Hist Path-String Void))
867(define (url-nick-hist->file unh filepath)
8532efc9
SK
868 (define out (open-output-file filepath #:exists 'replace))
869 (for-each
870 (match-lambda
871 [(cons url nick->hist)
872 (displayln (url->string url) out)
873 (for-each (match-lambda
874 [(cons nick (Hist freq last))
875 (displayln (format " ~a ~a ~a" nick freq last) out)])
876 (sort (hash->list nick->hist)
877 (match-lambda**
878 [((cons _ (Hist a _)) (cons _ (Hist b _)))
879 (> a b)])))])
880 (sort
5fef9856 881 (hash->list unh)
8532efc9
SK
882 (λ (a b) (string<? (url-host (car a))
883 (url-host (car b))))))
884 (close-output-port out))
885
5fef9856
SK
886(: url-nick-hist->dir (-> Url-Nick-Hist Path-String Void))
887(define (url-nick-hist->dir unh dirpath)
5272d418 888 (hash-for-each
5fef9856 889 unh
651cf37d 890 (λ (url nick->hist)
96412b0a 891 (define filename (string-append (uri-encode (url->string url)) ".txt"))
8532efc9 892 (define filepath (build-path dirpath filename))
96412b0a 893 (make-parent-directory* filepath)
5272d418 894 (display-lines-to-file
651cf37d
SK
895 (map (match-lambda
896 [(cons nick (Hist freq last))
897 (format "~a ~a ~a" nick freq last)])
898 (sort (hash->list nick->hist)
899 (match-lambda**
900 [((cons _ (Hist a _)) (cons _ (Hist b _)))
901 (> a b)])))
96412b0a 902 filepath
5272d418
SK
903 #:exists 'replace))))
904
5fef9856
SK
905(: update-nicks-history-files (-> Url-Nick-Hist Void))
906(define (update-nicks-history-files unh)
8532efc9 907 (define nicks-dir (build-path tt-home-dir "nicks"))
5fef9856
SK
908 (url-nick-hist->file unh (build-path nicks-dir "seen.txt"))
909 (url-nick-hist->dir unh (build-path nicks-dir "seen")))
8532efc9 910
5fef9856
SK
911(: url-nick-hist-most-by (-> Url-Nick-Hist Url (-> Hist Nonnegative-Integer) (Option String)))
912(define (url-nick-hist-most-by url->nick->hist url by)
651cf37d
SK
913 (match (hash-ref url->nick->hist url #f)
914 [#f #f]
915 [nick->hist
916 (match (sort (hash->list nick->hist)
917 (λ (a b) (> (by (cdr a))
918 (by (cdr b)))))
919 ['() #f]
920 [(cons (cons nick _) _) nick])]))
921
5fef9856
SK
922(: url-nick-hist-latest (-> Url-Nick-Hist Url (Option String)))
923(define (url-nick-hist-latest unh url)
924 (url-nick-hist-most-by unh url Hist-last))
651cf37d 925
5fef9856
SK
926(: url-nick-hist-common (-> Url-Nick-Hist Url (Option String)))
927(define (url-nick-hist-common unh url)
928 (url-nick-hist-most-by unh url Hist-freq))
651cf37d 929
5fef9856
SK
930(: peers-update-nick-to-common (-> Url-Nick-Hist (Listof Peer) (Listof Peer)))
931(define (peers-update-nick-to-common unh peers)
49df5062
SK
932 (map
933 (λ (p)
1ecda371 934 (match (url-nick-hist-common unh (Peer-url p))
49df5062
SK
935 [#f p]
936 [n (struct-copy Peer p [nick n])]))
937 peers))
938
651cf37d
SK
939(module+ test
940 (let* ([url-str "http://foo"]
941 [url (string->url url-str)]
942 [nick1 "a"]
943 [nick2 "b"]
944 [nick3 "c"]
945 [ts-str-1 "2021-11-29T23:29:08-0500"]
946 [ts-str-2 "2021-11-29T23:30:00-0500"]
947 [ts-1 (rfc3339->epoch ts-str-1)]
948 [ts-2 (rfc3339->epoch ts-str-2)]
949 [msgs
950 (map (match-lambda
951 [(cons ts-str nick)
952 (str->msg (str->peer "test http://test")
953 (string-append ts-str " Hi @<" nick " " url-str ">"))])
954 (list (cons ts-str-2 nick1)
955 (cons ts-str-1 nick2)
956 (cons ts-str-1 nick2)
957 (cons ts-str-1 nick3)
958 (cons ts-str-1 nick3)
959 (cons ts-str-1 nick3)))]
960 [hist
961 (msgs->nick-hist msgs)])
962 (check-equal? (hash-ref (hash-ref hist url) nick1) (Hist 1 ts-2))
963 (check-equal? (hash-ref (hash-ref hist url) nick2) (Hist 2 ts-1))
964 (check-equal? (hash-ref (hash-ref hist url) nick3) (Hist 3 ts-1))
5fef9856
SK
965 (check-equal? (url-nick-hist-common hist url) nick3)
966 (check-equal? (url-nick-hist-latest hist url) nick1)))
651cf37d 967
e8856d5c
SK
968(: crawl (-> Void))
969(define (crawl)
dd098ae3 970 ; TODO Test the non-io parts of crawling
e2840743 971 (let* ([peers-all-file
96412b0a 972 (build-path pub-peers-dir "all.txt")]
e8856d5c 973 [peers-mentioned-file
96412b0a 974 (build-path pub-peers-dir "mentioned.txt")]
e8856d5c 975 [peers-parsed-file
96412b0a 976 (build-path pub-peers-dir "downloaded-and-parsed.txt")]
50f0609d 977 [peers-cached-file
96412b0a 978 (build-path pub-peers-dir "downloaded.txt")]
50f0609d
SK
979 [peers-cached
980 (peers-cached)]
981 [cached-timeline
982 (peers->timeline peers-cached)]
5fef9856 983 [url-nick-hist
49df5062 984 (msgs->nick-hist cached-timeline)]
e8856d5c 985 [peers-mentioned-curr
50f0609d 986 (peers-mentioned cached-timeline)]
e8856d5c
SK
987 [peers-mentioned-prev
988 (file->peers peers-mentioned-file)]
e8856d5c
SK
989 [peers-all-prev
990 (file->peers peers-all-file)]
5272d418 991 [peers-mentioned
49df5062
SK
992 (peers-merge peers-mentioned-prev
993 peers-mentioned-curr)]
e8856d5c 994 [peers-all
49df5062 995 (peers-update-nick-to-common
5fef9856 996 url-nick-hist
49df5062
SK
997 (peers-merge peers-mentioned
998 peers-all-prev
999 peers-cached))]
e8856d5c 1000 [peers-discovered
dd098ae3
SK
1001 (set->list (set-subtract (make-immutable-peers peers-all)
1002 (make-immutable-peers peers-all-prev)))]
e8856d5c 1003 [peers-parsed
dd098ae3 1004 (filter (λ (p) (> (length (peer->msgs p)) 0)) peers-all)])
e8856d5c 1005 ; TODO Deeper de-duping
dd098ae3
SK
1006 (log-info "Known peers cached ~a" (length peers-cached))
1007 (log-info "Known peers mentioned: ~a" (length peers-mentioned))
1008 (log-info "Known peers parsed ~a" (length peers-parsed))
1009 (log-info "Known peers total: ~a" (length peers-all))
e8856d5c 1010 (log-info "Discovered ~a new peers:~n~a"
dd098ae3 1011 (length peers-discovered)
e8856d5c 1012 (pretty-format (map
e2840743
SK
1013 (match-lambda
1014 [(Peer n _ u c) (list n u c)])
dd098ae3 1015 peers-discovered)))
5fef9856 1016 (update-nicks-history-files url-nick-hist)
50f0609d
SK
1017 (peers->file peers-cached
1018 peers-cached-file)
e8856d5c
SK
1019 (peers->file peers-mentioned
1020 peers-mentioned-file)
1021 (peers->file peers-parsed
1022 peers-parsed-file)
1023 (peers->file peers-all
1024 peers-all-file)))
1025
1026(: read (-> (Listof String) Number Number Timeline-Order Out-Format Void))
1027(define (read file-paths ts-min ts-max order out-format)
1028 (let* ([peers
1029 (paths->peers file-paths)]
1030 [msgs
1031 (timeline-sort (peers->timeline peers) order)]
1032 [include?
1033 (λ (m)
1034 (and (or (not ts-min) (>= (Msg-ts-epoch m) ts-min))
1035 (or (not ts-max) (<= (Msg-ts-epoch m) ts-max))))])
1036 (timeline-print out-format (filter include? msgs))))
1037
1038(: upload (-> Void))
1039(define (upload)
1040 ; FIXME Should not exit from here, but only after cleanup/logger-stoppage.
1041 (if (system (path->string (build-path tt-home-dir "hooks" "upload")))
1042 (exit 0)
1043 (exit 1)))
1044
1045(: download (-> (Listof String) Positive-Integer Positive-Float Void))
1046(define (download file-paths num-workers timeout)
432a72b0
SK
1047 (let* ([peers-given (paths->peers file-paths)]
1048 [peers-kept (peers-filter-denied-domains peers-given)]
1049 [peers-denied (set-subtract peers-given peers-kept)])
1050 (log-info "Denied ~a peers" (length peers-denied))
e8856d5c 1051 (define-values (_res _cpu real-ms _gc)
432a72b0 1052 (time-apply timeline-download (list num-workers timeout peers-kept)))
e8856d5c 1053 (log-info "Downloaded timelines from ~a peers in ~a seconds."
432a72b0 1054 (length peers-kept)
e8856d5c
SK
1055 (/ real-ms 1000.0))))
1056
1057(: dispatch (-> String Void))
1058(define (dispatch command)
1059 (match command
1060 [(or "d" "download")
5b27fc74 1061 (let ([num-workers 20] ; 20 was fastest out of the tried: 1, 5, 10, 20, 25, 30.
e8856d5c
SK
1062 [timeout 10.0])
1063 (command-line
1064 #:program "tt download"
1065 #:once-each
1066 [("-j" "--jobs")
1067 njobs "Number of concurrent jobs."
1068 (set! num-workers (string->number njobs))]
1069 [("-t" "--timeout")
1070 seconds "Timeout seconds per request."
1071 (set! timeout (string->number seconds))]
1072 #:args file-paths
1073 (download file-paths num-workers timeout)))]
1074 [(or "u" "upload")
1075 (command-line
1076 #:program "tt upload" #:args () (upload))]
1077 [(or "r" "read")
1078 (let ([out-format 'multi-line]
1079 [order 'old->new]
1080 [ts-min #f]
1081 [ts-max #f])
1082 (command-line
1083 #:program "tt read"
1084 #:once-each
1085 [("-r" "--rev")
1086 "Reverse displayed timeline order."
1087 (set! order 'new->old)]
1088 [("-m" "--min")
1089 m "Earliest time to display (ignore anything before it)."
1090 (set! ts-min (rfc3339->epoch m))]
1091 [("-x" "--max")
1092 x "Latest time to display (ignore anything after it)."
1093 (set! ts-max (rfc3339->epoch x))]
1094 #:once-any
1095 [("-s" "--short")
1096 "Short output format"
1097 (set! out-format 'single-line)]
1098 [("-l" "--long")
1099 "Long output format"
1100 (set! out-format 'multi-line)]
1101 #:args file-paths
1102 (read file-paths ts-min ts-max order out-format)))]
1103 [(or "c" "crawl")
1104 (command-line
1105 #:program "tt crawl" #:args () (crawl))]
1106 [command
1107 (eprintf "Error: invalid command: ~v\n" command)
1108 (eprintf "Please use the \"--help\" option to see a list of available commands.\n")
1109 (exit 1)]))
1110
24c6a76b 1111(module+ main
24f1f64b 1112 (let ([log-level 'info])
c562bea3 1113 (command-line
24f1f64b
SK
1114 #:program
1115 "tt"
c562bea3 1116 #:once-each
01e4c499
SK
1117 [("-d" "--debug")
1118 "Enable debug log level."
1119 (set! log-level 'debug)]
24f1f64b
SK
1120 #:help-labels
1121 ""
1122 "and <command> is one of"
a60c484e 1123 "r, read : Read the timeline (offline operation)."
4214c0f3 1124 "d, download : Download the timeline."
edadb804 1125 ; TODO Add path dynamically
0868c39a 1126 "u, upload : Upload your twtxt file (alias to execute ~/.tt/hooks/upload)."
a60c484e 1127 "c, crawl : Discover new peers mentioned by known peers (offline operation)."
24f1f64b
SK
1128 ""
1129 #:args (command . args)
0d3f753c 1130 (define log-writer (log-writer-start log-level))
4214c0f3 1131 (current-command-line-arguments (list->vector args))
96412b0a 1132 (set-user-agent-str (build-path tt-home-dir "user.txt"))
e8856d5c
SK
1133 ; TODO dispatch should return status with which we should exit after cleanups
1134 (dispatch command)
0d3f753c 1135 (log-writer-stop log-writer))))
This page took 0.202488 seconds and 4 git commands to generate.