Use lang typed/racket/no-check
[tt.git] / tt.rkt
1 #lang typed/racket/no-check
2
3 (require openssl/sha1)
4 (require racket/date)
5 (require
6 net/http-client
7 net/url-string
8 net/url-structs)
9
10 (require (prefix-in info: "info.rkt"))
11
12 (module+ test
13 (require rackunit))
14
15 (struct msg
16 ([ts_epoch : Integer]
17 [ts_rfc3339 : String]
18 [nick : String]
19 [uri : net/url-structs:url]
20 [text : String]))
21
22 (struct feed
23 ([nick : String]
24 [uri : net/url-structs:url]))
25
26 (define (concurrent-filter-map num_workers f xs)
27 ; TODO preserve order of elements OR communicate that reorder is expected
28 ; TODO switch from mailboxes to channels
29 (define (make-worker id f)
30 (define parent (current-thread))
31 (λ ()
32 (define self (current-thread))
33 (define (work)
34 (thread-send parent (cons 'next self))
35 (match (thread-receive)
36 ['done (thread-send parent (cons 'exit id))]
37 [(cons 'unit x) (begin
38 (define y (f x))
39 (when y (thread-send parent (cons 'result y)))
40 (work))]))
41 (work)))
42 (define (dispatch ws xs ys)
43 (if (empty? ws)
44 ys
45 (match (thread-receive)
46 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
47 [(cons 'result y) (dispatch ws xs (cons y ys))]
48 [(cons 'next thd) (match xs
49 ['() (begin
50 (thread-send thd 'done)
51 (dispatch ws xs ys))]
52 [(cons x xs) (begin
53 (thread-send thd (cons 'unit x))
54 (dispatch ws xs ys))])])))
55 (define workers (range num_workers))
56 (define threads (map (λ (id) (thread (make-worker id f))) workers))
57 (define results (dispatch workers xs '()))
58 (for-each thread-wait threads)
59 results)
60
61 (module+ test
62 (let* ([f (λ (x) (if (even? x) x #f))]
63 [xs (range 11)]
64 [actual (sort (concurrent-filter-map 10 f xs) <)]
65 [expected (sort ( filter-map f xs) <)])
66 (check-equal? actual expected "concurrent-filter-map")))
67
68 (define msg-print
69 (let* ([colors (vector 36 33)]
70 [n (vector-length colors)])
71 (λ (out-format color-i msg)
72 (let ([color (vector-ref colors (modulo color-i n))]
73 [nick (msg-nick msg)]
74 [uri (url->string (msg-uri msg))]
75 [text (msg-text msg)])
76 (match out-format
77 ['single-line
78 (printf "~a \033[1;37m<~a>\033[0m \033[0;~am~a\033[0m~n"
79 (parameterize ([date-display-format 'iso-8601])
80 (date->string (seconds->date [msg-ts_epoch msg]) #t))
81 nick color text)]
82 ['multi-line
83 (printf "~a~n\033[1;37m<~a ~a>\033[0m~n\033[0;~am~a\033[0m~n~n"
84 (parameterize ([date-display-format 'rfc2822])
85 (date->string (seconds->date [msg-ts_epoch msg]) #t))
86 nick uri color text)])))))
87
88 (define str->msg
89 ; TODO Split parsing into 2 stages: 1) line->list; 2) rfc3339->epoch.
90 (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]+(.*)$")])
91 (λ (nick uri str)
92 (with-handlers*
93 ([exn:fail?
94 (λ (e)
95 (log-error
96 "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v"
97 str nick (url->string uri) e)
98 #f)])
99 (match (regexp-match re str)
100 [(list _wholething ts yyyy mm dd HH MM _:SS SS _f tz text)
101 (let*
102 ; TODO handle tz offset
103 ([ts_rfc3339 (string-append ts (if SS "" ":00") (if tz tz ""))]
104 [ts_epoch (find-seconds (if SS (string->number SS) 0)
105 (string->number MM)
106 (string->number HH)
107 (string->number dd)
108 (string->number mm)
109 (string->number yyyy))])
110 (msg ts_epoch ts_rfc3339 nick uri text))]
111 [_
112 (log-debug "Non-msg line from nick:~a, line:~a" nick str)
113 #f])))))
114
115 (module+ test
116 (let* ([tzs (for*/list ([d '("-" "+")]
117 [h '("5" "05")]
118 [m '("00" ":00" "57" ":57")])
119 (string-append d h m))]
120 [tzs (list* "" "Z" tzs)])
121 (for* ([n '("fake-nick")]
122 [u '("fake-uri")]
123 [s '("" ":10")]
124 [f '("" ".1337")]
125 [z tzs]
126 [sep (list "\t" " ")]
127 [txt '("foo bar baz" "'jaz poop bear giraffe / tea" "@*\"``")])
128 (let* ([ts (string-append "2020-11-18T22:22"
129 (if (non-empty-string? s) s ":00")
130 z)]
131 [m (str->msg n u (string-append ts sep txt))])
132 (check-not-false m)
133 (check-equal? (msg-nick m) n)
134 (check-equal? (msg-uri m) u)
135 (check-equal? (msg-text m) txt)
136 (check-equal? (msg-ts_rfc3339 m) ts (format "Given: ~v" ts))
137 )))
138
139 (let* ([ts "2020-11-18T22:22:09-0500"]
140 [tab " "]
141 [text "Lorem ipsum"]
142 [nick "foo"]
143 [uri "bar"]
144 [actual (str->msg nick uri (string-append ts tab text))]
145 [expected (msg 1605756129 ts nick uri text)])
146 ; FIXME re-enable after handling tz offset
147 ;(check-equal?
148 ; (msg-ts_epoch actual)
149 ; (msg-ts_epoch expected)
150 ; "str->msg ts_epoch")
151 (check-equal?
152 (msg-ts_rfc3339 actual)
153 (msg-ts_rfc3339 expected)
154 "str->msg ts_rfc3339")
155 (check-equal?
156 (msg-nick actual)
157 (msg-nick expected)
158 "str->msg nick")
159 (check-equal?
160 (msg-uri actual)
161 (msg-uri expected)
162 "str->msg uri")
163 (check-equal?
164 (msg-text actual)
165 (msg-text expected)
166 "str->msg text")))
167
168 (define (str->lines str)
169 (string-split str (regexp "[\r\n]+")))
170
171 (module+ test
172 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
173
174 (define (str->msgs nick uri str)
175 (filter-map (λ (line) (str->msg nick uri line)) (str->lines str)))
176
177 (define (hash-sha1 str)
178 (define in (open-input-string str))
179 (define digest (sha1 in))
180 (close-input-port in)
181 digest)
182
183 (define (url->cache-file-path uri)
184 ; TODO Replace hashing with encoding
185 (expand-user-path (string-append "~/.tt/cache/" (hash-sha1 (url->string uri)))))
186
187 (define (uri-read-cached uri)
188 (define path (url->cache-file-path uri))
189 (if (file-exists? path)
190 (file->string path)
191 (begin
192 (log-warning "Cache file not found for URI: ~a" (url->string uri))
193 "")))
194
195 (define (str->feed str)
196 (log-debug "Parsing feed string: ~v" str)
197 (match (string-split str)
198 [(list nick u)
199 (with-handlers*
200 ([exn:fail?
201 (λ (e)
202 (log-error "Invalid URI: ~v, exn: ~v" u e)
203 #f)])
204 (feed nick (string->url u)))]
205 [_
206 (log-error "Invalid feed string: ~v" str)
207 #f]))
208
209 (define (filter-comments lines)
210 (filter-not (λ (line) (string-prefix? line "#")) lines))
211
212 (define (str->feeds str)
213 (filter-map str->feed (filter-comments (str->lines str))))
214
215 (define (file->feeds filename)
216 (str->feeds (file->string filename)))
217
218 (define user-agent
219 (let*
220 ([prog-name "tt"]
221 [prog-version (info:#%info-lookup 'version)]
222 [prog-uri "https://github.com/xandkar/tt"]
223 [user-feed-file (expand-user-path "~/twtxt-me.txt")]
224 [user
225 (if (file-exists? user-feed-file)
226 (let ([user (first (file->feeds user-feed-file))])
227 (format "+~a; @~a" (url->string (feed-uri user)) (feed-nick user)))
228 (format "+~a" prog-uri))])
229 (format "~a/~a (~a)" prog-name prog-version user)))
230
231 ; uri-download : net/url-structs:url -> Void
232 (define (uri-download u)
233 (define cache-file-path (url->cache-file-path u))
234 (log-debug "uri-download ~v into ~v" u cache-file-path)
235 (match* ((url-scheme u) (url-host u) (url-port u))
236 [(s h p)
237 #:when (and s h)
238 (define ssl? (string=? s "https"))
239 (define-values (status-line headers body-input)
240 ; TODO Timeout. Currently hangs on slow connections.
241 (http-sendrecv
242 h
243 (url->string (struct-copy url u [scheme #f] [host #f]))
244 #:ssl? ssl?
245 #:port (cond [p p] [ssl? 443] [else 80])
246 #:headers (list (format "User-Agent: ~a" user-agent))
247 ))
248 (log-debug "headers: ~v" headers)
249 (log-debug "status-line: ~v" status-line)
250 (define status
251 (string->number (second (string-split (bytes->string/utf-8 status-line)))))
252 (log-debug "status: ~v" status)
253 ; TODO Handle redirects
254 (if (= 200 status)
255 (call-with-output-file cache-file-path
256 (λ (cache-output)
257 (copy-port body-input cache-output))
258 #:exists 'replace)
259 (raise status))]
260 [(_ _ _)
261 (log-error "Invalid URI: ~v" u)]))
262
263 (define (timeline-print out-format timeline)
264 (void (foldl (match-lambda**
265 [((and m (msg _ _ nick _ _)) (cons prev-nick i))
266 (let ([i (if (string=? prev-nick nick) i (+ 1 i))])
267 (msg-print out-format i m)
268 (cons nick i))])
269 (cons "" 0)
270 timeline)))
271
272 ; feed->msgs : Feed -> (Listof Msg)
273 (define (feed->msgs f)
274 (match-define (feed nick uri) f)
275 (log-info "Reading feed nick:~a uri:~v" nick uri)
276 (str->msgs nick uri (uri-read-cached uri)))
277
278 ; feed-download : Feed -> Void
279 (define (feed-download f)
280 (match-define (feed nick uri) f)
281 (log-info "Downloading feed nick:~a uri:~a" nick (url->string uri))
282 (with-handlers
283 ([exn:fail?
284 (λ (e)
285 (log-error "Network error nick:~a uri:~v exn:~v" nick uri e)
286 #f)]
287 [integer?
288 (λ (status)
289 (log-error "HTTP error nick:~a uri:~a status:~a" nick uri status)
290 #f)])
291 (uri-download uri)))
292
293 ; timeline-download : Integer -> (Listof Feed) -> Void
294 (define (timeline-download num_workers feeds)
295 ; TODO No need for map - can just iter
296 (void (concurrent-filter-map num_workers feed-download feeds)))
297
298 ; TODO timeline contract : time-sorted list of messages
299 ; timeline-read : (U 'old->new 'new->old) -> (Listof Feeds) -> (Listof Msg)
300 (define (timeline-read order feeds)
301 (define cmp (match order
302 ['old->new <]
303 ['new->old >]))
304 (sort (append* (filter-map feed->msgs feeds))
305 (λ (a b) (cmp (msg-ts_epoch a) (msg-ts_epoch b)))))
306
307 (define (start-logger level)
308 (let* ([logger (make-logger #f #f level #f)]
309 [log-receiver (make-log-receiver logger level)])
310 (void (thread (λ ()
311 (parameterize
312 ([date-display-format 'iso-8601])
313 (let loop ()
314 (define data (sync log-receiver))
315 (define level (vector-ref data 0))
316 (define msg (vector-ref data 1))
317 (define ts (date->string (current-date) #t))
318 (eprintf "~a [~a] ~a~n" ts level msg)
319 (loop))))))
320 (current-logger logger)))
321
322 (module+ main
323 (let ([log-level 'info])
324 (command-line
325 #:program
326 "tt"
327 #:once-each
328 [("-d" "--debug")
329 "Enable debug log level."
330 (set! log-level 'debug)]
331 #:help-labels
332 ""
333 "and <command> is one of"
334 "r, read i : Read the timeline."
335 "d, download : Download the timeline."
336 "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)."
337 ""
338 #:args (command . args)
339 (start-logger log-level)
340 (current-command-line-arguments (list->vector args))
341 (match command
342 [(or "d" "download")
343 (let ([num_workers 15]) ; 15 was fastest out of the tried: 1, 5, 10, 20.
344 (command-line
345 #:program
346 "tt download"
347 #:once-each
348 [("-j" "--jobs")
349 njobs "Number of concurrent jobs."
350 (set! num_workers (string->number njobs))]
351 #:args (filename)
352 (timeline-download num_workers (file->feeds filename))))]
353 [(or "u" "upload")
354 (command-line
355 #:program
356 "tt upload"
357 #:args ()
358 (if (system (path->string (expand-user-path "~/.tt/upload")))
359 (exit 0)
360 (exit 1)))]
361 [(or "r" "read")
362 (let ([out-format 'multi-line]
363 [order 'old->new])
364 (command-line
365 #:program
366 "tt read"
367 #:once-each
368 [("-r" "--rev")
369 "Reverse displayed timeline order."
370 (set! order 'new->old)]
371 #:once-any
372 [("-s" "--short")
373 "Short output format"
374 (set! out-format 'single-line)]
375 [("-l" "--long")
376 "Long output format"
377 (set! out-format 'multi-line)]
378 #:args (filename)
379 (timeline-print out-format (timeline-read order (file->feeds filename)))))]
380 ))))
This page took 0.062683 seconds and 4 git commands to generate.