aboutsummaryrefslogtreecommitdiffstats
path: root/youtube_podcaster/youtube/downloader.py
blob: 24fa1b06798a4707ff8115143139371167350a73 (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
#!/usr/bin/env python3

import os
import sys
import mimetypes

import youtube_dl


class Downloader:
    instance = None

    def get_instance(file_format, location, base_url):
        if not Downloader.instance:
            Downloader.instance = Downloader(file_format, location, base_url)
        return Downloader.instance

    def __init__(self, file_format, location, base_url):
        self.file_format = file_format
        self.location = location
        self.base_url = base_url

        self.downloaded = []

        if file_format == "vorbis":
            self.extension = "ogg"
        elif file_format == "opus":
            self.extension = "opus"

        if sys.platform == "linux" and not hasattr(sys, "real_prefix"):
            self.tmp_dir = "/tmp/youtube-podcaster"
        else:
            self.tmp_dir= "%s/tmp/youtube-podcaster" % (sys.prefix)

        os.makedirs(self.tmp_dir, 0o755, True)

    def download(self, video, video_id, feed_id):

        # Real output
        filename = "%s.%s" % (video_id, self.extension)
        output_dir = "%s/%s" % (self.location, feed_id)
        output = "%s/%s" % (output_dir, filename)

        # Tmp output
        tmp_filename = "%s.webm" % (video_id)
        tmp_output = "%s/%s" % (self.tmp_dir, tmp_filename)

        options = {"format": "bestaudio/best",
                   "outtmpl": tmp_output,
                   "postprocessors": [{
                       "key": "FFmpegExtractAudio",
                       "preferredcodec": self.file_format
                   }]}

        video_url = "https://www.youtube.com/watch?v=%s" % (video["snippet"]["resourceId"]["videoId"])
        youtube_dl.YoutubeDL(options).download([video_url])

        tmp_output = "%s/%s" % (self.tmp_dir, filename)

        url = "%s/%s/%s.%s" % (self.base_url, feed_id, video_id, self.extension)
        size = str(os.path.getsize(tmp_output))
        mime = mimetypes.guess_type(tmp_output)[0]

        os.makedirs(output_dir, 0o755, True)
        os.rename(tmp_output, output)

        self.downloaded.append(output)

        return (url, size, mime)

#  vim: set ts=8 sw=4 tw=0 et :