Commit | Line | Data |
---|---|---|
4764ff89 SK |
1 | #lang racket |
2 | ||
1d753430 | 3 | (require openssl/sha1) |
4764ff89 | 4 | (require racket/date) |
9c464d95 SK |
5 | (require |
6 | net/http-client | |
7 | net/url-string | |
8 | net/url-structs) | |
4764ff89 | 9 | |
3c9c8266 SK |
10 | (require (prefix-in info: "info.rkt")) |
11 | ||
78398948 | 12 | (module+ test |
de3ff448 | 13 | (require rackunit)) |
78398948 | 14 | |
9c464d95 SK |
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 | )) | |
4764ff89 | 29 | |
895a32cf | 30 | (define (concurrent-filter-map num_workers f xs) |
dad4504d | 31 | ; TODO preserve order of elements OR communicate that reorder is expected |
a239a233 | 32 | ; TODO switch from mailboxes to channels |
895a32cf SK |
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) | |
c562bea3 SK |
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))])) | |
895a32cf SK |
45 | (work))) |
46 | (define (dispatch ws xs ys) | |
47 | (if (empty? ws) | |
f1493e49 SK |
48 | ys |
49 | (match (thread-receive) | |
c562bea3 SK |
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))])]))) | |
9926c9a9 SK |
59 | (define workers (range num_workers)) |
60 | (define threads (map (λ (id) (thread (make-worker id f))) workers)) | |
61 | (define results (dispatch workers xs '())) | |
895a32cf SK |
62 | (for-each thread-wait threads) |
63 | results) | |
64 | ||
dad4504d | 65 | (module+ test |
de3ff448 SK |
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) <)]) | |
c562bea3 | 70 | (check-equal? actual expected "concurrent-filter-map"))) |
dad4504d | 71 | |
3d042e75 SK |
72 | (define msg-print |
73 | (let* ([colors (vector 36 33)] | |
74 | [n (vector-length colors)]) | |
75 | (λ (out-format color-i msg) | |
01e4c499 SK |
76 | (let ([color (vector-ref colors (modulo color-i n))] |
77 | [nick (msg-nick msg)] | |
9c464d95 | 78 | [uri (url->string (msg-uri msg))] |
01e4c499 | 79 | [text (msg-text msg)]) |
3d042e75 | 80 | (match out-format |
01e4c499 SK |
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]) | |
9f94cca9 | 84 | (date->string (seconds->date [msg-ts_epoch msg]) #t)) |
01e4c499 SK |
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]) | |
9f94cca9 | 89 | (date->string (seconds->date [msg-ts_epoch msg]) #t)) |
01e4c499 | 90 | nick uri color text)]))))) |
e96264cc | 91 | |
b4689464 | 92 | (define str->msg |
f9d1c7fe SK |
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]+(.*)$")]) | |
b4689464 SK |
95 | (λ (nick uri str) |
96 | (with-handlers* | |
97 | ([exn:fail? | |
98 | (λ (e) | |
9c464d95 SK |
99 | (log-error |
100 | "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v" | |
101 | str nick (url->string uri) e) | |
b4689464 SK |
102 | #f)]) |
103 | (match (regexp-match re str) | |
f9d1c7fe | 104 | [(list _wholething ts yyyy mm dd HH MM _:SS SS _f tz text) |
c562bea3 | 105 | (let* |
c562bea3 | 106 | ; TODO handle tz offset |
f9d1c7fe SK |
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))]) | |
b4689464 SK |
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]))))) | |
88d50b3e | 118 | |
63afa259 | 119 | (module+ test |
b4689464 SK |
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 | ||
de3ff448 SK |
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)]) | |
c562bea3 SK |
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"))) | |
63afa259 | 171 | |
e96264cc SK |
172 | (define (str->lines str) |
173 | (string-split str (regexp "[\r\n]+"))) | |
174 | ||
63afa259 | 175 | (module+ test |
de3ff448 | 176 | (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi"))) |
63afa259 | 177 | |
b201e854 SK |
178 | (define (str->msgs nick uri str) |
179 | (filter-map (λ (line) (str->msg nick uri line)) (str->lines str))) | |
4764ff89 | 180 | |
1d753430 SK |
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 | ||
9c464d95 SK |
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 | ||
4214c0f3 | 191 | (define (uri-read-cached uri) |
9c464d95 SK |
192 | (define path (url->cache-file-path uri)) |
193 | (if (file-exists? path) | |
194 | (file->string path) | |
0e16a46c | 195 | (begin |
9c464d95 | 196 | (log-warning "Cache file not found for URI: ~a" (url->string uri)) |
4214c0f3 SK |
197 | ""))) |
198 | ||
9c464d95 SK |
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"] | |
3c9c8266 | 225 | [prog-version (info:#%info-lookup 'version)] |
9c464d95 SK |
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)])) | |
4764ff89 | 266 | |
b201e854 | 267 | (define (timeline-print out-format timeline) |
3d042e75 SK |
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))) | |
4764ff89 | 275 | |
4214c0f3 | 276 | ; feed->msgs : Feed -> (Listof Msg) |
9c464d95 SK |
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))) | |
4214c0f3 SK |
281 | |
282 | ; feed-download : Feed -> Void | |
9c464d95 SK |
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)) | |
9a6a9f9a | 286 | (with-handlers |
9c464d95 | 287 | ([exn:fail? |
9a6a9f9a | 288 | (λ (e) |
9c464d95 | 289 | (log-error "Network error nick:~a uri:~v exn:~v" nick uri e) |
9a6a9f9a SK |
290 | #f)] |
291 | [integer? | |
292 | (λ (status) | |
9c464d95 | 293 | (log-error "HTTP error nick:~a uri:~a status:~a" nick uri status) |
9a6a9f9a | 294 | #f)]) |
9c464d95 | 295 | (uri-download uri))) |
4214c0f3 SK |
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))) | |
9a6a9f9a SK |
301 | |
302 | ; TODO timeline contract : time-sorted list of messages | |
a4899240 SK |
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 >])) | |
4214c0f3 | 308 | (sort (append* (filter-map feed->msgs feeds)) |
a4899240 | 309 | (λ (a b) (cmp (msg-ts_epoch a) (msg-ts_epoch b))))) |
4764ff89 | 310 | |
01e4c499 SK |
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 | ||
24c6a76b | 326 | (module+ main |
24f1f64b | 327 | (let ([log-level 'info]) |
c562bea3 | 328 | (command-line |
24f1f64b SK |
329 | #:program |
330 | "tt" | |
c562bea3 | 331 | #:once-each |
01e4c499 SK |
332 | [("-d" "--debug") |
333 | "Enable debug log level." | |
334 | (set! log-level 'debug)] | |
24f1f64b SK |
335 | #:help-labels |
336 | "" | |
337 | "and <command> is one of" | |
4214c0f3 SK |
338 | "r, read i : Read the timeline." |
339 | "d, download : Download the timeline." | |
3a4b2233 | 340 | "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)." |
24f1f64b SK |
341 | "" |
342 | #:args (command . args) | |
4214c0f3 SK |
343 | (start-logger log-level) |
344 | (current-command-line-arguments (list->vector args)) | |
24f1f64b | 345 | (match command |
4214c0f3 SK |
346 | [(or "d" "download") |
347 | (let ([num_workers 15]) ; 15 was fastest out of the tried: 1, 5, 10, 20. | |
24f1f64b SK |
348 | (command-line |
349 | #:program | |
4214c0f3 | 350 | "tt download" |
24f1f64b SK |
351 | #:once-each |
352 | [("-j" "--jobs") | |
353 | njobs "Number of concurrent jobs." | |
354 | (set! num_workers (string->number njobs))] | |
4214c0f3 | 355 | #:args (filename) |
9c464d95 | 356 | (timeline-download num_workers (file->feeds filename))))] |
3a4b2233 SK |
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)))] | |
4214c0f3 | 365 | [(or "r" "read") |
a4899240 SK |
366 | (let ([out-format 'multi-line] |
367 | [order 'old->new]) | |
4214c0f3 SK |
368 | (command-line |
369 | #:program | |
370 | "tt read" | |
a4899240 SK |
371 | #:once-each |
372 | [("-r" "--rev") | |
373 | "Reverse displayed timeline order." | |
374 | (set! order 'new->old)] | |
24f1f64b SK |
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) | |
a4899240 | 383 | (timeline-print out-format (timeline-read order (file->feeds filename)))))] |
24f1f64b | 384 | )))) |