Commit | Line | Data |
---|---|---|
cd541405 | 1 | #lang typed/racket/no-check |
4764ff89 | 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 | 15 | (struct msg |
cd541405 SK |
16 | ([ts_epoch : Integer] |
17 | [ts_rfc3339 : String] | |
18 | [nick : String] | |
19 | [uri : net/url-structs:url] | |
20 | [text : String])) | |
9c464d95 SK |
21 | |
22 | (struct feed | |
cd541405 SK |
23 | ([nick : String] |
24 | [uri : net/url-structs:url])) | |
4764ff89 | 25 | |
895a32cf | 26 | (define (concurrent-filter-map num_workers f xs) |
dad4504d | 27 | ; TODO preserve order of elements OR communicate that reorder is expected |
a239a233 | 28 | ; TODO switch from mailboxes to channels |
895a32cf SK |
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) | |
c562bea3 SK |
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))])) | |
895a32cf SK |
41 | (work))) |
42 | (define (dispatch ws xs ys) | |
43 | (if (empty? ws) | |
f1493e49 SK |
44 | ys |
45 | (match (thread-receive) | |
c562bea3 SK |
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))])]))) | |
9926c9a9 SK |
55 | (define workers (range num_workers)) |
56 | (define threads (map (λ (id) (thread (make-worker id f))) workers)) | |
57 | (define results (dispatch workers xs '())) | |
895a32cf SK |
58 | (for-each thread-wait threads) |
59 | results) | |
60 | ||
dad4504d | 61 | (module+ test |
de3ff448 SK |
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) <)]) | |
c562bea3 | 66 | (check-equal? actual expected "concurrent-filter-map"))) |
dad4504d | 67 | |
3d042e75 SK |
68 | (define msg-print |
69 | (let* ([colors (vector 36 33)] | |
70 | [n (vector-length colors)]) | |
71 | (λ (out-format color-i msg) | |
01e4c499 SK |
72 | (let ([color (vector-ref colors (modulo color-i n))] |
73 | [nick (msg-nick msg)] | |
9c464d95 | 74 | [uri (url->string (msg-uri msg))] |
01e4c499 | 75 | [text (msg-text msg)]) |
3d042e75 | 76 | (match out-format |
01e4c499 SK |
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]) | |
9f94cca9 | 80 | (date->string (seconds->date [msg-ts_epoch msg]) #t)) |
01e4c499 SK |
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]) | |
9f94cca9 | 85 | (date->string (seconds->date [msg-ts_epoch msg]) #t)) |
01e4c499 | 86 | nick uri color text)]))))) |
e96264cc | 87 | |
b4689464 | 88 | (define str->msg |
f9d1c7fe SK |
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]+(.*)$")]) | |
b4689464 SK |
91 | (λ (nick uri str) |
92 | (with-handlers* | |
93 | ([exn:fail? | |
94 | (λ (e) | |
9c464d95 SK |
95 | (log-error |
96 | "Failed to parse msg: ~v, from: ~v, at: ~v, because: ~v" | |
97 | str nick (url->string uri) e) | |
b4689464 SK |
98 | #f)]) |
99 | (match (regexp-match re str) | |
f9d1c7fe | 100 | [(list _wholething ts yyyy mm dd HH MM _:SS SS _f tz text) |
c562bea3 | 101 | (let* |
c562bea3 | 102 | ; TODO handle tz offset |
f9d1c7fe SK |
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))]) | |
b4689464 SK |
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]))))) | |
88d50b3e | 114 | |
63afa259 | 115 | (module+ test |
b4689464 SK |
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 | ||
de3ff448 SK |
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)]) | |
c562bea3 SK |
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"))) | |
63afa259 | 167 | |
e96264cc SK |
168 | (define (str->lines str) |
169 | (string-split str (regexp "[\r\n]+"))) | |
170 | ||
63afa259 | 171 | (module+ test |
de3ff448 | 172 | (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi"))) |
63afa259 | 173 | |
b201e854 SK |
174 | (define (str->msgs nick uri str) |
175 | (filter-map (λ (line) (str->msg nick uri line)) (str->lines str))) | |
4764ff89 | 176 | |
1d753430 SK |
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 | ||
9c464d95 SK |
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 | ||
4214c0f3 | 187 | (define (uri-read-cached uri) |
9c464d95 SK |
188 | (define path (url->cache-file-path uri)) |
189 | (if (file-exists? path) | |
190 | (file->string path) | |
0e16a46c | 191 | (begin |
9c464d95 | 192 | (log-warning "Cache file not found for URI: ~a" (url->string uri)) |
4214c0f3 SK |
193 | ""))) |
194 | ||
9c464d95 SK |
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"] | |
3c9c8266 | 221 | [prog-version (info:#%info-lookup 'version)] |
9c464d95 SK |
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)])) | |
4764ff89 | 262 | |
b201e854 | 263 | (define (timeline-print out-format timeline) |
3d042e75 SK |
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))) | |
4764ff89 | 271 | |
4214c0f3 | 272 | ; feed->msgs : Feed -> (Listof Msg) |
9c464d95 SK |
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))) | |
4214c0f3 SK |
277 | |
278 | ; feed-download : Feed -> Void | |
9c464d95 SK |
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)) | |
9a6a9f9a | 282 | (with-handlers |
9c464d95 | 283 | ([exn:fail? |
9a6a9f9a | 284 | (λ (e) |
9c464d95 | 285 | (log-error "Network error nick:~a uri:~v exn:~v" nick uri e) |
9a6a9f9a SK |
286 | #f)] |
287 | [integer? | |
288 | (λ (status) | |
9c464d95 | 289 | (log-error "HTTP error nick:~a uri:~a status:~a" nick uri status) |
9a6a9f9a | 290 | #f)]) |
9c464d95 | 291 | (uri-download uri))) |
4214c0f3 SK |
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))) | |
9a6a9f9a SK |
297 | |
298 | ; TODO timeline contract : time-sorted list of messages | |
a4899240 SK |
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 >])) | |
4214c0f3 | 304 | (sort (append* (filter-map feed->msgs feeds)) |
a4899240 | 305 | (λ (a b) (cmp (msg-ts_epoch a) (msg-ts_epoch b))))) |
4764ff89 | 306 | |
01e4c499 SK |
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 | ||
24c6a76b | 322 | (module+ main |
24f1f64b | 323 | (let ([log-level 'info]) |
c562bea3 | 324 | (command-line |
24f1f64b SK |
325 | #:program |
326 | "tt" | |
c562bea3 | 327 | #:once-each |
01e4c499 SK |
328 | [("-d" "--debug") |
329 | "Enable debug log level." | |
330 | (set! log-level 'debug)] | |
24f1f64b SK |
331 | #:help-labels |
332 | "" | |
333 | "and <command> is one of" | |
4214c0f3 SK |
334 | "r, read i : Read the timeline." |
335 | "d, download : Download the timeline." | |
3a4b2233 | 336 | "u, upload : Upload your twtxt file (alias to execute ~/.tt/upload)." |
24f1f64b SK |
337 | "" |
338 | #:args (command . args) | |
4214c0f3 SK |
339 | (start-logger log-level) |
340 | (current-command-line-arguments (list->vector args)) | |
24f1f64b | 341 | (match command |
4214c0f3 SK |
342 | [(or "d" "download") |
343 | (let ([num_workers 15]) ; 15 was fastest out of the tried: 1, 5, 10, 20. | |
24f1f64b SK |
344 | (command-line |
345 | #:program | |
4214c0f3 | 346 | "tt download" |
24f1f64b SK |
347 | #:once-each |
348 | [("-j" "--jobs") | |
349 | njobs "Number of concurrent jobs." | |
350 | (set! num_workers (string->number njobs))] | |
4214c0f3 | 351 | #:args (filename) |
9c464d95 | 352 | (timeline-download num_workers (file->feeds filename))))] |
3a4b2233 SK |
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)))] | |
4214c0f3 | 361 | [(or "r" "read") |
a4899240 SK |
362 | (let ([out-format 'multi-line] |
363 | [order 'old->new]) | |
4214c0f3 SK |
364 | (command-line |
365 | #:program | |
366 | "tt read" | |
a4899240 SK |
367 | #:once-each |
368 | [("-r" "--rev") | |
369 | "Reverse displayed timeline order." | |
370 | (set! order 'new->old)] | |
24f1f64b SK |
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) | |
a4899240 | 379 | (timeline-print out-format (timeline-read order (file->feeds filename)))))] |
24f1f64b | 380 | )))) |