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