1 ;;; youtube-dl.el --- manages a youtube-dl queue -*- lexical-binding: t; -*-
3 ;; This is free and unencumbered software released into the public domain.
5 ;; Author: Christopher Wellons <wellons@nullprogram.com>
6 ;; URL: https://github.com/skeeto/youtube-dl-emacs
8 ;; Package-Requires: ((emacs "27.1"))
12 ;; This package manages a video download queue for the youtube-dl
13 ;; command line program, which serves as its back end. It manages a
14 ;; single youtube-dl subprocess to download one video at a time. New
15 ;; videos can be queued at any time.
17 ;; The `youtube-dl' command queues a URL for download. Failures are
18 ;; retried up to `youtube-dl-max-failures'. Items can be paused or set
19 ;; to be downloaded at a slower download rate (`youtube-dl-slow-rate-limit').
21 ;; The `youtube-dl-download-playlist' command queues an entire playlist, just
22 ;; as if you had individually queued each video on the playlist.
24 ;; The `youtube-dl-list' command displays a list of all active video
25 ;; downloads. From this list, items under point can be canceled (d),
26 ;; paused (p), slowed (s), and have its priority adjusted ([ and ]).
33 (require 'notifications
)
35 (defgroup youtube-dl
()
36 "Download queue for the youtube-dl command line program."
39 (defcustom youtube-dl-directory
"~/Downloads/"
40 "Directory in which to run youtube-dl."
44 (defcustom youtube-dl-program
45 ;; "yt-dlp" is a fork of "youtube-dl".
47 ((executable-find "yt-dlp") "yt-dlp")
48 ((executable-find "youtube-dl") "youtube-dl"))
49 "The name of the program invoked for downloading YouTube videos.
50 NOTE: It's specified by program name instead of program path."
55 (defcustom youtube-dl-arguments
56 '("--newline" "--no-mtime" "--restrict-filenames" "--no-warnings")
57 "Arguments to be send to youtube-dl.
58 Instead of --limit-rate use custom option `youtube-dl-slow-rate-limit'."
59 :type
'(repeat string
)
63 (defcustom youtube-dl-proxy
""
64 "Specify the proxy for youtube-dl command.
68 socks5://127.0.0.1:1086"
73 (defcustom youtube-dl-proxy-url-list
'()
74 "A list of URL domains which should use proxy for youtube-dl."
79 (defcustom youtube-dl-auto-show-list t
80 "Auto show youtube-dl-list buffer."
85 (defcustom youtube-dl-process-model
'multiple-processes
86 "Determine youtube-dl.el downloading process model."
88 :type
'(choice (symbol :tag
"single process only" 'single-process
)
89 (symbol :tag
"multiple processes" 'multiple-processes
)))
91 (defcustom youtube-dl-max-failures
8
92 "Maximum number of retries for a single video."
97 (defcustom youtube-dl-slow-rate-limit
"2M"
98 "Download rate for slow item (corresponding to option --limit-rate)."
103 (defcustom youtube-dl-notify
(cl-case system-type
107 "Whether raise notifications."
112 (defcustom youtube-dl-destination-illegal-filename-chars-regex
"[#$%+!<>&*|{}?=@:/\\\"'`]"
113 "Specify the regex of invalid destination filename.
114 This will avoid youtube-dl can't save invalid filename caused error.
115 https://www.mtu.edu/umc/services/websites/writing/characters-avoid/"
121 ;; (replace-regexp-in-string
122 ;; youtube-dl-destination-illegal-filename-chars-regex "-"
123 ;; "[#$%+!<>&*|{}?=@:/\\\"'`]")
125 (defface youtube-dl-active
126 '((t :inherit font-lock-function-name-face
:foreground
"forest green"))
127 "Face for highlighting the active download item."
130 (defface youtube-dl-slow
131 '((t :inherit font-lock-variable-name-face
:foreground
"orange"))
132 "Face for highlighting the slow (S) tag."
135 (defface youtube-dl-pause
136 '((t :inherit font-lock-type-face
:foreground
"gray"))
137 "Face for highlighting the pause (P) tag."
140 (defface youtube-dl-priority
141 '((t :inherit font-lock-keyword-face
:foreground
"light blue"))
142 "Face for highlighting the priority marker."
145 (defface youtube-dl-failure
146 '((t :inherit font-lock-warning-face
:foreground
"red"))
147 "Face for highlighting the failure marker."
150 (defvar-local youtube-dl--log-item nil
151 "Item currently being displayed in the log buffer.")
153 (cl-defstruct (youtube-dl-item (:constructor youtube-dl-item--create
)
155 "Represents a single video to be downloaded with youtube-dl."
156 url
; Video URL (string)
157 vid
; Video ID (integer)
158 directory
; Working directory for youtube-dl (string or nil)
159 destination
; Preferred destination file (string or nil)
160 running
; Status indicator of process (boolean)
161 failures
; Number of video download failures (integer)
162 priority
; Download priority (integer)
163 title
; Listing display title (string or nil)
164 percentage
; Current download percentage (string or nil)
165 total-size
; Total download size (string or nil)
166 log
; All program output (list of strings)
167 log-end
; Last log item (list of strings)
168 paused-p
; Non-nil if download is paused (boolean)
169 slow-p
; Non-nil if download should be rate limited (boolean)
170 rate-limit
; Download rate limit (e.g. 50K or 2M)
171 buffer
; the process buffer name
172 process
; the process object
173 download-rate
; Download rate in bytes per second (e.g. 50K or 2M)
174 eta
; ETA time (e.g. 01:01:57)
177 (defvar youtube-dl-items
()
178 "List of all items still to be downloaded.")
180 (defvar youtube-dl-process nil
181 "The currently active youtube-dl process.")
183 (defun youtube-dl--process-buffer-name (vid)
184 "Return the process buffer name which constructed with VID."
185 (format " *youtube-dl vid:%s*" vid
))
187 (defun youtube-dl--proxy-append (url &optional option value
)
188 "Decide whether append proxy option in youtube-dl command based on URL."
189 (let ((domain (url-domain (url-generic-parse-url url
))))
190 (if (and (member domain youtube-dl-proxy-url-list
) ; <-- whether toggle proxy?
191 (not (string-empty-p youtube-dl-proxy
)))
192 (if option
; <-- whether has command-line option?
193 (list "--proxy" youtube-dl-proxy option value
)
194 (list "--proxy" youtube-dl-proxy
))
195 (if option
; <-- return original arguments for no proxy
197 nil
; <-- return nothing for url no need proxy
200 (defun youtube-dl--next ()
201 "Returns the next item to be downloaded."
202 (let (best best-score
)
203 (dolist (item youtube-dl-items best
)
204 (let* ((failures (youtube-dl-item-failures item
))
205 (priority (youtube-dl-item-priority item
))
206 (paused-p (youtube-dl-item-paused-p item
))
207 (score (- priority failures
)))
208 (when (and (not paused-p
)
209 (< failures youtube-dl-max-failures
))
213 ((> score best-score
)
215 best-score score
))))))))
217 (defun youtube-dl--current ()
218 "Return the item currently being downloaded."
219 (when youtube-dl-process
220 (plist-get (process-plist youtube-dl-process
) :item
)))
222 (defun youtube-dl--remove (item)
223 "Remove ITEM from the queue and kill process."
224 (let ((proc (youtube-dl-item-process item
)))
225 (when (process-live-p proc
) ; `kill-process' only when `proc' is still alive.
226 (kill-process proc
)))
227 (setf youtube-dl-items
(cl-delete item youtube-dl-items
)))
229 (defun youtube-dl--add (item)
230 "Add ITEM to the queue."
231 (setf youtube-dl-items
(nconc youtube-dl-items
(list item
))))
233 (defvar youtube-dl--timer-item nil
234 "A global variable for passing ITEM into `youtube-dl--run' in `run-with-timer'.")
236 (defun youtube-dl--sentinel (proc status
)
237 (when-let ((item (plist-get (process-plist proc
) :item
)))
238 ;; (setf youtube-dl-process proc) ; dont' need to set current process.
240 ;; process status is finished.
241 ((equal status
"finished\n")
242 ;; mark item structure property `:running' to `nil'.
243 (setf (youtube-dl-item-running item
) nil
)
244 (youtube-dl--remove item
)
245 (when youtube-dl-notify
246 (notifications-notify :title
"youtube-dl.el" :body
"Download finished.")))
247 ;; detect whether process is in "pause" process status?
248 ((youtube-dl-item-paused-p item
)
249 ;; mark item structure property `:running' to `nil'.
250 (setf (youtube-dl-item-running item
) nil
)
251 (message "[youtube-dl] process %s is paused." proc
))
252 ;; when process downloading failed, then retry downloading.
253 ((equal status
"killed: 9\n")
254 ;; mark item structure property `:running' to `nil'.
255 (setf (youtube-dl-item-running item
) nil
)
256 (message "[youtube-dl] process %s is killed." proc
))
258 ;; mark item structure property `:running' to `nil'.
259 (setf (youtube-dl-item-running item
) nil
)
260 (cl-incf (youtube-dl-item-failures item
))
261 ;; record log output to process buffer
262 (let ((buf (youtube-dl--log-buffer item
))
263 (inhibit-read-only t
))
264 (with-current-buffer buf
266 (print (process-plist proc
) buf
)))
268 (if (<= (youtube-dl-item-failures item
) 10)
270 (setq youtube-dl--timer-item item
)
271 (run-with-timer (* 60 5) nil
#'youtube-dl--run
)
272 (message (format "[youtube-dl] delay process %s" proc
)))))))
274 (defun youtube-dl--progress (output)
275 "Return the download progress for the given output.
276 Progress lines that straddle output chunks are lost. That's fine
277 since this is just used for display purposes.
279 Return list: (\"34.6%\" \"~2.61GiB\" \"929.50KiB/s\") "
283 ;; [download] 34.6% of ~2.61GiB at 929.50KiB/s ETA 01:01:57
284 ;; +---+ +------+ +---------+ +------+
285 ((string-equal youtube-dl-program
"youtube-dl")
286 (while (string-match "\\[download\\] +\\([^ ]+%\\) +of *~? *\\([^ ]+\\) +at +\\([^ ]+\\) +ETA +\\([^ \n]+\\)" output start
)
287 (let ((percent (match-string 1 output
))
288 (total-size (match-string 2 output
))
289 (download-rate (match-string 3 output
))
290 (eta (match-string 4 output
)))
291 (setf progress
(list percent total-size download-rate eta
)
292 start
(match-end 0)))))
293 ((string-equal youtube-dl-program
"yt-dlp")
294 ;; The output has non-ASCII shell color codes. Disable it with command-line option "--no-colors".
295 ;; [download] 0.4% of ~ 314.23MiB at 7.54KiB/s ETA 11:48:26 (frag 0/216)
296 ;; +--+ +-------+ +-------+ +------+
297 (while (string-match "\\[download\\] +\\([^ ]+%\\) +of *~? *\\([^ ]+\\) +at +\\([^ ]+\\) +ETA +\\([^ \n]+\\)" output start
)
298 (let ((percent (match-string 1 output
))
299 (total-size (match-string 2 output
))
300 (download-rate (match-string 3 output
))
301 (eta (match-string 4 output
)))
302 ;; filter out not correct matched data.
304 ;; (message "[DEBUG] [youtube-dl] download-rate regexp matched: >>> %s <<<" download-rate)
305 ;; (message "[DEBUG] [youtube-dl] eta regexp matched: >>> %s <<<" eta)
306 (unless (or (string-equal-ignore-case total-size
"Unknown.*")
307 (string-equal-ignore-case eta
"Unknown.*") ; [download] 0.0% of 2.14MiB at Unknown B/s ETA Unknown
309 (setf progress
(list percent total-size download-rate eta
)
310 start
(match-end 0)))))))
313 ;; (cl-destructuring-bind (percentage total-size download-rate eta) progress
314 ;; (message "[DEBUG] [youtube-dl] progress: percent: %s, total-size: %s, speed: %s, eta: %s."
315 ;; percentage total-size download-rate eta)))
318 (defun youtube-dl--get-destination (url)
319 "Return the destination filename for the given `URL' (if any).
320 The destination filename may potentially straddle two output
321 chunks, but this is incredibly unlikely. It's only used for
322 display purposes anyway.
324 $ youtube-dl --get-filename <URL>"
325 (message "[youtube-dl] getting video destination.")
326 (let* ((get-destination-buffer " *youtube-dl-get-destination*")
327 (get-destination-error-buffer " *youtube-dl-get-destination error*")
329 ;; clear destination buffer content to clear destination history.
331 (when (buffer-live-p (get-buffer get-destination-buffer
))
332 (with-current-buffer get-destination-buffer
(erase-buffer)))
333 (when (buffer-live-p (get-buffer get-destination-error-buffer
))
334 (with-current-buffer get-destination-error-buffer
(erase-buffer))))
335 ;; retrieve destination
337 :command
(list youtube-dl-program
"--get-filename" url
)
338 :sentinel
(lambda (proc event
)
339 (if (string= event
"finished\n")
341 (replace-regexp-in-string
342 "\\ +\\[.*\\]" "" ; delete trailing [...] in filename.
343 (replace-regexp-in-string
344 "\n" "" ; delete trailing "\n" character.
345 (with-current-buffer get-destination-buffer
(buffer-string)))))
346 (let* ((buffer-str (with-current-buffer get-destination-error-buffer
(buffer-string)))
347 (match-regex "\\(ERROR\\|Error\\): \\(.*\\)")
348 (error-p (string-match-p match-regex buffer-str
))
349 (matched-str (when (string-match match-regex buffer-str
) (match-string 2 buffer-str
))))
352 (message "[youtube-dl] `youtube-dl--get-destination' error!\n%s" matched-str
)
354 ;; (funcall 'youtube-dl--get-destination url)
357 (message "[youtube-dl] get output filename success.")
358 ;; (kill-process proc)
359 ;; (kill-buffer (process-buffer proc))
361 :name
"youtube-dl-get-destination"
362 :buffer get-destination-buffer
363 :stderr get-destination-error-buffer
)
365 (setq destination-not-returned t
)
367 (when destination-not-returned
369 (if destination
(setq destination-not-returned nil
))))
371 ;; Prompt for user the destination interactively.
373 (setq destination
(substring-no-properties (read-string "[youtube-dl] input destination: "))))
376 (kill-new destination
) ; copy to Emacs kill-ring for later operation.
377 (message "[youtube-dl] destination (filename.mp4): %s" destination
)
380 (defun youtube-dl--filter (proc output
)
381 (if (plist-get (process-plist proc
) :item
)
382 (let* ((item (plist-get (process-plist proc
) :item
))
383 (progress (youtube-dl--progress output
))
384 (destination (youtube-dl-item-destination item
)))
385 ;; Append to program log.
386 (let ((logged (list output
)))
387 (if (and (youtube-dl-item-log item
) (youtube-dl-item-log-end item
)) ; make sure not nil.
388 (setf (cdr (youtube-dl-item-log-end item
)) logged
389 (youtube-dl-item-log-end item
) logged
)
390 (setf (youtube-dl-item-log item
) logged
391 (youtube-dl-item-log-end item
) logged
)))
392 ;; Update progress information.
394 (cl-destructuring-bind (percentage total-size download-rate eta
) progress
395 (setf (youtube-dl-item-percentage item
) percentage
396 (youtube-dl-item-total-size item
) total-size
397 (youtube-dl-item-download-rate item
) download-rate
398 (youtube-dl-item-eta item
) eta
)))
399 ;; monitor process output whether error occured?
400 (let* ((item-log-end (youtube-dl-item-log-end item
))
402 ((stringp item-log-end
) item-log-end
)
403 ((listp item-log-end
) (car (last item-log-end
))))))
404 (if (and (stringp log-end-str
)
405 (or (string-match "ERROR:.*" log-end-str
)
406 (string-match "exited abnormally with code 1" log-end-str
)))
408 ;; mark item structure property `:running' to `nil'.
409 (setf (youtube-dl-item-running item
) nil
)
410 (message (format "[youtube-dl] process %s error!" (youtube-dl-item-process item
))))
411 (setf (youtube-dl-item-running item
) t
)))
413 ;; (message "[DEBUG] [youtube-dl] destination/title: %s" destination)
414 ;; Set item title to destination if it's empty.
415 (unless (youtube-dl-item-title item
)
416 (setf (youtube-dl-item-title item
) destination
))
417 ;; write output to process associated buffer.
418 (with-current-buffer (process-buffer proc
)
419 (let ((moving (= (point) (process-mark proc
)))
420 ;; avoid process buffer read-only issue for `insert'.
421 (inhibit-read-only t
))
423 ;; Insert the text, advancing the process marker.
424 (goto-char (process-mark proc
))
426 (set-marker (process-mark proc
) (point)))
427 (if moving
(goto-char (process-mark proc
)))))
428 (youtube-dl--redisplay))))
430 (defun youtube-dl--run-single-process ()
431 "Start youtube-dl downloading in single process."
432 (let ((item (youtube-dl--next))
433 (current-item (youtube-dl--current)))
434 (if (eq item current-item
)
435 (youtube-dl--redisplay) ; do nothing, just display the youtube-dl-list buffer.
436 (if youtube-dl-process
438 ;; Switch to higher priority job, but offset error count first.
439 (cl-decf (youtube-dl-item-failures current-item
))
440 (kill-process youtube-dl-process
)) ; sentinel will clean up
441 ;; No subprocess running, start a one.
442 (let* ((item-url (youtube-dl-item-url item
))
443 ;; fix link is an org-mode link is a property list.
444 (url (if (stringp item-url
) item-url
(substring-no-properties item-url
)))
445 (directory (youtube-dl-item-directory item
))
446 (destination (youtube-dl-item-destination item
))
447 (vid (youtube-dl-item-vid item
))
448 (proc-buffer-name (youtube-dl--process-buffer-name vid
))
451 (concat (directory-file-name directory
) "/")
452 (concat (directory-file-name youtube-dl-directory
) "/")))
453 (_ (mkdir default-directory t
))
454 (slow-p (youtube-dl-item-slow-p item
))
455 (rate-limit (or (youtube-dl-item-rate-limit item
) youtube-dl-slow-rate-limit
))
457 :name proc-buffer-name
458 :command
(let ((command (append (list youtube-dl-program
)
460 (cl-copy-list youtube-dl-arguments
)
461 ;; Disable non-ASCII shell color codes in output.
463 ((string-equal youtube-dl-program
"youtube-dl")
465 ((string-equal youtube-dl-program
"yt-dlp")
467 (youtube-dl--proxy-append url
)
469 `("--rate-limit" ,rate-limit
))
471 `("--output" ,destination
))
473 ;; Insert complete command into process buffer for debugging.
474 (with-current-buffer (get-buffer-create proc-buffer-name
)
475 (insert (format "Command: %s" command
)))
477 :sentinel
#'youtube-dl--sentinel
478 :filter
#'youtube-dl--filter
479 :buffer proc-buffer-name
)))
480 (set-process-plist proc
(list :item item
))
481 (setf youtube-dl-process proc
)
482 ;; mark item structure property `:running' to `t'.
483 (setf (youtube-dl-item-running item
) t
))))
484 (youtube-dl--redisplay)))
486 (defun youtube-dl--run-multiple-processes (&optional item
)
487 "Start youtube-dl downloading in multiple processes."
488 (let* ((item (or item
489 youtube-dl--timer-item
; use item from `run-with-timer'.
490 (with-current-buffer (youtube-dl--list-buffer)
491 (nth (1- (line-number-at-pos)) youtube-dl-items
))))
492 (current-item (youtube-dl--current)) ; `youtube-dl-process' currently actived process.
493 (proc (youtube-dl-item-process item
)))
494 (unless (and item
(youtube-dl-item-running item
)) ; whether item structure property `:running' is `t'?
495 (let* ((item-url (youtube-dl-item-url item
))
496 ;; fix link is an org-mode link is a property list.
497 (url (if (stringp item-url
) item-url
(substring-no-properties item-url
)))
498 (directory (youtube-dl-item-directory item
))
499 (destination (youtube-dl-item-destination item
))
500 (vid (youtube-dl-item-vid item
))
501 (proc-buffer-name (youtube-dl--process-buffer-name vid
))
504 (concat (directory-file-name directory
) "/")
505 (concat (directory-file-name youtube-dl-directory
) "/")))
506 (_ (mkdir default-directory t
))
507 (slow-p (youtube-dl-item-slow-p item
))
508 (rate-limit (or (youtube-dl-item-rate-limit item
) youtube-dl-slow-rate-limit
))
509 (failures (youtube-dl-item-failures item
))
510 (proc (when (<= failures
10) ; re-run process only when failures <= 10.
512 :name proc-buffer-name
513 :command
(let ((command (append (list youtube-dl-program
"--newline")
515 (cl-copy-list youtube-dl-arguments
)
516 ;; Disable non-ASCII shell color codes in output.
518 ((string-equal youtube-dl-program
"youtube-dl")
520 ((string-equal youtube-dl-program
"yt-dlp")
522 (youtube-dl--proxy-append url
)
524 `("--rate-limit" ,rate-limit
))
526 `("--output" ,destination
))
528 ;; Insert complete command into process buffer for debugging.
529 (let ((inhibit-read-only t
))
530 (with-current-buffer (get-buffer-create proc-buffer-name
)
531 (insert (format "Command: %s" command
))))
533 :sentinel
#'youtube-dl--sentinel
534 :filter
#'youtube-dl--filter
535 :buffer proc-buffer-name
))))
536 ;; clear temporary item variable `youtube-dl--timer-item'.
537 (setq youtube-dl--timer-item nil
)
538 (when (processp proc
)
539 ;; set process property list.
540 (set-process-plist proc
(list :item item
))
541 ;; assign `proc' object to item slot `:process'.
542 (setf (youtube-dl-item-process item
) proc
)
543 ;; set current youtube-dl process variable.
544 (setf youtube-dl-process proc
)
545 ;; mark item structure property `:running' to `t'.
546 (setf (youtube-dl-item-running item
) t
))))
547 (youtube-dl--redisplay)))
549 (defun youtube-dl--run (&optional item
)
550 "Start youtube-dl downloading."
551 ;; if single process model, then start download next item.
552 ;; if multiple processes model, then don't start next item `youtube-dl--run'.
553 (cl-case youtube-dl-process-model
554 (single-process (youtube-dl--run-single-process item
))
555 (multiple-processes (youtube-dl--run-multiple-processes item
))))
557 (defun youtube-dl--get-vid (url)
558 "Get video `URL' video vid with youtube-dl option `--get-id'."
559 (message "[youtube-dl] getting video vid.")
560 (let* ((parsed-url (url-generic-parse-url url
))
561 (domain (url-domain parsed-url
))
562 (parameters (url-filename parsed-url
)))
563 ;; URL domain matching with regexp to extract vid.
565 ("bilibili.com" ; "/video/BV1B8411L7te/", "/video/BV1uj411N7cp?spm_id_from=..0.0"
566 (when (string-match "/video/\\([^/?&]*\\)" parameters
)
567 (match-string 1 parameters
)))
568 ("pornhub.com" ; "/view_video.php?viewkey=ph6238f9c7cc9e2"
569 (when (string-match "/view_video\\.php\\?viewkey=\\([^/?&]*\\)" parameters
)
570 (match-string 1 parameters
)))
571 ("youtube.com" ; "/watch?v=q-iLEteyeUQ", "/watch?v=48JlgiBpw_I&t=311s"
572 (when (string-match "/watch\\?v=\\([^/?&]*\\)" parameters
)
573 (match-string 1 parameters
)))
575 (let* ((output (with-temp-buffer
576 (apply #'call-process
579 (youtube-dl--proxy-append url
"--get-id" url
))
581 (output-lines-list (string-lines output
))
582 (error-p (string-match-p "ERROR" output
)))
584 ;; ("VrAfJvZGGXE" "")
585 ;; TEST: (youtube-dl--get-vid "https://www.youtube.com/watch?v=VROjLiq9LeQ")
586 ((length= output-lines-list
2) (car output-lines-list
))
587 ;; TEST: (youtube-dl--get-vid "https://hanime1.me/watch?v=22454")
588 ;; ("WARNING: Falling back on generic information extractor." "watch?v=22454" "")
589 ((length= output-lines-list
3) (car (last output-lines-list
1)))
590 ;; TEST: (youtube-dl--get-vid "https://www.pornhub.com/view_video.php?viewkey=ph637ed6daf1795")
591 ;; WARNING: unable to extract view count; please report this issue on https://yt-dl.org/bug . Make sure you are using the latest version; see https://yt-dl.org/update on how to update. Be sure to call youtube-dl with the --verbose flag and include its complete output.
592 ((string-match-p "WARNING" (car output-lines-list
))
593 (car (last output-lines-list
1)))
594 ;; get vid failed, use URL string regex matching instead.
597 ;; WARNING: Could not send HEAD request to https://hanime1.me/watch?v=22709:
598 ;; HTTP Error 503: Service Temporarily Unavailable
599 ;; ERROR: Unable to download webpage: HTTP Error 503: Service Temporarily
600 ;; Unavailable (caused by <HTTPError 503: 'Service Temporarily
601 ;; Unavailable'>); please report this issue on https://yt-dl.org/bug . Make
602 ;; sure you are using the latest version; see https://yt-dl.org/update on
603 ;; how to update. Be sure to call youtube-dl with the --verbose flag and
604 ;; include its complete output.
606 ;; WARNING: unable to extract view count; please report this
607 ;; issue on https://yt-dl.org/bug . Make sure you are using
608 ;; the latest version; see https://yt-dl.org/update on how
609 ;; to update. Be sure to call youtube-dl with the --verbose
610 ;; flag and include its complete output.
611 (error (format "[youtube-dl] `youtube-dl--get-vid' retrive video vid error!\n%s" output
)))
615 ;; (let ((parameters "/video/BV1B8411L7te/"))
616 ;; (when (string-match "/video/\\([^/]*\\)" parameters)
617 ;; (match-string 1 parameters)))
619 ;; (youtube-dl--get-vid "https://www.youtube.com/watch?v=VROjLiq9LeQ")
620 ;; (youtube-dl--get-vid "https://www.pornhub.com/view_video.php?viewkey=ph637ed6daf1795")
624 (url &key title
(priority 0) directory destination paused slow
)
625 "Queues URL for download using youtube-dl, returning the new item.
626 By default, it downloads to ~/Downloads/."
628 (list (substring-no-properties
629 (read-from-minibuffer
630 "URL: " (or (thing-at-point 'url
)
631 (when interprogram-paste-function
632 (funcall interprogram-paste-function
)))))))
633 ;; remove this ID failure only on youtube.com, use URL as ID. or use youtube-dl extracted title, or hash on URL.
634 (let* ((vid (youtube-dl--get-vid url
))
635 (destination (replace-regexp-in-string ; replace illegal filename characters in `destination'.
636 youtube-dl-destination-illegal-filename-chars-regex
"-"
637 (or (youtube-dl--get-destination url
)
639 (title (or (replace-regexp-in-string (format "-%s.*" vid
) "" destination
)
640 (car (split-string destination
"-"))))
641 (proc-buffer-name (youtube-dl--process-buffer-name vid
))
642 (full-dir (expand-file-name (or directory
"") youtube-dl-directory
))
643 (item (youtube-dl-item--create :url url
651 :destination destination
653 :buffer proc-buffer-name
656 (unless (youtube-dl-item-running item
)
657 (youtube-dl--add item
) ; Add ITEM to the queue.
658 (youtube-dl--run item
) ; Start ITEM in the queue.
659 (when youtube-dl-auto-show-list
660 (youtube-dl-list))))))
662 (defalias 'youtube-dl-download-video
'youtube-dl
)
664 (defun youtube-dl--playlist-list (playlist)
665 "For each video, return one plist with :index, :vid, and :title."
667 (when (zerop (call-process youtube-dl-program nil t nil
672 (goto-char (point-min))
673 (cl-loop with json-object-type
= 'plist
675 for video
= (ignore-errors (json-read))
677 collect
(list :index index
678 :vid
(plist-get video
:vid
)
679 :title
(plist-get video
:title
))))))
681 (defun youtube-dl--playlist-reverse (list)
682 "Return a copy of LIST with the indexes reversed."
683 (let ((max (cl-loop for entry in list
684 maximize
(plist-get entry
:index
))))
685 (cl-loop for entry in list
686 for index
= (plist-get entry
:index
)
687 for copy
= (copy-sequence entry
)
688 collect
(plist-put copy
:index
(- (1+ max
) index
)))))
690 (defun youtube-dl--playlist-cutoff (list n
)
691 "Return a sorted copy of LIST with all items except where :index < N."
692 (let ((key (lambda (v) (plist-get v
:index
)))
693 (filter (lambda (v) (< (plist-get v
:index
) n
)))
694 (copy (copy-sequence list
)))
695 (cl-delete-if filter
(cl-stable-sort copy
#'< :key key
))))
698 (cl-defun youtube-dl-download-playlist
699 (url &key directory
(first 1) paused
(priority 0) reverse slow
)
700 "Add entire playlist to download queue, with index prefixes.
702 :directory PATH -- Destination directory for all videos.
704 :first INDEX -- Start downloading from a given one-based index.
706 :paused BOOL -- Start all download entries as paused.
708 :priority PRIORITY -- Use this priority for all download entries.
710 :reverse BOOL -- Reverse the video numbering, solving the problem
711 of reversed playlists.
713 :slow BOOL -- Start all download entries in slow mode."
715 (list (read-from-minibuffer
717 (when interprogram-paste-function
718 (funcall interprogram-paste-function
)))))
719 (message "[youtube-dl] fetching playlist ...")
720 (let ((videos (youtube-dl--playlist-list url
)))
722 (error "Failed to fetch playlist (%s)." url
)
723 (let* ((max (cl-loop for entry in videos
724 maximize
(plist-get entry
:index
)))
725 (width (1+ (floor (log max
10))))
726 (prefix-format (format "%%0%dd" width
)))
728 (setf videos
(youtube-dl--playlist-reverse videos
)))
729 (dolist (video (youtube-dl--playlist-cutoff videos first
))
730 (let* ((index (plist-get video
:index
))
731 (prefix (format prefix-format index
))
732 (title (format "%s-%s" prefix
(plist-get video
:title
)))
733 (dest (format "%s-%s" prefix
"%(title)s-%(id)s.%(ext)s")))
734 (youtube-dl (plist-get video
:url
)
742 ;; List user interface:
744 ;;; refresh youtube-dl-list buffer (2).
745 (defun youtube-dl-list-redisplay ()
746 "Immediately redraw the queue list buffer."
748 (with-current-buffer (youtube-dl--list-buffer)
749 (let ((save-point (point))
750 (window (get-buffer-window (current-buffer))))
751 (youtube-dl--fill-listing)
752 (goto-char save-point
)
754 (set-window-point window save-point
))
756 (hl-line-highlight)))))
758 ;;; refresh youtube-dl-list buffer (1).
759 (defun youtube-dl--redisplay ()
760 "Redraw the queue list buffer only if visible."
761 (let ((log-buffer (youtube-dl--log-buffer)))
763 (with-current-buffer log-buffer
764 (let ((inhibit-read-only t
)
765 (window (get-buffer-window log-buffer
)))
767 (mapc #'insert
(youtube-dl-item-log youtube-dl--log-item
))
769 (set-window-point window
(point-max)))))))
770 (when (get-buffer-window (youtube-dl--list-buffer))
771 (youtube-dl-list-redisplay)))
773 (defun youtube-dl-list-log ()
774 "Display the log of the video under point."
776 (let* ((n (1- (line-number-at-pos)))
777 (item (nth n youtube-dl-items
))
778 (buffer (youtube-dl--log-buffer item
)))
780 (display-buffer buffer
)
781 (select-window (get-buffer-window buffer
))
782 (youtube-dl--redisplay))))
784 (defun youtube-dl-list-kill-log ()
785 "Kill the youtube-dl log buffer."
787 (let ((buffer (youtube-dl--log-buffer)))
789 (kill-buffer buffer
))))
791 (defun youtube-dl-list-yank ()
792 "Copy the URL of the video under point to the clipboard."
794 (let* ((n (1- (line-number-at-pos)))
795 (item (nth n youtube-dl-items
)))
797 (let ((url (concat "https://youtu.be/" (youtube-dl-item-vid item
))))
798 (if (fboundp 'gui-set-selection
)
799 (gui-set-selection nil url
) ; >= Emacs 25
801 (x-set-selection 'PRIMARY url
))) ; <= Emacs 24
802 (message "[youtube-dl] yanked %s" url
)))))
804 (defun youtube-dl-list-kill ()
805 "Remove the selected item from the queue."
807 (when youtube-dl-items
; avoid `youtube-dl-items' is `nil'.
808 (let* ((n (1- (line-number-at-pos)))
809 (item (nth n youtube-dl-items
)))
811 (when (= n
(1- (length youtube-dl-items
)))
813 (youtube-dl--remove item
))))
814 (youtube-dl-list-redisplay))
816 (defun youtube-dl-list-pause ()
817 "Pause downloading of item under point."
819 (let* ((n (1- (line-number-at-pos)))
820 (item (nth n youtube-dl-items
))
821 (proc (youtube-dl-item-process item
))
822 (paused-p (youtube-dl-item-paused-p item
)))
823 (if (and item paused-p
)
824 ;; if paused, resume process.
826 (setf (youtube-dl-item-paused-p item
) nil
)
828 ;; kill the process, but keep item on list buffer for pause status.
829 (when (process-live-p proc
) (kill-process proc
))
830 ;; after killed process, also setting item structure status properties.
831 (setf (youtube-dl-item-paused-p item
) t
)
832 (setf (youtube-dl-item-running item
) nil
))
833 (youtube-dl-list-redisplay)
834 (message "[youtube-dl] process %s is paused." proc
)))
836 (defun youtube-dl-list-resume ()
837 "Resume failure/paused downloading item under point."
839 (when-let* ((n (1- (line-number-at-pos)))
840 (item (nth n youtube-dl-items
))
841 (proc (youtube-dl-item-process item
)))
843 (setf (youtube-dl-item-failures item
) 0)
845 ((youtube-dl-item-paused-p item
)
846 (setf (youtube-dl-item-paused-p item
) nil
)
848 ((not (youtube-dl-item-running item
))
851 (setf (youtube-dl-item-running item
) nil
)
853 ;; (user-error (format "[youtube-dl] Can't resume process %s correctly. Try resume again." proc))
855 (youtube-dl-list-redisplay))
857 (defun youtube-dl-list-toggle-slow (item &optional rate-limit
)
858 "Set slow rate limit on item under point."
860 (let* ((n (1- (line-number-at-pos))))
861 (list (nth n youtube-dl-items
))))
863 (let ((proc (youtube-dl-item-process item
))
864 (slow-p (youtube-dl-item-slow-p item
))
865 (rate-limit (substring-no-properties
867 (completing-read "[youtube-dl] limit download rate (e.g. 100K): "
868 '("20K" "50K" "100K" "200K" "500K" "1M" "2M"))))))
869 ;; restart with a slower download rate.
870 (when (process-live-p proc
) (kill-process proc
))
871 (setf (youtube-dl-item-slow-p item
) (not slow-p
))
872 (setf (youtube-dl-item-rate-limit item
) rate-limit
)
874 (youtube-dl-list-redisplay))
876 (defun youtube-dl-list-toggle-slow-all ()
877 "Set slow rate on all items."
879 (let* ((count (length youtube-dl-items
))
880 (slow-count (cl-count-if #'youtube-dl-item-slow-p youtube-dl-items
))
881 (target (< slow-count
(- count slow-count
)))
882 (rate-limit (completing-read "[youtube-dl] limit download rate (e.g. 100K): "
883 '("20K" "50K" "100K" "200K" "500K" "1M" "2M"))))
884 (dolist (item youtube-dl-items
)
885 (youtube-dl-list-toggle-slow item rate-limit
)))
886 (youtube-dl--redisplay))
888 (defun youtube-dl-list-priority-modify (delta)
889 "Change priority of item under point by DELTA."
890 (let* ((n (1- (line-number-at-pos)))
891 (item (nth n youtube-dl-items
)))
893 (cl-incf (youtube-dl-item-priority item
) delta
)
896 (defun youtube-dl-list-priority-up ()
897 "Decrease priority of item under point."
899 (youtube-dl-list-priority-modify 1))
901 (defun youtube-dl-list-priority-down ()
902 "Increase priority of item under point."
904 (youtube-dl-list-priority-modify -
1))
906 (defvar youtube-dl-list-mode-map
907 (let ((map (make-sparse-keymap)))
909 (define-key map
"a" #'youtube-dl
)
910 (define-key map
"g" #'youtube-dl-list-redisplay
)
911 (define-key map
"l" #'youtube-dl-list-log
)
912 (define-key map
"L" #'youtube-dl-list-kill-log
)
913 (define-key map
"y" #'youtube-dl-list-yank
)
914 (define-key map
"k" #'youtube-dl-list-kill
)
915 (define-key map
"p" #'youtube-dl-list-pause
)
916 (define-key map
"r" #'youtube-dl-list-resume
)
917 (define-key map
"s" #'youtube-dl-list-toggle-slow
)
918 (define-key map
"S" #'youtube-dl-list-toggle-slow-all
)
919 (define-key map
"]" #'youtube-dl-list-priority-up
)
920 (define-key map
"[" #'youtube-dl-list-priority-down
)))
921 "Keymap for `youtube-dl-list-mode'")
923 (defvar-local youtube-dl-list--auto-close-window-timer nil
924 "A timer to auto close youtube-dl list window.")
926 (defun youtube-dl-list--auto-close-window ()
927 "Auto close '*youtube-dl list*' buffer after finished all downloading."
928 (when (equal (length youtube-dl-items
) 0)
929 (when-let ((buf (get-buffer-window (youtube-dl--list-buffer))))
931 (when (timerp youtube-dl-list--auto-close-window-timer
)
932 (cancel-timer youtube-dl-list--auto-close-window-timer
)))))
934 (defvar youtube-dl-list--format
935 ;; (percentage download-rate)
937 ;;space,vid,progress size eta fails
939 ;;| | | | | | | title
941 "%s%-16s %-22.22s %-10.10s %-6.6s %-7.7s %-8.8s %s"
942 "Define the `youtube-dl-list-mode' `header-line-format' and list item format.")
944 (define-derived-mode youtube-dl-list-mode special-mode
"youtube-dl"
945 "Major mode for listing the youtube-dl download queue."
947 (use-local-map youtube-dl-list-mode-map
)
949 (setq-local truncate-lines t
) ; truncate long line text.
950 (setf header-line-format
952 (format youtube-dl-list--format
953 (propertize " " 'display
'((space :align-to
0))) ; space
954 " vid " "| progress" "| size" "| ETA" "| fails" "| status"
955 (concat "| title " (make-string 100 (string-to-char " "))))
956 'face
'(:inverse-video t
:extend t
))))
958 (defvar youtube-dl--list-buffer-name
" *youtube-dl list*"
959 "The buffer name of `youtube-dl-list-mode'.")
961 (defun youtube-dl--list-buffer ()
962 "Returns the queue listing buffer."
963 (if-let ((buf (get-buffer-create youtube-dl--list-buffer-name
)))
964 (with-current-buffer buf
965 ;; TODO: use `tabulated-list-mode'.
966 ;; (tabulated-list-mode)
967 (youtube-dl-list-mode)
970 (defun youtube-dl--log-buffer (&optional item
)
971 "Returns a youtube-dl log buffer for ITEM."
973 (let* ((name (youtube-dl-item-buffer item
))
974 (buffer (get-buffer-create name
)))
975 (with-current-buffer buffer
976 (unless (eq major-mode
'special-mode
)
978 (setf youtube-dl--log-item item
)
979 (setf (youtube-dl-item-log item
) item
)
982 ;;; refresh youtube-dl-list buffer (3).
983 (defun youtube-dl--fill-listing ()
984 "Erase and redraw the queue in the queue listing buffer."
985 (with-current-buffer (youtube-dl--list-buffer)
986 (let* ((inhibit-read-only t
)
987 (active (youtube-dl--current)))
989 (dolist (item youtube-dl-items
)
990 (let ((vid (youtube-dl-item-vid item
))
991 (running (youtube-dl-item-running item
))
992 (failures (youtube-dl-item-failures item
))
993 (priority (youtube-dl-item-priority item
))
994 (percentage (youtube-dl-item-percentage item
))
995 (download-rate (youtube-dl-item-download-rate item
))
996 (paused-p (youtube-dl-item-paused-p item
))
997 (slow-p (youtube-dl-item-slow-p item
))
998 (rate-limit (youtube-dl-item-rate-limit item
))
999 (total-size (youtube-dl-item-total-size item
))
1000 (eta (youtube-dl-item-eta item
))
1001 (title (youtube-dl-item-title item
))
1002 (url (youtube-dl-item-url item
)))
1005 (format (concat youtube-dl-list--format
"\n")
1008 ;; (propertize " " 'display '((space :align-to 0)))
1010 (if running
; update `:running' property every time process update.
1011 (propertize vid
'face
'default
)
1012 (propertize vid
'face
'youtube-dl-pause
))
1013 ;; progress (percentage download-rate)
1014 (if (and percentage download-rate
)
1015 (propertize (format "⦼%-5.5s ⇩%-17.17s " percentage download-rate
) 'face
'youtube-dl-active
)
1016 (propertize (format "⦼%-5.5s ⇩%-17.17s " percentage download-rate
) 'face
'youtube-dl-pause
))
1018 (or (propertize (format "%s" total-size
) 'face
'youtube-dl-pause
) "-")
1020 (or (propertize (format "%s" eta
) 'face
'youtube-dl-pause
) "?")
1024 (propertize (format " [%d] " failures
) 'face
'youtube-dl-failure
))
1026 ;; (if (= priority 0)
1028 ;; (propertize (format "%+d " priority) 'face 'youtube-dl-priority))
1031 (if slow-p
(propertize "SLOW" 'face
'youtube-dl-slow
))
1032 (if rate-limit
(propertize (format "≤ %s" rate-limit
) 'face
'youtube-dl-slow
))
1033 (if paused-p
(propertize "PAUSE" 'face
'youtube-dl-pause
)))
1039 (defun youtube-dl-list ()
1040 "Display a list of all videos queued for download."
1042 (youtube-dl--fill-listing)
1043 ;; set timer to auto close `youtube-dl--list-buffer' "*youtube-dl list*" buffer after finished all downloading.
1044 (with-current-buffer (youtube-dl--list-buffer)
1045 (unless (timerp youtube-dl-list--auto-close-window-timer
)
1046 (setq-local youtube-dl-list--auto-close-window-timer
1047 (run-with-timer 0 (* 60 2) #'youtube-dl-list--auto-close-window
)))
1048 ;; jump to beginning of buffer.
1049 (goto-char (point-min)))
1050 (display-buffer (youtube-dl--list-buffer)))
1053 (defun youtube-dl-download-audio (url)
1054 "Download audio format of URL."
1056 (list (read-from-minibuffer
1057 "URL: " (or (thing-at-point 'url
)
1058 (when interprogram-paste-function
1059 (funcall interprogram-paste-function
))))))
1060 (let ((youtube-dl-arguments (append youtube-dl-arguments
'("-x" "--audio-format" "best"))))
1064 (defun youtube-dl-download-subtitle (url)
1065 "Download video subtitle of URL."
1067 (list (read-from-minibuffer
1068 "URL: " (or (thing-at-point 'url
)
1069 (when interprogram-paste-function
1070 (funcall interprogram-paste-function
))))))
1071 (let ((youtube-dl-arguments (append youtube-dl-arguments
1072 '("--skip-download" "--no-warnings"
1073 ;; "--write-auto-sub" ; YouTube only, for auto-generated subtitle.
1075 "--sub-lang" "en,zh-Hans"
1076 "--sub-format" "ass/srt/best" ; ass/srt/best, srt, vtt, ttml, srv3, srv2, srv1
1081 (defun youtube-dl-download-thumbnail (url)
1082 "Download video thumbnail of URL."
1084 (list (read-from-minibuffer
1085 "URL: " (or (thing-at-point 'url
)
1086 (when interprogram-paste-function
1087 (funcall interprogram-paste-function
))))))
1088 (let ((youtube-dl-arguments (append youtube-dl-arguments
1089 '("--skip-download" "--no-warnings"
1090 "--write-thumbnail"))))
1093 (provide 'youtube-dl
)
1095 ;;; youtube-dl.el ends here