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