Beispiel #1
0
def initYTDL():
    global ydl
    if ydl: return
    print("waiting for ytdl to start...")
    from youtube_dl import YoutubeDL
    from youtube_dl.postprocessor.common import PostProcessor
    ydl = YoutubeDL({
        'format':
        'bestaudio/best',
        'outtmpl':
        'songs/%(id)s.%(ext)s',
        'continue_dl':
        True,
        'addmetadata':
        True,
        'postprocessors': [{
            'key': 'FFmpegMetadata',
        }, {
            'key': 'FFmpegExtractAudio',
        }]
    })

    class TestPP(PostProcessor):
        def run(self, inf):
            Video._lastDownload = inf  #hack
            return [], inf

    ydl.add_post_processor(TestPP())
Beispiel #2
0
def main(csvfile, filepath):
    # input path
    names, artists, links = read_csv(csvfile)

    ydl_opts = {
            'verbose': True,
            'geo_verification_proxy': '',
            'format': 'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
                }],
            'logger': MyLogger(),
            'progress_hooks': [my_hook],
            'outtmpl': filepath+'/'
            }

    for i in range (0, len(links)):
        path = os.path.join(filepath, '{} - {}.%(ext)s'.format(names[i], artists[i]))

        metadata = {
            "title": names[i],
            "artist": artists[i],
        }

        url = [links[i]]
        ydl_opts['outtmpl'] = path
        ydl = YoutubeDL(ydl_opts)
        MyLogger().debug("DOWNLOADING {} : {} ".format(path, url))

        ffmpeg_mp3_metadata_pp = FFmpegMP3MetadataPP(ydl, metadata)
        ydl.add_post_processor(ffmpeg_mp3_metadata_pp)
        download(ydl, url)
Beispiel #3
0
def download_youtube(url,filepath,params=None):
    tmp_filepath = compat_str(filepath)
    print "download to",tmp_filepath
    params = params or settings.youtube_params
    params.update({"outtmpl":tmp_filepath,"daterange":DateRange(None,None)})
    y = YoutubeDL(params) 
     #y = YoutubeDL({"format":"18/34/35/5/17","outtmpl":filepath}) 
     #y.print_debug_header()
    y.add_default_info_extractors()
    y.add_post_processor(FFmpegExtractAudioPP(preferredcodec="m4a",preferredquality=5, nopostoverwrites=False))
    value = y.download([url])
    #cmd = 'youtube-dl {url} --extract-audio --audio-format wav -o {filepath}'.format(url=url,filepath=filepath)
    #print cmd
    #result = subprocess.call(cmd,shell=True)
    #print result
    return True
Beispiel #4
0
    def run(self, release_task_pk: int, custom_options: Optional[dict]=None) -> None:
        try:
            with transaction.atomic():
                self.download_task = DownloadTask.objects.get(pk=release_task_pk)
                self.download_task.downloader = DownloadTask.YOUTUBE_DL
                self.download_task.celery_id = self.request.id
                self.download_task.state = DownloadTask.DOWNLOADING
                self.download_task.started_at = timezone.now()
                self.download_task.save()

            options = copy.deepcopy(self.YOUTUBE_DL_OPTIONS)
            options['outtmpl'] = options['outtmpl'].format(self.request.id.replace('-', ''))
            options['progress_hooks'] = [self._progress_hook]

            if custom_options:
                custom_options = self._clean_options(custom_options)
                options.update(custom_options)

            downloader = YoutubeDL(options)
            downloader.add_post_processor(self._get_postprocessor())
            downloader.download([self.download_task.url])
        except SystemExit:
            try:
                os.remove(self._last_status['tmpfilename'])
            except AttributeError:
                return
            except:
                log.exception('Exception while removing temporary file. id={0}, tempfilename={1}'.format(
                        release_task_pk, self._last_status['tmpfilename'])
                )
                raise
        except (BaseDatabaseError, ObjectDoesNotExist, MultipleObjectsReturned):
            # Hope we've caught everything
            log.exception('Exception while updating DownloadTask. id={0}'.format(release_task_pk))
            raise
        except:
            try:
                with transaction.atomic():
                    self.download_task.state = DownloadTask.ERROR
                    self.download_task.finished_at = timezone.now()
                    self.download_task.save()

                    self.download_task.tracebacks.create(text=traceback.format_exc())
                raise
            except (BaseDatabaseError, ObjectDoesNotExist, MultipleObjectsReturned):
                log.exception('Exception while changing DownloadTask.state to ERROR. id={0}'.format(release_task_pk))
                raise
Beispiel #5
0
 def run_pp(params, PP):
     with open(filename, 'wt') as f:
         f.write('EXAMPLE')
     ydl = YoutubeDL(params)
     ydl.add_post_processor(PP())
     ydl.post_process(filename, {'filepath': filename})
 def run_pp(params, PP):
     with open(filename, 'wt') as f:
         f.write('EXAMPLE')
     ydl = YoutubeDL(params)
     ydl.add_post_processor(PP())
     ydl.post_process(filename, {'filepath': filename})
Beispiel #7
0
from flask.ext.restful import reqparse, abort, Api, Resource
from youtube_dl import YoutubeDL
from youtube_dl import FFmpegExtractAudioPP
import redis
import boto
import boto.s3.connection
from boto.s3.key import Key


ydl = YoutubeDL({
  'outtmpl': '%(id)s.%(ext)s',
  'format': 'bestaudio/best',
  'verbose': 'yes',
  })
ydl.add_default_info_extractors()
ydl.add_post_processor(FFmpegExtractAudioPP(preferredcodec='mp3', preferredquality='5', nopostoverwrites=False))
ydl.print_debug_header()
app = Flask(__name__)
api = Api(app)

conn = boto.connect_s3()
bucket = conn.get_bucket('turntable.dongs.in')

r = redis.Redis("localhost")

def abort_if_song_doesnt_exist(song_id):
        abort(404, message="song {} doesn't exist".format(song_id))

parser = reqparse.RequestParser()
parser.add_argument('hash', type=str)
parser.add_argument('username', type=str)