summaryrefslogtreecommitdiff
path: root/qkbox/toot.scm
blob: 38819347ba1310f14c983d3148851bc5e99fde93 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
;;; Qkbox --- TojoQK's toybox
;;; Copyright © 2020 Masaya Tojo <masaya@tojo.tokyo>
;;;
;;; This file is part of Qkbox.
;;;
;;; Qkbox is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or
;;; (at your option) any later version.
;;;
;;; Qkbox is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Qkbox.  If not, see <http://www.gnu.org/licenses/>.

(define-module (qkbox toot)
  #:use-module (ice-9 format)
  #:use-module (web response)
  #:use-module (web client)
  #:use-module (json builder)
  #:use-module (json parser)
  #:use-module (rnrs bytevectors)
  #:use-module (ice-9 binary-ports)
  #:use-module (ice-9 receive)
  #:use-module (ice-9 regex)
  #:use-module (ice-9 optargs)
  #:use-module (srfi srfi-9)
  #:use-module (srfi srfi-1)
  #:use-module (srfi srfi-9 gnu)
  #:use-module (pict)
  #:use-module ((htmlprag)
                #:select (html->sxml))
  #:use-module ((sxml fold)
                #:select (foldt))
  #:use-module ((sxml xpath)
                #:select (sxpath)))

(define-syntax-rule (and/nil test expr)
  (if test
      expr
      '()))

(define current-mastodon-host
  (make-parameter (getenv "MASTODON_HOST")))

(define current-mastodon-access-token
  (make-parameter (getenv "MASTODON_ACCESS_TOKEN")))

(define*-public (post text
                      #:key
                      spoiler-text
                      visibility
                      sensitive?
                      reply-to)
  (receive (res body)
      (/api/v1/statuses #:status text
                        #:spoiler-text spoiler-text
                        #:visibility visibility
                        #:sensitive? sensitive?
                        #:reply-to reply-to)
    (case (response-code res)
      ((200)
       (assoc-ref body "id"))
      (else
       (error "post: failed" res body)))))

(define* (/api/v1/statuses #:key
                           status
                           spoiler-text
                           visibility
                           sensitive?
                           reply-to
                           media-ids)
  (request
   'POST
   "/api/v1/statuses"
   #:json
   `(,@(and/nil status
                `((status . ,(if (string? status)
                                 status
                                 (format #f "~y" status)))))
     ,@(and/nil spoiler-text
                `((spoiler_text . ,spoiler-text)))
     ,@(and/nil visibility
                (case visibility
                  ((public unlisted private direct)
                   `((visibility . ,visibility)))
                  (else
                   (error "post: invalid visibility (must be one of: public unlisted private direct)"))))
     ,@(and/nil sensitive?
                `((sensitive . (if sensitive? #t #f))))
     ,@(and/nil reply-to
                `((in_reply_to_id . ,reply-to)))
     ,@(and/nil media-ids
                `((media_ids . ,(list->vector (map number->string media-ids))))))
   #:authorization? #t))

(define-record-type <status>
  (make-status json)
  status?
  (json status-json))

(set-record-type-printer! <status>
  (lambda (status port)
    (format port
            "#<status id: ~s ...>"
            (status-id status))))

(define-record-type <account>
  (make-account json)
  account?
  (json account-json))

(set-record-type-printer! <account>
  (lambda (account port)
    (format port "#<account id: ~s acct: ~s ...>"
            (account-id account)
            (account-acct account))))

(define-public (status-public? status)
  (eq? 'public (status-visibility status)))

(define (account-to-string account)
  (format #f "~{~a~} <~a> (account-id: ~s)"
          (insert-emoji-picts (account-emojis account)
                              (content-filter (account-display-name account)))
          (account-acct account)
          (account-id account)))

(define*-public (display-status status
                                #:key
                                (port (current-output-port))
                                display-cw?
                                display-sensitive?
                                (display-id? #t))
  (let ((status (or (status-reblog status) status))
        (status/original status))
    (let ((account (status-account status)))
      (cond
       (else
        (format port
                "~s ~a~@?~@?~@?~@?~@?~%~@?~@?"
                (status-avatar-pict status/original)
                (account-to-string account)
                "~@[~%  * status-id: ~s~]"
                (and display-id? (status-id status/original))
                "~@[~%  * visibility: ~:@(~a~)~]"
                (and (not (status-public? status))
                     (status-visibility status))
                "~@[~%  * boosted-by: ~a~]"
                (and (status-reblog status/original)
                     (account-to-string
                      (status-account status/original)))
                "~@[~%  * in-reply-to-id: ~s~]"
                (status-in-reply-to-id status)
                "~@[~%  * content-warning: ~a~]"
                (status-spoiler-text status)
                "~@[~a~%~]"
                (and (or (not (status-spoiler-text status))
                         display-cw?)
                     (content-filter
                      (status-to-content-string status)))
                "~{~a~%~}"
                (map (lambda (att)
                       (if (or (not (status-sensitive? status))
                               display-sensitive?)
                           (case (attachment-type att)
                             ((image)
                              (cond
                               ((fetch-attachment-preview-pict att)
                                => identity)
                               (else
                                "FAILED: IMAGE")))
                             (else
                              =>
                              (lambda (type)
                                (format #f "UNSUPPORTED: ~:@(~a~)" type))))
                           (format #f "NSFW: ~:@(~a~)" (attachment-type att))))
                     (status-media-attachments status))))))))

(define (status-avatar-pict status)
  (let ((status-pict (or (fetch-avatar-static
                          (account-avatar-static
                           (status-account status)))
                         no-image)))
    (cond
     ((status-reblog status)
      =>
      (lambda (reblog)
        (let ((reblog-pict (status-avatar-pict reblog)))
          (rb-superimpose
           (lt-superimpose (ghost reblog-pict) (scale reblog-pict 0.8))
           (scale status-pict 0.5)))))
     (else status-pict))))

(define-public (status-id status)
  (assoc-ref (status-json status) "id"))

(define-public (status-account status)
  (make-account (assoc-ref (status-json status) "account")))

(define-public (status-reblog status)
  (let ((reblog/json (assoc-ref (status-json status) "reblog")))
    (if (eq? reblog/json 'null)
        #f
        (make-status reblog/json))))

(define-public (status-sensitive? status)
  (assoc-ref (status-json status) "sensitive"))

(define-public (status-content status)
  (assoc-ref (status-json status) "content"))

(define (content-filter x)
  (string-delete (char-set #\x202d #\x202e) x))

(define (content->sxml content)
  (html->sxml content))

(define (status-to-content-string status)
  (let ((content (status-content status))
        (emojis (status-emojis status)))
    (call-with-output-string
      (lambda (port)
        (for-each (lambda (x) (display x port))
                  (append-map
                   (lambda (x) (insert-emoji-picts emojis x))
                   (flatten
                    (foldt (lambda (xs)
                             (define (unexpected)
                               (format #f "~%[DEBUG] UNEXPECTED ~s~%" xs))
                             (case (car xs)
                               ((*TOP* span status p a) (cdr xs))
                               ((br) #\newline)
                               ((@ class target rel href) '())
                               ((*ENTITY*)
                                (if (equal? '(*ENTITY* "additional" "nbsp") xs)
                                    " "
                                    (unexpected)))
                               (else (unexpected))))
                           (lambda (obj) obj)
                           (content->sxml content)))))
        (get-output-string port)))))

(define (flatten x)
  (cond
   ((list? x)
    (append-map flatten x))
   (else (list x))))

(define-public (status-visibility status)
  (string->symbol (assoc-ref (status-json status) "visibility")))

(define-public (status-spoiler-text status)
  (let ((s (assoc-ref (status-json status) "spoiler_text")))
    (if (zero? (string-length s))
        #f
        s)))

(define-record-type <emoji>
  (make-emoji json)
  emoji?
  (json emoji-json))

(define (emojis->regexp emojis)
  (string-append ":("
                 (string-join (map (compose regexp-quote emoji-shortcode) emojis)
                              "|")
                 "):"))

(define-public (status-emojis status)
  (map make-emoji (vector->list (assoc-ref (status-json status) "emojis"))))

(define-record-type <attachment>
  (make-attachment json)
  attachment?
  (json attachment-json))

(define (attachment-type attachment)
  (string->symbol (assoc-ref (attachment-json attachment) "type")))

(define (attachment-preview-url attachment)
  (assoc-ref (attachment-json attachment) "preview_url"))

(define (attachment-url attachment)
  (assoc-ref (attachment-json attachment) "url"))

(define (fetch-attachment-preview-pict attachment)
  (fetch-pict (attachment-preview-url attachment)
              #:height> 128))

(define (fetch-attachment-pict attachment)
  (fetch-pict (attachment-url attachment)))

(define-public (status-media-attachments status)
  (let ((v (assoc-ref (status-json status) "media_attachments")))
    (map make-attachment (vector->list v))))

(define (status-in-reply-to-id status)
  (let ((id (assoc-ref (status-json status) "in_reply_to_id")))
    (if (eq? 'null id)
        #f
        id)))

(define (status-in-reply-to-account-id status)
  (let ((id (assoc-ref (status-json status) "in_reply_to_account_id")))
    (if (eq? 'null id)
        #f
        id)))

(define (emoji-static-url emoji)
  (assoc-ref (emoji-json emoji) "static_url"))

(define (emoji-shortcode emoji)
  (assoc-ref (emoji-json emoji) "shortcode"))

(define (emoji-visible-in-picker? emoji)
  (assoc-ref (emoji-json emoji) "visible_in_picker"))

(define emoji-cache (make-hash-table))

(define (fetch-emoji-pict emoji)
  (let ((url (emoji-static-url emoji)))
    (cond
     ((hash-ref emoji-cache url) => identity)
     ((fetch-pict (emoji-static-url emoji)
                  #:resize '(24 24))
      =>
      (lambda (pict)
        (hash-set! emoji-cache url pict)
        pict))
     (else #f))))

(define (insert-emoji-picts emojis x)
  (let ((r (emojis->regexp emojis)))
    (if (string? x)
        (let loop ((s x))
          (cond ((string-match r s)
                 =>
                 (lambda (mat)
                   (let ((shortcode (match:substring mat 1)))
                     (cons* (match:prefix mat)
                            (cond
                             ((emojis-ref emojis shortcode)
                              =>
                              (lambda (emoji)
                                (or (fetch-emoji-pict emoji)
                                    shortcode))))
                            (loop (match:suffix mat))))))
                (else
                 (list s))))
        (list x))))

(define (emojis-ref emojis shortcode)
  (find (lambda (emoji) (equal? shortcode (emoji-shortcode emoji)))
        emojis))

(define-public (account-id account)
  (assoc-ref (account-json account) "id"))

(define-public (account-avatar-static account)
  (assoc-ref (account-json account) "avatar_static"))

(define-public (account-acct account)
  (assoc-ref (account-json account) "acct"))

(define-public (account-display-name account)
  (assoc-ref (account-json account) "display_name"))

(define-public (account-emojis account)
  (map make-emoji (vector->list (assoc-ref (account-json account) "emojis"))))

(define avatar-static-cache (make-hash-table))

(define* (fetch-pict url #:key resize height>)
  (receive (res body)
      (http-get url)
    (let ((tmp (tmpnam)))
      (let ((in (open tmp (logior O_WRONLY O_CREAT O_EXCL))))
        (put-bytevector in body)
        (close in))
      (case (response-code res)
        ((200)
         (let ((pict (and (zero? (apply system* "convert"
                                        `(,@(and/nil resize
                                                     `("-resize"
                                                       ,(format #f "~dx~d!"
                                                                (car resize)
                                                                (cadr resize))))
                                          ,@(and/nil height>
                                                     `("-resize"
                                                       ,(format #f "x~d>"
                                                                height>)))
                                          ,(string-append tmp "[0]")
                                          ,(string-append "png:" tmp))))
                          (pict-from-file tmp))))
           (delete-file tmp)
           pict))
        (else
         #f)))))

(define* (fetch-avatar-static url)
  (cond
   ((hash-ref avatar-static-cache url) => identity)
   (else
    (cond
     ((fetch-pict url #:resize '(32 32))
      =>
      (lambda (pict)
        (hash-set! avatar-static-cache url pict)
        pict))
     (else #f)))))

(define no-image
  (cc-superimpose
   (filled-rectangle 32 32
                     #:color "white"
                     #:border-width 0)
   (line 0 0 32 32 #:color "red")
   (line 0 32 32 0 #:color "red")))

(define*-public (fetch-status id #:key (authorization? #t))
  (receive (res body)
      (/api/v1/statuses/:id id #:authorization? authorization?)
    (case (response-code res)
      ((200) (make-status body))
      (else
       (error "fetch-status: failed" res body)))))

(define* (/api/v1/statuses/:id id #:key (authorization? #t))
  (request
   'GET
   (format #f "/api/v1/statuses/~a" id)
   #:authorization? authorization?))

(define*-public (fetch-home-timeline #:key max-id since-id min-id limit local?)
  (receive (res body)
      (/api/v1/timelines/home #:max-id max-id
                              #:since-id since-id
                              #:min-id min-id
                              #:limit limit
                              #:local? local?)
    (case (response-code res)
      ((200)
       (map make-status (vector->list body)))
      ((206)
       (error "fetch-home-timeline: Home feed is regenerating"))
      (else
       (error "fetch-home-timeline: failed" res body)))))

(define*-public (fetch-public-timeline #:key max-id since-id min-id limit local? remote? only-media?)
  (receive (res body)
      (/api/v1/timelines/public #:max-id max-id
                                #:since-id since-id
                                #:min-id min-id
                                #:limit limit
                                #:local? local?
                                #:remote? remote?
                                #:only-media? only-media?)
    (case (response-code res)
      ((200)
       (map make-status (vector->list body)))
      (else
       (error "fetch-public-timeline: failed" res body)))))

(define* (/api/v1/timelines/home #:key max-id since-id min-id limit local?)
  (request
   'GET
   "/api/v1/timelines/home"
   #:json
   `(,@(and/nil max-id `((max_id . ,max-id)))
     ,@(and/nil since-id `((since_id . ,since-id)))
     ,@(and/nil min-id `((min_id . ,min-id)))
     ,@(and/nil limit `((limit . ,limit)))
     ,@(and/nil local? `((local . ,local?))))
   #:authorization? #t))

(define* (/api/v1/timelines/public #:key max-id since-id min-id limit local? remote? only-media?)
  (request
   'GET
   "/api/v1/timelines/public"
   #:json
   `(,@(and/nil max-id `((max_id . ,max-id)))
     ,@(and/nil since-id `((since_id . ,since-id)))
     ,@(and/nil min-id `((min_id . ,min-id)))
     ,@(and/nil limit `((limit . ,limit)))
     ,@(and/nil local? `((local . ,local?)))
     ,@(and/nil remote? `((remote . ,remote?)))
     ,@(and/nil only-media? `((only_media . ,only-media?))))
   #:authorization? #t))

(define-public (favourite id)
  (define-values (res body)
    (/api/v1/statuses/:id/favourite id))
  (case (response-code res)
    ((200) #t)
    (else
     (error "favourite: failed" res body))))

(define (/api/v1/statuses/:id/favourite id)
  (request
   'POST
   (format #f "/api/v1/statuses/~a/favourite" id)
   #:authorization? #t))

(define-public (unfavourite id)
  (define-values (res body)
    (/api/v1/statuses/:id/unfavourite id))
  (case (response-code res)
    ((200) #t)
    (else
     (error "unfavourite: failed" res body))))

(define (/api/v1/statuses/:id/unfavourite id)
  (request
   'POST
   (format #f "/api/v1/statuses/~a/unfavourite" id)
   #:authorization? #t))

(define-public (reblog id)
  (define-values (res body)
    (/api/v1/statuses/:id/reblog id))
  (case (response-code res)
    ((200) #t)
    (else
     (error "reblog: failed" res body))))

(define (/api/v1/statuses/:id/reblog id)
  (request
   'POST
   (format #f "/api/v1/statuses/~a/reblog" id)
   #:authorization? #t))

(define-public (unreblog id)
  (define-values (res body)
    (/api/v1/statuses/:id/unreblog id))
  (case (response-code res)
    ((200) #t)
    (else
     (error "unreblog: failed" res body))))

(define (/api/v1/statuses/:id/unreblog id)
  (request
   'POST
   (format #f "/api/v1/statuses/~a/unreblog" id)
   #:authorization? #t))

(define* (raw-request method path #:key (headers '()) (body "") authorization? streaming?)
  (receive (res body)
      (http-request (string-append "https://"
                                   (current-mastodon-host)
                                   path)
                    #:method method
                    #:headers `(,@headers
                                ,@(and/nil
                                   authorization?
                                   `((authorization
                                      ,(string->symbol
                                        (string-append
                                         "Bearer "
                                         (current-mastodon-access-token)))))))
                    #:decode-body? #f
                    #:streaming? streaming?
                    #:body body)
    (values res body)))

(define* (request method path
                  #:key
                  json
                  authorization?)
  (receive (res body)
      (raw-request method path
                   #:body (and json
                               (scm->json-string json))
                   #:headers (and/nil json
                                      '((content-type application/json)))
                   #:authorization? authorization?)
    (if (= 200 (response-code res))
        (values res (json-string->scm (utf8->string body)))
        (values res body))))

(define*-public (fetch-account id)
  (receive (res body)
      (/api/v1/accounts/:id id)
    (case (response-code res)
      ((200) (make-account body))
      ((401)
       (error "fetch-account: Unauthorized" id))
      ((404)
       (error "fetch-account: Not Found" id))
      ((410)
       (error "fetch-account: Account is suspended" id))
      (else
       (error "fetch-account: failed"
              (response-code res)
              (utf8->string body))))))

(define* (/api/v1/accounts/:id id)
  (request
   'GET
   (format #f "/api/v1/accounts/~a" id)))