class DownloadProcess(multiprocessing.Process):
    """
    Actual download process which calls youtube-dl. You should never need to interact with this directly.
    """

    def __init__(self, url, status_queue, output_writer):
        super(DownloadProcess, self).__init__()

        self.url = url
        self.status_queue = status_queue

        self.info = {}

        sys.stdout = output_writer
        sys.stderr = output_writer

        self.downloader = YoutubeDL({"progress_hooks": [self.update_status]})
        self.downloader.add_default_info_extractors()

    def update_status(self, status):
        self.status_queue.put(status)

    def run(self):
        self.info = self.downloader.extract_info(self.url)

    def stop(self):
        # Kill any child processes that may have spawned (e.g. ffmpeg)
        import psutil, signal

        s = psutil.Process()
        for child in s.children(recursive=True):
            child.send_signal(signal.SIGINT)
Exemple #2
0
 def extract_info(self):
     opts = {
         'simulate': True
     }
     opts.update(YTDL_PLAYER_OPTS)
     ydl = YoutubeDL(opts)
     return ydl.extract_info(self.resource)
Exemple #3
0
def upload_video(video_info,access_token,youku_client_id):
    downloader = YoutubeDL()
    title = video_info[u"title"]
    file_name  = downloader.prepare_filename(video_info)
    tags = ["dassio",video_info["uploader"]]
    discription  = video_info["description"][0:1950]
    
    
    youku = YoukuUpload(youku_client_id,access_token,file_name)
    params = youku.prepare_video_params(title,tags,discription,'reproduced')
    try:
        if os.path.isfile(file_name + ".upload"):
            youku._read_upload_state_from_file()
            video_id = youku.upload(params)
        else:
            video_id = youku.upload(params)
    except:
        video_id = youku.upload(params)
    else:
        if video_id != "":
            try:
                os.remove(file_name)
            except:
                write_string("traceback.print_exc()")
            return video_id 
	def getVideoUrl(self):
		VIDEO_FMT_PRIORITY_MAP = {
			1 : '38', #MP4 Original (HD)
			2 : '37', #MP4 1080p (HD)
			3 : '22', #MP4 720p (HD)
			4 : '18', #MP4 360p
			5 : '35', #FLV 480p
			6 : '34', #FLV 360p
		}
		KEY_FORMAT_ID = u"format_id"
		KEY_URL = u"url"
		KEY_ENTRIES = u"entries"
		KEY_FORMATS = u"formats"

		video_url = None
		video_id = str(self.getTubeId())

		# Getting video webpage
		#URLs for YouTube video pages will change from the format http://www.youtube.com/watch?v=ylLzyHk54Z0 to http://www.youtube.com/watch#!v=ylLzyHk54Z0.
		watch_url = 'http://www.youtube.com/watch?v=%s' % video_id
		format_prio = "/".join(VIDEO_FMT_PRIORITY_MAP.itervalues())
		ytdl = YoutubeDL(params={"youtube_include_dash_manifest": False, "format" : format_prio})
		result = ytdl.extract_info(watch_url, download=False)
		if KEY_ENTRIES in result: # Can be a playlist or a list of videos
			entry = result[KEY_ENTRIES][0] #TODO handle properly
		else:# Just a video
			entry = result

		video_url = entry.get(KEY_URL)
		return str(video_url)
    def test_info_json(self):
        expected = list(EXPECTED_ANNOTATIONS) #Two annotations could have the same text.
        ie = youtube_dl.extractor.YoutubeIE()
        ydl = YoutubeDL(params)
        ydl.add_info_extractor(ie)
        ydl.download([TEST_ID])
        self.assertTrue(os.path.exists(ANNOTATIONS_FILE))
        annoxml = None
        with io.open(ANNOTATIONS_FILE, 'r', encoding='utf-8') as annof:
                annoxml = xml.etree.ElementTree.parse(annof)
        self.assertTrue(annoxml is not None, 'Failed to parse annotations XML')
        root = annoxml.getroot()
        self.assertEqual(root.tag, 'document')
        annotationsTag = root.find('annotations')
        self.assertEqual(annotationsTag.tag, 'annotations')
        annotations = annotationsTag.findall('annotation')

        #Not all the annotations have TEXT children and the annotations are returned unsorted.
        for a in annotations:
                self.assertEqual(a.tag, 'annotation')
                if a.get('type') == 'text':
                        textTag = a.find('TEXT')
                        text = textTag.text
                        self.assertTrue(text in expected) #assertIn only added in python 2.7
                        #remove the first occurance, there could be more than one annotation with the same text
                        expected.remove(text)
        #We should have seen (and removed) all the expected annotation texts.
        self.assertEqual(len(expected), 0, 'Not all expected annotations were found.')
Exemple #6
0
class YoutubeDLDownloader(DownloaderBase):
    scheme = "ytdl"

    def __init__(self, extractor, output):
        DownloaderBase.__init__(self, extractor, output)

        options = {
            "format": self.config("format") or None,
            "ratelimit": text.parse_bytes(self.config("rate"), None),
            "retries": self.config("retries", extractor._retries),
            "socket_timeout": self.config("timeout", extractor._timeout),
            "nocheckcertificate": not self.config("verify", extractor._verify),
            "nopart": not self.part,
        }
        options.update(self.config("raw-options") or {})

        if self.config("logging", True):
            options["logger"] = self.log

        self.ytdl = YoutubeDL(options)

    def download(self, url, pathfmt):
        try:
            info_dict = self.ytdl.extract_info(url[5:], download=False)
        except Exception:
            return False

        if "entries" in info_dict:
            index = pathfmt.keywords.get("_ytdl_index")
            if index is None:
                return self._download_playlist(pathfmt, info_dict)
            else:
                info_dict = info_dict["entries"][index]
        return self._download_video(pathfmt, info_dict)

    def _download_video(self, pathfmt, info_dict):
        pathfmt.set_extension(info_dict["ext"])
        if pathfmt.exists():
            pathfmt.temppath = ""
            return True
        if self.part and self.partdir:
            pathfmt.temppath = os.path.join(
                self.partdir, pathfmt.filename)
        self.ytdl.params["outtmpl"] = pathfmt.temppath.replace("%", "%%")

        self.out.start(pathfmt.path)
        try:
            self.ytdl.process_info(info_dict)
        except Exception:
            self.log.debug("Traceback", exc_info=True)
            return False
        return True

    def _download_playlist(self, pathfmt, info_dict):
        pathfmt.set_extension("%(playlist_index)s.%(ext)s")
        self.ytdl.params["outtmpl"] = pathfmt.realpath

        for entry in info_dict["entries"]:
            self.ytdl.process_info(entry)
        return True
Exemple #7
0
def get_video_url(params):
    """Get video URL and start video player"""
    url_selected = ''
    all_datas_videos_quality = []
    all_datas_videos_path = []
    videos_html = utils.get_webcontent(params.video_url)
    videos_soup = bs(videos_html, 'html.parser')

    list_videos = videos_soup.find(
        'ul', class_='nav nav-tabs').find_all('a')

    for video in list_videos:
        if '#video-' in video.get('href'):
            # Find a better solution to strip
            all_datas_videos_quality.append(video.get_text().strip())
            # Get link
            value_jwplayer_id = video.get('data-jwplayer-id')
            # Case mp4
            if value_jwplayer_id != '':
                list_streams = videos_soup.find_all(
                    'div', class_='jwplayer')
                for stream in list_streams:
                    if stream.get('id') == value_jwplayer_id:
                        url = stream.get('data-source')
            # Cas Yt
            else:
                video_id = re.compile(
                    'youtube.com/embed/(.*?)\?').findall(videos_html)[0]
                url = resolver.get_stream_youtube(video_id, False)
            all_datas_videos_path.append(url)
        # Get link from FranceTV
        elif '#ftv-player-' in video.get('href'):
            # Find a better solution to strip
            all_datas_videos_quality.append(video.get_text().strip())
            # Get link
            value_ftvlayer_id = video.get('data-ftvplayer-id')
            list_streams = videos_soup.find_all(
                'iframe', class_='embed-responsive-item')
            for stream in list_streams:
                if stream.get('id') == value_ftvlayer_id:
                    url_id = stream.get('src')
            ydl = YoutubeDL()
            ydl.add_default_info_extractors()
            with ydl:
                result = ydl.extract_info(
                    url_id, download=False)
                for format_video in result['formats']:
                    url = format_video['url']
            all_datas_videos_path.append(url)

    if len(all_datas_videos_quality) > 1:
        seleted_item = common.sp.xbmcgui.Dialog().select(
            common.GETTEXT('Choose video quality'),
            all_datas_videos_quality)
        if seleted_item == -1:
            return ''
        url_selected = all_datas_videos_path[seleted_item]
        return url_selected
    else:
        return all_datas_videos_path[0]
class InfoParser():
    def __init__(self, url=None, ydl_opt={}):
        self.__url = url
        self.__ydl = YoutubeDL(ydl_opt)
        self.__ydl_obj = YDLObject()

    @property
    def url(self):
        return self.__url

    @url.setter
    def url(self, url):
        self.__url = url

    @property
    def ydl_object(self):
        return self.__ydl_obj

    def generate_info(self):
        try:
            info_dict = self.__ydl.extract_info(self.__url, download=False)
            self.__ydl_obj.title = info_dict['title']
            self.__ydl_obj.url = self.__url
            for format in info_dict['formats']:
                filesize = format.get('filesize') if format.get('filesize') else format.get('filesize_approx')
                self.__ydl_obj.format_info.append({
                    'format_id': format['format'],
                    'extension': format['ext'],
                    'resolution': self.__ydl.format_resolution(format),
                    'filesize': format_bytes(filesize)
                })
            return True
        except Exception as e:
            print(e)
            return False
Exemple #9
0
 def start_youtube_dl(self):
     # Start downloading the specified url
     if self._output_path.get():
         output_path = self._output_path.get()
     else:
         try:
             output_path = os.path.dirname(os.path.abspath(__file__))
         except NameError:
             import sys
             output_path = os.path.dirname(os.path.abspath(sys.argv[0]))
     output_tmpl = output_path + '/%(title)s-%(id)s.%(ext)s'
     options = {
         'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo+bestaudio/best',
         'merge_output_format': 'mp4',
         'socket_timeout': '15',
         'progress_hooks': [self._logger.log],
         'ignoreerrors': True,
         'outtmpl': output_tmpl,
     }
     if self._extract_audio.get():
         options['format'] = 'bestaudio/best',
         options['postprocessors'] = [{
             'key': 'FFmpegExtractAudio',
             'preferredcodec': 'mp3',
             'preferredquality': '3',
         }]
     dl = YoutubeDL(options)
     status = dl.download([self._video_url.get()])
     if status != 0:
         mbox.showerror("youtube-dl error", "An error happened whilst processing your video(s)")
     else:
         mbox.showinfo("youtube-dl finished", "Your video(s) have been successfully processed")
Exemple #10
0
class PyJizzParser(object):
	def __init__(self, model):
		self.model = model
		self.model.parser = self
		self.ydl = YoutubeDL()
		self.ydl.add_default_info_extractors()
		
	def parseCategories(self):
		c = PornHubCategoryParser(self.model)
		c.run()
	
	def parseCategoryPage(self, category, page = 1):
		if page == 0 or page == 1:
			url = self.model.categories_url[category]
		else:
			url = "{site}{page_url}{page}".format(
				site = self.model.site,
				page_url = self.model.p**n[category]['page_url'],
				page = page)
		print("page parser creating for page", page)
		p = PornHubPageParser(self.model, url, category, page)
		p.run()
		print("page parser exit for page", page)
		
	def getInfo(self, vkey):
		info = self.ydl.extract_info('http://www.pornhub.com/view_video.php?viewkey={v}'.format(v = vkey), download=False)
		return info
class YoutubeDLWrapper(object):
    """ Used to wrap youtubedl import, since youtubedl currently overrides
    global HTMLParser.locatestarttagend regex with a different regex
    that doesn't quite work.

    This wrapper ensures that this regex is only set for YoutubeDL and unset
    otherwise
    """
    def __init__(self):
        import HTMLParser as htmlparser
        self.htmlparser = htmlparser

        self.orig_tagregex = htmlparser.locatestarttagend

        from youtube_dl import YoutubeDL as YoutubeDL

        self.ydl_tagregex = htmlparser.locatestarttagend

        htmlparser.locatestarttagend = self.orig_tagregex

        self.ydl = YoutubeDL(dict(simulate=True,
                                  youtube_include_dash_manifest=False))
        self.ydl.add_default_info_extractors()

    def extract_info(self, url):
        info = None
        try:
            self.htmlparser.locatestarttagend = self.ydl_tagregex
            info = self.ydl.extract_info(url)
        finally:
            self.htmlparser.locatestarttagend = self.orig_tagregex

        return info
Exemple #12
0
def v_info_url(url):
    url = urllib.parse.unquote(url)  # workaround
    format = request.forms.get('format', 'best')
    ytdl = YoutubeDL({'format': format, 'source_address': '0.0.0.0'})
    info = ytdl.extract_info(url, download=False)

    response.set_header('Access-Control-Allow-Origin', '*')
    return info
Exemple #13
0
def get_youtube_info(url):
    ydl = YoutubeDL()
    ydl.add_default_info_extractors()
    try:
        info = ydl.extract_info(url, download=False)
    except:
        return None
    return info
Exemple #14
0
 def test_proxy_with_idn(self):
     ydl = YoutubeDL({
         'proxy': '127.0.0.1:{0}'.format(self.port),
     })
     url = 'http://中文.tw/'
     response = ydl.urlopen(url).read().decode('utf-8')
     # b'xn--fiq228c' is '中文'.encode('idna')
     self.assertEqual(response, 'normal: http://xn--fiq228c.tw/')
Exemple #15
0
    def test_unicode_path_redirection(self):
        # XXX: Python 3 http server does not allow non-ASCII header values
        if sys.version_info[0] == 3:
            return

        ydl = YoutubeDL({'logger': FakeLogger()})
        r = ydl.extract_info('http://127.0.0.1:%d/302' % self.port)
        self.assertEqual(r['entries'][0]['url'], 'http://127.0.0.1:%d/vid.mp4' % self.port)
def get_info(url):
    ydl = YoutubeDL({
        'forceurl': True,
        'quiet': True
    })

    ydl.add_default_info_extractors()
    return ydl.extract_info(url, download=False)
 def test_format_note(self):
     ydl = YoutubeDL()
     self.assertEqual(ydl._format_note({}), '')
     assertRegexpMatches(self, ydl._format_note({
         'vbr': 10,
     }), r'^\s*10k$')
     assertRegexpMatches(self, ydl._format_note({
         'fps': 30,
     }), r'^30fps$')
Exemple #18
0
    def test_nocheckcertificate(self):
        if sys.version_info >= (2, 7, 9):  # No certificate checking anyways
            ydl = YoutubeDL({'logger': FakeLogger()})
            self.assertRaises(
                Exception,
                ydl.extract_info, 'https://127.0.0.1:%d/video.html' % self.port)

        ydl = YoutubeDL({'logger': FakeLogger(), 'nocheckcertificate': True})
        r = ydl.extract_info('https://127.0.0.1:%d/video.html' % self.port)
        self.assertEqual(r['entries'][0]['url'], 'https://127.0.0.1:%d/vid.mp4' % self.port)
Exemple #19
0
 def download(self, url=None, output=None):
     opts = {
         'outtmpl':
             os.path.join(
                 output, '%(title)s-%(id)s.%(ext)s'
             ),
         'progress_hooks': [self.progress_hook],
     }
     y = YoutubeDL(params=opts)
     y.download([url])
Exemple #20
0
def download_video(url,google_user_dict):
    if google_user_dict["google_username"] != None and google_user_dict["google_passwd"]:
        params = {"username":google_user_dict["google_username"],"password":google_user_dict["google_passwd"]}
    else:
        params = {}
    downloader =  YoutubeDL(params)
    res = downloader.download([url])
    filename = downloader.prepare_filename(res[1])
    ret_code = res[0]
    video_info = res[1]
    return video_info
	def viceLink(self, callback, url):
		video_url = None
		m = re.search('share_url=(.+)("|&)*', url)
		if m:
			url = m.group(1)
			#print 'url:',url
			try:
				ytdl = YoutubeDL()
				result = ytdl.extract_info(url, download=False)
				#print 'result:',result
				video_url = str(result["url"])
			except Exception, e:
				printl(str(e),self,"E")
    def get_stream_selector(self):
        """Return format selector for the media URL."""
        from youtube_dl import YoutubeDL
        from youtube_dl.utils import DownloadError, ExtractorError

        ydl = YoutubeDL({'quiet': True, 'logger': _LOGGER})

        try:
            all_media = ydl.extract_info(self.get_media_url(),
                                         process=False)
        except DownloadError:
            # This exception will be logged by youtube-dl itself
            raise MEDownloadException()

        if 'entries' in all_media:
            _LOGGER.warning("Playlists are not supported, "
                            "looking for the first video")
            entries = list(all_media['entries'])
            if len(entries) > 0:
                selected_media = entries[0]
            else:
                _LOGGER.error("Playlist is empty")
                raise MEDownloadException()
        else:
            selected_media = all_media

        try:
            media_info = ydl.process_ie_result(selected_media,
                                               download=False)
        except (ExtractorError, DownloadError):
            # This exception will be logged by youtube-dl itself
            raise MEDownloadException()

        def stream_selector(query):
            """Find stream url that matches query."""
            try:
                format_selector = ydl.build_format_selector(query)
            except (SyntaxError, ValueError, AttributeError) as ex:
                _LOGGER.error(ex)
                raise MEQueryException()

            try:
                requested_stream = next(format_selector(media_info))
            except (KeyError, StopIteration):
                _LOGGER.error("Could not extract stream for the query: %s",
                              query)
                raise MEQueryException()

            return requested_stream['url']

        return stream_selector
Exemple #23
0
    def test_proxy(self):
        geo_proxy = '127.0.0.1:{0}'.format(self.geo_port)
        ydl = YoutubeDL({
            'proxy': '127.0.0.1:{0}'.format(self.port),
            'geo_verification_proxy': geo_proxy,
        })
        url = 'http://foo.com/bar'
        response = ydl.urlopen(url).read().decode('utf-8')
        self.assertEqual(response, 'normal: {0}'.format(url))

        req = compat_urllib_request.Request(url)
        req.add_header('Ytdl-request-proxy', geo_proxy)
        response = ydl.urlopen(req).read().decode('utf-8')
        self.assertEqual(response, 'geo: {0}'.format(url))
Exemple #24
0
    def _parse_post(self):
        """
        Parse all available photos using the best image sizes available
        """
        super()._parse_post()

        video_info = YoutubeDL().extract_info(self.url.as_string(), False)

        self.title = video_info.get('title')

        self.description    = video_info.get('description')
        self.duration       = int(video_info.get('duration', 0))
        self.format         = video_info.get('format', 'Unknown')

        self.files.append(TumblrVideo(video_info, self))
Exemple #25
0
    def __init__(self):
        credentials = _read_json("credentials.json")

        self.api_key = credentials["google_key"]

        self.http_session = aiohttp.ClientSession()

        self.ytdl = YoutubeDL({
            "format": "webm[abr>0]/bestaudio/best",
            "restrictfilenames": True,
            "noplaylist": True,
            "nocheckcertificate": True,
            "ignoreerrors": False,
            "logtostderr": False,
            "quiet": True,
            "no_warnings": True,
            "default_search": "error",
            "source_address": "0.0.0.0",
            "prefer_ffmpeg": True
        })

        self.extractor = YoutubeIE()
        self.extractor._downloader = self.ytdl

        self.raw_video_id_regex = re.compile(r"^([\w-]+)$")
        self.video_id_regex = re.compile(r"watch/?\?v=([\w-]+)")
        self.playlist_id_regex = re.compile(r"playlist/?\?list=([\w-]+)")
Exemple #26
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
class VideoLoader(BaseLoader):
    CONTENT_TYPE = 'application/vnd.youtube-dl_formats+json'

    def __init__(self):
        try:
            from youtube_dl import YoutubeDL as YoutubeDL
        except ImportError:
            self.ydl = None
            return

        self.ydl = YoutubeDL(dict(simulate=True,
                                  youtube_include_dash_manifest=False))

        self.ydl.add_default_info_extractors()

    def load_resource(self, cdx, params):
        load_url = cdx.get('load_url')
        if not load_url:
            return None

        if params.get('content_type') != self.CONTENT_TYPE:
            return None

        if not self.ydl:
            return None

        info = self.ydl.extract_info(load_url)
        info_buff = json.dumps(info)
        info_buff = info_buff.encode('utf-8')

        warc_headers = {}

        schema, rest = load_url.split('://', 1)
        target_url = 'metadata://' + rest

        dt = timestamp_to_datetime(cdx['timestamp'])

        warc_headers['WARC-Type'] = 'metadata'
        warc_headers['WARC-Record-ID'] = self._make_warc_id()
        warc_headers['WARC-Target-URI'] = target_url
        warc_headers['WARC-Date'] = datetime_to_iso_date(dt)
        warc_headers['Content-Type'] = self.CONTENT_TYPE
        warc_headers['Content-Length'] = str(len(info_buff))

        warc_headers = StatusAndHeaders('WARC/1.0', warc_headers.items())

        return warc_headers, None, BytesIO(info_buff)
def test_ydl():
    ydl = YoutubeDL(ydl_opt)
    with ydl:
        try:
            info_dict = ydl.extract_info('https://www.youtube.com/watch?v=QwoghxwETng', download=False)
            # print(info_dict.keys())
            #print(info_dict['title'])
            #print(ydl.list_formats(info_dict))
            #for f in info_dict['formats']:
            #    filesize = f.get('filesize') if f.get('filesize') else f.get('filesize_approx')
            #    filesize2 = f['filesize'] if f['filesize'] else f['filesize_approx']
            #    print("%s, %s, %s, %s" % (f['format'], f['ext'], ydl.format_resolution(f), format_bytes(filesize2)))

            #print(ydl.list_formats(info_dict))

        except Exception as e:
            print(e)
Exemple #29
0
    def on_task_output(self, task, config):
        import youtube_dl.YoutubeDL
        from youtube_dl.utils import ExtractorError

        class YoutubeDL(youtube_dl.YoutubeDL):
            def __init__(self, *args, **kwargs):
                self.to_stderr = self.to_screen
                self.processed_info_dicts = []
                super(YoutubeDL, self).__init__(*args, **kwargs)

            def report_warning(self, message):
                raise ExtractorError(message)

            def process_info(self, info_dict):
                self.processed_info_dicts.append(info_dict)
                return super(YoutubeDL, self).process_info(info_dict)
        for entry in task.accepted:
            if task.options.test:
                log.info('Would download %s' % entry['title'])
            else:
                try:
                    outtmpl = entry.render(config['path']) + '/' + pathscrub(entry.render(config['template']) + '.%(ext)s', filename=True)
                    log.info("Output file: %s" % outtmpl)
                except RenderError as e:
                    log.error('Error setting output file: %s' % e)
                    entry.fail('Error setting output file: %s' % e)
                params = {'quiet': True, 'outtmpl': outtmpl}
                if 'username' in config and 'password' in config:
                    params.update({'username': config['username'], 'password': config['password']})
                elif 'username' in config or 'password' in config:
                    log.error('Both username and password is required')
                if 'videopassword' in config:
                    params.update({'videopassword': config['videopassword']})
                if 'title' in config:
                    params.update({'title': config['title']})
                ydl = YoutubeDL(params)
                ydl.add_default_info_extractors()
                log.info('Downloading %s' % entry['title'])
                try:
                    ydl.download([entry['url']])
                except ExtractorError as e:
                    log.error('Youtube-DL was unable to download the video. Error message %s' % e.message)
                    entry.fail('Youtube-DL was unable to download the video. Error message %s' % e.message)
                except Exception as e:
                    log.error('Youtube-DL failed. Error message %s' % e.message)
                    entry.fail('Youtube-DL failed. Error message %s' % e.message)
def _download_restricted(url, filename, age):
    """ Returns true iff the file has been downloaded """

    params = {
        'age_limit': age,
        'skip_download': True,
        'writeinfojson': True,
        "outtmpl": "%(id)s.%(ext)s",
    }
    ydl = YoutubeDL(params)
    ydl.add_default_info_extractors()
    json_filename = filename + '.info.json'
    try_rm(json_filename)
    ydl.download([url])
    res = os.path.exists(json_filename)
    try_rm(json_filename)
    return res
Exemple #31
0
async def _ytdl(url, is_it, event, tgbot):
    await event.edit(
        "`Ok Downloading This Video / Audio - Please Wait.` \n**Powered By @FridayOT**"
    )
    if is_it:
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "480",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
        video = False
        song = True
    else:
        opts = {
            "format":
            "best",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegVideoConvertor",
                "preferedformat": "mp4"
            }],
            "outtmpl":
            "%(id)s.mp4",
            "logtostderr":
            False,
            "quiet":
            True,
        }
        song = False
        video = True
    try:
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
    except Exception as e:
        await event.edit(f"**Failed To Download** \n**Error :** `{str(e)}`")
        return
    c_time = time.time()
    if song:
        file_stark = f"{ytdl_data['id']}.mp3"
        lol_m = await upload_file(
            file_name=f"{ytdl_data['title']}.mp3",
            client=tgbot,
            file=open(file_stark, 'rb'),
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, event, c_time, "Uploading Youtube Audio..",
                         file_stark)),
        )
        await event.edit(
            file=lol_m,
            text=f"{ytdl_data['title']} \n**Uploaded Using @FRidayOt**")
        os.remove(file_stark)
    elif video:
        file_stark = f"{ytdl_data['id']}.mp4"
        lol_m = await upload_file(
            file_name=f"{ytdl_data['title']}.mp4",
            client=tgbot,
            file=open(file_stark, 'rb'),
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, event, c_time, "Uploading Youtube Video..",
                         file_stark)),
        )
        await event.edit(
            file=lol_m,
            text=f"{ytdl_data['title']} \n**Uploaded Using @FRidayOt**")
        os.remove(file_stark)
Exemple #32
0
async def download_video(v_url):
    lazy = v_url
    sender = await lazy.get_sender()
    me = await lazy.client.get_me()
    if not sender.id == me.id:
        rkp = await lazy.reply("`Processing...`")
    else:
        rkp = await lazy.edit("`Processing...`")
    url = v_url.pattern_match.group(1)
    if not url:
        return await rkp.edit("`Error \nusage song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except:
        return await rkp.edit("`failed to find`")
    type = "audio"
    await rkp.edit("Preparing to download 😌")
    if type == "audio":
        opts = {
            "format":
            "best",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegVideoConvertor",
                "preferedformat": "mp4"
            }],
            "outtmpl":
            "%(id)s.mp4",
            "logtostderr":
            False,
            "quiet":
            True,
        }
        song = False
        video = True
    try:
        await rkp.edit("Fetching data, please wait 😉")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await rkp.edit(f"`Preparing to upload song:`\
        \n**{rip_data['title']}**\
        \nby **{rip_data['uploader']}**")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(rip_data["duration"]),
                    title=str(rip_data["title"]),
                    performer=str(rip_data["uploader"]),
                )
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Uploading...",
                         f"{rip_data['title']}.mp3")),
        )
        os.remove(f"{rip_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await rkp.edit(f"`Preparing to upload video song:`\
        \n**{rip_data['title']}**\
        \nby **{rip_data['uploader']}**")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data["title"],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Uploading...",
                         f"{rip_data['title']}.mp4")),
        )
        os.remove(f"{rip_data['id']}.mp4")
        await rkp.delete()
Exemple #33
0
 def fname(templ):
     ydl = YoutubeDL({'outtmpl': templ})
     return ydl.prepare_filename(info)
# SEARCH and DOWNLOAD the first video from Youtube
from youtube_dl import YoutubeDL

option = {
    'default_search':'ytsearch',# SEARCHING before download
    'download':1
}
dl = YoutubeDL(option)
dl.download(['Một đêm say'])
Exemple #35
0
    async def choose_song(self, ctx: commands.Context, *, arg: str = ''):
        """Lets the user play a song from songlist or start a playlist.

        Also used by other methods of Music class which substitute user input.
        """
        playlist = False
        if not arg:
            playlist = True
        if arg and arg.startswith('loop'):
            self._stop_loop = False
            self._looped = True
            await ctx.send(boxed_string(_('Loop activated!')))
            return
        elif arg and arg.startswith('random'):
            number = random.randint(0, len(_songlist) - 1)
        elif playlist or arg.startswith('playlist'):
            if _playlist:
                number = _songlist.index(_playlist[0]) + 1
                _playlist.pop(0)
            else:
                await ctx.send(boxed_string(_('Nothing to play!')))
                return
        elif arg and arg.split(maxsplit=1)[0].isnumeric():
            number = int(arg.split(maxsplit=1)[0])
        if 'number' in locals():
            self.current_song = {
                'name':
                _songlist[int(number) -
                          1][:-len(MUSIC_EXT)],  # type: ignore # nopep8
                'source': MUSIC_PATH +
                _songlist[int(number) - 1]  # type: ignore # nopep8
            }
            ffmpeg_opts = {}
        else:
            ydl_opts = {'format': 'bestaudio'}
            ffmpeg_opts = {
                'before_options':
                '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
                'options': '-vn'
            }
            if arg.startswith('http'):
                url = arg
            else:
                searchrequest = arg
                url = 'https://www.youtube.com' + \
                    YoutubeSearch(searchrequest, max_results=1).to_dict()[
                        0]['url_suffix']  # type: ignore
            with YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(url, download=False)
            self.current_song = {
                'name': info['title'],
                'source': info['formats'][0]['url']
            }
        arg_split = arg.split()
        if len(arg_split) > 1 and arg_split[1] == 'loop' and str(
                arg_split[0]).isnumeric():
            self._looped = True
        self._stop_loop = False
        self.is_stopped = False

        await self.player(ctx, ffmpeg_opts)
Exemple #36
0
async def process(v_url, dtype, opts):
    lazy = v_url ; sender = await lazy.get_sender() ; me = await lazy.client.get_me()
    if not sender.id == me.id:
        rkp = await lazy.reply("`processing...`")
    else:
    	rkp = await lazy.edit("`processing...`")   
    url = v_url.pattern_match.group(1)
    if not url:
         return await rkp.edit("`Error \nusage song <song name>`")
    search = SearchVideos(url, offset = 1, mode = "json", max_results = 1)
    test = search.result()
    p = json.loads(test)
    q = p.get('search_result')
    try:
       url = q[0]['link']
    except:
    	return await rkp.edit("`failed to find`")
    type = "audio"
    await rkp.edit("`Preparing to download...`")
  
    try:
        await rkp.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()

    if dtype == "song":
        await rkp.edit(f"`Preparing to upload song:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(rip_data['duration']),
                                       title=str(rip_data['title']),
                                       performer=str(rip_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp3")))

    else:
        await rkp.edit(f"`Preparing to upload video:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=url,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp4")))

    try:
        for f in glob.glob("*.mp*"):
            os.remove(f)
    except Exception:
        pass
Exemple #37
0
async def download_video(v_url):
    pro = v_url
    sender = await pro.get_sender()
    me = await pro.client.get_me()
    pro1 = v_url.text
    if not sender.id == me.id:
        dc = await pro.reply("`processing, please weit...`")
    else:
        dc = await pro.edit("`processing, please weit...😍`")
    teamcobra = pro1[8:]
    if not teamcobra:
        return await dc.edit("`Error \nusage vsong <song name>`")
    search = SearchVideos(teamcobra, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        teamcobra = q[0]["link"]
    except:
        return await dc.edit("`failed to find your desired song`")
    type = "audio"
    await dc.edit("`Ok downloading your song🤓...`")
    if type == "audio":
        opts = {
            "format":
            "best",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegVideoConvertor",
                "preferedformat": "mp4"
            }],
            "outtmpl":
            "%(id)s.mp4",
            "logtostderr":
            False,
            "quiet":
            True,
        }
        song = False
        video = True
    try:
        await dc.edit("`Fetching data, please wait..😋😍😎`")
        with YoutubeDL(opts) as darkcobra:
            darkcobra_data = darkcobra.extract_info(teamcobra)
    except DownloadError as error:
        await dc.edit(f"`{str(error)}`")
        return
    except ContentTooShortError:
        await dc.edit("`Oof the download content was too short😮🤐.`")
        return
    except GeoRestrictedError:
        await dc.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website🤔.`"
        )
        return
    except MaxDownloadsReached:
        await dc.edit("`Max-downloads limit has been reached😶.`")
        return
    except PostProcessingError:
        await dc.edit("`There was an error during post processing😐.`")
        return
    except UnavailableVideoError:
        await dc.edit(
            "`sorry, media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await dc.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await dc.edit("`There was an error while fetching your query...`")
        return
    except Exception as e:
        await dc.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await dc.edit(f"`Preparing to upload your video song😎 `\
        \n**{darkcobra_data['title']}**\
        \nby *{darkcobra_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{darkcobra_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(darkcobra_data["duration"]),
                    title=str(darkcobra_data["title"]),
                    performer=str(darkcobra_data["uploader"]),
                )
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(
                    d,
                    t,
                    v_url,
                    c_time,
                    "Uploading your video song😍..",
                    f"{darkcobra_data['title']}.mp3",
                )),
        )
        os.remove(f"{darkcobra_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await dc.edit(f"`Preparing to upload your video song🤗❤ :`\
        \n**{darkcobra_data['title']}**\
        \nby *{darkcobra_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{darkcobra_data['id']}.mp4",
            supports_streaming=True,
            caption=darkcobra_data["title"],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{darkcobra_data['title']}.mp4")),
        )
        os.remove(f"{darkcobra_data['id']}.mp4")
        await dc.delete()
Exemple #38
0
import os
import shlex
from youtube_dl import YoutubeDL
from subprocess import Popen, PIPE
from sys import argv
from bs4 import BeautifulSoup
import requests

for i in argv[1:]:
    data = requests.get(i)
    soup = BeautifulSoup(data.content)
    title = str(soup.title.text)
    print title
    os.getcwd()
    os.chdir('/home/hadn/Downloads/adsense/football/')
    ydl = YoutubeDL()
    ydl.add_default_info_extractors()
    try:
        print i
        ydl.download([i])
        for file_mp4 in os.listdir("/home/hadn/Downloads/adsense/football/"):
            if file_mp4.endswith(".mp4"):
                cmd = '/home/hadn/Downloads/adsense/python/bin/python /home/hadn/Downloads/adsense/donguyenha-upload-youtube.py --file "/home/hadn/Downloads/adsense/football/%s" --title "%s" --description "%s"' % (
                    file_mp4, title, title)
                cmd = shlex.split(cmd)
                print cmd
                #: upload video to Youtube
                up = Popen(cmd, stdout=PIPE)
                temp = up.communicate()
                videoId = temp[0].split()[-4]
                #: remove file which uploaded to youtube
Exemple #39
0
def youtube_callback(update: Update, context: CallbackContext):
    bot = context.bot
    message = update.effective_message
    chat = update.effective_chat
    query = update.callback_query

    media = query.data.split(";")
    media_type = media[1]
    media_url = media[2]

    if media_type == "audio":
        deltext = message.edit_text("Processing song...")
        opts = {
            "format":
            "bestaudio/best",
            "addmetadata":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "128",
            }],
            "outtmpl":
            "%(title)s.%(etx)s",
            "quiet":
            True,
            "logtostderr":
            False,
        }

        codec = "mp3"

        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(media_url,
                                        download=False,
                                        process=False)
            if int(rip_data['duration'] / 60) < 10:
                try:
                    rip_data = rip.extract_info(media_url)
                    delmsg = bot.send_audio(chat_id=chat.id,
                                            audio=open(
                                                f"{rip_data['title']}.{codec}",
                                                "rb"),
                                            duration=int(rip_data['duration']),
                                            title=str(rip_data['title']),
                                            parse_mode=ParseMode.HTML)
                    context.dispatcher.run_async(delete, deltext, 0)
                except:
                    delmsg = message.edit_text(
                        "Song is too large for processing, or any other error happened. Try again later"
                    )
            else:
                delmsg = message.edit_text(
                    "Song is too large for processing. Duration is limited to 10 minutes max"
                )

    elif media_type == "video":
        deltext = message.edit_text("Processing video...")
        opts = {
            "format":
            "best",
            "addmetadata":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegVideoConvertor",
                "preferedformat": "mp4",
            }],
            "outtmpl":
            "%(title)s.mp4",
            "quiet":
            True,
            "logtostderr":
            False,
        }

        codec = "mp4"

        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(media_url,
                                        download=False,
                                        process=False)
            if int(rip_data['duration'] / 60) < 10:
                try:
                    rip_data = rip.extract_info(media_url)
                    delmsg = bot.send_video(chat_id=chat.id,
                                            video=open(
                                                f"{rip_data['title']}.{codec}",
                                                "rb"),
                                            duration=int(rip_data['duration']),
                                            caption=rip_data['title'],
                                            supports_streaming=True,
                                            parse_mode=ParseMode.HTML)
                    context.dispatcher.run_async(delete, deltext, 0)
                except:
                    delmsg = message.edit_text(
                        "Video is too large for processing, or any other error happened. Try again later"
                    )
            else:
                delmsg = message.edit_text(
                    "Video is too large for processing. Duration is limited to 10 minutes max"
                )
    else:
        delmsg = message.edit_text("Canceling...")
        context.dispatcher.run_async(delete, delmsg, 1)

    try:
        os.remove(f"{rip_data['title']}.{codec}")
    except Exception:
        pass

    cleartime = get_clearcmd(chat.id, "youtube")

    if cleartime:
        context.dispatcher.run_async(delete, delmsg, cleartime.time)
Exemple #40
0
    title = a.string.strip()

    # 3.b: lấy ra artist:
    h4 = li.h4
    a = h4.a
    artist = a.string.strip()

    dic = OrderedDict({'Title': title, 'Artist': artist})
    empty_list.append(dic)

# # 4 save data: lưu vào excel
# import pyexcel
# make sure you had pyexcel-xls installed

# pyexcel.save_as(records=empty_list, dest_file_name="Itunes_table.xls")

# 2.2: Download youtube:
from youtube_dl import YoutubeDL

options = {
    'default_search': 'ytsearch',
    'max_downloads': 1,
    'format': 'bestaudio/audio'
}

dl = YoutubeDL(options)

# print(empty_list)

for li in empty_list:
    dl.download([li['Title'] + li['Artist']])  # sao ko tải đc hết nhở
Exemple #41
0
async def download_video(v_url):
    """ .rip komutu ile YouTube ve birkaç farklı siteden medya çekebilirsin. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await v_url.edit("`İndirmeye hazırlanıyor...`")

    if type == "audio":
        opts = {
            'format':
            'bestaudio',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'writethumbnail':
            True,
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '320',
            }],
            'outtmpl':
            '%(id)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True

    elif type == "video":
        opts = {
            'format':
            'best',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegVideoConvertor',
                'preferedformat': 'mp4'
            }],
            'outtmpl':
            '%(id)s.mp4',
            'logtostderr':
            False,
            'quiet':
            True
        }
        song = False
        video = True

    try:
        await v_url.edit("`Veri çekiliyor, lütfen bekleyin...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await v_url.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await v_url.edit("`İndirilecek içerik fazla kısa.`")
        return
    except GeoRestrictedError:
        await v_url.edit(
            "`Maalesef coğrafi kısıtlamalar sebebiyle bu videoyla işlem yapamazsın.`"
        )
        return
    except MaxDownloadsReached:
        await v_url.edit("`Maksimum indirme limitini aştın.`")
        return
    except PostProcessingError:
        await v_url.edit("`İstek işlenirken bir hata oluştu.`")
        return
    except UnavailableVideoError:
        await v_url.edit("`Medya belirtilen dosya formatında mevcut değil.`")
        return
    except XAttrMetadataError as XAME:
        await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await v_url.edit("`Bilgi çıkarılırken bir hata gerçekleşti.`")
        return
    except Exception as e:
        await v_url.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await v_url.edit(f"`Şarkı yüklenmeye hazırlanıyor:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(rip_data['duration']),
                                       title=str(rip_data['title']),
                                       performer=str(rip_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Karşıya yükleniyor...",
                         f"{rip_data['title']}.mp3")))
        os.remove(f"{rip_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await v_url.edit(f"`Şarkı yüklenmeye hazırlanıyor:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data['title'],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Karşıya yükleniyor...",
                         f"{rip_data['title']}.mp4")))
        os.remove(f"{rip_data['id']}.mp4")
        await v_url.delete()
Exemple #42
0
print("\nEnter youtube searches consecutively. Enter 'done' to begin downloads.\n\n")
query_list = []

while True:					# Loop to take in user requests for songs
	user_search = input("Enter song:\t")

	if user_search == "done":
		break
	
	user_search = user_search.replace(' ',"+")
	query_list.append(user_search)
		

for query in query_list:	# Loop to iterate over each song and download it to PC

	html = urllib.request.urlopen("https://www.youtube.com/results?search_query=" + query)	# Opens html for song search
	video_ids = re.findall(r"watch\?v=(\S{11})", html.read().decode())  # Use of Regex findall to find and decode song IDs from youtube
	download_link = "https://www.youtube.com/watch?v=" + video_ids[0]	# Finally, the download link is ready
	print("https://www.youtube.com/watch?v=" + video_ids[0])

	ydl_opts = {			# Sets options for youtube downloader
		'format': 'bestaudio/best',
		'postprocessors': [{'key': 'FFmpegExtractAudio',
			            'preferredcodec': 'mp3',
			            'preferredquality': '192',}],
	       }

	with YoutubeDL(ydl_opts) as ydl:	# Downloads the song to the PC using youtube_dl
		ydl.download([download_link])
Exemple #43
0
from os import path

from youtube_dl import YoutubeDL

from config import BOT_NAME as bn, DURATION_LIMIT
from helpers.errors import DurationLimitError
ydl_opts = {
    "format": "bestaudio[ext=m4a]",
    "geo-bypass": True,
    "nocheckcertificate": True,
    "outtmpl": "downloads/%(id)s.%(ext)s",
}

ydl = YoutubeDL(ydl_opts)


def download(url: str) -> str:
    info = ydl.extract_info(url, False)
    duration = round(info["duration"] / 60)

    if duration > DURATION_LIMIT:
        raise DurationLimitError(
            f"❌ Video lebih lama dari {DURATION_LIMIT} minute(s) tidak diizinkan, video yang disediakan adalah {duration} minute(s)"
        )
    try:
        ydl.download([url])
    except:
        raise DurationLimitError(
            f"❌ Video lebih lama dari {DURATION_LIMIT} minute(s) tidak diizinkan, video yang disediakan adalah {duration} minute(s)"
        )
    return path.join("downloads", f"{info['id']}.{info['ext']}")
Exemple #44
0
async def download_video(v_url):
    if v_url.fwd_from:
        return
    """ For .ytdl command, download media from YouTube and many other sites. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await edit_or_reply(v_url, "`Preparing to download...`")

    if type == "a":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "480",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
        video = False
        song = True

    elif type == "v":
        opts = {
            "format":
            "best",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegVideoConvertor",
                "preferedformat": "mp4"
            }],
            "outtmpl":
            "%(id)s.mp4",
            "logtostderr":
            False,
            "quiet":
            True,
        }
        song = False
        video = True

    try:
        await edit_or_reply(v_url, "`Fetching data, please wait..`")
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
    except DownloadError as DE:
        await edit_or_reply(v_url, f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await edit_or_reply(v_url, "`The download content was too short.`")
        return
    except GeoRestrictedError:
        await edit_or_reply(
            v_url,
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await edit_or_reply(v_url, "`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await edit_or_reply(v_url,
                            "`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await edit_or_reply(
            v_url, "`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await edit_or_reply(v_url, f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await edit_or_reply(v_url,
                            "`There was an error during info extraction.`")
        return
    except Exception as e:
        await edit_or_reply(v_url, f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await edit_or_reply(
            v_url, f"`Preparing to upload song:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{ytdl_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(ytdl_data["duration"]),
                    title=str(ytdl_data["title"]),
                    performer=str(ytdl_data["uploader"]),
                )
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{ytdl_data['title']}.mp3")),
        )
        os.remove(f"{ytdl_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await edit_or_reply(
            v_url, f"`Preparing to upload video:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{ytdl_data['id']}.mp4",
            supports_streaming=True,
            caption=ytdl_data["title"],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{ytdl_data['title']}.mp4")),
        )
        os.remove(f"{ytdl_data['id']}.mp4")
        await v_url.delete()
Exemple #45
0
                tracks_start.append(t_start * 1000)
                tracks_titles.append(curr_title)

    if DRYRUN:
        exit()

    album = None
    if YT_URL:
        url_data = urlparse(YT_URL)
        query = parse_qs(url_data.query)
        video_id = query["v"][0]
        FILENAME = video_id + ".wav"
        if not os.path.isfile(FILENAME):
            print("Downloading video from YouTube")
            with YoutubeDL(ydl_opts) as ydl:
                ydl.download(['http://www.youtube.com/watch?v=' + video_id])
            print("\nConversion complete")
        else:
            print("Found matching file")
        print("Loading audio file")
        album = AudioSegment.from_file(FILENAME, 'wav')
    else:
        print("Loading audio file")
        album = AudioSegment.from_file(FILENAME, 'mp3')
    print("Audio file loaded")

    #given the length of the album, determine the split size, for 5 min segment each
    albumLen = len(album)
    print("Album Len: ", albumLen)
Exemple #46
0
async def download_video(v_url):
    """For .rip command, download media from YouTube and many other sites."""
    dl_type = v_url.pattern_match.group(1).lower()
    reso = v_url.pattern_match.group(2)
    reso = reso.strip() if reso else None
    url = v_url.pattern_match.group(3)

    await v_url.edit("`Preparing to Download...`")
    s_time = time.time()
    video = False
    audio = False

    if "audio" in dl_type:
        opts = {
            "format":
            "bestaudio/best",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "328",
            }],
            "outtmpl":
            os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time),
                         "%(title)s.%(ext)s"),
            "quiet":
            True,
            "logtostderr":
            False,
        }
        audio = True

    elif "video" in dl_type:
        quality = (f"bestvideo[height<={reso}]+bestaudio/best[height<={reso}]"
                   if reso else "bestvideo+bestaudio/best")
        opts = {
            "format":
            quality,
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "outtmpl":
            os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time),
                         "%(title)s.%(ext)s"),
            "logtostderr":
            False,
            "quiet":
            True,
        }
        video = True

    try:
        await v_url.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        return await v_url.edit(f"`{str(DE)}`")
    except ContentTooShortError:
        return await v_url.edit("`The download content was too short.`")
    except GeoRestrictedError:
        return await v_url.edit(
            "`Video is not available from your geographic location "
            "due to geographic restrictions imposed by a website.`")
    except MaxDownloadsReached:
        return await v_url.edit("`Max-downloads limit has been reached.`")
    except PostProcessingError:
        return await v_url.edit("`There was an error during post processing.`")
    except UnavailableVideoError:
        return await v_url.edit(
            "`Media is not available in the requested format.`")
    except XAttrMetadataError as XAME:
        return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await v_url.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await v_url.edit(f"{str(type(e)): {str(e)}}")
    c_time = time.time()
    if audio:
        await v_url.edit(
            f"`Preparing to upload song:`\n**{rip_data.get('title')}**"
            f"\nby **{rip_data.get('uploader')}**")
        f_name = glob(os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time),
                                   "*"))[0]
        with open(f_name, "rb") as f:
            result = await upload_file(
                client=v_url.client,
                file=f,
                name=f_name,
                progress_callback=lambda d, t: get_event_loop().create_task(
                    progress(d, t, v_url, c_time, "Uploading..",
                             f"{rip_data['title']}.mp3")),
            )

        thumb_image = [
            x for x in glob(
                os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time), "*"))
            if not x.endswith(".mp3")
        ][0]
        metadata = extractMetadata(createParser(f_name))
        duration = 0
        if metadata.has("duration"):
            duration = metadata.get("duration").seconds
        await v_url.client.send_file(
            v_url.chat_id,
            result,
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=duration,
                    title=rip_data.get("title"),
                    performer=rip_data.get("uploader"),
                )
            ],
            thumb=thumb_image,
        )
        await v_url.delete()
    elif video:
        await v_url.edit(
            f"`Preparing to upload video:`\n**{rip_data.get('title')}**"
            f"\nby **{rip_data.get('uploader')}**")
        f_path = glob(os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time),
                                   "*"))[0]
        # Noob way to convert from .mkv to .mp4
        if f_path.endswith(".mkv"):
            base = os.path.splitext(f_path)[0]
            os.rename(f_path, base + ".mp4")
            f_path = glob(
                os.path.join(TEMP_DOWNLOAD_DIRECTORY, str(s_time), "*"))[0]
        f_name = os.path.basename(f_path)
        with open(f_path, "rb") as f:
            result = await upload_file(
                client=v_url.client,
                file=f,
                name=f_name,
                progress_callback=lambda d, t: get_event_loop().create_task(
                    progress(d, t, v_url, c_time, "Uploading..", f_name)),
            )
        thumb_image = await get_video_thumb(f_path, "thumb.png")
        metadata = extractMetadata(createParser(f_path))
        duration = 0
        width = 0
        height = 0
        if metadata.has("duration"):
            duration = metadata.get("duration").seconds
        if metadata.has("width"):
            width = metadata.get("width")
        if metadata.has("height"):
            height = metadata.get("height")
        await v_url.client.send_file(
            v_url.chat_id,
            result,
            thumb=thumb_image,
            attributes=[
                DocumentAttributeVideo(
                    duration=duration,
                    w=width,
                    h=height,
                    supports_streaming=True,
                )
            ],
            caption=f"[{rip_data.get('title')}]({url})",
        )
        os.remove(thumb_image)
        await v_url.delete()
Exemple #47
0
async def download_video(ult):
    x = await eor(ult, "Searching...")
    url = ult.pattern_match.group(1)
    if not url:
        return await x.edit("**Error**\nUsage - `.song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await x.edit("`No matching song found...`")
    type = "audio"
    await x.edit(f"`Preparing to download {url}...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
    try:
        await x.edit("`Getting info...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await x.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await x.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await x.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await x.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await x.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await x.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        return await x.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await x.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await x.edit(f"{str(type(e)): {str(e)}}")
    upteload = """
Uploading...
Song name - {}
By - {}
""".format(rip_data["title"], rip_data["uploader"])
    await x.edit(f"`{upteload}`")
    await ultroid_bot.send_file(
        ult.chat_id,
        f"{rip_data['id']}.mp3",
        supports_streaming=True,
        caption=
        f"⫸ Song - {rip_data['title']}\n⫸ By - {rip_data['uploader']}\n",
        attributes=[
            DocumentAttributeAudio(
                duration=int(rip_data["duration"]),
                title=str(rip_data["title"]),
                performer=str(rip_data["uploader"]),
            )
        ],
    )
    os.remove(f"{rip_data['id']}.mp3")
Exemple #48
0
from flask import *
from model.video import Video
import mlab
from youtube_dl import YoutubeDL

app = Flask(__name__)
mlab.connect()
app.secret_key = "atom"
ydl = YoutubeDL()


@app.route('/')
def index():
    videos = Video.objects()
    return render_template('index.html', videos=videos)


@app.route('/admin', methods=['GET', 'POST'])
def admin():
    if request.method == 'GET':
        if "logged_in" in session:
            videos = Video.objects()
            return render_template('admin.html', videos=videos)
        else:
            return render_template("error.html")
    elif request.method == 'POST':
        form = request.form
        link = form['link']
        data = ydl.extract_info(link, download=False)
        title = data['title']
        thumbnail = data['thumbnail']
Exemple #49
0
async def download_video(v_url):
    """ Para o comando .rip, baixa mídia do YouTube e de muitos outros sites. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await v_url.edit("`Preparando para baixar...`")

    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
        video = False
        song = True

    elif type == "video":
        opts = {
            "format":
            "best",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegVideoConvertor",
                "preferedformat": "mp4"
            }],
            "outtmpl":
            "%(id)s.mp4",
            "logtostderr":
            False,
            "quiet":
            True,
        }
        song = False
        video = True

    try:
        await v_url.edit("`Buscando dados, por favor aguarde..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        return await v_url.edit(f"`{str(DE)}`")
    except ContentTooShortError:
        return await v_url.edit("`O conteúdo do download era muito curto.`")
    except GeoRestrictedError:
        return await v_url.edit(
            "`O vídeo não está disponível em sua localização geográfica "
            "devido a restrições geográficas impostas pelo site.`")
    except MaxDownloadsReached:
        return await v_url.edit("`O limite máximo de downloads foi atingido.`")
    except PostProcessingError:
        return await v_url.edit(
            "`Ocorreu um erro durante o pós-processamento.`")
    except UnavailableVideoError:
        return await v_url.edit(
            "`A mídia não está disponível no formato solicitado.`")
    except XAttrMetadataError as XAME:
        return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await v_url.edit(
            "`Ocorreu um erro durante a extração de informações.`")
    except Exception as e:
        return await v_url.edit(f"{str(type(e)): {str(e)}}")
    c_time = time.time()
    if song:
        await v_url.edit(
            f"`Preparando para fazer upload da música:`\n**{rip_data['title']}**"
        )
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(rip_data["duration"]),
                    title=str(rip_data["title"]),
                    performer=str(rip_data["uploader"]),
                )
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Enviando..",
                         f"{rip_data['title']}.mp3")),
        )
        os.remove(f"{rip_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await v_url.edit(
            f"`Preparando para enviar vídeo:`\n**{rip_data['title']}**")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data["title"],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Enviando..",
                         f"{rip_data['title']}.mp4")),
        )
        os.remove(f"{rip_data['id']}.mp4")
        await v_url.delete()
Exemple #50
0
async def download_video(v_url):

    lazy = v_url ; sender = await lazy.get_sender() ; me = await lazy.client.get_me()

    if not sender.id == me.id:
        rkp = await lazy.reply("`processing...`")
    else:
    	rkp = await lazy.edit("`processing...`")   
    url = v_url.pattern_match.group(1)
    if not url:
         return await rkp.edit("`Error \nusage song <song name>`")
    search = SearchVideos(url, offset = 1, mode = "json", max_results = 1)
    test = search.result()
    p = json.loads(test)
    q = p.get('search_result')
    try:
       url = q[0]['link']
    except:
    	return await rkp.edit("`failed to find`")
    type = "audio"
    await rkp.edit("`Preparing to download...`")
    if type == "audio":
        opts = {
            'format':
            'bestaudio',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'writethumbnail':
            True,
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '320',
            }],
            'outtmpl':
            '%(id)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True    
    try:
        await rkp.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await rkp.edit(f"`Preparing to upload song:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(rip_data['duration']),
                                       title=str(rip_data['title']),
                                       performer=str(rip_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp3")))
        os.remove(f"{rip_data['id']}.mp3")
    elif video:
        await rkp.edit(f"`Preparing to upload song :`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=url,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp4")))
        os.remove(f"{rip_data['id']}.mp4")
Exemple #51
0
from flask import Flask, jsonify
from flask_restful import Api, Resource, reqparse

from youtube_dl import YoutubeDL

logger = logging.getLogger(__name__)
logging.basicConfig(
    format="[%(asctime)s] (%(name)s) %(levelname)s: %(message)s")

app = Flask(__name__)
api = Api(app)

app.debug = True

ydl = YoutubeDL(params={
    'logger': app.logger,
    'extract_flat': 'in_playlist',
})

parser = reqparse.RequestParser()
parser.add_argument('url', action='append', required=True)


class VideoInfo(Resource):
    def post(self):  #pylint: disable=R0201
        args = parser.parse_args()
        infos = [ydl.extract_info(url, download=False) for url in args['url']]
        playlists, videos = [], []
        for info in infos:
            # TODO: hunt for more _types
            info.pop('http_headers', None)
            if info.get('_type', '') == 'playlist':
from youtube_dl import YoutubeDL

# Sample 1: Download a single youtube video
dl = YoutubeDL()
dl.download([
    'https://www.youtube.com/watch?v=WHK5p7JL7g4'
])  # Remember to put your video in a list, eventhough one video is downloaded

# Sample 2: Download multiple youtube videos
dl = YoutubeDL()
# Put list of song urls in download function to download them, one by one
dl.download([
    'https://www.youtube.com/watch?v=wNVIn-QS4DE',
    'https://www.youtube.com/watch?v=JZjRrg2rpic'
])

# Sample 3: Download audio
options = {
    'format':
    'bestaudio/audio'  # Tell the downloader to download only the best quality of audio
}
dl = YoutubeDL(options)
dl.download(['https://www.youtube.com/watch?v=c3jHlYsnEe0'])

# Sample 4: Search and then download the first video
options = {
    'default_search':
    'ytsearch',  # tell downloader to search instead of directly downloading
    'max_downloads':
    1  # Tell downloader to download only the first entry (video)
}
Exemple #53
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})
Exemple #54
0
    'format': 'bestaudio/best',
    'outtmpl': 'downloads/%(extractor)s-%(id)s-%(title)s.%(ext)s',
    'restrictfilenames': True,
    'noplaylist': True,
    'nocheckcertificate': True,
    'ignoreerrors': False,
    'logtostderr': False,
    'quiet': True,
    'no_warnings': True,
    'default_search': 'auto',
    'source_address': '0.0.0.0'  # ipv6 addresses cause issues sometimes
}

ffmpegopts = {'before_options': '-nostdin', 'options': '-vn'}

ytdl = YoutubeDL(ytdlopts)


class VoiceConnectionError(commands.CommandError):
    """Custom Exception class for connection errors."""


class InvalidVoiceChannel(VoiceConnectionError):
    """Exception for cases of invalid Voice Channels."""


class YTDLSource(discord.PCMVolumeTransformer):
    def __init__(self, source, *, data, requester):
        super().__init__(source)
        self.requester = requester
async def vid(client, message):
    input_str = get_text(message)
    pablo = await edit_or_reply(message, f"`Processing...`")
    if not input_str:
        await pablo.edit(
            "Invalid Command Syntax, Please Check Help Menu To Know More!")
        return
    await pablo.edit(
        f"`Getting {input_str} From Youtube Servers. Please Wait.`")
    search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1)
    rt = search.result()
    result_s = rt["search_result"]
    url = result_s[0]["link"]
    vid_title = result_s[0]["title"]
    yt_id = result_s[0]["id"]
    uploade_r = result_s[0]["channel"]
    thumb_url = f"https://img.youtube.com/vi/{yt_id}/hqdefault.jpg"
    await asyncio.sleep(0.6)
    downloaded_thumb = wget.download(thumb_url)
    opts = {
        "format":
        "best",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegVideoConvertor",
            "preferedformat": "mp4"
        }],
        "outtmpl":
        "%(id)s.mp4",
        "logtostderr":
        False,
        "quiet":
        True,
    }
    try:
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url, download=True)
    except Exception as e:
        await pablo.edit(event,
                         f"**Failed To Download** \n**Error :** `{str(e)}`")
        return
    c_time = time.time()
    file_stark = f"{ytdl_data['id']}.mp4"
    capy = f"**Video Name ➠** `{vid_title}` \n**Requested For ➠** `{input_str}` \n**Channel ➠** `{uploade_r}` \n**Link ➠** `{url}`"
    await client.send_video(
        message.chat.id,
        video=open(file_stark, "rb"),
        duration=int(ytdl_data["duration"]),
        file_name=str(ytdl_data["title"]),
        thumb=downloaded_thumb,
        caption=capy,
        supports_streaming=True,
        progress=progress,
        progress_args=(
            pablo,
            c_time,
            f"`Uploading {input_str} Song From YouTube Music!`",
            file_stark,
        ),
    )
    await pablo.delete()
    for files in (downloaded_thumb, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
Exemple #56
0
import sys
from youtube_dl import YoutubeDL

if __name__ == '__main__':
    if len(sys.argv) > 1:
        ydl_opts = {}
        ydl = YoutubeDL(ydl_opts)
        ydl.download(sys.argv[1:])
    else:
        print("Enter list of urls to download")
        exit(0)
Exemple #57
0
async def download_video(v_url):
    """ For .ytdl command, download media from YouTube and many other sites. """
    url = v_url.pattern_match.group(2)
    if not url:
        rmsg = await v_url.get_reply_message()
        myString = rmsg.text
        url = re.search("(?P<url>https?://[^\s]+)", myString).group("url")
    if not url:
        await edit_or_reply(v_url,
                            " ما الذي من المفترض أن أجده ؟  أعط الرابـط")
        return
    ytype = v_url.pattern_match.group(1).lower()
    v_url = await edit_or_reply(v_url, "**إحضار البيانات ، يرجى الانتظار...**")
    reply_to_id = await reply_id(v_url)
    if ytype == "a":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
        video = False
        song = True
    elif ytype == "v":
        opts = {
            "format":
            "best",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegVideoConvertor",
                "preferedformat": "mp4"
            }],
            "outtmpl":
            "%(id)s.mp4",
            "logtostderr":
            False,
            "quiet":
            True,
        }
        song = False
        video = True
    try:
        await v_url.edit("**  إحضار البيانـات ، يرجى الانتـظار **")
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
    except DownloadError as DE:
        await v_url.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await v_url.edit(" محـتوى التنزيـل كان قصيرًا جدًا جـاري الارسـال")
        return
    except GeoRestrictedError:
        await v_url.edit(
            "** الفيديـو غير متـاح من موقـعك الجغرافـي بسبب القيود الجغرافية التي يفرضهـا موقع الويب**"
        )
        return
    except MaxDownloadsReached:
        await v_url.edit("** تم الوصـول إلى الحـد الأقـصى لعدد التـنزيـلات**")
        return
    except PostProcessingError:
        await v_url.edit("** حـدث خـطأ أثناء معالجـة ما بعد**")
        return
    except UnavailableVideoError:
        await v_url.edit("** الوسـائـط غير متوفـرة بالتنسـيق المطـلوب**")
        return
    except XAttrMetadataError as XAME:
        await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await v_url.edit("** حـدث خـطأ أثناء معالجـة ما بعد**")
        return
    except Exception as e:
        await v_url.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    catthumb = Path(f"{ytdl_data['id']}.jpg")
    if not os.path.exists(catthumb):
        catthumb = Path(f"{ytdl_data['id']}.webp")
    if not os.path.exists(catthumb):
        catthumb = None
    if song:
        await v_url.edit(f"** التحضـير لتحـميل الأغنـية**:`\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{ytdl_data['id']}.mp3",
            supports_streaming=True,
            thumb=catthumb,
            reply_to=reply_to_id,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(ytdl_data["duration"]),
                    title=str(ytdl_data["title"]),
                    performer=str(ytdl_data["uploader"]),
                )
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, " جــاري تحميـل ..",
                         f"{ytdl_data['title']}.mp3")),
        )
        os.remove(f"{ytdl_data['id']}.mp3")
    elif video:
        await v_url.edit(f"** التحـضير لتحميـل الفيـديو:**\
        \n**{ytdl_data['title']}**\
        \nby *{ytdl_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{ytdl_data['id']}.mp4",
            reply_to=reply_to_id,
            supports_streaming=True,
            caption=ytdl_data["title"],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, " ... جـاري تحميل ..",
                         f"{ytdl_data['title']}.mp4")),
        )
        os.remove(f"{ytdl_data['id']}.mp4")
    if catthumb:
        os.remove(catthumb)
    await v_url.delete()
Exemple #58
0
async def download_video(v_url):
    """ For .rip command, download media from YouTube and many other sites. """
    url = v_url.pattern_match.group(2)
    type = v_url.pattern_match.group(1).lower()

    await v_url.edit("`Preparing to download...`")

    if type == "audio":
        opts = {
            'format':
            'bestaudio',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'writethumbnail':
            True,
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '320',
            }],
            'outtmpl':
            '%(id)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True

    elif type == "video":
        opts = {
            'format':
            'best',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegVideoConvertor',
                'preferedformat': 'mp4'
            }],
            'outtmpl':
            '%(id)s.mp4',
            'logtostderr':
            False,
            'quiet':
            True
        }
        song = False
        video = True

    try:
        await v_url.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        return await v_url.edit(f"`{str(DE)}`")
    except ContentTooShortError:
        return await v_url.edit("`The download content was too short.`")
    except GeoRestrictedError:
        return await v_url.edit(
            "`Video is not available from your geographic location "
            "due to geographic restrictions imposed by a website.`")
    except MaxDownloadsReached:
        return await v_url.edit("`Max-downloads limit has been reached.`")
    except PostProcessingError:
        return await v_url.edit("`There was an error during post processing.`")
    except UnavailableVideoError:
        return await v_url.edit(
            "`Media is not available in the requested format.`")
    except XAttrMetadataError as XAME:
        return await v_url.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await v_url.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await v_url.edit(f"{str(type(e)): {str(e)}}")
    c_time = time.time()
    if song:
        await v_url.edit(
            f"`Preparing to upload song:`\n**{rip_data['title']}**")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(rip_data['duration']),
                                       title=str(rip_data['title']),
                                       performer=str(rip_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp3")))
        os.remove(f"{rip_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await v_url.edit(
            f"`Preparing to upload video:`\n**{rip_data['title']}**")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data['title'],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp4")))
        os.remove(f"{rip_data['id']}.mp4")
        await v_url.delete()
from youtube_dl import YoutubeDL
dl = YoutubeDL()
dl.download(['https://www.youtube.com/watch?v=WHK5p7JL7g4'])


dl = YoutubeDL()
dl.download(['https://www.youtube.com/watch?v=wNVIn-QS4DE', 'https://www.youtube.com/watch?v=JZjRrg2rpic'])


options = {
    'format': 'bestaudio/audio'
}
dl = YoutubeDL(options)
dl.download(['https://www.youtube.com/watch?v=c3jHlYsnEe0'])


options = {
    'default_search': 'ytsearch',
    'max_downloads': 1
}
dl = YoutubeDL(options)
dl.download(['con điên TAMKA PKL'])


options = {
    'default_search': 'ytsearch',
    'max_downloads': 1,
    'format': 'bestaudio/audio'
}
dl = YoutubeDL(options)
dl.download(['Nhớ mưa sài gòn lam trường'])
from youtube_dl import YoutubeDL
options = {'default_search': 'ytsearch', 'max_downloads': 1}
dl = YoutubeDL(options)
dl.download(['con điên TAMKA PKL'])