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