YoutubeDL.py 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import datetime
  6. import errno
  7. import io
  8. import json
  9. import locale
  10. import os
  11. import platform
  12. import re
  13. import shutil
  14. import subprocess
  15. import socket
  16. import sys
  17. import time
  18. import traceback
  19. if os.name == 'nt':
  20. import ctypes
  21. from .utils import (
  22. compat_cookiejar,
  23. compat_expanduser,
  24. compat_http_client,
  25. compat_str,
  26. compat_urllib_error,
  27. compat_urllib_request,
  28. escape_url,
  29. ContentTooShortError,
  30. date_from_str,
  31. DateRange,
  32. DEFAULT_OUTTMPL,
  33. determine_ext,
  34. DownloadError,
  35. encodeFilename,
  36. ExtractorError,
  37. format_bytes,
  38. formatSeconds,
  39. get_term_width,
  40. locked_file,
  41. make_HTTPS_handler,
  42. MaxDownloadsReached,
  43. PagedList,
  44. PostProcessingError,
  45. platform_name,
  46. preferredencoding,
  47. SameFileError,
  48. sanitize_filename,
  49. subtitles_filename,
  50. takewhile_inclusive,
  51. UnavailableVideoError,
  52. url_basename,
  53. write_json_file,
  54. write_string,
  55. YoutubeDLHandler,
  56. prepend_extension,
  57. )
  58. from .cache import Cache
  59. from .extractor import get_info_extractor, gen_extractors
  60. from .downloader import get_suitable_downloader
  61. from .downloader.rtmp import rtmpdump_version
  62. from .postprocessor import FFmpegMergerPP, FFmpegPostProcessor
  63. from .version import __version__
  64. class YoutubeDL(object):
  65. """YoutubeDL class.
  66. YoutubeDL objects are the ones responsible of downloading the
  67. actual video file and writing it to disk if the user has requested
  68. it, among some other tasks. In most cases there should be one per
  69. program. As, given a video URL, the downloader doesn't know how to
  70. extract all the needed information, task that InfoExtractors do, it
  71. has to pass the URL to one of them.
  72. For this, YoutubeDL objects have a method that allows
  73. InfoExtractors to be registered in a given order. When it is passed
  74. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  75. finds that reports being able to handle it. The InfoExtractor extracts
  76. all the information about the video or videos the URL refers to, and
  77. YoutubeDL process the extracted information, possibly using a File
  78. Downloader to download the video.
  79. YoutubeDL objects accept a lot of parameters. In order not to saturate
  80. the object constructor with arguments, it receives a dictionary of
  81. options instead. These options are available through the params
  82. attribute for the InfoExtractors to use. The YoutubeDL also
  83. registers itself as the downloader in charge for the InfoExtractors
  84. that are added to it, so this is a "mutual registration".
  85. Available options:
  86. username: Username for authentication purposes.
  87. password: Password for authentication purposes.
  88. videopassword: Password for acces a video.
  89. usenetrc: Use netrc for authentication instead.
  90. verbose: Print additional info to stdout.
  91. quiet: Do not print messages to stdout.
  92. no_warnings: Do not print out anything for warnings.
  93. forceurl: Force printing final URL.
  94. forcetitle: Force printing title.
  95. forceid: Force printing ID.
  96. forcethumbnail: Force printing thumbnail URL.
  97. forcedescription: Force printing description.
  98. forcefilename: Force printing final filename.
  99. forceduration: Force printing duration.
  100. forcejson: Force printing info_dict as JSON.
  101. dump_single_json: Force printing the info_dict of the whole playlist
  102. (or video) as a single JSON line.
  103. simulate: Do not download the video files.
  104. format: Video format code.
  105. format_limit: Highest quality format to try.
  106. outtmpl: Template for output names.
  107. restrictfilenames: Do not allow "&" and spaces in file names
  108. ignoreerrors: Do not stop on download errors.
  109. nooverwrites: Prevent overwriting files.
  110. playliststart: Playlist item to start at.
  111. playlistend: Playlist item to end at.
  112. matchtitle: Download only matching titles.
  113. rejecttitle: Reject downloads for matching titles.
  114. logger: Log messages to a logging.Logger instance.
  115. logtostderr: Log messages to stderr instead of stdout.
  116. writedescription: Write the video description to a .description file
  117. writeinfojson: Write the video description to a .info.json file
  118. writeannotations: Write the video annotations to a .annotations.xml file
  119. writethumbnail: Write the thumbnail image to a file
  120. writesubtitles: Write the video subtitles to a file
  121. writeautomaticsub: Write the automatic subtitles to a file
  122. allsubtitles: Downloads all the subtitles of the video
  123. (requires writesubtitles or writeautomaticsub)
  124. listsubtitles: Lists all available subtitles for the video
  125. subtitlesformat: Subtitle format [srt/sbv/vtt] (default=srt)
  126. subtitleslangs: List of languages of the subtitles to download
  127. keepvideo: Keep the video file after post-processing
  128. daterange: A DateRange object, download only if the upload_date is in the range.
  129. skip_download: Skip the actual download of the video file
  130. cachedir: Location of the cache files in the filesystem.
  131. False to disable filesystem cache.
  132. noplaylist: Download single video instead of a playlist if in doubt.
  133. age_limit: An integer representing the user's age in years.
  134. Unsuitable videos for the given age are skipped.
  135. min_views: An integer representing the minimum view count the video
  136. must have in order to not be skipped.
  137. Videos without view count information are always
  138. downloaded. None for no limit.
  139. max_views: An integer representing the maximum view count.
  140. Videos that are more popular than that are not
  141. downloaded.
  142. Videos without view count information are always
  143. downloaded. None for no limit.
  144. download_archive: File name of a file where all downloads are recorded.
  145. Videos already present in the file are not downloaded
  146. again.
  147. cookiefile: File name where cookies should be read from and dumped to.
  148. nocheckcertificate:Do not verify SSL certificates
  149. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  150. At the moment, this is only supported by YouTube.
  151. proxy: URL of the proxy server to use
  152. socket_timeout: Time to wait for unresponsive hosts, in seconds
  153. bidi_workaround: Work around buggy terminals without bidirectional text
  154. support, using fridibi
  155. debug_printtraffic:Print out sent and received HTTP traffic
  156. include_ads: Download ads as well
  157. default_search: Prepend this string if an input url is not valid.
  158. 'auto' for elaborate guessing
  159. encoding: Use this encoding instead of the system-specified.
  160. extract_flat: Do not resolve URLs, return the immediate result.
  161. Pass in 'in_playlist' to only show this behavior for
  162. playlist items.
  163. The following parameters are not used by YoutubeDL itself, they are used by
  164. the FileDownloader:
  165. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  166. noresizebuffer, retries, continuedl, noprogress, consoletitle
  167. The following options are used by the post processors:
  168. prefer_ffmpeg: If True, use ffmpeg instead of avconv if both are available,
  169. otherwise prefer avconv.
  170. exec_cmd: Arbitrary command to run after downloading
  171. """
  172. params = None
  173. _ies = []
  174. _pps = []
  175. _download_retcode = None
  176. _num_downloads = None
  177. _screen_file = None
  178. def __init__(self, params=None, auto_init=True):
  179. """Create a FileDownloader object with the given options."""
  180. if params is None:
  181. params = {}
  182. self._ies = []
  183. self._ies_instances = {}
  184. self._pps = []
  185. self._progress_hooks = []
  186. self._download_retcode = 0
  187. self._num_downloads = 0
  188. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  189. self._err_file = sys.stderr
  190. self.params = params
  191. self.cache = Cache(self)
  192. if params.get('bidi_workaround', False):
  193. try:
  194. import pty
  195. master, slave = pty.openpty()
  196. width = get_term_width()
  197. if width is None:
  198. width_args = []
  199. else:
  200. width_args = ['-w', str(width)]
  201. sp_kwargs = dict(
  202. stdin=subprocess.PIPE,
  203. stdout=slave,
  204. stderr=self._err_file)
  205. try:
  206. self._output_process = subprocess.Popen(
  207. ['bidiv'] + width_args, **sp_kwargs
  208. )
  209. except OSError:
  210. self._output_process = subprocess.Popen(
  211. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  212. self._output_channel = os.fdopen(master, 'rb')
  213. except OSError as ose:
  214. if ose.errno == 2:
  215. self.report_warning('Could not find fribidi executable, ignoring --bidi-workaround . Make sure that fribidi is an executable file in one of the directories in your $PATH.')
  216. else:
  217. raise
  218. if (sys.version_info >= (3,) and sys.platform != 'win32' and
  219. sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  220. and not params.get('restrictfilenames', False)):
  221. # On Python 3, the Unicode filesystem API will throw errors (#1474)
  222. self.report_warning(
  223. 'Assuming --restrict-filenames since file system encoding '
  224. 'cannot encode all characters. '
  225. 'Set the LC_ALL environment variable to fix this.')
  226. self.params['restrictfilenames'] = True
  227. if '%(stitle)s' in self.params.get('outtmpl', ''):
  228. self.report_warning('%(stitle)s is deprecated. Use the %(title)s and the --restrict-filenames flag(which also secures %(uploader)s et al) instead.')
  229. self._setup_opener()
  230. if auto_init:
  231. self.print_debug_header()
  232. self.add_default_info_extractors()
  233. def add_info_extractor(self, ie):
  234. """Add an InfoExtractor object to the end of the list."""
  235. self._ies.append(ie)
  236. self._ies_instances[ie.ie_key()] = ie
  237. ie.set_downloader(self)
  238. def get_info_extractor(self, ie_key):
  239. """
  240. Get an instance of an IE with name ie_key, it will try to get one from
  241. the _ies list, if there's no instance it will create a new one and add
  242. it to the extractor list.
  243. """
  244. ie = self._ies_instances.get(ie_key)
  245. if ie is None:
  246. ie = get_info_extractor(ie_key)()
  247. self.add_info_extractor(ie)
  248. return ie
  249. def add_default_info_extractors(self):
  250. """
  251. Add the InfoExtractors returned by gen_extractors to the end of the list
  252. """
  253. for ie in gen_extractors():
  254. self.add_info_extractor(ie)
  255. def add_post_processor(self, pp):
  256. """Add a PostProcessor object to the end of the chain."""
  257. self._pps.append(pp)
  258. pp.set_downloader(self)
  259. def add_progress_hook(self, ph):
  260. """Add the progress hook (currently only for the file downloader)"""
  261. self._progress_hooks.append(ph)
  262. def _bidi_workaround(self, message):
  263. if not hasattr(self, '_output_channel'):
  264. return message
  265. assert hasattr(self, '_output_process')
  266. assert isinstance(message, compat_str)
  267. line_count = message.count('\n') + 1
  268. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  269. self._output_process.stdin.flush()
  270. res = ''.join(self._output_channel.readline().decode('utf-8')
  271. for _ in range(line_count))
  272. return res[:-len('\n')]
  273. def to_screen(self, message, skip_eol=False):
  274. """Print message to stdout if not in quiet mode."""
  275. return self.to_stdout(message, skip_eol, check_quiet=True)
  276. def _write_string(self, s, out=None):
  277. write_string(s, out=out, encoding=self.params.get('encoding'))
  278. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  279. """Print message to stdout if not in quiet mode."""
  280. if self.params.get('logger'):
  281. self.params['logger'].debug(message)
  282. elif not check_quiet or not self.params.get('quiet', False):
  283. message = self._bidi_workaround(message)
  284. terminator = ['\n', ''][skip_eol]
  285. output = message + terminator
  286. self._write_string(output, self._screen_file)
  287. def to_stderr(self, message):
  288. """Print message to stderr."""
  289. assert isinstance(message, compat_str)
  290. if self.params.get('logger'):
  291. self.params['logger'].error(message)
  292. else:
  293. message = self._bidi_workaround(message)
  294. output = message + '\n'
  295. self._write_string(output, self._err_file)
  296. def to_console_title(self, message):
  297. if not self.params.get('consoletitle', False):
  298. return
  299. if os.name == 'nt' and ctypes.windll.kernel32.GetConsoleWindow():
  300. # c_wchar_p() might not be necessary if `message` is
  301. # already of type unicode()
  302. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  303. elif 'TERM' in os.environ:
  304. self._write_string('\033]0;%s\007' % message, self._screen_file)
  305. def save_console_title(self):
  306. if not self.params.get('consoletitle', False):
  307. return
  308. if 'TERM' in os.environ:
  309. # Save the title on stack
  310. self._write_string('\033[22;0t', self._screen_file)
  311. def restore_console_title(self):
  312. if not self.params.get('consoletitle', False):
  313. return
  314. if 'TERM' in os.environ:
  315. # Restore the title from stack
  316. self._write_string('\033[23;0t', self._screen_file)
  317. def __enter__(self):
  318. self.save_console_title()
  319. return self
  320. def __exit__(self, *args):
  321. self.restore_console_title()
  322. if self.params.get('cookiefile') is not None:
  323. self.cookiejar.save()
  324. def trouble(self, message=None, tb=None):
  325. """Determine action to take when a download problem appears.
  326. Depending on if the downloader has been configured to ignore
  327. download errors or not, this method may throw an exception or
  328. not when errors are found, after printing the message.
  329. tb, if given, is additional traceback information.
  330. """
  331. if message is not None:
  332. self.to_stderr(message)
  333. if self.params.get('verbose'):
  334. if tb is None:
  335. if sys.exc_info()[0]: # if .trouble has been called from an except block
  336. tb = ''
  337. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  338. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  339. tb += compat_str(traceback.format_exc())
  340. else:
  341. tb_data = traceback.format_list(traceback.extract_stack())
  342. tb = ''.join(tb_data)
  343. self.to_stderr(tb)
  344. if not self.params.get('ignoreerrors', False):
  345. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  346. exc_info = sys.exc_info()[1].exc_info
  347. else:
  348. exc_info = sys.exc_info()
  349. raise DownloadError(message, exc_info)
  350. self._download_retcode = 1
  351. def report_warning(self, message):
  352. '''
  353. Print the message to stderr, it will be prefixed with 'WARNING:'
  354. If stderr is a tty file the 'WARNING:' will be colored
  355. '''
  356. if self.params.get('logger') is not None:
  357. self.params['logger'].warning(message)
  358. else:
  359. if self.params.get('no_warnings'):
  360. return
  361. if self._err_file.isatty() and os.name != 'nt':
  362. _msg_header = '\033[0;33mWARNING:\033[0m'
  363. else:
  364. _msg_header = 'WARNING:'
  365. warning_message = '%s %s' % (_msg_header, message)
  366. self.to_stderr(warning_message)
  367. def report_error(self, message, tb=None):
  368. '''
  369. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  370. in red if stderr is a tty file.
  371. '''
  372. if self._err_file.isatty() and os.name != 'nt':
  373. _msg_header = '\033[0;31mERROR:\033[0m'
  374. else:
  375. _msg_header = 'ERROR:'
  376. error_message = '%s %s' % (_msg_header, message)
  377. self.trouble(error_message, tb)
  378. def report_file_already_downloaded(self, file_name):
  379. """Report file has already been fully downloaded."""
  380. try:
  381. self.to_screen('[download] %s has already been downloaded' % file_name)
  382. except UnicodeEncodeError:
  383. self.to_screen('[download] The file has already been downloaded')
  384. def prepare_filename(self, info_dict):
  385. """Generate the output filename."""
  386. try:
  387. template_dict = dict(info_dict)
  388. template_dict['epoch'] = int(time.time())
  389. autonumber_size = self.params.get('autonumber_size')
  390. if autonumber_size is None:
  391. autonumber_size = 5
  392. autonumber_templ = '%0' + str(autonumber_size) + 'd'
  393. template_dict['autonumber'] = autonumber_templ % self._num_downloads
  394. if template_dict.get('playlist_index') is not None:
  395. template_dict['playlist_index'] = '%0*d' % (len(str(template_dict['n_entries'])), template_dict['playlist_index'])
  396. if template_dict.get('resolution') is None:
  397. if template_dict.get('width') and template_dict.get('height'):
  398. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  399. elif template_dict.get('height'):
  400. template_dict['resolution'] = '%sp' % template_dict['height']
  401. elif template_dict.get('width'):
  402. template_dict['resolution'] = '?x%d' % template_dict['width']
  403. sanitize = lambda k, v: sanitize_filename(
  404. compat_str(v),
  405. restricted=self.params.get('restrictfilenames'),
  406. is_id=(k == 'id'))
  407. template_dict = dict((k, sanitize(k, v))
  408. for k, v in template_dict.items()
  409. if v is not None)
  410. template_dict = collections.defaultdict(lambda: 'NA', template_dict)
  411. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  412. tmpl = compat_expanduser(outtmpl)
  413. filename = tmpl % template_dict
  414. return filename
  415. except ValueError as err:
  416. self.report_error('Error in output template: ' + str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  417. return None
  418. def _match_entry(self, info_dict):
  419. """ Returns None iff the file should be downloaded """
  420. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  421. if 'title' in info_dict:
  422. # This can happen when we're just evaluating the playlist
  423. title = info_dict['title']
  424. matchtitle = self.params.get('matchtitle', False)
  425. if matchtitle:
  426. if not re.search(matchtitle, title, re.IGNORECASE):
  427. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  428. rejecttitle = self.params.get('rejecttitle', False)
  429. if rejecttitle:
  430. if re.search(rejecttitle, title, re.IGNORECASE):
  431. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  432. date = info_dict.get('upload_date', None)
  433. if date is not None:
  434. dateRange = self.params.get('daterange', DateRange())
  435. if date not in dateRange:
  436. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  437. view_count = info_dict.get('view_count', None)
  438. if view_count is not None:
  439. min_views = self.params.get('min_views')
  440. if min_views is not None and view_count < min_views:
  441. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  442. max_views = self.params.get('max_views')
  443. if max_views is not None and view_count > max_views:
  444. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  445. age_limit = self.params.get('age_limit')
  446. if age_limit is not None:
  447. actual_age_limit = info_dict.get('age_limit')
  448. if actual_age_limit is None:
  449. actual_age_limit = 0
  450. if age_limit < actual_age_limit:
  451. return 'Skipping "' + title + '" because it is age restricted'
  452. if self.in_download_archive(info_dict):
  453. return '%s has already been recorded in archive' % video_title
  454. return None
  455. @staticmethod
  456. def add_extra_info(info_dict, extra_info):
  457. '''Set the keys from extra_info in info dict if they are missing'''
  458. for key, value in extra_info.items():
  459. info_dict.setdefault(key, value)
  460. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  461. process=True):
  462. '''
  463. Returns a list with a dictionary for each video we find.
  464. If 'download', also downloads the videos.
  465. extra_info is a dict containing the extra values to add to each result
  466. '''
  467. if ie_key:
  468. ies = [self.get_info_extractor(ie_key)]
  469. else:
  470. ies = self._ies
  471. for ie in ies:
  472. if not ie.suitable(url):
  473. continue
  474. if not ie.working():
  475. self.report_warning('The program functionality for this site has been marked as broken, '
  476. 'and will probably not work.')
  477. try:
  478. ie_result = ie.extract(url)
  479. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  480. break
  481. if isinstance(ie_result, list):
  482. # Backwards compatibility: old IE result format
  483. ie_result = {
  484. '_type': 'compat_list',
  485. 'entries': ie_result,
  486. }
  487. self.add_default_extra_info(ie_result, ie, url)
  488. if process:
  489. return self.process_ie_result(ie_result, download, extra_info)
  490. else:
  491. return ie_result
  492. except ExtractorError as de: # An error we somewhat expected
  493. self.report_error(compat_str(de), de.format_traceback())
  494. break
  495. except MaxDownloadsReached:
  496. raise
  497. except Exception as e:
  498. if self.params.get('ignoreerrors', False):
  499. self.report_error(compat_str(e), tb=compat_str(traceback.format_exc()))
  500. break
  501. else:
  502. raise
  503. else:
  504. self.report_error('no suitable InfoExtractor for URL %s' % url)
  505. def add_default_extra_info(self, ie_result, ie, url):
  506. self.add_extra_info(ie_result, {
  507. 'extractor': ie.IE_NAME,
  508. 'webpage_url': url,
  509. 'webpage_url_basename': url_basename(url),
  510. 'extractor_key': ie.ie_key(),
  511. })
  512. def process_ie_result(self, ie_result, download=True, extra_info={}):
  513. """
  514. Take the result of the ie(may be modified) and resolve all unresolved
  515. references (URLs, playlist items).
  516. It will also download the videos if 'download'.
  517. Returns the resolved ie_result.
  518. """
  519. result_type = ie_result.get('_type', 'video')
  520. if result_type in ('url', 'url_transparent'):
  521. extract_flat = self.params.get('extract_flat', False)
  522. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info) or
  523. extract_flat is True):
  524. if self.params.get('forcejson', False):
  525. self.to_stdout(json.dumps(ie_result))
  526. return ie_result
  527. if result_type == 'video':
  528. self.add_extra_info(ie_result, extra_info)
  529. return self.process_video_result(ie_result, download=download)
  530. elif result_type == 'url':
  531. # We have to add extra_info to the results because it may be
  532. # contained in a playlist
  533. return self.extract_info(ie_result['url'],
  534. download,
  535. ie_key=ie_result.get('ie_key'),
  536. extra_info=extra_info)
  537. elif result_type == 'url_transparent':
  538. # Use the information from the embedding page
  539. info = self.extract_info(
  540. ie_result['url'], ie_key=ie_result.get('ie_key'),
  541. extra_info=extra_info, download=False, process=False)
  542. def make_result(embedded_info):
  543. new_result = ie_result.copy()
  544. for f in ('_type', 'url', 'ext', 'player_url', 'formats',
  545. 'entries', 'ie_key', 'duration',
  546. 'subtitles', 'annotations', 'format',
  547. 'thumbnail', 'thumbnails'):
  548. if f in new_result:
  549. del new_result[f]
  550. if f in embedded_info:
  551. new_result[f] = embedded_info[f]
  552. return new_result
  553. new_result = make_result(info)
  554. assert new_result.get('_type') != 'url_transparent'
  555. if new_result.get('_type') == 'compat_list':
  556. new_result['entries'] = [
  557. make_result(e) for e in new_result['entries']]
  558. return self.process_ie_result(
  559. new_result, download=download, extra_info=extra_info)
  560. elif result_type == 'playlist':
  561. # We process each entry in the playlist
  562. playlist = ie_result.get('title', None) or ie_result.get('id', None)
  563. self.to_screen('[download] Downloading playlist: %s' % playlist)
  564. playlist_results = []
  565. playliststart = self.params.get('playliststart', 1) - 1
  566. playlistend = self.params.get('playlistend', None)
  567. # For backwards compatibility, interpret -1 as whole list
  568. if playlistend == -1:
  569. playlistend = None
  570. if isinstance(ie_result['entries'], list):
  571. n_all_entries = len(ie_result['entries'])
  572. entries = ie_result['entries'][playliststart:playlistend]
  573. n_entries = len(entries)
  574. self.to_screen(
  575. "[%s] playlist %s: Collected %d video ids (downloading %d of them)" %
  576. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  577. else:
  578. assert isinstance(ie_result['entries'], PagedList)
  579. entries = ie_result['entries'].getslice(
  580. playliststart, playlistend)
  581. n_entries = len(entries)
  582. self.to_screen(
  583. "[%s] playlist %s: Downloading %d videos" %
  584. (ie_result['extractor'], playlist, n_entries))
  585. for i, entry in enumerate(entries, 1):
  586. self.to_screen('[download] Downloading video #%s of %s' % (i, n_entries))
  587. extra = {
  588. 'n_entries': n_entries,
  589. 'playlist': playlist,
  590. 'playlist_index': i + playliststart,
  591. 'extractor': ie_result['extractor'],
  592. 'webpage_url': ie_result['webpage_url'],
  593. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  594. 'extractor_key': ie_result['extractor_key'],
  595. }
  596. reason = self._match_entry(entry)
  597. if reason is not None:
  598. self.to_screen('[download] ' + reason)
  599. continue
  600. entry_result = self.process_ie_result(entry,
  601. download=download,
  602. extra_info=extra)
  603. playlist_results.append(entry_result)
  604. ie_result['entries'] = playlist_results
  605. return ie_result
  606. elif result_type == 'compat_list':
  607. def _fixup(r):
  608. self.add_extra_info(r,
  609. {
  610. 'extractor': ie_result['extractor'],
  611. 'webpage_url': ie_result['webpage_url'],
  612. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  613. 'extractor_key': ie_result['extractor_key'],
  614. })
  615. return r
  616. ie_result['entries'] = [
  617. self.process_ie_result(_fixup(r), download, extra_info)
  618. for r in ie_result['entries']
  619. ]
  620. return ie_result
  621. else:
  622. raise Exception('Invalid result type: %s' % result_type)
  623. def select_format(self, format_spec, available_formats):
  624. if format_spec == 'best' or format_spec is None:
  625. return available_formats[-1]
  626. elif format_spec == 'worst':
  627. return available_formats[0]
  628. elif format_spec == 'bestaudio':
  629. audio_formats = [
  630. f for f in available_formats
  631. if f.get('vcodec') == 'none']
  632. if audio_formats:
  633. return audio_formats[-1]
  634. elif format_spec == 'worstaudio':
  635. audio_formats = [
  636. f for f in available_formats
  637. if f.get('vcodec') == 'none']
  638. if audio_formats:
  639. return audio_formats[0]
  640. elif format_spec == 'bestvideo':
  641. video_formats = [
  642. f for f in available_formats
  643. if f.get('acodec') == 'none']
  644. if video_formats:
  645. return video_formats[-1]
  646. elif format_spec == 'worstvideo':
  647. video_formats = [
  648. f for f in available_formats
  649. if f.get('acodec') == 'none']
  650. if video_formats:
  651. return video_formats[0]
  652. else:
  653. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a']
  654. if format_spec in extensions:
  655. filter_f = lambda f: f['ext'] == format_spec
  656. else:
  657. filter_f = lambda f: f['format_id'] == format_spec
  658. matches = list(filter(filter_f, available_formats))
  659. if matches:
  660. return matches[-1]
  661. return None
  662. def process_video_result(self, info_dict, download=True):
  663. assert info_dict.get('_type', 'video') == 'video'
  664. if 'id' not in info_dict:
  665. raise ExtractorError('Missing "id" field in extractor result')
  666. if 'title' not in info_dict:
  667. raise ExtractorError('Missing "title" field in extractor result')
  668. if 'playlist' not in info_dict:
  669. # It isn't part of a playlist
  670. info_dict['playlist'] = None
  671. info_dict['playlist_index'] = None
  672. thumbnails = info_dict.get('thumbnails')
  673. if thumbnails:
  674. thumbnails.sort(key=lambda t: (
  675. t.get('width'), t.get('height'), t.get('url')))
  676. for t in thumbnails:
  677. if 'width' in t and 'height' in t:
  678. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  679. if thumbnails and 'thumbnail' not in info_dict:
  680. info_dict['thumbnail'] = thumbnails[-1]['url']
  681. if 'display_id' not in info_dict and 'id' in info_dict:
  682. info_dict['display_id'] = info_dict['id']
  683. if info_dict.get('upload_date') is None and info_dict.get('timestamp') is not None:
  684. upload_date = datetime.datetime.utcfromtimestamp(
  685. info_dict['timestamp'])
  686. info_dict['upload_date'] = upload_date.strftime('%Y%m%d')
  687. # This extractors handle format selection themselves
  688. if info_dict['extractor'] in ['Youku']:
  689. if download:
  690. self.process_info(info_dict)
  691. return info_dict
  692. # We now pick which formats have to be downloaded
  693. if info_dict.get('formats') is None:
  694. # There's only one format available
  695. formats = [info_dict]
  696. else:
  697. formats = info_dict['formats']
  698. if not formats:
  699. raise ExtractorError('No video formats found!')
  700. # We check that all the formats have the format and format_id fields
  701. for i, format in enumerate(formats):
  702. if 'url' not in format:
  703. raise ExtractorError('Missing "url" key in result (index %d)' % i)
  704. if format.get('format_id') is None:
  705. format['format_id'] = compat_str(i)
  706. if format.get('format') is None:
  707. format['format'] = '{id} - {res}{note}'.format(
  708. id=format['format_id'],
  709. res=self.format_resolution(format),
  710. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  711. )
  712. # Automatically determine file extension if missing
  713. if 'ext' not in format:
  714. format['ext'] = determine_ext(format['url']).lower()
  715. format_limit = self.params.get('format_limit', None)
  716. if format_limit:
  717. formats = list(takewhile_inclusive(
  718. lambda f: f['format_id'] != format_limit, formats
  719. ))
  720. # TODO Central sorting goes here
  721. if formats[0] is not info_dict:
  722. # only set the 'formats' fields if the original info_dict list them
  723. # otherwise we end up with a circular reference, the first (and unique)
  724. # element in the 'formats' field in info_dict is info_dict itself,
  725. # wich can't be exported to json
  726. info_dict['formats'] = formats
  727. if self.params.get('listformats', None):
  728. self.list_formats(info_dict)
  729. return
  730. req_format = self.params.get('format')
  731. if req_format is None:
  732. req_format = 'best'
  733. formats_to_download = []
  734. # The -1 is for supporting YoutubeIE
  735. if req_format in ('-1', 'all'):
  736. formats_to_download = formats
  737. else:
  738. for rfstr in req_format.split(','):
  739. # We can accept formats requested in the format: 34/5/best, we pick
  740. # the first that is available, starting from left
  741. req_formats = rfstr.split('/')
  742. for rf in req_formats:
  743. if re.match(r'.+?\+.+?', rf) is not None:
  744. # Two formats have been requested like '137+139'
  745. format_1, format_2 = rf.split('+')
  746. formats_info = (self.select_format(format_1, formats),
  747. self.select_format(format_2, formats))
  748. if all(formats_info):
  749. selected_format = {
  750. 'requested_formats': formats_info,
  751. 'format': rf,
  752. 'ext': formats_info[0]['ext'],
  753. }
  754. else:
  755. selected_format = None
  756. else:
  757. selected_format = self.select_format(rf, formats)
  758. if selected_format is not None:
  759. formats_to_download.append(selected_format)
  760. break
  761. if not formats_to_download:
  762. raise ExtractorError('requested format not available',
  763. expected=True)
  764. if download:
  765. if len(formats_to_download) > 1:
  766. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  767. for format in formats_to_download:
  768. new_info = dict(info_dict)
  769. new_info.update(format)
  770. self.process_info(new_info)
  771. # We update the info dict with the best quality format (backwards compatibility)
  772. info_dict.update(formats_to_download[-1])
  773. return info_dict
  774. def process_info(self, info_dict):
  775. """Process a single resolved IE result."""
  776. assert info_dict.get('_type', 'video') == 'video'
  777. max_downloads = self.params.get('max_downloads')
  778. if max_downloads is not None:
  779. if self._num_downloads >= int(max_downloads):
  780. raise MaxDownloadsReached()
  781. info_dict['fulltitle'] = info_dict['title']
  782. if len(info_dict['title']) > 200:
  783. info_dict['title'] = info_dict['title'][:197] + '...'
  784. # Keep for backwards compatibility
  785. info_dict['stitle'] = info_dict['title']
  786. if 'format' not in info_dict:
  787. info_dict['format'] = info_dict['ext']
  788. reason = self._match_entry(info_dict)
  789. if reason is not None:
  790. self.to_screen('[download] ' + reason)
  791. return
  792. self._num_downloads += 1
  793. filename = self.prepare_filename(info_dict)
  794. # Forced printings
  795. if self.params.get('forcetitle', False):
  796. self.to_stdout(info_dict['fulltitle'])
  797. if self.params.get('forceid', False):
  798. self.to_stdout(info_dict['id'])
  799. if self.params.get('forceurl', False):
  800. # For RTMP URLs, also include the playpath
  801. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  802. if self.params.get('forcethumbnail', False) and info_dict.get('thumbnail') is not None:
  803. self.to_stdout(info_dict['thumbnail'])
  804. if self.params.get('forcedescription', False) and info_dict.get('description') is not None:
  805. self.to_stdout(info_dict['description'])
  806. if self.params.get('forcefilename', False) and filename is not None:
  807. self.to_stdout(filename)
  808. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  809. self.to_stdout(formatSeconds(info_dict['duration']))
  810. if self.params.get('forceformat', False):
  811. self.to_stdout(info_dict['format'])
  812. if self.params.get('forcejson', False):
  813. info_dict['_filename'] = filename
  814. self.to_stdout(json.dumps(info_dict))
  815. if self.params.get('dump_single_json', False):
  816. info_dict['_filename'] = filename
  817. # Do nothing else if in simulate mode
  818. if self.params.get('simulate', False):
  819. return
  820. if filename is None:
  821. return
  822. try:
  823. dn = os.path.dirname(encodeFilename(filename))
  824. if dn and not os.path.exists(dn):
  825. os.makedirs(dn)
  826. except (OSError, IOError) as err:
  827. self.report_error('unable to create directory ' + compat_str(err))
  828. return
  829. if self.params.get('writedescription', False):
  830. descfn = filename + '.description'
  831. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  832. self.to_screen('[info] Video description is already present')
  833. else:
  834. try:
  835. self.to_screen('[info] Writing video description to: ' + descfn)
  836. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  837. descfile.write(info_dict['description'])
  838. except (KeyError, TypeError):
  839. self.report_warning('There\'s no description to write.')
  840. except (OSError, IOError):
  841. self.report_error('Cannot write description file ' + descfn)
  842. return
  843. if self.params.get('writeannotations', False):
  844. annofn = filename + '.annotations.xml'
  845. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  846. self.to_screen('[info] Video annotations are already present')
  847. else:
  848. try:
  849. self.to_screen('[info] Writing video annotations to: ' + annofn)
  850. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  851. annofile.write(info_dict['annotations'])
  852. except (KeyError, TypeError):
  853. self.report_warning('There are no annotations to write.')
  854. except (OSError, IOError):
  855. self.report_error('Cannot write annotations file: ' + annofn)
  856. return
  857. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  858. self.params.get('writeautomaticsub')])
  859. if subtitles_are_requested and 'subtitles' in info_dict and info_dict['subtitles']:
  860. # subtitles download errors are already managed as troubles in relevant IE
  861. # that way it will silently go on when used with unsupporting IE
  862. subtitles = info_dict['subtitles']
  863. sub_format = self.params.get('subtitlesformat', 'srt')
  864. for sub_lang in subtitles.keys():
  865. sub = subtitles[sub_lang]
  866. if sub is None:
  867. continue
  868. try:
  869. sub_filename = subtitles_filename(filename, sub_lang, sub_format)
  870. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  871. self.to_screen('[info] Video subtitle %s.%s is already_present' % (sub_lang, sub_format))
  872. else:
  873. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  874. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8') as subfile:
  875. subfile.write(sub)
  876. except (OSError, IOError):
  877. self.report_error('Cannot write subtitles file ' + sub_filename)
  878. return
  879. if self.params.get('writeinfojson', False):
  880. infofn = os.path.splitext(filename)[0] + '.info.json'
  881. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  882. self.to_screen('[info] Video description metadata is already present')
  883. else:
  884. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  885. try:
  886. write_json_file(info_dict, encodeFilename(infofn))
  887. except (OSError, IOError):
  888. self.report_error('Cannot write metadata to JSON file ' + infofn)
  889. return
  890. if self.params.get('writethumbnail', False):
  891. if info_dict.get('thumbnail') is not None:
  892. thumb_format = determine_ext(info_dict['thumbnail'], 'jpg')
  893. thumb_filename = os.path.splitext(filename)[0] + '.' + thumb_format
  894. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  895. self.to_screen('[%s] %s: Thumbnail is already present' %
  896. (info_dict['extractor'], info_dict['id']))
  897. else:
  898. self.to_screen('[%s] %s: Downloading thumbnail ...' %
  899. (info_dict['extractor'], info_dict['id']))
  900. try:
  901. uf = self.urlopen(info_dict['thumbnail'])
  902. with open(thumb_filename, 'wb') as thumbf:
  903. shutil.copyfileobj(uf, thumbf)
  904. self.to_screen('[%s] %s: Writing thumbnail to: %s' %
  905. (info_dict['extractor'], info_dict['id'], thumb_filename))
  906. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  907. self.report_warning('Unable to download thumbnail "%s": %s' %
  908. (info_dict['thumbnail'], compat_str(err)))
  909. if not self.params.get('skip_download', False):
  910. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(filename)):
  911. success = True
  912. else:
  913. try:
  914. def dl(name, info):
  915. fd = get_suitable_downloader(info)(self, self.params)
  916. for ph in self._progress_hooks:
  917. fd.add_progress_hook(ph)
  918. if self.params.get('verbose'):
  919. self.to_stdout('[debug] Invoking downloader on %r' % info.get('url'))
  920. return fd.download(name, info)
  921. if info_dict.get('requested_formats') is not None:
  922. downloaded = []
  923. success = True
  924. merger = FFmpegMergerPP(self, not self.params.get('keepvideo'))
  925. if not merger._executable:
  926. postprocessors = []
  927. self.report_warning('You have requested multiple '
  928. 'formats but ffmpeg or avconv are not installed.'
  929. ' The formats won\'t be merged')
  930. else:
  931. postprocessors = [merger]
  932. for f in info_dict['requested_formats']:
  933. new_info = dict(info_dict)
  934. new_info.update(f)
  935. fname = self.prepare_filename(new_info)
  936. fname = prepend_extension(fname, 'f%s' % f['format_id'])
  937. downloaded.append(fname)
  938. partial_success = dl(fname, new_info)
  939. success = success and partial_success
  940. info_dict['__postprocessors'] = postprocessors
  941. info_dict['__files_to_merge'] = downloaded
  942. else:
  943. # Just a single file
  944. success = dl(filename, info_dict)
  945. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  946. self.report_error('unable to download video data: %s' % str(err))
  947. return
  948. except (OSError, IOError) as err:
  949. raise UnavailableVideoError(err)
  950. except (ContentTooShortError, ) as err:
  951. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  952. return
  953. if success:
  954. try:
  955. self.post_process(filename, info_dict)
  956. except (PostProcessingError) as err:
  957. self.report_error('postprocessing: %s' % str(err))
  958. return
  959. self.record_download_archive(info_dict)
  960. def download(self, url_list):
  961. """Download a given list of URLs."""
  962. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  963. if (len(url_list) > 1 and
  964. '%' not in outtmpl
  965. and self.params.get('max_downloads') != 1):
  966. raise SameFileError(outtmpl)
  967. for url in url_list:
  968. try:
  969. #It also downloads the videos
  970. res = self.extract_info(url)
  971. except UnavailableVideoError:
  972. self.report_error('unable to download video')
  973. except MaxDownloadsReached:
  974. self.to_screen('[info] Maximum number of downloaded files reached.')
  975. raise
  976. else:
  977. if self.params.get('dump_single_json', False):
  978. self.to_stdout(json.dumps(res))
  979. return self._download_retcode
  980. def download_with_info_file(self, info_filename):
  981. with io.open(info_filename, 'r', encoding='utf-8') as f:
  982. info = json.load(f)
  983. try:
  984. self.process_ie_result(info, download=True)
  985. except DownloadError:
  986. webpage_url = info.get('webpage_url')
  987. if webpage_url is not None:
  988. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  989. return self.download([webpage_url])
  990. else:
  991. raise
  992. return self._download_retcode
  993. def post_process(self, filename, ie_info):
  994. """Run all the postprocessors on the given file."""
  995. info = dict(ie_info)
  996. info['filepath'] = filename
  997. keep_video = None
  998. pps_chain = []
  999. if ie_info.get('__postprocessors') is not None:
  1000. pps_chain.extend(ie_info['__postprocessors'])
  1001. pps_chain.extend(self._pps)
  1002. for pp in pps_chain:
  1003. try:
  1004. keep_video_wish, new_info = pp.run(info)
  1005. if keep_video_wish is not None:
  1006. if keep_video_wish:
  1007. keep_video = keep_video_wish
  1008. elif keep_video is None:
  1009. # No clear decision yet, let IE decide
  1010. keep_video = keep_video_wish
  1011. except PostProcessingError as e:
  1012. self.report_error(e.msg)
  1013. if keep_video is False and not self.params.get('keepvideo', False):
  1014. try:
  1015. self.to_screen('Deleting original file %s (pass -k to keep)' % filename)
  1016. os.remove(encodeFilename(filename))
  1017. except (IOError, OSError):
  1018. self.report_warning('Unable to remove downloaded video file')
  1019. def _make_archive_id(self, info_dict):
  1020. # Future-proof against any change in case
  1021. # and backwards compatibility with prior versions
  1022. extractor = info_dict.get('extractor_key')
  1023. if extractor is None:
  1024. if 'id' in info_dict:
  1025. extractor = info_dict.get('ie_key') # key in a playlist
  1026. if extractor is None:
  1027. return None # Incomplete video information
  1028. return extractor.lower() + ' ' + info_dict['id']
  1029. def in_download_archive(self, info_dict):
  1030. fn = self.params.get('download_archive')
  1031. if fn is None:
  1032. return False
  1033. vid_id = self._make_archive_id(info_dict)
  1034. if vid_id is None:
  1035. return False # Incomplete video information
  1036. try:
  1037. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1038. for line in archive_file:
  1039. if line.strip() == vid_id:
  1040. return True
  1041. except IOError as ioe:
  1042. if ioe.errno != errno.ENOENT:
  1043. raise
  1044. return False
  1045. def record_download_archive(self, info_dict):
  1046. fn = self.params.get('download_archive')
  1047. if fn is None:
  1048. return
  1049. vid_id = self._make_archive_id(info_dict)
  1050. assert vid_id
  1051. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1052. archive_file.write(vid_id + '\n')
  1053. @staticmethod
  1054. def format_resolution(format, default='unknown'):
  1055. if format.get('vcodec') == 'none':
  1056. return 'audio only'
  1057. if format.get('resolution') is not None:
  1058. return format['resolution']
  1059. if format.get('height') is not None:
  1060. if format.get('width') is not None:
  1061. res = '%sx%s' % (format['width'], format['height'])
  1062. else:
  1063. res = '%sp' % format['height']
  1064. elif format.get('width') is not None:
  1065. res = '?x%d' % format['width']
  1066. else:
  1067. res = default
  1068. return res
  1069. def _format_note(self, fdict):
  1070. res = ''
  1071. if fdict.get('ext') in ['f4f', 'f4m']:
  1072. res += '(unsupported) '
  1073. if fdict.get('format_note') is not None:
  1074. res += fdict['format_note'] + ' '
  1075. if fdict.get('tbr') is not None:
  1076. res += '%4dk ' % fdict['tbr']
  1077. if fdict.get('container') is not None:
  1078. if res:
  1079. res += ', '
  1080. res += '%s container' % fdict['container']
  1081. if (fdict.get('vcodec') is not None and
  1082. fdict.get('vcodec') != 'none'):
  1083. if res:
  1084. res += ', '
  1085. res += fdict['vcodec']
  1086. if fdict.get('vbr') is not None:
  1087. res += '@'
  1088. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  1089. res += 'video@'
  1090. if fdict.get('vbr') is not None:
  1091. res += '%4dk' % fdict['vbr']
  1092. if fdict.get('fps') is not None:
  1093. res += ', %sfps' % fdict['fps']
  1094. if fdict.get('acodec') is not None:
  1095. if res:
  1096. res += ', '
  1097. if fdict['acodec'] == 'none':
  1098. res += 'video only'
  1099. else:
  1100. res += '%-5s' % fdict['acodec']
  1101. elif fdict.get('abr') is not None:
  1102. if res:
  1103. res += ', '
  1104. res += 'audio'
  1105. if fdict.get('abr') is not None:
  1106. res += '@%3dk' % fdict['abr']
  1107. if fdict.get('asr') is not None:
  1108. res += ' (%5dHz)' % fdict['asr']
  1109. if fdict.get('filesize') is not None:
  1110. if res:
  1111. res += ', '
  1112. res += format_bytes(fdict['filesize'])
  1113. elif fdict.get('filesize_approx') is not None:
  1114. if res:
  1115. res += ', '
  1116. res += '~' + format_bytes(fdict['filesize_approx'])
  1117. return res
  1118. def list_formats(self, info_dict):
  1119. def line(format, idlen=20):
  1120. return (('%-' + compat_str(idlen + 1) + 's%-10s%-12s%s') % (
  1121. format['format_id'],
  1122. format['ext'],
  1123. self.format_resolution(format),
  1124. self._format_note(format),
  1125. ))
  1126. formats = info_dict.get('formats', [info_dict])
  1127. idlen = max(len('format code'),
  1128. max(len(f['format_id']) for f in formats))
  1129. formats_s = [line(f, idlen) for f in formats]
  1130. if len(formats) > 1:
  1131. formats_s[0] += (' ' if self._format_note(formats[0]) else '') + '(worst)'
  1132. formats_s[-1] += (' ' if self._format_note(formats[-1]) else '') + '(best)'
  1133. header_line = line({
  1134. 'format_id': 'format code', 'ext': 'extension',
  1135. 'resolution': 'resolution', 'format_note': 'note'}, idlen=idlen)
  1136. self.to_screen('[info] Available formats for %s:\n%s\n%s' %
  1137. (info_dict['id'], header_line, '\n'.join(formats_s)))
  1138. def urlopen(self, req):
  1139. """ Start an HTTP download """
  1140. # According to RFC 3986, URLs can not contain non-ASCII characters, however this is not
  1141. # always respected by websites, some tend to give out URLs with non percent-encoded
  1142. # non-ASCII characters (see telemb.py, ard.py [#3412])
  1143. # urllib chokes on URLs with non-ASCII characters (see http://bugs.python.org/issue3991)
  1144. # To work around aforementioned issue we will replace request's original URL with
  1145. # percent-encoded one
  1146. req_is_string = isinstance(req, basestring if sys.version_info < (3, 0) else compat_str)
  1147. url = req if req_is_string else req.get_full_url()
  1148. url_escaped = escape_url(url)
  1149. # Substitute URL if any change after escaping
  1150. if url != url_escaped:
  1151. if req_is_string:
  1152. req = url_escaped
  1153. else:
  1154. req = compat_urllib_request.Request(
  1155. url_escaped, data=req.data, headers=req.headers,
  1156. origin_req_host=req.origin_req_host, unverifiable=req.unverifiable)
  1157. return self._opener.open(req, timeout=self._socket_timeout)
  1158. def print_debug_header(self):
  1159. if not self.params.get('verbose'):
  1160. return
  1161. if type('') is not compat_str:
  1162. # Python 2.6 on SLES11 SP1 (https://github.com/rg3/youtube-dl/issues/3326)
  1163. self.report_warning(
  1164. 'Your Python is broken! Update to a newer and supported version')
  1165. encoding_str = (
  1166. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  1167. locale.getpreferredencoding(),
  1168. sys.getfilesystemencoding(),
  1169. sys.stdout.encoding,
  1170. self.get_encoding()))
  1171. write_string(encoding_str, encoding=None)
  1172. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  1173. try:
  1174. sp = subprocess.Popen(
  1175. ['git', 'rev-parse', '--short', 'HEAD'],
  1176. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  1177. cwd=os.path.dirname(os.path.abspath(__file__)))
  1178. out, err = sp.communicate()
  1179. out = out.decode().strip()
  1180. if re.match('[0-9a-f]+', out):
  1181. self._write_string('[debug] Git HEAD: ' + out + '\n')
  1182. except:
  1183. try:
  1184. sys.exc_clear()
  1185. except:
  1186. pass
  1187. self._write_string('[debug] Python version %s - %s\n' % (
  1188. platform.python_version(), platform_name()))
  1189. exe_versions = FFmpegPostProcessor.get_versions()
  1190. exe_versions['rtmpdump'] = rtmpdump_version()
  1191. exe_str = ', '.join(
  1192. '%s %s' % (exe, v)
  1193. for exe, v in sorted(exe_versions.items())
  1194. if v
  1195. )
  1196. if not exe_str:
  1197. exe_str = 'none'
  1198. self._write_string('[debug] exe versions: %s\n' % exe_str)
  1199. proxy_map = {}
  1200. for handler in self._opener.handlers:
  1201. if hasattr(handler, 'proxies'):
  1202. proxy_map.update(handler.proxies)
  1203. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  1204. def _setup_opener(self):
  1205. timeout_val = self.params.get('socket_timeout')
  1206. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  1207. opts_cookiefile = self.params.get('cookiefile')
  1208. opts_proxy = self.params.get('proxy')
  1209. if opts_cookiefile is None:
  1210. self.cookiejar = compat_cookiejar.CookieJar()
  1211. else:
  1212. self.cookiejar = compat_cookiejar.MozillaCookieJar(
  1213. opts_cookiefile)
  1214. if os.access(opts_cookiefile, os.R_OK):
  1215. self.cookiejar.load()
  1216. cookie_processor = compat_urllib_request.HTTPCookieProcessor(
  1217. self.cookiejar)
  1218. if opts_proxy is not None:
  1219. if opts_proxy == '':
  1220. proxies = {}
  1221. else:
  1222. proxies = {'http': opts_proxy, 'https': opts_proxy}
  1223. else:
  1224. proxies = compat_urllib_request.getproxies()
  1225. # Set HTTPS proxy to HTTP one if given (https://github.com/rg3/youtube-dl/issues/805)
  1226. if 'http' in proxies and 'https' not in proxies:
  1227. proxies['https'] = proxies['http']
  1228. proxy_handler = compat_urllib_request.ProxyHandler(proxies)
  1229. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  1230. https_handler = make_HTTPS_handler(
  1231. self.params.get('nocheckcertificate', False), debuglevel=debuglevel)
  1232. ydlh = YoutubeDLHandler(debuglevel=debuglevel)
  1233. opener = compat_urllib_request.build_opener(
  1234. https_handler, proxy_handler, cookie_processor, ydlh)
  1235. # Delete the default user-agent header, which would otherwise apply in
  1236. # cases where our custom HTTP handler doesn't come into play
  1237. # (See https://github.com/rg3/youtube-dl/issues/1309 for details)
  1238. opener.addheaders = []
  1239. self._opener = opener
  1240. def encode(self, s):
  1241. if isinstance(s, bytes):
  1242. return s # Already encoded
  1243. try:
  1244. return s.encode(self.get_encoding())
  1245. except UnicodeEncodeError as err:
  1246. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  1247. raise
  1248. def get_encoding(self):
  1249. encoding = self.params.get('encoding')
  1250. if encoding is None:
  1251. encoding = preferredencoding()
  1252. return encoding