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