Forgive common format errors
[tt.git] / tt.rkt
CommitLineData
4764ff89
SK
1#lang racket
2
1d753430 3(require openssl/sha1)
4764ff89
SK
4(require racket/date)
5
6(require http-client)
7(require rfc3339-old)
8
78398948 9(module+ test
de3ff448 10 (require rackunit))
78398948 11
87d0eb92 12(struct msg (ts_epoch ts_rfc3339 nick uri text))
4764ff89
SK
13(struct feed (nick uri))
14
895a32cf 15(define (concurrent-filter-map num_workers f xs)
dad4504d 16 ; TODO preserve order of elements OR communicate that reorder is expected
a239a233 17 ; TODO switch from mailboxes to channels
895a32cf
SK
18 (define (make-worker id f)
19 (define parent (current-thread))
20 (λ ()
21 (define self (current-thread))
22 (define (work)
23 (thread-send parent (cons 'next self))
24 (match (thread-receive)
c562bea3
SK
25 ['done (thread-send parent (cons 'exit id))]
26 [(cons 'unit x) (begin
27 (define y (f x))
28 (when y (thread-send parent (cons 'result y)))
29 (work))]))
895a32cf
SK
30 (work)))
31 (define (dispatch ws xs ys)
32 (if (empty? ws)
f1493e49
SK
33 ys
34 (match (thread-receive)
c562bea3
SK
35 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
36 [(cons 'result y) (dispatch ws xs (cons y ys))]
37 [(cons 'next thd) (match xs
38 ['() (begin
39 (thread-send thd 'done)
40 (dispatch ws xs ys))]
41 [(cons x xs) (begin
42 (thread-send thd (cons 'unit x))
43 (dispatch ws xs ys))])])))
9926c9a9
SK
44 (define workers (range num_workers))
45 (define threads (map (λ (id) (thread (make-worker id f))) workers))
46 (define results (dispatch workers xs '()))
895a32cf
SK
47 (for-each thread-wait threads)
48 results)
49
dad4504d 50(module+ test
de3ff448
SK
51 (let* ([f (λ (x) (if (even? x) x #f))]
52 [xs (range 11)]
53 [actual (sort (concurrent-filter-map 10 f xs) <)]
54 [expected (sort ( filter-map f xs) <)])
c562bea3 55 (check-equal? actual expected "concurrent-filter-map")))
dad4504d 56
3d042e75
SK
57(define msg-print
58 (let* ([colors (vector 36 33)]
59 [n (vector-length colors)])
60 (λ (out-format color-i msg)
01e4c499
SK
61 (let ([color (vector-ref colors (modulo color-i n))]
62 [nick (msg-nick msg)]
63 [uri (msg-uri msg)]
64 [text (msg-text msg)])
3d042e75 65 (match out-format
01e4c499
SK
66 ['single-line
67 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
68 (parameterize ([date-display-format 'iso-8601])
69 (date->string (seconds->date [msg-ts_epoch msg]) #t))
70 nick color text)]
71 ['multi-line
72 (printf "~a~n\033[1;37m<~a ~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
73 (parameterize ([date-display-format 'rfc2822])
74 (date->string (seconds->date [msg-ts_epoch msg]) #t))
75 nick uri color text)])))))
e96264cc 76
b4689464
SK
77(define str->msg
78 (let ([re (pregexp "^([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}(:[0-9]{2})?)(\\.[0-9]+)?([^\\s\t]*)[\\s\t]+(.*)$")])
79 (λ (nick uri str)
80 (with-handlers*
81 ([exn:fail?
82 (λ (e)
83 (log-error "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v" str nick uri e)
84 #f)])
85 (match (regexp-match re str)
86 [(list _wholething ts s _fractional tz text)
c562bea3 87 (let*
b4689464 88 ([ts_rfc3339 (string-append ts (if s "" ":00") (if tz tz ""))]
c562bea3 89 [t (string->rfc3339-record ts_rfc3339)]
b4689464 90 [s (rfc3339-record:second t)]
c562bea3 91 ; TODO handle tz offset
b4689464 92 [ts_epoch (find-seconds [if s s 0]
c562bea3
SK
93 [rfc3339-record:minute t]
94 [rfc3339-record:hour t]
95 [rfc3339-record:mday t]
96 [rfc3339-record:month t]
97 [rfc3339-record:year t])])
b4689464
SK
98 (msg ts_epoch ts_rfc3339 nick uri text))]
99 [_
100 (log-debug "Non-msg line from nick:~a, line:~a" nick str)
101 #f])))))
88d50b3e 102
63afa259 103(module+ test
b4689464
SK
104 (let* ([tzs (for*/list ([d '("-" "+")]
105 [h '("5" "05")]
106 [m '("00" ":00" "57" ":57")])
107 (string-append d h m))]
108 [tzs (list* "" "Z" tzs)])
109 (for* ([n '("fake-nick")]
110 [u '("fake-uri")]
111 [s '("" ":10")]
112 [f '("" ".1337")]
113 [z tzs]
114 [sep (list "\t" " ")]
115 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
116 (let* ([ts (string-append "2020-11-18T22:22"
117 (if (non-empty-string? s) s ":00")
118 z)]
119 [m (str->msg n u (string-append ts sep txt))])
120 (check-not-false m)
121 (check-equal? (msg-nick m) n)
122 (check-equal? (msg-uri m) u)
123 (check-equal? (msg-text m) txt)
124 (check-equal? (msg-ts_rfc3339 m) ts (format "Given: ~v" ts))
125 )))
126
de3ff448
SK
127 (let* ([ts "2020-11-18T22:22:09-0500"]
128 [tab " "]
129 [text "Lorem ipsum"]
130 [nick "foo"]
131 [uri "bar"]
132 [actual (str->msg nick uri (string-append ts tab text))]
133 [expected (msg 1605756129 ts nick uri text)])
c562bea3
SK
134 ; FIXME re-enable after handling tz offset
135 ;(check-equal?
136 ; (msg-ts_epoch actual)
137 ; (msg-ts_epoch expected)
138 ; "str->msg ts_epoch")
139 (check-equal?
140 (msg-ts_rfc3339 actual)
141 (msg-ts_rfc3339 expected)
142 "str->msg ts_rfc3339")
143 (check-equal?
144 (msg-nick actual)
145 (msg-nick expected)
146 "str->msg nick")
147 (check-equal?
148 (msg-uri actual)
149 (msg-uri expected)
150 "str->msg uri")
151 (check-equal?
152 (msg-text actual)
153 (msg-text expected)
154 "str->msg text")))
63afa259 155
e96264cc
SK
156(define (str->lines str)
157 (string-split str (regexp "[\r\n]+")))
158
63afa259 159(module+ test
de3ff448 160 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
63afa259 161
b201e854
SK
162(define (str->msgs nick uri str)
163 (filter-map (λ (line) (str->msg nick uri line)) (str->lines str)))
4764ff89 164
1d753430
SK
165(define (hash-sha1 str)
166 (define in (open-input-string str))
167 (define digest (sha1 in))
168 (close-input-port in)
169 digest)
170
0e16a46c
SK
171(define (uri-fetch use-cache uri)
172 (define cache-file-path
173 (expand-user-path (string-append "~/.tt/cache/" (hash-sha1 uri))))
174 (if (and use-cache (file-exists? cache-file-path))
175 (begin
176 (log-info "uri-fetch cached ~a" uri)
177 (file->string cache-file-path))
178 (begin
179 (log-info "uri-fetch new ~a" uri)
01e4c499 180 ; TODO Timeout. Currently hangs on slow connections.
0e16a46c
SK
181 (let* ([resp (http-get uri)]
182 [status (http-response-code resp)]
183 [body (http-response-body resp)])
c562bea3
SK
184 (log-debug "finished GET ~a status:~a body length:~a"
185 uri status (string-length body))
186 ; TODO Handle redirects
187 (if (= status 200)
188 (begin
189 (display-to-file body cache-file-path #:exists 'replace)
190 body)
191 ; TODO A more-informative exception
192 (raise status))))))
4764ff89 193
b201e854 194(define (timeline-print out-format timeline)
3d042e75
SK
195 (void (foldl (match-lambda**
196 [((and m (msg _ _ nick _ _)) (cons prev-nick i))
197 (let ([i (if (string=? prev-nick nick) i (+ 1 i))])
198 (msg-print out-format i m)
199 (cons nick i))])
200 (cons "" 0)
201 timeline)))
4764ff89 202
0e16a46c 203(define (feed->msgs use-cache feed)
9a6a9f9a
SK
204 (log-info "downloading feed nick:~a uri:~a"
205 (feed-nick feed)
206 (feed-uri feed))
207 (with-handlers
208 ([exn:fail:network?
209 (λ (e)
210 (log-error "network error nick:~a uri:~a exn:~a"
211 (feed-nick feed)
212 (feed-uri feed)
213 e)
214 #f)]
215 [integer?
216 (λ (status)
217 (log-error "http error nick:~a uri:~a status:~a"
218 (feed-nick feed)
219 (feed-uri feed)
220 status)
221 #f)])
b201e854 222 (define uri (feed-uri feed))
0e16a46c 223 (str->msgs [feed-nick feed] uri [uri-fetch use-cache uri])))
9a6a9f9a
SK
224
225; TODO timeline contract : time-sorted list of messages
0e16a46c
SK
226(define (timeline use-cache num_workers feeds)
227 (sort (append* (concurrent-filter-map num_workers (curry feed->msgs use-cache) feeds))
87d0eb92 228 (λ (a b) [< (msg-ts_epoch a) (msg-ts_epoch b)])))
4764ff89 229
be96956c
SK
230(define (str->feed str)
231 ; TODO validation
232 (define toks (string-split str))
87d0eb92 233 (apply feed toks))
be96956c 234
4a94ef7b
SK
235(define (filter-comments lines)
236 (filter-not (λ (line) (string-prefix? line "#")) lines))
237
be96956c 238(define (str->feeds str)
4a94ef7b 239 (map str->feed (filter-comments (str->lines str))))
be96956c
SK
240
241(define (file->feeds filename)
242 (str->feeds (file->string filename)))
243
4f3dbb24 244(define (user-agent prog-name prog-version)
24c6a76b 245 (let*
4f3dbb24 246 ([prog-uri "https://github.com/xandkar/tt"]
24c6a76b
SK
247 [user-feed-file (expand-user-path "~/twtxt-me.txt")]
248 [user
249 (if (file-exists? user-feed-file)
f1493e49 250 (let ([user (first (file->feeds user-feed-file))])
c562bea3 251 (format "+~a; @~a" (feed-uri user) (feed-nick user)))
f1493e49 252 (format "+~a" prog-uri))]
24c6a76b
SK
253 )
254 (format "~a/~a (~a)" prog-name prog-version user)))
255
01e4c499
SK
256(define (start-logger level)
257 (let* ([logger (make-logger #f #f level #f)]
258 [log-receiver (make-log-receiver logger level)])
259 (void (thread (λ ()
260 (parameterize
261 ([date-display-format 'iso-8601])
262 (let loop ()
263 (define data (sync log-receiver))
264 (define level (vector-ref data 0))
265 (define msg (vector-ref data 1))
266 (define ts (date->string (current-date) #t))
267 (eprintf "~a [~a] ~a~n" ts level msg)
268 (loop))))))
269 (current-logger logger)))
270
24c6a76b 271(module+ main
de3ff448 272 (require setup/getinfo)
26d172a9 273
dd3fa56a 274 (current-http-client/response-auto #f)
de3ff448
SK
275 (let* ([prog-name "tt"]
276 [prog-version ((get-info (list prog-name)) 'version)]
277 [user-agent (user-agent prog-name prog-version)])
dd3fa56a 278 (current-http-client/user-agent user-agent))
de3ff448
SK
279 (let* ([use-cache
280 #f]
01e4c499
SK
281 [log-level
282 'info]
de3ff448
SK
283 [out-format
284 'multi-line]
285 [num_workers
286 15]) ; 15 was fastest out of the tried 1, 5, 10, 15 and 20.
c562bea3
SK
287 (command-line
288 #:once-each
289 [("-c" "--cached")
290 "Read cached data instead of downloading."
291 (set! use-cache #t)]
0e16a46c 292
01e4c499
SK
293 [("-d" "--debug")
294 "Enable debug log level."
295 (set! log-level 'debug)]
296
c562bea3
SK
297 [("-j" "--jobs")
298 njobs "Number of concurrent jobs."
299 (set! num_workers (string->number njobs))]
0e16a46c 300
01e4c499
SK
301 #:once-any
302 [("-s" "--short")
303 "Short output format"
304 (set! out-format 'single-line)]
0e16a46c 305
01e4c499
SK
306 [("-l" "--long")
307 "Long output format"
308 (set! out-format 'multi-line)]
309
310 #:args (filename)
311 (start-logger log-level)
c562bea3
SK
312 (timeline-print out-format
313 (timeline use-cache
314 num_workers
315 (file->feeds filename))))))
This page took 0.077051 seconds and 4 git commands to generate.