YoutubeDL.py 74 KB

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