1 #lang typed/racket/no-check
11 (require (prefix-in info: "info.rkt"))
19 (define-type Out-Format
23 (define-type Timeline-Order
30 [nick : (Option String)]
33 [mentions : (Listof Feed)])
37 ([nick : (Option String)]
41 (: tt-home-dir Path-String)
42 (define tt-home-dir (build-path (expand-user-path "~") ".tt"))
44 (: concurrent-filter-map (∀ (α β) (-> Natural (-> α β) (Listof α))))
45 (define (concurrent-filter-map num-workers f xs)
46 ; TODO preserve order of elements OR communicate that reorder is expected
47 ; TODO switch from mailboxes to channels
48 (define (make-worker id f)
49 (define parent (current-thread))
51 (define self : Thread (current-thread))
52 (: work (∀ (α) (-> α)))
54 (thread-send parent (cons 'next self))
55 (match (thread-receive)
56 ['done (thread-send parent (cons 'exit id))]
57 [(cons 'unit x) (begin
59 (when y (thread-send parent (cons 'result y)))
62 (: dispatch (∀ (α β) (-> (Listof Nonnegative-Integer) (Listof α) (Listof β))))
63 (define (dispatch ws xs ys)
66 (match (thread-receive)
67 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
68 [(cons 'result y) (dispatch ws xs (cons y ys))]
69 [(cons 'next thd) (match xs
71 (thread-send thd 'done)
74 (thread-send thd (cons 'unit x))
75 (dispatch ws xs ys))])])))
76 (define workers (range num-workers))
77 (define threads (map (λ (id) (thread (make-worker id f))) workers))
78 (define results (dispatch workers xs '()))
79 (for-each thread-wait threads)
83 (let* ([f (λ (x) (if (even? x) x #f))]
85 [actual (sort (concurrent-filter-map 10 f xs) <)]
86 [expected (sort ( filter-map f xs) <)])
87 (check-equal? actual expected "concurrent-filter-map")))
89 (: msg-print (-> Out-Format Integer Msg Void))
91 (let* ([colors (vector 36 33)]
92 [n (vector-length colors)])
93 (λ (out-format color-i msg)
94 (let ([color (vector-ref colors (modulo color-i n))]
96 [uri (url->string (msg-uri msg))]
98 [mentions (msg-mentions msg)])
101 (let ([nick (if nick nick uri)])
102 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
104 ([date-display-format 'iso-8601])
105 (date->string (seconds->date [msg-ts-epoch msg]) #t))
108 (let ([nick (if nick (string-append nick " ") "")])
109 (printf "~a (~a)~n\033[1;37m<~a~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
111 ([date-display-format 'rfc2822])
112 (date->string (seconds->date [msg-ts-epoch msg]) #t))
114 nick uri color text))])))))
116 (: rfc3339->epoch (-> String (Option Nonnegative-Integer)))
117 (define rfc3339->epoch
118 (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}))?$")])
120 (match (regexp-match re ts)
121 [(list _wholething yyyy mm dd HH MM _:SS SS _fractional tz-whole tz-sign tz-HH tz-MM)
124 (match* (tz-whole tz-sign tz-HH tz-MM)
127 [(_ (or "-" "+") (? identity h) (? identity m))
128 (let ([h (string->number h)]
129 [m (string->number m)]
130 ; Reverse to get back to UTC:
131 [op (match tz-sign ["+" -] ["-" +])])
132 (op 0 (+ (* 60 m) (* 60 (* 60 h)))))]
134 (log-warning "Impossible TZ string: ~v, components: ~v ~v ~v ~v" tz-whole a b c d)
138 [ts-epoch (find-seconds (if SS (string->number SS) 0)
143 (string->number yyyy)
145 (+ ts-epoch tz-offset))]
147 (log-error "Invalid timestamp: ~v" ts)
150 (: str->msg (-> (Option String) Url String (Option Msg)))
152 (let ([re (pregexp "^([^\\s\t]+)[\\s\t]+(.*)$")])
158 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
159 str nick (url->string uri) e)
161 (match (regexp-match re str)
162 [(list _wholething ts-orig text)
163 (let ([ts-epoch (rfc3339->epoch ts-orig)])
167 (λ (m) (match (regexp-match #px"@<([^>]+)>" m)
168 [(list _wholething nick-uri)
169 (str->feed nick-uri)]))
170 (regexp-match* #px"@<[^\\s]+([\\s]+)?[^>]+>" text))])
171 (msg ts-epoch ts-orig nick uri text mentions))
174 "Msg rejected due to invalid timestamp: ~v, nick:~v, uri:~v"
175 str nick (url->string uri))
178 (log-debug "Non-msg line from nick:~v, line:~a" nick str)
182 ; TODO Test for when missing-nick case
183 (let* ([tzs (for*/list ([d '("-" "+")]
185 [m '("00" ":00" "57" ":57")])
186 (string-append d h m))]
187 [tzs (list* "" "Z" tzs)])
188 (for* ([n '("fake-nick")]
193 [sep (list "\t" " ")]
194 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
195 (let* ([ts (string-append "2020-11-18T22:22"
196 (if (non-empty-string? s) s ":00")
198 [m (str->msg n u (string-append ts sep txt))])
200 (check-equal? (msg-nick m) n)
201 (check-equal? (msg-uri m) u)
202 (check-equal? (msg-text m) txt)
203 (check-equal? (msg-ts-orig m) ts (format "Given: ~v" ts))
206 (let* ([ts "2020-11-18T22:22:09-0500"]
211 [actual (str->msg nick uri (string-append ts tab text))]
212 [expected (msg 1605756129 ts nick uri text)])
214 (msg-ts-epoch actual)
215 (msg-ts-epoch expected)
219 (msg-ts-orig expected)
234 (: str->lines (-> String (Listof String)))
235 (define (str->lines str)
236 (string-split str (regexp "[\r\n]+")))
239 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
241 (: str->msgs (-> (Option String) Url String (Listof Msg)))
242 (define (str->msgs nick uri str)
243 (filter-map (λ (line) (str->msg nick uri line)) (filter-comments (str->lines str))))
245 (: cache-dir Path-String)
246 (define cache-dir (build-path tt-home-dir "cache"))
248 (: url->cache-file-path-v1 (-> Url Path-String))
249 (define (url->cache-file-path-v1 uri)
250 (define (hash-sha1 str) : (-> String String)
251 (define in (open-input-string str))
252 (define digest (sha1 in))
253 (close-input-port in)
255 (build-path cache-dir (hash-sha1 (url->string uri))))
257 (: url->cache-file-path-v2 (-> Url Path-String))
258 (define (url->cache-file-path-v2 uri)
259 (build-path cache-dir (uri-encode (url->string uri))))
261 (define url->cache-file-path url->cache-file-path-v2)
264 (: uri-read-cached (-> Url String))
265 (define (uri-read-cached uri)
266 (define path-v1 (url->cache-file-path-v1 uri))
267 (define path-v2 (url->cache-file-path-v2 uri))
268 (when (file-exists? path-v1)
269 (rename-file-or-directory path-v1 path-v2 #t))
270 (if (file-exists? path-v2)
271 (file->string path-v2)
273 (log-warning "Cache file not found for URI: ~a" (url->string uri))
276 (: str->feed (String (Option Feed)))
277 (define (str->feed str)
278 (log-debug "Parsing feed string: ~v" str)
282 (log-error "Invalid URI in string: ~v, exn: ~v" str e)
284 (match (string-split str)
285 [(list u) (feed #f (string->url u))]
286 [(list n u) (feed n (string->url u))]
288 (log-error "Invalid feed string: ~v" str)
292 (: filter-comments (-> (Listof String) (Listof String)))
293 (define (filter-comments lines)
294 (filter-not (λ (line) (string-prefix? line "#")) lines))
296 (: str->feeds (-> String (Listof Feed)))
297 (define (str->feeds str)
298 (filter-map str->feed (filter-comments (str->lines str))))
300 (: file->feeds (-> Path-String (Listof Feed)))
301 (define (file->feeds filename)
302 (str->feeds (file->string filename)))
304 (: user-agent String)
308 [prog-version (info:#%info-lookup 'version)]
309 [prog-uri "https://github.com/xandkar/tt"]
310 [user-feed-file (build-path tt-home-dir "me")]
312 (if (file-exists? user-feed-file)
313 (match (first (file->feeds user-feed-file))
314 [(feed #f u) (format "+~a" (url->string u) )]
315 [(feed n u) (format "+~a; @~a" (url->string u) n)])
316 (format "+~a" prog-uri))])
317 (format "~a/~a (~a)" prog-name prog-version user)))
319 (: uri-download (-> Url Void))
320 (define (uri-download u)
321 (define cache-file-path (url->cache-file-path u))
322 (log-debug "uri-download ~v into ~v" u cache-file-path)
323 (match* ((url-scheme u) (url-host u) (url-port u))
326 (define ssl? (string=? s "https"))
327 (define-values (status-line headers body-input)
328 ; TODO Timeout. Currently hangs on slow connections.
331 (url->string (struct-copy url u [scheme #f] [host #f]))
333 #:port (cond [p p] [ssl? 443] [else 80])
334 #:headers (list (format "User-Agent: ~a" user-agent))
336 (log-debug "headers: ~v" headers)
337 (log-debug "status-line: ~v" status-line)
339 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
340 (log-debug "status: ~v" status)
341 ; TODO Handle redirects
344 (make-parent-directory* cache-file-path)
345 (call-with-output-file cache-file-path
346 (curry copy-port body-input)
350 (log-error "Invalid URI: ~v" u)]))
352 (: timeline-print (-> Out-Format (Listof Msg) Void))
353 (define (timeline-print out-format timeline)
354 (void (foldl (match-lambda**
355 [((and m (msg _ _ nick _ _ _)) (cons prev-nick i))
356 (let ([i (if (equal? prev-nick nick) i (+ 1 i))])
357 (msg-print out-format i m)
362 (: feed->msgs (-> Feed (Listof Msg)))
363 (define (feed->msgs f)
364 (match-define (feed nick uri) f)
365 (log-info "Reading feed nick:~v uri:~v" nick (url->string uri))
366 (str->msgs nick uri (uri-read-cached uri)))
368 (: feed-download (-> Feed Void))
369 (define (feed-download f)
370 (match-define (feed nick uri) f)
371 (define u (url->string uri))
372 (log-info "Downloading feed uri:~a" u)
376 (log-error "Network error nick:~v uri:~v exn:~v" nick u e)
380 (log-error "HTTP error nick:~v uri:~a status:~a" nick u status)
382 (define-values (_result _tm-cpu-ms tm-real-ms _tm-gc-ms)
383 (time-apply uri-download (list uri)))
384 (log-info "Feed downloaded in ~a seconds, uri: ~a" (/ tm-real-ms 1000.0) u)))
386 (: timeline-download (-> Integer (Listof Feed) Void))
387 (define (timeline-download num-workers feeds)
388 ; TODO No need for map - can just iter
389 (void (concurrent-filter-map num-workers feed-download feeds)))
391 ; TODO timeline contract : time-sorted list of messages
392 (: timeline-read (-> Timeline-Order (Listof Feed) (Listof Msg)))
393 (define (timeline-read order feeds)
394 (define cmp (match order
397 (sort (append* (filter-map feed->msgs feeds))
398 (λ (a b) (cmp (msg-ts-epoch a) (msg-ts-epoch b)))))
400 (: log-writer-stop (-> Thread Void))
401 (define (log-writer-stop log-writer)
402 (log-message (current-logger) 'fatal 'stop "Exiting." #f)
403 (thread-wait log-writer))
405 (: logger-start (-> Log-Level Thread))
406 (define (logger-start level)
408 (make-logger #f #f level #f)]
410 (make-log-receiver logger level)]
415 ([date-display-format 'iso-8601])
417 (match-define (vector level msg _ topic) (sync log-receiver))
418 (unless (equal? topic 'stop)
419 (eprintf "~a [~a] ~a~n" (date->string (current-date) #t) level msg)
421 (current-logger logger)
425 (let ([log-level 'info])
431 "Enable debug log level."
432 (set! log-level 'debug)]
435 "and <command> is one of"
436 "r, read i : Read the timeline."
437 "d, download : Download the timeline."
438 ; TODO Add path dynamically
439 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
441 #:args (command . args)
442 (define log-writer (logger-start log-level))
443 (current-command-line-arguments (list->vector args))
446 ; Initially, 15 was fastest out of the tried: 1, 5, 10, 20. Then I
447 ; started noticing significant slowdowns. Reducing to 5 seems to help.
448 (let ([num-workers 5])
454 njobs "Number of concurrent jobs."
455 (set! num-workers (string->number njobs))]
457 (define-values (_res _cpu real-ms _gc)
458 (time-apply timeline-download (list num-workers (file->feeds filename))))
459 (log-info "Timeline downloaded in ~a seconds." (/ real-ms 1000.0))
460 (log-writer-stop log-writer)))]
466 (if (system (path->string (build-path tt-home-dir "upload")))
470 (let ([out-format 'multi-line]
477 "Reverse displayed timeline order."
478 (set! order 'new->old)]
481 "Short output format"
482 (set! out-format 'single-line)]
485 (set! out-format 'multi-line)]
487 (timeline-print out-format (timeline-read order (file->feeds filename)))))]