Downloading YouTube Videos Using the Command Line Tool `youtube-dl`

I am actually trying to create a macro that downloads youtube videos using youtube-dl by just selecting the youtube url and triggering the macro.On some occasions, the url can not be selected but can be copied using the right click menu and "copy link".

I will like the macro to first check if text is selected and if the selected text is a youtube url. If both conditions are true, then the selected text is copied to the clipboard. However, if either of these conditions are false, then the last entry in the clipboard is checked to ensure it is a valid youtube url.

The youtube url is then appended to the command "youtube-dl -f 18" in the terminal and the return key is typed.
Below is a screenshot of the macro using only selected text.

I don’t have KM in front of me, but here’s what you’re basically looking for:

  1. Save the clipboard
  2. Copy selected text (CMD + C)
  3. If/Then: See if the clipboard text contains youtube.com or not. Not a 100% perfect test but probably good enough, Alternately you could use regex for this.
  4. True:
  5. Activate terminal
  6. wait a little bit
  7. Insert text (end of macro, everything else happens in the False section)
  8. False:
  9. Restore clipboard
  10. If/Then: Clipboard text contains youtube.com
    1. True:
      1. Activate Terminal
      2. pause for a bit,
      3. Insert text
    2. False:
      1. Leave blank, show message, whatever you want

The Terminal is scriptable.

Although strangely you cannot create a new Tab via AppleScript.

You can create a new window using:

tell application "Terminal"
   do script ""
end tell

So you can keep it all in AppleScript if you want, or you can mix and match it with Keyboard Maestro.

In any case this is an easy one.

-Chris

--------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2015/03/10 11:37
# dMod: 2015/05/15 16:19
# Appl: Terminal
# Task: Download a video in the Terminal using `youtube-dl`.
# Libs: None
# Osax: None
# Tags: @Applescript, @Terminal, @Run, @Script, @Active, @Tab, @Download, @Video
--------------------------------------------------------

set videoURL to "http://www.youtube.com/watch?v=PuPAM0qhl4g"
set downloadDir to POSIX path of (path to downloads folder)

tell application "Terminal"
   if not running then run
   activate
   
   tell front window
      if not busy then
         do script "cd " & quoted form of downloadDir in selected tab
         
         set shCMD to "youtube-dl -f 18 " & quoted form of videoURL
         do script shCMD in selected tab
         
      end if
   end tell
   
end tell

--------------------------------------------------------

Thanks again for your unwavering support. I wish I had even a tenth of this exotic knowledge.

I modified this since the download address will vary:
set videoURL to the clipboard

Is it possible for me to get a prompt telling me the size of the proposed download and if I want to continue with the download?

A yes/no prompt should suffice.

Hey Mirizzi,

Spend 30 years automating Macs and 20+ years writing AppleScript — you'll get there.

:sunglasses:

Yes. That exercise was left to the reader.

Not as far as I know.

I did take a quick look through the youtube-dl man page and didn't find anything relevant, although I could have missed something.

-Chris

1 Like

Still within my first year of using a Mac and I absolutely love it.

We can't thank you enough for the immense work and knowledge you contribute on this forum.

If the script initially sends the terminal command "youtube-dl -F url", the sizes of the various formats are displayed.

Is it possible for me to then get a prompt asking me if I want to continue?

If my answer is "Yes" or I click the "Return" button, then the terminal asks for the format I want?

My answer can be something like this "18" or "22" or "17" or "137+141".

It then enters the inputted format I input in the command " youtube-dl -f inputtedformat url".

It should then download the video in the format of one's choice.

Hey Mirizzi,

Aha! I missed that when I was perusing the man page.

The following script presents a pick-list of available formats.

You pick one.

It gets downloaded.

* The commented-out section shows how to do the download directly from AppleScript. In general I think it's better to offload this job to the Terminal, because the other method will tie up your AppleScript-Runner-Utility until the download is finished - unless it is capable of running asynchronously. (KM can do this, but it will still be slowed down somewhat.)

-Chris

Edit 2015/05/16 16:39:

  • Fixed issue where choose-from dialog would not show from KM Execute AppleScript Action.
--------------------------------------------------------
# Auth: Christopher Stone
# dCre: 2015/03/10 11:37
# dMod: 2015/05/16 16:41
# Appl: Terminal
# Task: Download a video in the Terminal using `youtube-dl`.
# Libs: None
# Osax: None
# Tags: @Applescript, @Terminal, @Run, @Script, @Active, @Tab, @Download, @Video
--------------------------------------------------------

set videoURL to "http://www.youtube.com/watch?v=PuPAM0qhl4g"
set downloadDir to POSIX path of (path to downloads folder)

set shCMD to "
export PATH=/opt/local/bin/:$PATH;
youtube-dl -F " & videoURL & ";"

set AppleScript's text item delimiters to "format code  extension  resolution note" & return
set vidFormatList to text item 2 of (do shell script shCMD)
set vidFormatList to paragraphs of vidFormatList

tell application "Keyboard Maestro Engine"
   activate
   set myVidFormatChoice to choose from list vidFormatList ¬
      with title "YouTube Video Format List" with prompt ¬
      "Pick Your Poison:" default items {item 1 of vidFormatList}
end tell

if myVidFormatChoice ≠ false then
   set myVidFormatChoice to item 1 of myVidFormatChoice
   set AppleScript's text item delimiters to " "
   set myVidFormatChoice to text item 1 of myVidFormatChoice
   
   # Directly download from AppleScript.  
   # Will tie up the AppleScript-Runner for the duration of the download unless run asynchronously.
   # set shCMD to "
   # export PATH=/opt/local/bin/:$PATH;
   # cd " & quoted form of downloadDir & ";
   # youtube-dl -f " & myVidFormatChoice & " " & videoURL & ";"
   # do shell script shCMD
   
   tell application "Terminal"
      if not running then run
      activate
      
      tell front window
         if not busy then
            do script "cd " & quoted form of downloadDir in selected tab
            set shCMD to "youtube-dl -f " & myVidFormatChoice & " " & quoted form of videoURL
            do script shCMD in selected tab
         end if
      end tell
   end tell
   
end if

--------------------------------------------------------

Thanks.
I can’t get it to work. Can you please look through the code? It is too complicated for me.

Where are you running it from? KM?

-ccs

[quote=“ccstone, post:9, topic:1277”]
Where are you running it from? KM?
[/quote]Yes, I pasted it in an Execute Applescript action.

2015/05/16 16:42

Edited post #7 Script — 1 fix.

-ccs

Okay, give the edited version a try, and let me know what happens.

-Chris

It is still not working. The only thing that happens is

cd ~/Downloads

I was able to accomplish it using KBM without Applescript but I will prefer if it is refined using Applescript.
<img src="/uploads/default/1085/ec7e4af77b31b135.png" width="500 height=“230”>

Hey Mirizzi,

You ran the script verbatim?

And it didn't work?

Which OSX are you using?

Try running it verbatim from the Applescript Editor (Script Editor on Yosemite).

If you used a url different than the one in the script send it to me.

-Chris

Yes, I ran it verbatim. I run OS X 10.10.3.
This is the error it gave

sh: line 2: youtube-dl: command not found

Oh, ho...

Run this in the Terminal, and tell me what path it returns.

which youtube-dl

How did you install youtube-dl?

I used MacPorts, but I'm guessing you used something else.

-Chris

I have solved the issue why it was not running. I changed the path to the executable file “youtube-dl” to “/usr/local/bin/”

However, I noticed a few bugs.
I changed videourl to “the clipboard” but noticed that it would not work with urls such as https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&cad=rja&uact=8&sqi=2&ved=0CB0QtwIwAA&url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DqBNmY7S0BG8&ei=4DxYVdSUHsmuUe7SgKAE&usg=AFQjCNEgN5MbWpylUTE_RpKsxqBZ9jnOnQ&sig2=1y6Qn53VIdPZ8jvSNjIY6Q&bvm=bv.93564037,d.d24 but this will work in the terminal.
It however works with urls such as www.youtube.com/watch?v=qBNmY7S0BG8.

It also gave errors if I had earlier done the following:

  • closed a terminal session using the red button or
  • typed “exit” in a terminal which then gave a “[Process completed]” message.

Thanks a million for the great job.

I really appreciate all the help. I was eventually able to modify the macro to download a youtube url from a google-search redirected url.

This I did by getting some applescript to decode the URL and used a regular expression to extract the video URL.

I also found that the macro works better with iTerm2 and so, I ported the applescript from Terminal to iTerm 2.

Thanks a million. You guys are the best.

This code works for me. Thank you very much.

1 Like