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