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