Completed
Push — master ( 712b49...28eda1 )
by Dmitry
31s
created

fuel.downloaders.fill_subparser()   A

Complexity

Conditions 1

Size

Total Lines 17

Duplication

Lines 0
Ratio 0 %
Metric Value
cc 1
dl 0
loc 17
rs 9.4285
1
import os
2
3
try:
4
    import pafy
5
    PAFY_AVAILABLE = True
6
except ImportError:
7
    PAFY_AVAILABLE = False
8
9
10
def download(directory, youtube_id, clear=False):
11
    """Download the audio of a YouTube video.
12
13
    The audio is downloaded in the highest available quality. Progress is
14
    printed to `stdout`. The file is named `youtube_id.m4a`, where
15
    `youtube_id` is the 11-character code identifiying the YouTube video
16
    (can be determined from the URL).
17
18
    Parameters
19
    ----------
20
    directory : str
21
        The directory in which to save the downloaded audio file.
22
    youtube_id : str
23
        11-character video ID (taken from YouTube URL)
24
    clear : bool
25
        If `True`, it deletes the downloaded video. Otherwise it downloads
26
        it. Defaults to `False`.
27
28
    """
29
    filepath = os.path.join(directory, '{}.m4a'.format(youtube_id))
30
    if clear:
31
        os.remove(filepath)
32
        return
33
    if not PAFY_AVAILABLE:
34
        raise ImportError("pafy is required to download YouTube videos")
35
    url = 'https://www.youtube.com/watch?v={}'.format(youtube_id)
36
    video = pafy.new(url)
37
    audio = video.getbestaudio()
38
    audio.download(quiet=False, filepath=filepath)
39
40
41
def fill_subparser(subparser):
42
    """Sets up a subparser to download audio of YouTube videos.
43
44
    Adds the compulsory `--youtube-id` flag.
45
46
    Parameters
47
    ----------
48
    subparser : :class:`argparse.ArgumentParser`
49
        Subparser handling the `youtube_audio` command.
50
51
    """
52
    subparser.add_argument(
53
        '--youtube-id', type=str, required=True,
54
        help=("The YouTube ID of the video from which to extract audio, "
55
              "usually an 11-character string.")
56
    )
57
    return download
58