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