Re-indent with module+ as LIN 0
[tt.git] / tt.rkt
... / ...
CommitLineData
1; TODO optional text wrap
2; TODO write
3; TODO caching (use cache by default, unless explicitly asked for update)
4; - [x] value --> cache
5; - [x] value <-- cache
6; requires: commands
7; TODO timeline limits
8; TODO feed set operations (perhaps better done externally?)
9; TODO timeline as a result of a query (feed set op + filter expressions)
10; TODO named timelines
11; TODO config files
12; TODO parse "following" from feed
13; - following = <nick> <uri>
14; TODO parse mentions:
15; - @<source.nick source.url> | @<source.url>
16; TODO highlight mentions
17; TODO filter on mentions
18; TODO highlight hashtags
19; TODO filter on hashtags
20; TODO hashtags as channels? initial hashtag special?
21; TODO query language
22; TODO console logger colors by level ('error)
23; TODO file logger ('debug)
24; TODO commands:
25; - r | read
26; - see timeline ops above
27; - w | write
28; - arg or stdin
29; - nick expand to URI
30; - q | query
31; - see timeline ops above
32; - see hashtag and channels above
33; - d | download
34; - u | upload
35; - calls user-configured command to upload user's own feed file to their server
36;
37; Looks like a better CLI parser than "racket/cmdline":
38; https://docs.racket-lang.org/natural-cli/
39
40#lang racket
41
42(require openssl/sha1)
43(require racket/date)
44
45(require http-client)
46(require rfc3339-old)
47
48(module+ test
49 (require rackunit))
50
51(struct msg (ts_epoch ts_rfc3339 nick uri text))
52(struct feed (nick uri))
53
54(define (concurrent-filter-map num_workers f xs)
55 ; TODO preserve order of elements OR communicate that reorder is expected
56 ; TODO switch from mailboxes to channels
57 (define (make-worker id f)
58 (define parent (current-thread))
59 (λ ()
60 (define self (current-thread))
61 (define (work)
62 (thread-send parent (cons 'next self))
63 (match (thread-receive)
64 ['done (thread-send parent (cons 'exit id))]
65 [(cons 'unit x) (begin
66 (define y (f x))
67 (when y (thread-send parent (cons 'result y)))
68 (work))]))
69 (work)))
70 (define (dispatch ws xs ys)
71 (if (empty? ws)
72 ys
73 (match (thread-receive)
74 [(cons 'exit w) (dispatch (remove w ws =) xs ys)]
75 [(cons 'result y) (dispatch ws xs (cons y ys))]
76 [(cons 'next thd) (match xs
77 ['() (begin
78 (thread-send thd 'done)
79 (dispatch ws xs ys))]
80 [(cons x xs) (begin
81 (thread-send thd (cons 'unit x))
82 (dispatch ws xs ys))])])))
83 (define workers (range num_workers))
84 (define threads (map (λ (id) (thread (make-worker id f))) workers))
85 (define results (dispatch workers xs '()))
86 (for-each thread-wait threads)
87 results)
88
89(module+ test
90 (let* ([f (λ (x) (if (even? x) x #f))]
91 [xs (range 11)]
92 [actual (sort (concurrent-filter-map 10 f xs) <)]
93 [expected (sort ( filter-map f xs) <)])
94 (check-equal? actual expected "concurrent-filter-map")))
95
96(define (msg-print out-format odd msg)
97 (printf
98 (match out-format
99 ['single-line "~a \033[1;37m<~a ~a>\033[0m \033[0;~am~a\033[0m~n"]
100 ['multi-line "~a~n\033[1;37m<~a ~a>\033[0m~n\033[0;~am~a\033[0m~n~n"]
101 [_ (raise (format "Invalid output format: ~a" out-format))])
102 (date->string (seconds->date [msg-ts_epoch msg]) #t)
103 (msg-nick msg)
104 (msg-uri msg)
105 (if odd 36 33)
106 (msg-text msg)))
107
108(define re-msg-begin
109 ; TODO Zulu offset. Maybe in several formats. Which ones?
110 (pregexp "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}"))
111
112(define (str->msg nick uri str)
113 (if (not (regexp-match? re-msg-begin str))
114 (begin
115 (log-debug "Non-msg line from nick:~a, line:~a" nick str)
116 #f)
117 (let ([toks (string-split str (regexp "\t+"))])
118 (if (not (= 2 (length toks)))
119 (begin
120 (log-warning "Invalid msg line from nick:~a, msg:~a" nick str)
121 #f)
122 (let*
123 ([ts_rfc3339 (first toks)]
124 [text (second toks)]
125 [t (string->rfc3339-record ts_rfc3339)]
126 ; TODO handle tz offset
127 [ts_epoch (find-seconds [rfc3339-record:second t]
128 [rfc3339-record:minute t]
129 [rfc3339-record:hour t]
130 [rfc3339-record:mday t]
131 [rfc3339-record:month t]
132 [rfc3339-record:year t])])
133 (msg ts_epoch ts_rfc3339 nick uri text))))))
134
135(module+ test
136 (let* ([ts "2020-11-18T22:22:09-0500"]
137 [tab " "]
138 [text "Lorem ipsum"]
139 [nick "foo"]
140 [uri "bar"]
141 [actual (str->msg nick uri (string-append ts tab text))]
142 [expected (msg 1605756129 ts nick uri text)])
143 ; FIXME re-enable after handling tz offset
144 ;(check-equal?
145 ; (msg-ts_epoch actual)
146 ; (msg-ts_epoch expected)
147 ; "str->msg ts_epoch")
148 (check-equal?
149 (msg-ts_rfc3339 actual)
150 (msg-ts_rfc3339 expected)
151 "str->msg ts_rfc3339")
152 (check-equal?
153 (msg-nick actual)
154 (msg-nick expected)
155 "str->msg nick")
156 (check-equal?
157 (msg-uri actual)
158 (msg-uri expected)
159 "str->msg uri")
160 (check-equal?
161 (msg-text actual)
162 (msg-text expected)
163 "str->msg text")))
164
165(define (str->lines str)
166 (string-split str (regexp "[\r\n]+")))
167
168(module+ test
169 (check-equal? (str->lines "abc\ndef\n\nghi") '("abc" "def" "ghi")))
170
171(define (str->msgs nick uri str)
172 (filter-map (λ (line) (str->msg nick uri line)) (str->lines str)))
173
174(define (hash-sha1 str)
175 (define in (open-input-string str))
176 (define digest (sha1 in))
177 (close-input-port in)
178 digest)
179
180(define (uri-fetch use-cache uri)
181 (define cache-file-path
182 (expand-user-path (string-append "~/.tt/cache/" (hash-sha1 uri))))
183 (if (and use-cache (file-exists? cache-file-path))
184 (begin
185 (log-info "uri-fetch cached ~a" uri)
186 (file->string cache-file-path))
187 (begin
188 (log-info "uri-fetch new ~a" uri)
189 (let* ([resp (http-get uri)]
190 [status (http-response-code resp)]
191 [body (http-response-body resp)])
192 (log-debug "finished GET ~a status:~a body length:~a"
193 uri status (string-length body))
194 ; TODO Handle redirects
195 (if (= status 200)
196 (begin
197 (display-to-file body cache-file-path #:exists 'replace)
198 body)
199 ; TODO A more-informative exception
200 (raise status))))))
201
202(define (timeline-print out-format timeline)
203 (for ([msg timeline]
204 [i (in-naturals)])
205 (msg-print out-format (odd? i) msg)))
206
207(define (feed->msgs use-cache feed)
208 (log-info "downloading feed nick:~a uri:~a"
209 (feed-nick feed)
210 (feed-uri feed))
211 (with-handlers
212 ([exn:fail:network?
213 (λ (e)
214 (log-error "network error nick:~a uri:~a exn:~a"
215 (feed-nick feed)
216 (feed-uri feed)
217 e)
218 #f)]
219 [integer?
220 (λ (status)
221 (log-error "http error nick:~a uri:~a status:~a"
222 (feed-nick feed)
223 (feed-uri feed)
224 status)
225 #f)])
226 (define uri (feed-uri feed))
227 (str->msgs [feed-nick feed] uri [uri-fetch use-cache uri])))
228
229; TODO timeline contract : time-sorted list of messages
230(define (timeline use-cache num_workers feeds)
231 (sort (append* (concurrent-filter-map num_workers (curry feed->msgs use-cache) feeds))
232 (λ (a b) [< (msg-ts_epoch a) (msg-ts_epoch b)])))
233
234(define (str->feed str)
235 ; TODO validation
236 (define toks (string-split str))
237 (apply feed toks))
238
239(define (str->feeds str)
240 (map str->feed (str->lines str)))
241
242(define (file->feeds filename)
243 (str->feeds (file->string filename)))
244
245(define (user-agent prog-name prog-version)
246 (let*
247 ([prog-uri "https://github.com/xandkar/tt"]
248 [user-feed-file (expand-user-path "~/twtxt-me.txt")]
249 [user
250 (if (file-exists? user-feed-file)
251 (let ([user (first (file->feeds user-feed-file))])
252 (format "+~a; @~a" (feed-uri user) (feed-nick user)))
253 (format "+~a" prog-uri))]
254 )
255 (format "~a/~a (~a)" prog-name prog-version user)))
256
257(module+ main
258 (require setup/getinfo)
259
260 (let* ([level 'info]
261 [logger (make-logger #f #f level #f)]
262 [log-receiver (make-log-receiver logger level)])
263 (void (thread (λ ()
264 [date-display-format 'iso-8601]
265 [let loop ()
266 (define data (sync log-receiver))
267 (define level (vector-ref data 0))
268 (define msg (vector-ref data 1))
269 (define ts (date->string (current-date) #t))
270 (eprintf "~a [~a] ~a~n" ts level msg)
271 (loop)])))
272 (current-logger logger))
273 (current-http-response-auto #f)
274 (let* ([prog-name "tt"]
275 [prog-version ((get-info (list prog-name)) 'version)]
276 [user-agent (user-agent prog-name prog-version)])
277 (current-http-user-agent user-agent))
278 (date-display-format 'rfc2822)
279 (let* ([use-cache
280 #f]
281 [out-format
282 'multi-line]
283 [num_workers
284 15]) ; 15 was fastest out of the tried 1, 5, 10, 15 and 20.
285 (command-line
286 #:once-each
287 [("-c" "--cached")
288 "Read cached data instead of downloading."
289 (set! use-cache #t)]
290
291 [("-j" "--jobs")
292 njobs "Number of concurrent jobs."
293 (set! num_workers (string->number njobs))]
294
295 #:args (filename)
296
297 (timeline-print out-format
298 (timeline use-cache
299 num_workers
300 (file->feeds filename))))))
This page took 0.025388 seconds and 4 git commands to generate.