-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathytel-show.el
808 lines (640 loc) · 27.8 KB
/
ytel-show.el
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
;;; ytel-show.el --- Browse youtube in emacs -*- lexical-binding: t; -*-
;; Copyright (C) 2020 Valeriy Litkovskyy
;; Author: Valeriy Litkovskyy
;; Keywords: youtube multimedia
;; Version: 0.1.0
;; URL: https://github.com/xFA25E/ytel-show
;; Package-Requires: ((ytel "0.1.0") (emacs "26.1"))
;; This program 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.
;; This program 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 this program. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Ytel-Show: browse youtube video in Emacs
;;
;; This package relies on `YTEL' package to fetch information.
;;
;;
;; Easy setup:
;;
;; (define-key ytel-mode-map (kbd "RET") #'ytel-show)
;;
;; OR
;;
;; (use-package ytel-show
;; :after ytel
;; :bind (:map ytel-mode-map ("RET" . ytel-show)))
;;
;;
;; Usage:
;;
;; Ytel-Show:
;; n/p - switch videos
;; G - recache video information
;;
;; Ytel-Show-Comments:
;; l - go to previous page
;; g - retry downloading failed page
;;
;; Customization:
;;
;; Default buffer name: `YTEL-SHOW-DEFAULT-BUFFER-NAME'
;; `YTEL-SHOW-COMMENTS-DEFAULT-BUFFER-NAME'.
;;
;; Thumbnail sizes: `YTEL-SHOW-IMAGE-MAX-WIDTH' `YTEL-SHOW-IMAGE-MAX-HEIGHT'
;;
;; Faces: `YTEL-SHOW-VIDEO-LIKES-FACE' `YTEL-SHOW-AUTHOR-SUBS-FACE'
;; `YTEL-SHOW-COMMENTS-OWNER-FACE'
;;
;;
;; Extensibility:
;;
;; You can easily extend this package by giving `YTEL-SHOW' function a BUFFER
;; argument and a vector of VIDEO-IDS. Your videos will be display in a new
;; buffer. For example: you could customize `BROWSE-URL-BROWSER-FUNCTION' to
;; detect youtube video urls and display them using YTEL-SHOW.
;;
;; Same thing with `YTEL-SHOW-COMMENTS'. It takes ID, TITLE and a BUFFER.
;;
;; Note:
;;
;; Viewed videos are set with `YTEL-SHOW' command. In order to load videos from
;; other *ytel* pages, you should switch page in *ytel* buffer and call
;; `YTEL-SHOW' again.
;;
;; Same thing with `YTEL-SHOW-COMMENTS' command. It sets all the necessary
;; information.
;;
;; Caveats:
;;
;; Sometimes json-reader will fail to parse a response from invidious instance
;; or the connection will timeout. You will see an almost empty buffer.
;; Usually,hitting the /G/ (`YTEL-SHOW-RELOAD-VIDEO-DATA') key a couple of times
;; helps.
;;
;; Sometimes invidous instance will send empty author thumbnail urls, so they
;; will not be shown.
;;
;; If the first comments page will fail to load, try hitting /g/.
;;
;; If nothing of the above helps, change invidious instance.
;;
;; Currently, I don't have a solution for these problems.
;;; Code:
;;;; SHOW VIDEO
;;;;; IMPORTS
(require 'files)
(require 'simple)
(require 'subr-x)
(require 'seq)
(require 'shr)
(require 'ytel)
;;;;; TYPES
(cl-defstruct (ytel-show--video (:constructor ytel-show--video-create)
(:copier nil))
"Cached video data."
title thumbnail-data description published
length views likes dislikes author-id)
(cl-defstruct (ytel-show--author (:constructor ytel-show--author-create)
(:copier nil))
"Cached author data."
name thumbnail-data subs)
;;;;; VARIABLES
;;;;;; INTERNAL
(defvar-local ytel-show--video-ids nil
"A vector of stored video ids.")
(defvar-local ytel-show--index 0
"Current video index in `YTEL-SHOW--VIDEO-IDS'.")
(defvar ytel-show--video-fields
(string-join '("videoId" "title" "videoThumbnails"
"description" "published" "lengthSeconds"
"viewCount" "likeCount" "dislikeCount"
"author" "authorId" "authorThumbnails" "subCountText")
",")
"Requested fields in a query to indidious instance. Used to save bandwidth.")
(defvar ytel-show--videos-cache (make-hash-table :test 'equal :size 20)
"Hash-table with cached video data.")
(defvar ytel-show--authors-cache (make-hash-table :test 'equal :size 20)
"Hash-table with cached author data.")
;;;;;; MAPS
(defvar ytel-show-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "n") #'ytel-show-next-video)
(define-key map (kbd "p") #'ytel-show-previous-video)
(define-key map (kbd "G") #'ytel-show-reload-video-data)
(define-key map (kbd "c") #'ytel-show-comments)
map)
"Keymap for `YTEL-SHOW-MODE'.")
;;;;;; CUSTOM
(defgroup ytel-show nil
"View youtube video details from ytel."
:group 'applications)
(defcustom ytel-show-default-buffer-name "*ytel-show*"
"Default buffer name used when the `BUFFER' argument in `YTEL-SHOW' is nil."
:type 'string
:group 'ytel-show)
(defcustom ytel-show-image-max-width 800.0
"Max image width. This variable is used to scale images in buffer."
:type 'float
:group 'ytel-show)
(defcustom ytel-show-image-max-height 400.0
"Max image height. This variable is used to scale images in buffer."
:type 'float
:group 'ytel-show)
(defface ytel-show-video-likes-face
'((t :inherit font-lock-doc-face))
"Face used for the video likes and dislikes."
:group 'ytel-show)
(defface ytel-show-author-subs-face
'((t :inherit font-lock-string-face))
"Face used for the author subs."
:group 'ytel-show)
;;;;; FUNCTIONS
(defun ytel-show--current-video-id ()
"Get currently showed video id."
(aref ytel-show--video-ids ytel-show--index))
(defun ytel-show--check-response-error (response)
"Check if `RESPONSE' is an error and signal an error."
(if-let ((msg (alist-get 'error response)))
(error msg)
response))
(defun ytel-show--query-video (id)
"Query invidous instance for video data by `ID'."
(ytel-show--check-response-error
(ytel--API-call (concat "videos/" id) `(("fields" ,ytel-show--video-fields)))))
;;;;;; THUMBNAILS
(defun ytel-show--repair-thumbnail-urls (thumbnails)
"Repair broken urls in `THUMBNAILS'.
Some urls might be without \"https:\" or \"https://i.ytimg.com\" prefix. Detect
these urls and try to repair them."
(let* ((id (ytel-show--current-video-id))
(single-slash-rx (rx bos "/vi/" (literal id) "/maxres.jpg" eos)))
(seq-map
(lambda (thumbnail)
(let-alist thumbnail
(cond ((string-match-p single-slash-rx .url)
(setf (alist-get 'url thumbnail) (concat "https://i.ytimg.com" .url)))
((string-match-p (rx bos "//yt3.ggpht.com") .url)
(setf (alist-get 'url thumbnail) (concat "https:" .url)))))
thumbnail)
thumbnails)))
(defun ytel-show--filter-thumbnails (thumbnails)
"Filter `THUMBNAILS' from invidious response.
`THUMBNAILS' is a vector of alists with keys: url, width and height. Return a
sequence with alists with the following properties:
url
non empty string that tharts with \"https?://\" and does not includes
`YTEL-INVIDIOUS-API-URL'
width and height
number greater than 0"
(seq-filter
(lambda (thumbnail)
(let-alist thumbnail
(and (numberp .width) (< 0 .width)
(numberp .height) (< 0 .height)
(stringp .url) (not (string-empty-p .url))
(string-match-p (rx bos "http" (? "s") "://") .url)
(not (string-match-p (regexp-quote ytel-invidious-api-url) .url)))))
thumbnails))
(defun ytel-show--retrieve-image (url)
"Synchronously retrieve image from `URL'.
On 404 return :not-found."
(let ((buffer (url-retrieve-synchronously url)))
(unwind-protect
(with-current-buffer buffer
(goto-char (point-min))
(if (search-forward "HTTP/1.1 404" nil t)
:not-found
(search-forward "\n\n")
(buffer-substring (point) (point-max))))
(kill-buffer buffer))))
(defun ytel-show--valid-image-sizes-p (width height)
"Check whether `WIDTH' and `HEIGHT' are smaller than max allowed values."
(or (< ytel-show-image-max-width width) (< ytel-show-image-max-height height)))
(defun ytel-show--scale-images-sizes (width height)
"Scale `WIDTH' and `HEIGHT' to fit max allowed values."
(min (/ ytel-show-image-max-width width) (/ ytel-show-image-max-height height)))
(defun ytel-show--thumbnail-load-data (thumbnail)
"Load image data from `THUMBNAIL's url.
Scale it to satisfy `YTEL-SHOW-IMAGE-MAX-WIDTH' and
`YTEL-SHOW-IMAGE-MAX-HEIGHT'."
(when thumbnail
(let-alist thumbnail
(let ((data (ytel-show--retrieve-image .url)))
(cond ((eq :not-found data) data)
((ytel-show--valid-image-sizes-p .width .height)
(create-image
data nil t :scale (ytel-show--scale-images-sizes .width .height)))
(t (create-image data nil t)))))))
(defun ytel-show--select-thumbnail (thumbnails)
"Select thumbnail from `THUMBNAILS' with the biggest height."
(seq-reduce
(lambda (thumbnail next)
(if (<= (alist-get 'height thumbnail) (alist-get 'height next))
next
thumbnail))
(seq-subseq thumbnails 1) (elt thumbnails 0)))
(defun ytel-show--delete-thumbnail (thumbnail thumbnails)
"Delete element from `THUMBNAILS' matching `THUMBNAIL's url."
(cl-delete (alist-get 'url thumbnail) thumbnails
:test #'string-equal
:key (apply-partially #'alist-get 'url)))
(defun ytel-show--get-thumbnail (thumbnails)
"Select thumbnail from `THUMBNAILS' and load it's data."
(cl-case (length thumbnails)
(0 nil)
(1 (elt thumbnails 0))
(t (let* ((thumbnail (ytel-show--select-thumbnail thumbnails))
(data (ytel-show--thumbnail-load-data thumbnail)))
(if (and (not (eq :not-found data)) data) data
(ytel-show--get-thumbnail
(ytel-show--delete-thumbnail thumbnail thumbnails)))))))
(defun ytel-show--process-thumbnails (thumbnails)
"Repair `THUMBNAILS' | filter | select | load."
(thread-last thumbnails
ytel-show--repair-thumbnail-urls
ytel-show--filter-thumbnails
ytel-show--get-thumbnail))
;;;;;; UPDATE
(defun ytel-show--update-video (video query-response &optional recache-images)
"Update `VIDEO' struct with the data from `QUERY-RESPONSE'.
If `RECACHE-IMAGES' is non-nil, redownload thumbnails. Return updated `VIDEO'."
(let-alist query-response
(when (or recache-images (null (ytel-show--video-thumbnail-data video)))
(when-let ((thumbnail (ytel-show--process-thumbnails .videoThumbnails)))
(setf (ytel-show--video-thumbnail-data video) thumbnail)))
(when .title (setf (ytel-show--video-title video) .title))
(when .description (setf (ytel-show--video-description video) .description))
(when .published (setf (ytel-show--video-published video) .published))
(when .lengthSeconds (setf (ytel-show--video-length video) .lengthSeconds))
(when .viewCount (setf (ytel-show--video-views video) .viewCount))
(when .likeCount (setf (ytel-show--video-likes video) .likeCount))
(when .dislikeCount (setf (ytel-show--video-dislikes video) .dislikeCount))
(when .authorId (setf (ytel-show--video-author-id video) .authorId)))
video)
(defun ytel-show--update-author (author query-response &optional recache-images)
"Update `AUTHOR' struct with the data from `QUERY-RESPONSE'.
If `RECACHE-IMAGES' is supplied, redownload thumbnails. Return updated `AUTHOR'."
(let-alist query-response
(when (or recache-images (null (ytel-show--author-thumbnail-data author)))
(when-let ((thumbnail (ytel-show--process-thumbnails .authorThumbnails)))
(setf (ytel-show--author-thumbnail-data author) thumbnail)))
(when .author (setf (ytel-show--author-name author) .author))
(when .subCountText (setf (ytel-show--author-subs author) .subCountText)))
author)
(defun ytel-show--update-cache (id &optional recache-images)
"Update cached data by video `ID'.
If `RECACHE-IMAGES' is non-nil, redownlaod thumbnails. Return an alist with the
following keys:
id - video `ID'
video - video struct with cached data
author - author struct with cached data"
(let* ((query-response (ytel-show--query-video id))
(video (ytel-show--update-video
(or (gethash id ytel-show--videos-cache)
(puthash id (ytel-show--video-create)
ytel-show--videos-cache))
query-response recache-images))
(author-id (ytel-show--video-author-id video))
(author (ytel-show--update-author
(or (gethash author-id ytel-show--authors-cache)
(puthash author-id (ytel-show--author-create)
ytel-show--authors-cache))
query-response recache-images)))
`((id . ,id) (video . ,video) (author . ,author))))
(defun ytel-show--update-index (add &optional cycle)
"Update `YTEL-SHOW--INDEX' by adding `ADD' to it.
If `CYCLE' is non-nil then the addition is performed with modulus."
(let ((new-index (+ add ytel-show--index))
(length (length ytel-show--video-ids)))
(cond
(cycle
(setq ytel-show--index (mod new-index length)))
((<= 0 new-index (1- length))
(setq ytel-show--index new-index)))))
;;;;;; DATA
(defun ytel-show--video-data (id)
"Get cached data by video `ID'.
If the video is not cached, then query the invidious instance. Return value is
described in `YTEL-SHOW--UPDATE-CACHE'."
(if-let* ((video (gethash id ytel-show--videos-cache))
(author (gethash (ytel-show--video-author-id video)
ytel-show--authors-cache)))
`((id . ,id) (video . ,video) (author . ,author))
(ytel-show--update-cache id)))
;;;;;; DRAW
(defun ytel-show--draw-url (url title)
"Draw `URL' using shr with `TITLE' at current point."
(let ((point (point)))
(insert (format "%s" title))
(make-text-button
point (point)
'follow-link t 'mouse-face 'highlight 'shr-url url 'keymap shr-map)))
(defun ytel-show--draw-button (title action &rest props)
"Draw a `TITLE' button with `ACTION'."
(let ((point (point)))
(insert title)
(apply #'make-text-button point (point) 'follow-link t 'action action props)))
(defun ytel-show--format-video-likes-dislikes (likes &optional dislikes)
"Format `LIKES' and `DISLIKES' before inserting them to buffer."
(let ((s (concat (format "[likes:%s" likes)
(when dislikes (format "/%s" dislikes))
"]")))
(propertize s 'face 'ytel-show-video-likes-face)))
(defun ytel-show--format-author-subs (subs)
"Format `SUBS' before inserting them to buffer."
(propertize (format "(%s)" subs) 'face 'ytel-show-author-subs-face))
(defun ytel-show--draw-data (data)
"Draw video `DATA' to the buffer.
`DATA' is the value returned from `YTEL-SHOW--VIDEO-DATA'."
(let-alist data
(ytel-show--draw-button "Previous" '(lambda (_) (ytel-show-previous-video)))
(insert " - ")
(ytel-show--draw-button "Next" '(lambda (_) (ytel-show-next-video)))
(insert "\n")
(ytel-show--draw-url
(concat "https://www.youtube.com/watch?v=" .id)
(or (ytel-show--video-title .video) "no title"))
(insert " - ")
(when-let ((name (ytel-show--author-name .author))
(author-id (ytel-show--video-author-id .video)))
(ytel-show--draw-url (concat "https://www.youtube.com/channel/" author-id) name)
(insert " "))
(when-let ((subs (ytel-show--author-subs .author)))
(insert (ytel-show--format-author-subs subs) "\n"))
(when-let ((length (ytel-show--video-length .video)))
(insert (ytel--format-video-length length) " - "))
(when-let ((published (ytel-show--video-published .video)))
(insert (ytel--format-video-published published) " - "))
(when-let ((views (ytel-show--video-views .video)))
(insert (ytel--format-video-views views) " - "))
(when-let ((likes (ytel-show--video-likes .video))
(dislikes (ytel-show--video-dislikes .video)))
(insert (ytel-show--format-video-likes-dislikes likes dislikes) " - "))
(ytel-show--draw-button "View comments" '(lambda (_) (call-interactively 'ytel-show-comments)))
(insert " - ")
(ytel-show--draw-button "Close" '(lambda (_) (quit-window)))
(insert "\n")
(when-let ((thumbnail-data (ytel-show--video-thumbnail-data .video)))
(insert-image thumbnail-data) (insert "\n"))
(when-let ((description (ytel-show--video-description .video)))
(insert description "\n"))
(when-let ((author-thumbnail-data (ytel-show--author-thumbnail-data .author)))
(insert-image author-thumbnail-data) (insert "\n"))))
;;;;; COMMANDS
(defun ytel-show-revert-buffer (&rest _)
"Revert current Ytel-Show buffer.
Erase the buffer and redraw current video's data."
(interactive)
(let ((inhibit-read-only t)
(id (ytel-show--current-video-id)))
(message "Loading %s..." id)
(erase-buffer)
(ytel-show--draw-data (ytel-show--video-data id))
(goto-char (point-min))
(message "Showing %s..." id)))
(defun ytel-show-next-video (&optional cycle)
"Switch to the next video in `YTEL-SHOW--VIDEO-IDS' and draw it.
With overflow, cycle if `CYCLE' is provided."
(interactive "P")
(let ((inx ytel-show--index))
(ytel-show--update-index 1 cycle)
(if (= inx ytel-show--index)
(message "Wall! Use argument to cycle!")
(ytel-show-revert-buffer))))
(defun ytel-show-previous-video (&optional cycle)
"Switch to the previous video in `YTEL-SHOW--VIDEO-IDS' and draw it.
With overflow, cycle if `CYCLE' is provided."
(interactive "P")
(let ((inx ytel-show--index))
(ytel-show--update-index -1 cycle)
(if (= inx ytel-show--index)
(message "Wall! Use argument to cycle!")
(ytel-show-revert-buffer))))
(defun ytel-show-reload-video-data (&optional recache-images)
"Recache current video's data and redraw the current buffer.
If `RECACHE-IMAGES' is non-nil, redownload thumbnails."
(interactive "P")
(message "Reloading %s..." (ytel-show--current-video-id))
(ytel-show--update-cache (ytel-show--current-video-id) recache-images)
(ytel-show-revert-buffer))
;;;###autoload
(cl-defun ytel-show (video-ids &optional (index 0) (buffer ytel-show-default-buffer-name))
"Show video information in the Ytel-Show buffer.
This is the main entry function for this package. Interactively, it must be
called from a `YTEL' buffer.
`VIDEO-IDS' is a vector of strings with youtube video ids to show.
`INDEX' is the index of some video in `VIDEO-IDS' that will be cached and
displayed first.
If `BUFFER' is nil, then `YTEL-SHOW-DEFAULT-BUFFER-NAME' is used. To display
videos from `VIDEO-IDS'."
(interactive (if (not (derived-mode-p 'ytel-mode))
(error "Not in the ytel buffer")
(list (vconcat (seq-map #'ytel-video-id ytel-videos))
(1- (line-number-at-pos)))))
(unless (and (vectorp video-ids)
(seq-every-p (lambda (s) (and (stringp s) (= 11 (length s)))) video-ids)
(integerp index) (<= 0 index (1- (length video-ids))))
(error "Invalid arguments to `YTEL-SHOW'"))
(switch-to-buffer (get-buffer-create buffer))
(unless (derived-mode-p 'ytel-show-mode)
(ytel-show-mode))
(setq-local ytel-show--video-ids video-ids ytel-show--index index)
(ytel-show-revert-buffer))
(define-derived-mode ytel-show-mode special-mode "Ytel-Show"
"Mode for displaying youtube video information."
:group 'ytel-show
(setq-local revert-buffer-function #'ytel-show-revert-buffer))
(provide 'ytel-show)
;;;; SHOW COMMENTS
;;;;; TYPES
(cl-defstruct (ytel-show-comments--comment
(:constructor ytel-show-comments--comment-create)
(:copier nil))
author author-id content published likes ownerp heart replies)
;;;;; VARIABLES
;;;;;; INTERNAL
(defvar ytel-show-comments--authors-cache
(make-hash-table :test 'equal :size 100 :rehash-size 2.5)
"Cache used to store author thumbnails of comments.")
;;;;;;; LOCAL
(defvar-local ytel-show-comments--video-id nil
"Video id used it `YTEL-SHOW-COMMENTS-MODE'.")
(defvar-local ytel-show-comments--video-title "video"
"Title used at the top of the buffer.")
(defvar-local ytel-show-comments--history nil
"Stored pages of comments.")
(defvar-local ytel-show-comments--comment-count nil
"Communt count.")
;;;;;; MAPS
(defvar ytel-show-comments-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "l") #'ytel-show-comments-previous-page)
map)
"Map used by `YTEL-SHOW-COMMENTS-MODE'.")
;;;;;; CUSTOM
(defcustom ytel-show-comments-default-buffer-name "*ytel-show-comments*"
"Default buffer name for `YTEL-SHOW-COMMENTS-MODE'."
:type 'string
:group 'ytel-show)
(defface ytel-show-comments-owner-face
'((t :inherit hl-line))
"Face used for owner's text."
:group 'ytel-show)
;;;;; FUNCTIONS
(defun ytel-show-comments--query-comments (id &optional continuation)
"Query invidious instance for comments of video identified by `ID'.
If `CONTINUATION' is supplied, show continuation of comments."
(ytel-show--check-response-error
(ytel--API-call
(concat "comments/" id)
(when continuation `(("continuation" ,continuation))))))
;;;;;; UPDATE
(defun ytel-show-comments--parse-comment (response)
"Parse comment from `RESPONSE'.
Return comment on success, or nil."
(when response
(let-alist response
(when (and .authorId (null (gethash .authorId ytel-show-comments--authors-cache)))
(when-let ((ytel-show--video-ids (vector ytel-show-comments--video-id))
(thumbnail (ytel-show--process-thumbnails .authorThumbnails)))
(puthash .authorId thumbnail ytel-show-comments--authors-cache)))
(ytel-show-comments--comment-create
:author .author
:author-id .authorId
:content .content
:published .published
:likes .likeCount
:ownerp (when .authorIsChannelOwner (not (eq :json-false .authorIsChannelOwner)))
:heart .creatorHeart.creatorName
:replies (when .replies (cons .replies.replyCount .replies.continuation))))))
(defun ytel-show-comments--add-to-history (id &optional continuation)
"Add new page to comments history.
Comments are taken frome video `ID' and it's `CONTINUATION' (if supplied).
Return '(comments . continuation) on success, or nil. Comments is a sequence of
`ytel-show-comments--comment' struct."
(when-let ((response (ytel-show-comments--query-comments id continuation)))
(let-alist response
(when .commentCount
(setf ytel-show-comments--comment-count .commentCount))
(when-let ((comments (seq-map #'ytel-show-comments--parse-comment .comments)))
(car (push (cons comments .continuation) ytel-show-comments--history))))))
(defun ytel-show-comments--follow-continuation (button)
"Follow `CONTINUATION'.
Add new page to history and load it. This is used in buttons."
(message "Loading next page")
(if-let ((continuation (button-get button 'continuation)))
(ytel-show-comments--add-to-history ytel-show-comments--video-id continuation)
(error "no continuation in button"))
(ytel-show-comments-revert-buffer))
;;;;;; DATA
(defun ytel-show-comments--comments-data (id)
"Get comment data by `ID' or download first page of videos comments.
Return value is described in `YTEL-SHOW-COMMENTS--ADD-TO-HISTORY'."
(or (car ytel-show-comments--history)
(ytel-show-comments--add-to-history id)))
;;;;;; DRAW
(defun ytel-show-comments--format-owner (owner)
"Format `OWNER's text."
(propertize owner 'face 'ytel-show-comments-owner-face))
(defun ytel-show-comments--draw (data)
"Draw comment `DATA' on buffer.
`DATA' is a return value of `YTEL-SHOW-COMMENTS--COMMENTS-DATA'."
(when data
(cl-destructuring-bind (comments . continuation) data
(ytel-show--draw-url
(concat "https://www.youtube.com/watch?v=" ytel-show-comments--video-id)
ytel-show-comments--video-title)
(when ytel-show-comments--comment-count
(insert (format " (%s comments)\n" ytel-show-comments--comment-count)))
(let ((length (length ytel-show-comments--history)))
(insert (format "Page %s - " length))
(ytel-show--draw-button
(if (= 1 length) "Reload" "Go back")
'(lambda (_) (ytel-show-comments-previous-page)))
(insert " - "))
(ytel-show--draw-button "Close" '(lambda (_) (quit-window)))
(insert "\n\n")
(seq-doseq (comment comments)
(when-let* ((author-id (ytel-show-comments--comment-author-id comment))
(thumbnail (gethash author-id ytel-show-comments--authors-cache)))
(insert-image thumbnail))
(when-let ((name (ytel-show-comments--comment-author comment))
(author-id (ytel-show-comments--comment-author-id comment)))
(insert " ")
(ytel-show--draw-url (concat "https://www.youtube.com/channel/" author-id) name))
(when-let ((published (ytel-show-comments--comment-published comment)))
(insert " - " (ytel--format-video-published published)))
(when-let ((likes (ytel-show-comments--comment-likes comment)))
(when (< 0 likes)
(insert " - " (ytel-show--format-video-likes-dislikes likes))))
(when-let ((ownerp (ytel-show-comments--comment-ownerp comment)))
(insert " - " (ytel-show-comments--format-owner "OWNER")))
(insert "\n")
(when-let ((content (ytel-show-comments--comment-content comment)))
(insert content "\n\n"))
(when-let ((heart (ytel-show-comments--comment-heart comment)))
(insert (ytel-show-comments--format-owner
(concat heart " likes this comment"))
"\n\n"))
(when-let ((replies (ytel-show-comments--comment-replies comment)))
(cl-destructuring-bind (count . continuation) replies
(when continuation
(ytel-show--draw-button
(format "View %s replies" count)
#'ytel-show-comments--follow-continuation
'continuation continuation)
(insert "\n\n"))))
"\n")
(when continuation
(ytel-show--draw-button
"View next page"
#'ytel-show-comments--follow-continuation
'continuation continuation)
(insert "\n")))))
;;;;; COMMANDS
(defun ytel-show-comments-previous-page ()
"Go to previous page in comments history."
(interactive)
(message "Loading previous page")
(pop ytel-show-comments--history)
(ytel-show-comments-revert-buffer))
(defun ytel-show-comments-revert-buffer (&rest _)
"Revert current ytel-show-comments buffer."
(interactive)
(let ((inhibit-read-only t))
(message "Loading %s..." ytel-show-comments--video-id)
(erase-buffer)
(ytel-show-comments--draw
(ytel-show-comments--comments-data ytel-show-comments--video-id))
(goto-char (point-min))
(message "Showing %s..." ytel-show-comments--video-id)))
(defun ytel-show-comments (id &optional title buffer)
"Entry function to show video `ID's comments.
`TITLE' will be shown at the top of the buffer. `BUFFER' is a name of the
buffer the will be created. If called interactively, these values are taken
automatically from ytel-show buffer."
(interactive
(if (not (derived-mode-p 'ytel-show-mode))
(error "Not in the ytel-show buffer")
(let ((id (ytel-show--current-video-id)))
(list id (ytel-show--video-title (gethash id ytel-show--videos-cache))))))
(switch-to-buffer
(get-buffer-create (or buffer ytel-show-comments-default-buffer-name)))
(unless (derived-mode-p 'ytel-show-comments-mode)
(ytel-show-comments-mode))
(unless (string= ytel-show-comments--video-id id)
(when title (setq-local ytel-show-comments--video-title title))
(setq-local ytel-show-comments--video-id id ytel-show-comments--history nil))
(ytel-show-comments-revert-buffer))
(define-derived-mode ytel-show-comments-mode special-mode "Ytel-Show-Comments"
"Mode for displaying youtube video comments."
:group 'ytel-show
(setq-local revert-buffer-function #'ytel-show-comments-revert-buffer))
;;; ytel-show.el ends here