YoutubeDL.py 111 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. from __future__ import absolute_import, unicode_literals
  4. import collections
  5. import contextlib
  6. import copy
  7. import datetime
  8. import errno
  9. import fileinput
  10. import io
  11. import itertools
  12. import json
  13. import locale
  14. import operator
  15. import os
  16. import platform
  17. import re
  18. import shutil
  19. import subprocess
  20. import socket
  21. import sys
  22. import time
  23. import tokenize
  24. import traceback
  25. import random
  26. from string import ascii_letters
  27. from .compat import (
  28. compat_basestring,
  29. compat_cookiejar,
  30. compat_get_terminal_size,
  31. compat_http_client,
  32. compat_kwargs,
  33. compat_numeric_types,
  34. compat_os_name,
  35. compat_str,
  36. compat_tokenize_tokenize,
  37. compat_urllib_error,
  38. compat_urllib_request,
  39. compat_urllib_request_DataHandler,
  40. )
  41. from .utils import (
  42. age_restricted,
  43. args_to_str,
  44. ContentTooShortError,
  45. date_from_str,
  46. DateRange,
  47. DEFAULT_OUTTMPL,
  48. determine_ext,
  49. determine_protocol,
  50. DownloadError,
  51. encode_compat_str,
  52. encodeFilename,
  53. error_to_compat_str,
  54. expand_path,
  55. ExtractorError,
  56. format_bytes,
  57. formatSeconds,
  58. GeoRestrictedError,
  59. int_or_none,
  60. ISO3166Utils,
  61. locked_file,
  62. make_HTTPS_handler,
  63. MaxDownloadsReached,
  64. orderedSet,
  65. PagedList,
  66. parse_filesize,
  67. PerRequestProxyHandler,
  68. platform_name,
  69. PostProcessingError,
  70. preferredencoding,
  71. prepend_extension,
  72. process_communicate_or_kill,
  73. register_socks_protocols,
  74. render_table,
  75. replace_extension,
  76. SameFileError,
  77. sanitize_filename,
  78. sanitize_path,
  79. sanitize_url,
  80. sanitized_Request,
  81. std_headers,
  82. str_or_none,
  83. subtitles_filename,
  84. UnavailableVideoError,
  85. url_basename,
  86. version_tuple,
  87. write_json_file,
  88. write_string,
  89. YoutubeDLCookieJar,
  90. YoutubeDLCookieProcessor,
  91. YoutubeDLHandler,
  92. YoutubeDLRedirectHandler,
  93. )
  94. from .cache import Cache
  95. from .extractor import get_info_extractor, gen_extractor_classes, _LAZY_LOADER
  96. from .extractor.openload import PhantomJSwrapper
  97. from .downloader import get_suitable_downloader
  98. from .downloader.rtmp import rtmpdump_version
  99. from .postprocessor import (
  100. FFmpegFixupM3u8PP,
  101. FFmpegFixupM4aPP,
  102. FFmpegFixupStretchedPP,
  103. FFmpegMergerPP,
  104. FFmpegPostProcessor,
  105. get_postprocessor,
  106. )
  107. from .version import __version__
  108. if compat_os_name == 'nt':
  109. import ctypes
  110. class YoutubeDL(object):
  111. """YoutubeDL class.
  112. YoutubeDL objects are the ones responsible of downloading the
  113. actual video file and writing it to disk if the user has requested
  114. it, among some other tasks. In most cases there should be one per
  115. program. As, given a video URL, the downloader doesn't know how to
  116. extract all the needed information, task that InfoExtractors do, it
  117. has to pass the URL to one of them.
  118. For this, YoutubeDL objects have a method that allows
  119. InfoExtractors to be registered in a given order. When it is passed
  120. a URL, the YoutubeDL object handles it to the first InfoExtractor it
  121. finds that reports being able to handle it. The InfoExtractor extracts
  122. all the information about the video or videos the URL refers to, and
  123. YoutubeDL process the extracted information, possibly using a File
  124. Downloader to download the video.
  125. YoutubeDL objects accept a lot of parameters. In order not to saturate
  126. the object constructor with arguments, it receives a dictionary of
  127. options instead. These options are available through the params
  128. attribute for the InfoExtractors to use. The YoutubeDL also
  129. registers itself as the downloader in charge for the InfoExtractors
  130. that are added to it, so this is a "mutual registration".
  131. Available options:
  132. username: Username for authentication purposes.
  133. password: Password for authentication purposes.
  134. videopassword: Password for accessing a video.
  135. ap_mso: Adobe Pass multiple-system operator identifier.
  136. ap_username: Multiple-system operator account username.
  137. ap_password: Multiple-system operator account password.
  138. usenetrc: Use netrc for authentication instead.
  139. verbose: Print additional info to stdout.
  140. quiet: Do not print messages to stdout.
  141. no_warnings: Do not print out anything for warnings.
  142. forceurl: Force printing final URL.
  143. forcetitle: Force printing title.
  144. forceid: Force printing ID.
  145. forcethumbnail: Force printing thumbnail URL.
  146. forcedescription: Force printing description.
  147. forcefilename: Force printing final filename.
  148. forceduration: Force printing duration.
  149. forcejson: Force printing info_dict as JSON.
  150. dump_single_json: Force printing the info_dict of the whole playlist
  151. (or video) as a single JSON line.
  152. simulate: Do not download the video files.
  153. format: Video format code. See options.py for more information.
  154. outtmpl: Template for output names.
  155. outtmpl_na_placeholder: Placeholder for unavailable meta fields.
  156. restrictfilenames: Do not allow "&" and spaces in file names
  157. ignoreerrors: Do not stop on download errors.
  158. force_generic_extractor: Force downloader to use the generic extractor
  159. nooverwrites: Prevent overwriting files.
  160. playliststart: Playlist item to start at.
  161. playlistend: Playlist item to end at.
  162. playlist_items: Specific indices of playlist to download.
  163. playlistreverse: Download playlist items in reverse order.
  164. playlistrandom: Download playlist items in random order.
  165. matchtitle: Download only matching titles.
  166. rejecttitle: Reject downloads for matching titles.
  167. logger: Log messages to a logging.Logger instance.
  168. logtostderr: Log messages to stderr instead of stdout.
  169. writedescription: Write the video description to a .description file
  170. writeinfojson: Write the video description to a .info.json file
  171. writeannotations: Write the video annotations to a .annotations.xml file
  172. writethumbnail: Write the thumbnail image to a file
  173. write_all_thumbnails: Write all thumbnail formats to files
  174. writesubtitles: Write the video subtitles to a file
  175. writeautomaticsub: Write the automatically generated subtitles to a file
  176. allsubtitles: Downloads all the subtitles of the video
  177. (requires writesubtitles or writeautomaticsub)
  178. listsubtitles: Lists all available subtitles for the video
  179. subtitlesformat: The format code for subtitles
  180. subtitleslangs: List of languages of the subtitles to download
  181. keepvideo: Keep the video file after post-processing
  182. daterange: A DateRange object, download only if the upload_date is in the range.
  183. skip_download: Skip the actual download of the video file
  184. cachedir: Location of the cache files in the filesystem.
  185. False to disable filesystem cache.
  186. noplaylist: Download single video instead of a playlist if in doubt.
  187. age_limit: An integer representing the user's age in years.
  188. Unsuitable videos for the given age are skipped.
  189. min_views: An integer representing the minimum view count the video
  190. must have in order to not be skipped.
  191. Videos without view count information are always
  192. downloaded. None for no limit.
  193. max_views: An integer representing the maximum view count.
  194. Videos that are more popular than that are not
  195. downloaded.
  196. Videos without view count information are always
  197. downloaded. None for no limit.
  198. download_archive: File name of a file where all downloads are recorded.
  199. Videos already present in the file are not downloaded
  200. again.
  201. cookiefile: File name where cookies should be read from and dumped to.
  202. nocheckcertificate:Do not verify SSL certificates
  203. prefer_insecure: Use HTTP instead of HTTPS to retrieve information.
  204. At the moment, this is only supported by YouTube.
  205. proxy: URL of the proxy server to use
  206. geo_verification_proxy: URL of the proxy to use for IP address verification
  207. on geo-restricted sites.
  208. socket_timeout: Time to wait for unresponsive hosts, in seconds
  209. bidi_workaround: Work around buggy terminals without bidirectional text
  210. support, using fridibi
  211. debug_printtraffic:Print out sent and received HTTP traffic
  212. include_ads: Download ads as well
  213. default_search: Prepend this string if an input url is not valid.
  214. 'auto' for elaborate guessing
  215. encoding: Use this encoding instead of the system-specified.
  216. extract_flat: Do not resolve URLs, return the immediate result.
  217. Pass in 'in_playlist' to only show this behavior for
  218. playlist items.
  219. postprocessors: A list of dictionaries, each with an entry
  220. * key: The name of the postprocessor. See
  221. youtube_dl/postprocessor/__init__.py for a list.
  222. as well as any further keyword arguments for the
  223. postprocessor.
  224. progress_hooks: A list of functions that get called on download
  225. progress, with a dictionary with the entries
  226. * status: One of "downloading", "error", or "finished".
  227. Check this first and ignore unknown values.
  228. If status is one of "downloading", or "finished", the
  229. following properties may also be present:
  230. * filename: The final filename (always present)
  231. * tmpfilename: The filename we're currently writing to
  232. * downloaded_bytes: Bytes on disk
  233. * total_bytes: Size of the whole file, None if unknown
  234. * total_bytes_estimate: Guess of the eventual file size,
  235. None if unavailable.
  236. * elapsed: The number of seconds since download started.
  237. * eta: The estimated time in seconds, None if unknown
  238. * speed: The download speed in bytes/second, None if
  239. unknown
  240. * fragment_index: The counter of the currently
  241. downloaded video fragment.
  242. * fragment_count: The number of fragments (= individual
  243. files that will be merged)
  244. Progress hooks are guaranteed to be called at least once
  245. (with status "finished") if the download is successful.
  246. merge_output_format: Extension to use when merging formats.
  247. fixup: Automatically correct known faults of the file.
  248. One of:
  249. - "never": do nothing
  250. - "warn": only emit a warning
  251. - "detect_or_warn": check whether we can do anything
  252. about it, warn otherwise (default)
  253. source_address: Client-side IP address to bind to.
  254. call_home: Boolean, true iff we are allowed to contact the
  255. youtube-dl servers for debugging.
  256. sleep_interval: Number of seconds to sleep before each download when
  257. used alone or a lower bound of a range for randomized
  258. sleep before each download (minimum possible number
  259. of seconds to sleep) when used along with
  260. max_sleep_interval.
  261. max_sleep_interval:Upper bound of a range for randomized sleep before each
  262. download (maximum possible number of seconds to sleep).
  263. Must only be used along with sleep_interval.
  264. Actual sleep time will be a random float from range
  265. [sleep_interval; max_sleep_interval].
  266. listformats: Print an overview of available video formats and exit.
  267. list_thumbnails: Print a table of all thumbnails and exit.
  268. match_filter: A function that gets called with the info_dict of
  269. every video.
  270. If it returns a message, the video is ignored.
  271. If it returns None, the video is downloaded.
  272. match_filter_func in utils.py is one example for this.
  273. no_color: Do not emit color codes in output.
  274. geo_bypass: Bypass geographic restriction via faking X-Forwarded-For
  275. HTTP header
  276. geo_bypass_country:
  277. Two-letter ISO 3166-2 country code that will be used for
  278. explicit geographic restriction bypassing via faking
  279. X-Forwarded-For HTTP header
  280. geo_bypass_ip_block:
  281. IP range in CIDR notation that will be used similarly to
  282. geo_bypass_country
  283. The following options determine which downloader is picked:
  284. external_downloader: Executable of the external downloader to call.
  285. None or unset for standard (built-in) downloader.
  286. hls_prefer_native: Use the native HLS downloader instead of ffmpeg/avconv
  287. if True, otherwise use ffmpeg/avconv if False, otherwise
  288. use downloader suggested by extractor if None.
  289. The following parameters are not used by YoutubeDL itself, they are used by
  290. the downloader (see youtube_dl/downloader/common.py):
  291. nopart, updatetime, buffersize, ratelimit, min_filesize, max_filesize, test,
  292. noresizebuffer, retries, continuedl, noprogress, consoletitle,
  293. xattr_set_filesize, external_downloader_args, hls_use_mpegts,
  294. http_chunk_size.
  295. The following options are used by the post processors:
  296. prefer_ffmpeg: If False, use avconv instead of ffmpeg if both are available,
  297. otherwise prefer ffmpeg.
  298. ffmpeg_location: Location of the ffmpeg/avconv binary; either the path
  299. to the binary or its containing directory.
  300. postprocessor_args: A list of additional command-line arguments for the
  301. postprocessor.
  302. The following options are used by the Youtube extractor:
  303. youtube_include_dash_manifest: If True (default), DASH manifests and related
  304. data will be downloaded and processed by extractor.
  305. You can reduce network I/O by disabling it if you don't
  306. care about DASH.
  307. """
  308. _NUMERIC_FIELDS = set((
  309. 'width', 'height', 'tbr', 'abr', 'asr', 'vbr', 'fps', 'filesize', 'filesize_approx',
  310. 'timestamp', 'upload_year', 'upload_month', 'upload_day',
  311. 'duration', 'view_count', 'like_count', 'dislike_count', 'repost_count',
  312. 'average_rating', 'comment_count', 'age_limit',
  313. 'start_time', 'end_time',
  314. 'chapter_number', 'season_number', 'episode_number',
  315. 'track_number', 'disc_number', 'release_year',
  316. 'playlist_index',
  317. ))
  318. params = None
  319. _ies = []
  320. _pps = []
  321. _download_retcode = None
  322. _num_downloads = None
  323. _playlist_level = 0
  324. _playlist_urls = set()
  325. _screen_file = None
  326. def __init__(self, params=None, auto_init=True):
  327. """Create a FileDownloader object with the given options."""
  328. if params is None:
  329. params = {}
  330. self._ies = []
  331. self._ies_instances = {}
  332. self._pps = []
  333. self._progress_hooks = []
  334. self._download_retcode = 0
  335. self._num_downloads = 0
  336. self._screen_file = [sys.stdout, sys.stderr][params.get('logtostderr', False)]
  337. self._err_file = sys.stderr
  338. self.params = {
  339. # Default parameters
  340. 'nocheckcertificate': False,
  341. }
  342. self.params.update(params)
  343. self.cache = Cache(self)
  344. def check_deprecated(param, option, suggestion):
  345. if self.params.get(param) is not None:
  346. self.report_warning(
  347. '%s is deprecated. Use %s instead.' % (option, suggestion))
  348. return True
  349. return False
  350. if check_deprecated('cn_verification_proxy', '--cn-verification-proxy', '--geo-verification-proxy'):
  351. if self.params.get('geo_verification_proxy') is None:
  352. self.params['geo_verification_proxy'] = self.params['cn_verification_proxy']
  353. check_deprecated('autonumber_size', '--autonumber-size', 'output template with %(autonumber)0Nd, where N in the number of digits')
  354. check_deprecated('autonumber', '--auto-number', '-o "%(autonumber)s-%(title)s.%(ext)s"')
  355. check_deprecated('usetitle', '--title', '-o "%(title)s-%(id)s.%(ext)s"')
  356. if params.get('bidi_workaround', False):
  357. try:
  358. import pty
  359. master, slave = pty.openpty()
  360. width = compat_get_terminal_size().columns
  361. if width is None:
  362. width_args = []
  363. else:
  364. width_args = ['-w', str(width)]
  365. sp_kwargs = dict(
  366. stdin=subprocess.PIPE,
  367. stdout=slave,
  368. stderr=self._err_file)
  369. try:
  370. self._output_process = subprocess.Popen(
  371. ['bidiv'] + width_args, **sp_kwargs
  372. )
  373. except OSError:
  374. self._output_process = subprocess.Popen(
  375. ['fribidi', '-c', 'UTF-8'] + width_args, **sp_kwargs)
  376. self._output_channel = os.fdopen(master, 'rb')
  377. except OSError as ose:
  378. if ose.errno == errno.ENOENT:
  379. 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.')
  380. else:
  381. raise
  382. if (sys.platform != 'win32'
  383. and sys.getfilesystemencoding() in ['ascii', 'ANSI_X3.4-1968']
  384. and not params.get('restrictfilenames', False)):
  385. # Unicode filesystem API will throw errors (#1474, #13027)
  386. self.report_warning(
  387. 'Assuming --restrict-filenames since file system encoding '
  388. 'cannot encode all characters. '
  389. 'Set the LC_ALL environment variable to fix this.')
  390. self.params['restrictfilenames'] = True
  391. if isinstance(params.get('outtmpl'), bytes):
  392. self.report_warning(
  393. 'Parameter outtmpl is bytes, but should be a unicode string. '
  394. 'Put from __future__ import unicode_literals at the top of your code file or consider switching to Python 3.x.')
  395. self._setup_opener()
  396. if auto_init:
  397. self.print_debug_header()
  398. self.add_default_info_extractors()
  399. for pp_def_raw in self.params.get('postprocessors', []):
  400. pp_class = get_postprocessor(pp_def_raw['key'])
  401. pp_def = dict(pp_def_raw)
  402. del pp_def['key']
  403. pp = pp_class(self, **compat_kwargs(pp_def))
  404. self.add_post_processor(pp)
  405. for ph in self.params.get('progress_hooks', []):
  406. self.add_progress_hook(ph)
  407. register_socks_protocols()
  408. def warn_if_short_id(self, argv):
  409. # short YouTube ID starting with dash?
  410. idxs = [
  411. i for i, a in enumerate(argv)
  412. if re.match(r'^-[0-9A-Za-z_-]{10}$', a)]
  413. if idxs:
  414. correct_argv = (
  415. ['youtube-dl']
  416. + [a for i, a in enumerate(argv) if i not in idxs]
  417. + ['--'] + [argv[i] for i in idxs]
  418. )
  419. self.report_warning(
  420. 'Long argument string detected. '
  421. 'Use -- to separate parameters and URLs, like this:\n%s\n' %
  422. args_to_str(correct_argv))
  423. def add_info_extractor(self, ie):
  424. """Add an InfoExtractor object to the end of the list."""
  425. self._ies.append(ie)
  426. if not isinstance(ie, type):
  427. self._ies_instances[ie.ie_key()] = ie
  428. ie.set_downloader(self)
  429. def get_info_extractor(self, ie_key):
  430. """
  431. Get an instance of an IE with name ie_key, it will try to get one from
  432. the _ies list, if there's no instance it will create a new one and add
  433. it to the extractor list.
  434. """
  435. ie = self._ies_instances.get(ie_key)
  436. if ie is None:
  437. ie = get_info_extractor(ie_key)()
  438. self.add_info_extractor(ie)
  439. return ie
  440. def add_default_info_extractors(self):
  441. """
  442. Add the InfoExtractors returned by gen_extractors to the end of the list
  443. """
  444. for ie in gen_extractor_classes():
  445. self.add_info_extractor(ie)
  446. def add_post_processor(self, pp):
  447. """Add a PostProcessor object to the end of the chain."""
  448. self._pps.append(pp)
  449. pp.set_downloader(self)
  450. def add_progress_hook(self, ph):
  451. """Add the progress hook (currently only for the file downloader)"""
  452. self._progress_hooks.append(ph)
  453. def _bidi_workaround(self, message):
  454. if not hasattr(self, '_output_channel'):
  455. return message
  456. assert hasattr(self, '_output_process')
  457. assert isinstance(message, compat_str)
  458. line_count = message.count('\n') + 1
  459. self._output_process.stdin.write((message + '\n').encode('utf-8'))
  460. self._output_process.stdin.flush()
  461. res = ''.join(self._output_channel.readline().decode('utf-8')
  462. for _ in range(line_count))
  463. return res[:-len('\n')]
  464. def to_screen(self, message, skip_eol=False):
  465. """Print message to stdout if not in quiet mode."""
  466. return self.to_stdout(message, skip_eol, check_quiet=True)
  467. def _write_string(self, s, out=None):
  468. write_string(s, out=out, encoding=self.params.get('encoding'))
  469. def to_stdout(self, message, skip_eol=False, check_quiet=False):
  470. """Print message to stdout if not in quiet mode."""
  471. if self.params.get('logger'):
  472. self.params['logger'].debug(message)
  473. elif not check_quiet or not self.params.get('quiet', False):
  474. message = self._bidi_workaround(message)
  475. terminator = ['\n', ''][skip_eol]
  476. output = message + terminator
  477. self._write_string(output, self._screen_file)
  478. def to_stderr(self, message):
  479. """Print message to stderr."""
  480. assert isinstance(message, compat_str)
  481. if self.params.get('logger'):
  482. self.params['logger'].error(message)
  483. else:
  484. message = self._bidi_workaround(message)
  485. output = message + '\n'
  486. self._write_string(output, self._err_file)
  487. def to_console_title(self, message):
  488. if not self.params.get('consoletitle', False):
  489. return
  490. if compat_os_name == 'nt':
  491. if ctypes.windll.kernel32.GetConsoleWindow():
  492. # c_wchar_p() might not be necessary if `message` is
  493. # already of type unicode()
  494. ctypes.windll.kernel32.SetConsoleTitleW(ctypes.c_wchar_p(message))
  495. elif 'TERM' in os.environ:
  496. self._write_string('\033]0;%s\007' % message, self._screen_file)
  497. def save_console_title(self):
  498. if not self.params.get('consoletitle', False):
  499. return
  500. if self.params.get('simulate', False):
  501. return
  502. if compat_os_name != 'nt' and 'TERM' in os.environ:
  503. # Save the title on stack
  504. self._write_string('\033[22;0t', self._screen_file)
  505. def restore_console_title(self):
  506. if not self.params.get('consoletitle', False):
  507. return
  508. if self.params.get('simulate', False):
  509. return
  510. if compat_os_name != 'nt' and 'TERM' in os.environ:
  511. # Restore the title from stack
  512. self._write_string('\033[23;0t', self._screen_file)
  513. def __enter__(self):
  514. self.save_console_title()
  515. return self
  516. def __exit__(self, *args):
  517. self.restore_console_title()
  518. if self.params.get('cookiefile') is not None:
  519. self.cookiejar.save(ignore_discard=True, ignore_expires=True)
  520. def trouble(self, message=None, tb=None):
  521. """Determine action to take when a download problem appears.
  522. Depending on if the downloader has been configured to ignore
  523. download errors or not, this method may throw an exception or
  524. not when errors are found, after printing the message.
  525. tb, if given, is additional traceback information.
  526. """
  527. if message is not None:
  528. self.to_stderr(message)
  529. if self.params.get('verbose'):
  530. if tb is None:
  531. if sys.exc_info()[0]: # if .trouble has been called from an except block
  532. tb = ''
  533. if hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  534. tb += ''.join(traceback.format_exception(*sys.exc_info()[1].exc_info))
  535. tb += encode_compat_str(traceback.format_exc())
  536. else:
  537. tb_data = traceback.format_list(traceback.extract_stack())
  538. tb = ''.join(tb_data)
  539. self.to_stderr(tb)
  540. if not self.params.get('ignoreerrors', False):
  541. if sys.exc_info()[0] and hasattr(sys.exc_info()[1], 'exc_info') and sys.exc_info()[1].exc_info[0]:
  542. exc_info = sys.exc_info()[1].exc_info
  543. else:
  544. exc_info = sys.exc_info()
  545. raise DownloadError(message, exc_info)
  546. self._download_retcode = 1
  547. def report_warning(self, message):
  548. '''
  549. Print the message to stderr, it will be prefixed with 'WARNING:'
  550. If stderr is a tty file the 'WARNING:' will be colored
  551. '''
  552. if self.params.get('logger') is not None:
  553. self.params['logger'].warning(message)
  554. else:
  555. if self.params.get('no_warnings'):
  556. return
  557. if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
  558. _msg_header = '\033[0;33mWARNING:\033[0m'
  559. else:
  560. _msg_header = 'WARNING:'
  561. warning_message = '%s %s' % (_msg_header, message)
  562. self.to_stderr(warning_message)
  563. def report_error(self, message, tb=None):
  564. '''
  565. Do the same as trouble, but prefixes the message with 'ERROR:', colored
  566. in red if stderr is a tty file.
  567. '''
  568. if not self.params.get('no_color') and self._err_file.isatty() and compat_os_name != 'nt':
  569. _msg_header = '\033[0;31mERROR:\033[0m'
  570. else:
  571. _msg_header = 'ERROR:'
  572. error_message = '%s %s' % (_msg_header, message)
  573. self.trouble(error_message, tb)
  574. def report_file_already_downloaded(self, file_name):
  575. """Report file has already been fully downloaded."""
  576. try:
  577. self.to_screen('[download] %s has already been downloaded' % file_name)
  578. except UnicodeEncodeError:
  579. self.to_screen('[download] The file has already been downloaded')
  580. def prepare_filename(self, info_dict):
  581. """Generate the output filename."""
  582. try:
  583. template_dict = dict(info_dict)
  584. template_dict['epoch'] = int(time.time())
  585. autonumber_size = self.params.get('autonumber_size')
  586. if autonumber_size is None:
  587. autonumber_size = 5
  588. template_dict['autonumber'] = self.params.get('autonumber_start', 1) - 1 + self._num_downloads
  589. if template_dict.get('resolution') is None:
  590. if template_dict.get('width') and template_dict.get('height'):
  591. template_dict['resolution'] = '%dx%d' % (template_dict['width'], template_dict['height'])
  592. elif template_dict.get('height'):
  593. template_dict['resolution'] = '%sp' % template_dict['height']
  594. elif template_dict.get('width'):
  595. template_dict['resolution'] = '%dx?' % template_dict['width']
  596. sanitize = lambda k, v: sanitize_filename(
  597. compat_str(v),
  598. restricted=self.params.get('restrictfilenames'),
  599. is_id=(k == 'id' or k.endswith('_id')))
  600. template_dict = dict((k, v if isinstance(v, compat_numeric_types) else sanitize(k, v))
  601. for k, v in template_dict.items()
  602. if v is not None and not isinstance(v, (list, tuple, dict)))
  603. template_dict = collections.defaultdict(lambda: self.params.get('outtmpl_na_placeholder', 'NA'), template_dict)
  604. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  605. # For fields playlist_index and autonumber convert all occurrences
  606. # of %(field)s to %(field)0Nd for backward compatibility
  607. field_size_compat_map = {
  608. 'playlist_index': len(str(template_dict['n_entries'])),
  609. 'autonumber': autonumber_size,
  610. }
  611. FIELD_SIZE_COMPAT_RE = r'(?<!%)%\((?P<field>autonumber|playlist_index)\)s'
  612. mobj = re.search(FIELD_SIZE_COMPAT_RE, outtmpl)
  613. if mobj:
  614. outtmpl = re.sub(
  615. FIELD_SIZE_COMPAT_RE,
  616. r'%%(\1)0%dd' % field_size_compat_map[mobj.group('field')],
  617. outtmpl)
  618. # Missing numeric fields used together with integer presentation types
  619. # in format specification will break the argument substitution since
  620. # string NA placeholder is returned for missing fields. We will patch
  621. # output template for missing fields to meet string presentation type.
  622. for numeric_field in self._NUMERIC_FIELDS:
  623. if numeric_field not in template_dict:
  624. # As of [1] format syntax is:
  625. # %[mapping_key][conversion_flags][minimum_width][.precision][length_modifier]type
  626. # 1. https://docs.python.org/2/library/stdtypes.html#string-formatting
  627. FORMAT_RE = r'''(?x)
  628. (?<!%)
  629. %
  630. \({0}\) # mapping key
  631. (?:[#0\-+ ]+)? # conversion flags (optional)
  632. (?:\d+)? # minimum field width (optional)
  633. (?:\.\d+)? # precision (optional)
  634. [hlL]? # length modifier (optional)
  635. [diouxXeEfFgGcrs%] # conversion type
  636. '''
  637. outtmpl = re.sub(
  638. FORMAT_RE.format(numeric_field),
  639. r'%({0})s'.format(numeric_field), outtmpl)
  640. # expand_path translates '%%' into '%' and '$$' into '$'
  641. # correspondingly that is not what we want since we need to keep
  642. # '%%' intact for template dict substitution step. Working around
  643. # with boundary-alike separator hack.
  644. sep = ''.join([random.choice(ascii_letters) for _ in range(32)])
  645. outtmpl = outtmpl.replace('%%', '%{0}%'.format(sep)).replace('$$', '${0}$'.format(sep))
  646. # outtmpl should be expand_path'ed before template dict substitution
  647. # because meta fields may contain env variables we don't want to
  648. # be expanded. For example, for outtmpl "%(title)s.%(ext)s" and
  649. # title "Hello $PATH", we don't want `$PATH` to be expanded.
  650. filename = expand_path(outtmpl).replace(sep, '') % template_dict
  651. # Temporary fix for #4787
  652. # 'Treat' all problem characters by passing filename through preferredencoding
  653. # to workaround encoding issues with subprocess on python2 @ Windows
  654. if sys.version_info < (3, 0) and sys.platform == 'win32':
  655. filename = encodeFilename(filename, True).decode(preferredencoding())
  656. return sanitize_path(filename)
  657. except ValueError as err:
  658. self.report_error('Error in output template: ' + error_to_compat_str(err) + ' (encoding: ' + repr(preferredencoding()) + ')')
  659. return None
  660. def _match_entry(self, info_dict, incomplete):
  661. """ Returns None iff the file should be downloaded """
  662. video_title = info_dict.get('title', info_dict.get('id', 'video'))
  663. if 'title' in info_dict:
  664. # This can happen when we're just evaluating the playlist
  665. title = info_dict['title']
  666. matchtitle = self.params.get('matchtitle', False)
  667. if matchtitle:
  668. if not re.search(matchtitle, title, re.IGNORECASE):
  669. return '"' + title + '" title did not match pattern "' + matchtitle + '"'
  670. rejecttitle = self.params.get('rejecttitle', False)
  671. if rejecttitle:
  672. if re.search(rejecttitle, title, re.IGNORECASE):
  673. return '"' + title + '" title matched reject pattern "' + rejecttitle + '"'
  674. date = info_dict.get('upload_date')
  675. if date is not None:
  676. dateRange = self.params.get('daterange', DateRange())
  677. if date not in dateRange:
  678. return '%s upload date is not in range %s' % (date_from_str(date).isoformat(), dateRange)
  679. view_count = info_dict.get('view_count')
  680. if view_count is not None:
  681. min_views = self.params.get('min_views')
  682. if min_views is not None and view_count < min_views:
  683. return 'Skipping %s, because it has not reached minimum view count (%d/%d)' % (video_title, view_count, min_views)
  684. max_views = self.params.get('max_views')
  685. if max_views is not None and view_count > max_views:
  686. return 'Skipping %s, because it has exceeded the maximum view count (%d/%d)' % (video_title, view_count, max_views)
  687. if age_restricted(info_dict.get('age_limit'), self.params.get('age_limit')):
  688. return 'Skipping "%s" because it is age restricted' % video_title
  689. if self.in_download_archive(info_dict):
  690. return '%s has already been recorded in archive' % video_title
  691. if not incomplete:
  692. match_filter = self.params.get('match_filter')
  693. if match_filter is not None:
  694. ret = match_filter(info_dict)
  695. if ret is not None:
  696. return ret
  697. return None
  698. @staticmethod
  699. def add_extra_info(info_dict, extra_info):
  700. '''Set the keys from extra_info in info dict if they are missing'''
  701. for key, value in extra_info.items():
  702. info_dict.setdefault(key, value)
  703. def extract_info(self, url, download=True, ie_key=None, extra_info={},
  704. process=True, force_generic_extractor=False):
  705. """
  706. Return a list with a dictionary for each video extracted.
  707. Arguments:
  708. url -- URL to extract
  709. Keyword arguments:
  710. download -- whether to download videos during extraction
  711. ie_key -- extractor key hint
  712. extra_info -- dictionary containing the extra values to add to each result
  713. process -- whether to resolve all unresolved references (URLs, playlist items),
  714. must be True for download to work.
  715. force_generic_extractor -- force using the generic extractor
  716. """
  717. if not ie_key and force_generic_extractor:
  718. ie_key = 'Generic'
  719. if ie_key:
  720. ies = [self.get_info_extractor(ie_key)]
  721. else:
  722. ies = self._ies
  723. for ie in ies:
  724. if not ie.suitable(url):
  725. continue
  726. ie = self.get_info_extractor(ie.ie_key())
  727. if not ie.working():
  728. self.report_warning('The program functionality for this site has been marked as broken, '
  729. 'and will probably not work.')
  730. return self.__extract_info(url, ie, download, extra_info, process)
  731. else:
  732. self.report_error('no suitable InfoExtractor for URL %s' % url)
  733. def __handle_extraction_exceptions(func):
  734. def wrapper(self, *args, **kwargs):
  735. try:
  736. return func(self, *args, **kwargs)
  737. except GeoRestrictedError as e:
  738. msg = e.msg
  739. if e.countries:
  740. msg += '\nThis video is available in %s.' % ', '.join(
  741. map(ISO3166Utils.short2full, e.countries))
  742. msg += '\nYou might want to use a VPN or a proxy server (with --proxy) to workaround.'
  743. self.report_error(msg)
  744. except ExtractorError as e: # An error we somewhat expected
  745. self.report_error(compat_str(e), e.format_traceback())
  746. except MaxDownloadsReached:
  747. raise
  748. except Exception as e:
  749. if self.params.get('ignoreerrors', False):
  750. self.report_error(error_to_compat_str(e), tb=encode_compat_str(traceback.format_exc()))
  751. else:
  752. raise
  753. return wrapper
  754. @__handle_extraction_exceptions
  755. def __extract_info(self, url, ie, download, extra_info, process):
  756. ie_result = ie.extract(url)
  757. if ie_result is None: # Finished already (backwards compatibility; listformats and friends should be moved here)
  758. return
  759. if isinstance(ie_result, list):
  760. # Backwards compatibility: old IE result format
  761. ie_result = {
  762. '_type': 'compat_list',
  763. 'entries': ie_result,
  764. }
  765. self.add_default_extra_info(ie_result, ie, url)
  766. if process:
  767. return self.process_ie_result(ie_result, download, extra_info)
  768. else:
  769. return ie_result
  770. def add_default_extra_info(self, ie_result, ie, url):
  771. self.add_extra_info(ie_result, {
  772. 'extractor': ie.IE_NAME,
  773. 'webpage_url': url,
  774. 'webpage_url_basename': url_basename(url),
  775. 'extractor_key': ie.ie_key(),
  776. })
  777. def process_ie_result(self, ie_result, download=True, extra_info={}):
  778. """
  779. Take the result of the ie(may be modified) and resolve all unresolved
  780. references (URLs, playlist items).
  781. It will also download the videos if 'download'.
  782. Returns the resolved ie_result.
  783. """
  784. result_type = ie_result.get('_type', 'video')
  785. if result_type in ('url', 'url_transparent'):
  786. ie_result['url'] = sanitize_url(ie_result['url'])
  787. extract_flat = self.params.get('extract_flat', False)
  788. if ((extract_flat == 'in_playlist' and 'playlist' in extra_info)
  789. or extract_flat is True):
  790. self.__forced_printings(
  791. ie_result, self.prepare_filename(ie_result),
  792. incomplete=True)
  793. return ie_result
  794. if result_type == 'video':
  795. self.add_extra_info(ie_result, extra_info)
  796. return self.process_video_result(ie_result, download=download)
  797. elif result_type == 'url':
  798. # We have to add extra_info to the results because it may be
  799. # contained in a playlist
  800. return self.extract_info(ie_result['url'],
  801. download,
  802. ie_key=ie_result.get('ie_key'),
  803. extra_info=extra_info)
  804. elif result_type == 'url_transparent':
  805. # Use the information from the embedding page
  806. info = self.extract_info(
  807. ie_result['url'], ie_key=ie_result.get('ie_key'),
  808. extra_info=extra_info, download=False, process=False)
  809. # extract_info may return None when ignoreerrors is enabled and
  810. # extraction failed with an error, don't crash and return early
  811. # in this case
  812. if not info:
  813. return info
  814. force_properties = dict(
  815. (k, v) for k, v in ie_result.items() if v is not None)
  816. for f in ('_type', 'url', 'id', 'extractor', 'extractor_key', 'ie_key'):
  817. if f in force_properties:
  818. del force_properties[f]
  819. new_result = info.copy()
  820. new_result.update(force_properties)
  821. # Extracted info may not be a video result (i.e.
  822. # info.get('_type', 'video') != video) but rather an url or
  823. # url_transparent. In such cases outer metadata (from ie_result)
  824. # should be propagated to inner one (info). For this to happen
  825. # _type of info should be overridden with url_transparent. This
  826. # fixes issue from https://github.com/ytdl-org/youtube-dl/pull/11163.
  827. if new_result.get('_type') == 'url':
  828. new_result['_type'] = 'url_transparent'
  829. return self.process_ie_result(
  830. new_result, download=download, extra_info=extra_info)
  831. elif result_type in ('playlist', 'multi_video'):
  832. # Protect from infinite recursion due to recursively nested playlists
  833. # (see https://github.com/ytdl-org/youtube-dl/issues/27833)
  834. webpage_url = ie_result['webpage_url']
  835. if webpage_url in self._playlist_urls:
  836. self.to_screen(
  837. '[download] Skipping already downloaded playlist: %s'
  838. % ie_result.get('title') or ie_result.get('id'))
  839. return
  840. self._playlist_level += 1
  841. self._playlist_urls.add(webpage_url)
  842. try:
  843. return self.__process_playlist(ie_result, download)
  844. finally:
  845. self._playlist_level -= 1
  846. if not self._playlist_level:
  847. self._playlist_urls.clear()
  848. elif result_type == 'compat_list':
  849. self.report_warning(
  850. 'Extractor %s returned a compat_list result. '
  851. 'It needs to be updated.' % ie_result.get('extractor'))
  852. def _fixup(r):
  853. self.add_extra_info(
  854. r,
  855. {
  856. 'extractor': ie_result['extractor'],
  857. 'webpage_url': ie_result['webpage_url'],
  858. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  859. 'extractor_key': ie_result['extractor_key'],
  860. }
  861. )
  862. return r
  863. ie_result['entries'] = [
  864. self.process_ie_result(_fixup(r), download, extra_info)
  865. for r in ie_result['entries']
  866. ]
  867. return ie_result
  868. else:
  869. raise Exception('Invalid result type: %s' % result_type)
  870. def __process_playlist(self, ie_result, download):
  871. # We process each entry in the playlist
  872. playlist = ie_result.get('title') or ie_result.get('id')
  873. self.to_screen('[download] Downloading playlist: %s' % playlist)
  874. playlist_results = []
  875. playliststart = self.params.get('playliststart', 1) - 1
  876. playlistend = self.params.get('playlistend')
  877. # For backwards compatibility, interpret -1 as whole list
  878. if playlistend == -1:
  879. playlistend = None
  880. playlistitems_str = self.params.get('playlist_items')
  881. playlistitems = None
  882. if playlistitems_str is not None:
  883. def iter_playlistitems(format):
  884. for string_segment in format.split(','):
  885. if '-' in string_segment:
  886. start, end = string_segment.split('-')
  887. for item in range(int(start), int(end) + 1):
  888. yield int(item)
  889. else:
  890. yield int(string_segment)
  891. playlistitems = orderedSet(iter_playlistitems(playlistitems_str))
  892. ie_entries = ie_result['entries']
  893. def make_playlistitems_entries(list_ie_entries):
  894. num_entries = len(list_ie_entries)
  895. return [
  896. list_ie_entries[i - 1] for i in playlistitems
  897. if -num_entries <= i - 1 < num_entries]
  898. def report_download(num_entries):
  899. self.to_screen(
  900. '[%s] playlist %s: Downloading %d videos' %
  901. (ie_result['extractor'], playlist, num_entries))
  902. if isinstance(ie_entries, list):
  903. n_all_entries = len(ie_entries)
  904. if playlistitems:
  905. entries = make_playlistitems_entries(ie_entries)
  906. else:
  907. entries = ie_entries[playliststart:playlistend]
  908. n_entries = len(entries)
  909. self.to_screen(
  910. '[%s] playlist %s: Collected %d video ids (downloading %d of them)' %
  911. (ie_result['extractor'], playlist, n_all_entries, n_entries))
  912. elif isinstance(ie_entries, PagedList):
  913. if playlistitems:
  914. entries = []
  915. for item in playlistitems:
  916. entries.extend(ie_entries.getslice(
  917. item - 1, item
  918. ))
  919. else:
  920. entries = ie_entries.getslice(
  921. playliststart, playlistend)
  922. n_entries = len(entries)
  923. report_download(n_entries)
  924. else: # iterable
  925. if playlistitems:
  926. entries = make_playlistitems_entries(list(itertools.islice(
  927. ie_entries, 0, max(playlistitems))))
  928. else:
  929. entries = list(itertools.islice(
  930. ie_entries, playliststart, playlistend))
  931. n_entries = len(entries)
  932. report_download(n_entries)
  933. if self.params.get('playlistreverse', False):
  934. entries = entries[::-1]
  935. if self.params.get('playlistrandom', False):
  936. random.shuffle(entries)
  937. x_forwarded_for = ie_result.get('__x_forwarded_for_ip')
  938. for i, entry in enumerate(entries, 1):
  939. self.to_screen('[download] Downloading video %s of %s' % (i, n_entries))
  940. # This __x_forwarded_for_ip thing is a bit ugly but requires
  941. # minimal changes
  942. if x_forwarded_for:
  943. entry['__x_forwarded_for_ip'] = x_forwarded_for
  944. extra = {
  945. 'n_entries': n_entries,
  946. 'playlist': playlist,
  947. 'playlist_id': ie_result.get('id'),
  948. 'playlist_title': ie_result.get('title'),
  949. 'playlist_uploader': ie_result.get('uploader'),
  950. 'playlist_uploader_id': ie_result.get('uploader_id'),
  951. 'playlist_index': playlistitems[i - 1] if playlistitems else i + playliststart,
  952. 'extractor': ie_result['extractor'],
  953. 'webpage_url': ie_result['webpage_url'],
  954. 'webpage_url_basename': url_basename(ie_result['webpage_url']),
  955. 'extractor_key': ie_result['extractor_key'],
  956. }
  957. reason = self._match_entry(entry, incomplete=True)
  958. if reason is not None:
  959. self.to_screen('[download] ' + reason)
  960. continue
  961. entry_result = self.__process_iterable_entry(entry, download, extra)
  962. # TODO: skip failed (empty) entries?
  963. playlist_results.append(entry_result)
  964. ie_result['entries'] = playlist_results
  965. self.to_screen('[download] Finished downloading playlist: %s' % playlist)
  966. return ie_result
  967. @__handle_extraction_exceptions
  968. def __process_iterable_entry(self, entry, download, extra_info):
  969. return self.process_ie_result(
  970. entry, download=download, extra_info=extra_info)
  971. def _build_format_filter(self, filter_spec):
  972. " Returns a function to filter the formats according to the filter_spec "
  973. OPERATORS = {
  974. '<': operator.lt,
  975. '<=': operator.le,
  976. '>': operator.gt,
  977. '>=': operator.ge,
  978. '=': operator.eq,
  979. '!=': operator.ne,
  980. }
  981. operator_rex = re.compile(r'''(?x)\s*
  982. (?P<key>width|height|tbr|abr|vbr|asr|filesize|filesize_approx|fps)
  983. \s*(?P<op>%s)(?P<none_inclusive>\s*\?)?\s*
  984. (?P<value>[0-9.]+(?:[kKmMgGtTpPeEzZyY]i?[Bb]?)?)
  985. $
  986. ''' % '|'.join(map(re.escape, OPERATORS.keys())))
  987. m = operator_rex.search(filter_spec)
  988. if m:
  989. try:
  990. comparison_value = int(m.group('value'))
  991. except ValueError:
  992. comparison_value = parse_filesize(m.group('value'))
  993. if comparison_value is None:
  994. comparison_value = parse_filesize(m.group('value') + 'B')
  995. if comparison_value is None:
  996. raise ValueError(
  997. 'Invalid value %r in format specification %r' % (
  998. m.group('value'), filter_spec))
  999. op = OPERATORS[m.group('op')]
  1000. if not m:
  1001. STR_OPERATORS = {
  1002. '=': operator.eq,
  1003. '^=': lambda attr, value: attr.startswith(value),
  1004. '$=': lambda attr, value: attr.endswith(value),
  1005. '*=': lambda attr, value: value in attr,
  1006. }
  1007. str_operator_rex = re.compile(r'''(?x)
  1008. \s*(?P<key>ext|acodec|vcodec|container|protocol|format_id|language)
  1009. \s*(?P<negation>!\s*)?(?P<op>%s)(?P<none_inclusive>\s*\?)?
  1010. \s*(?P<value>[a-zA-Z0-9._-]+)
  1011. \s*$
  1012. ''' % '|'.join(map(re.escape, STR_OPERATORS.keys())))
  1013. m = str_operator_rex.search(filter_spec)
  1014. if m:
  1015. comparison_value = m.group('value')
  1016. str_op = STR_OPERATORS[m.group('op')]
  1017. if m.group('negation'):
  1018. op = lambda attr, value: not str_op(attr, value)
  1019. else:
  1020. op = str_op
  1021. if not m:
  1022. raise ValueError('Invalid filter specification %r' % filter_spec)
  1023. def _filter(f):
  1024. actual_value = f.get(m.group('key'))
  1025. if actual_value is None:
  1026. return m.group('none_inclusive')
  1027. return op(actual_value, comparison_value)
  1028. return _filter
  1029. def _default_format_spec(self, info_dict, download=True):
  1030. def can_merge():
  1031. merger = FFmpegMergerPP(self)
  1032. return merger.available and merger.can_merge()
  1033. def prefer_best():
  1034. if self.params.get('simulate', False):
  1035. return False
  1036. if not download:
  1037. return False
  1038. if self.params.get('outtmpl', DEFAULT_OUTTMPL) == '-':
  1039. return True
  1040. if info_dict.get('is_live'):
  1041. return True
  1042. if not can_merge():
  1043. return True
  1044. return False
  1045. req_format_list = ['bestvideo+bestaudio', 'best']
  1046. if prefer_best():
  1047. req_format_list.reverse()
  1048. return '/'.join(req_format_list)
  1049. def build_format_selector(self, format_spec):
  1050. def syntax_error(note, start):
  1051. message = (
  1052. 'Invalid format specification: '
  1053. '{0}\n\t{1}\n\t{2}^'.format(note, format_spec, ' ' * start[1]))
  1054. return SyntaxError(message)
  1055. PICKFIRST = 'PICKFIRST'
  1056. MERGE = 'MERGE'
  1057. SINGLE = 'SINGLE'
  1058. GROUP = 'GROUP'
  1059. FormatSelector = collections.namedtuple('FormatSelector', ['type', 'selector', 'filters'])
  1060. def _parse_filter(tokens):
  1061. filter_parts = []
  1062. for type, string, start, _, _ in tokens:
  1063. if type == tokenize.OP and string == ']':
  1064. return ''.join(filter_parts)
  1065. else:
  1066. filter_parts.append(string)
  1067. def _remove_unused_ops(tokens):
  1068. # Remove operators that we don't use and join them with the surrounding strings
  1069. # for example: 'mp4' '-' 'baseline' '-' '16x9' is converted to 'mp4-baseline-16x9'
  1070. ALLOWED_OPS = ('/', '+', ',', '(', ')')
  1071. last_string, last_start, last_end, last_line = None, None, None, None
  1072. for type, string, start, end, line in tokens:
  1073. if type == tokenize.OP and string == '[':
  1074. if last_string:
  1075. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1076. last_string = None
  1077. yield type, string, start, end, line
  1078. # everything inside brackets will be handled by _parse_filter
  1079. for type, string, start, end, line in tokens:
  1080. yield type, string, start, end, line
  1081. if type == tokenize.OP and string == ']':
  1082. break
  1083. elif type == tokenize.OP and string in ALLOWED_OPS:
  1084. if last_string:
  1085. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1086. last_string = None
  1087. yield type, string, start, end, line
  1088. elif type in [tokenize.NAME, tokenize.NUMBER, tokenize.OP]:
  1089. if not last_string:
  1090. last_string = string
  1091. last_start = start
  1092. last_end = end
  1093. else:
  1094. last_string += string
  1095. if last_string:
  1096. yield tokenize.NAME, last_string, last_start, last_end, last_line
  1097. def _parse_format_selection(tokens, inside_merge=False, inside_choice=False, inside_group=False):
  1098. selectors = []
  1099. current_selector = None
  1100. for type, string, start, _, _ in tokens:
  1101. # ENCODING is only defined in python 3.x
  1102. if type == getattr(tokenize, 'ENCODING', None):
  1103. continue
  1104. elif type in [tokenize.NAME, tokenize.NUMBER]:
  1105. current_selector = FormatSelector(SINGLE, string, [])
  1106. elif type == tokenize.OP:
  1107. if string == ')':
  1108. if not inside_group:
  1109. # ')' will be handled by the parentheses group
  1110. tokens.restore_last_token()
  1111. break
  1112. elif inside_merge and string in ['/', ',']:
  1113. tokens.restore_last_token()
  1114. break
  1115. elif inside_choice and string == ',':
  1116. tokens.restore_last_token()
  1117. break
  1118. elif string == ',':
  1119. if not current_selector:
  1120. raise syntax_error('"," must follow a format selector', start)
  1121. selectors.append(current_selector)
  1122. current_selector = None
  1123. elif string == '/':
  1124. if not current_selector:
  1125. raise syntax_error('"/" must follow a format selector', start)
  1126. first_choice = current_selector
  1127. second_choice = _parse_format_selection(tokens, inside_choice=True)
  1128. current_selector = FormatSelector(PICKFIRST, (first_choice, second_choice), [])
  1129. elif string == '[':
  1130. if not current_selector:
  1131. current_selector = FormatSelector(SINGLE, 'best', [])
  1132. format_filter = _parse_filter(tokens)
  1133. current_selector.filters.append(format_filter)
  1134. elif string == '(':
  1135. if current_selector:
  1136. raise syntax_error('Unexpected "("', start)
  1137. group = _parse_format_selection(tokens, inside_group=True)
  1138. current_selector = FormatSelector(GROUP, group, [])
  1139. elif string == '+':
  1140. if inside_merge:
  1141. raise syntax_error('Unexpected "+"', start)
  1142. video_selector = current_selector
  1143. audio_selector = _parse_format_selection(tokens, inside_merge=True)
  1144. if not video_selector or not audio_selector:
  1145. raise syntax_error('"+" must be between two format selectors', start)
  1146. current_selector = FormatSelector(MERGE, (video_selector, audio_selector), [])
  1147. else:
  1148. raise syntax_error('Operator not recognized: "{0}"'.format(string), start)
  1149. elif type == tokenize.ENDMARKER:
  1150. break
  1151. if current_selector:
  1152. selectors.append(current_selector)
  1153. return selectors
  1154. def _build_selector_function(selector):
  1155. if isinstance(selector, list):
  1156. fs = [_build_selector_function(s) for s in selector]
  1157. def selector_function(ctx):
  1158. for f in fs:
  1159. for format in f(ctx):
  1160. yield format
  1161. return selector_function
  1162. elif selector.type == GROUP:
  1163. selector_function = _build_selector_function(selector.selector)
  1164. elif selector.type == PICKFIRST:
  1165. fs = [_build_selector_function(s) for s in selector.selector]
  1166. def selector_function(ctx):
  1167. for f in fs:
  1168. picked_formats = list(f(ctx))
  1169. if picked_formats:
  1170. return picked_formats
  1171. return []
  1172. elif selector.type == SINGLE:
  1173. format_spec = selector.selector
  1174. def selector_function(ctx):
  1175. formats = list(ctx['formats'])
  1176. if not formats:
  1177. return
  1178. if format_spec == 'all':
  1179. for f in formats:
  1180. yield f
  1181. elif format_spec in ['best', 'worst', None]:
  1182. format_idx = 0 if format_spec == 'worst' else -1
  1183. audiovideo_formats = [
  1184. f for f in formats
  1185. if f.get('vcodec') != 'none' and f.get('acodec') != 'none']
  1186. if audiovideo_formats:
  1187. yield audiovideo_formats[format_idx]
  1188. # for extractors with incomplete formats (audio only (soundcloud)
  1189. # or video only (imgur)) we will fallback to best/worst
  1190. # {video,audio}-only format
  1191. elif ctx['incomplete_formats']:
  1192. yield formats[format_idx]
  1193. elif format_spec == 'bestaudio':
  1194. audio_formats = [
  1195. f for f in formats
  1196. if f.get('vcodec') == 'none']
  1197. if audio_formats:
  1198. yield audio_formats[-1]
  1199. elif format_spec == 'worstaudio':
  1200. audio_formats = [
  1201. f for f in formats
  1202. if f.get('vcodec') == 'none']
  1203. if audio_formats:
  1204. yield audio_formats[0]
  1205. elif format_spec == 'bestvideo':
  1206. video_formats = [
  1207. f for f in formats
  1208. if f.get('acodec') == 'none']
  1209. if video_formats:
  1210. yield video_formats[-1]
  1211. elif format_spec == 'worstvideo':
  1212. video_formats = [
  1213. f for f in formats
  1214. if f.get('acodec') == 'none']
  1215. if video_formats:
  1216. yield video_formats[0]
  1217. else:
  1218. extensions = ['mp4', 'flv', 'webm', '3gp', 'm4a', 'mp3', 'ogg', 'aac', 'wav']
  1219. if format_spec in extensions:
  1220. filter_f = lambda f: f['ext'] == format_spec
  1221. else:
  1222. filter_f = lambda f: f['format_id'] == format_spec
  1223. matches = list(filter(filter_f, formats))
  1224. if matches:
  1225. yield matches[-1]
  1226. elif selector.type == MERGE:
  1227. def _merge(formats_info):
  1228. format_1, format_2 = [f['format_id'] for f in formats_info]
  1229. # The first format must contain the video and the
  1230. # second the audio
  1231. if formats_info[0].get('vcodec') == 'none':
  1232. self.report_error('The first format must '
  1233. 'contain the video, try using '
  1234. '"-f %s+%s"' % (format_2, format_1))
  1235. return
  1236. # Formats must be opposite (video+audio)
  1237. if formats_info[0].get('acodec') == 'none' and formats_info[1].get('acodec') == 'none':
  1238. self.report_error(
  1239. 'Both formats %s and %s are video-only, you must specify "-f video+audio"'
  1240. % (format_1, format_2))
  1241. return
  1242. output_ext = (
  1243. formats_info[0]['ext']
  1244. if self.params.get('merge_output_format') is None
  1245. else self.params['merge_output_format'])
  1246. return {
  1247. 'requested_formats': formats_info,
  1248. 'format': '%s+%s' % (formats_info[0].get('format'),
  1249. formats_info[1].get('format')),
  1250. 'format_id': '%s+%s' % (formats_info[0].get('format_id'),
  1251. formats_info[1].get('format_id')),
  1252. 'width': formats_info[0].get('width'),
  1253. 'height': formats_info[0].get('height'),
  1254. 'resolution': formats_info[0].get('resolution'),
  1255. 'fps': formats_info[0].get('fps'),
  1256. 'vcodec': formats_info[0].get('vcodec'),
  1257. 'vbr': formats_info[0].get('vbr'),
  1258. 'stretched_ratio': formats_info[0].get('stretched_ratio'),
  1259. 'acodec': formats_info[1].get('acodec'),
  1260. 'abr': formats_info[1].get('abr'),
  1261. 'ext': output_ext,
  1262. }
  1263. video_selector, audio_selector = map(_build_selector_function, selector.selector)
  1264. def selector_function(ctx):
  1265. for pair in itertools.product(
  1266. video_selector(copy.deepcopy(ctx)), audio_selector(copy.deepcopy(ctx))):
  1267. yield _merge(pair)
  1268. filters = [self._build_format_filter(f) for f in selector.filters]
  1269. def final_selector(ctx):
  1270. ctx_copy = copy.deepcopy(ctx)
  1271. for _filter in filters:
  1272. ctx_copy['formats'] = list(filter(_filter, ctx_copy['formats']))
  1273. return selector_function(ctx_copy)
  1274. return final_selector
  1275. stream = io.BytesIO(format_spec.encode('utf-8'))
  1276. try:
  1277. tokens = list(_remove_unused_ops(compat_tokenize_tokenize(stream.readline)))
  1278. except tokenize.TokenError:
  1279. raise syntax_error('Missing closing/opening brackets or parenthesis', (0, len(format_spec)))
  1280. class TokenIterator(object):
  1281. def __init__(self, tokens):
  1282. self.tokens = tokens
  1283. self.counter = 0
  1284. def __iter__(self):
  1285. return self
  1286. def __next__(self):
  1287. if self.counter >= len(self.tokens):
  1288. raise StopIteration()
  1289. value = self.tokens[self.counter]
  1290. self.counter += 1
  1291. return value
  1292. next = __next__
  1293. def restore_last_token(self):
  1294. self.counter -= 1
  1295. parsed_selector = _parse_format_selection(iter(TokenIterator(tokens)))
  1296. return _build_selector_function(parsed_selector)
  1297. def _calc_headers(self, info_dict):
  1298. res = std_headers.copy()
  1299. add_headers = info_dict.get('http_headers')
  1300. if add_headers:
  1301. res.update(add_headers)
  1302. cookies = self._calc_cookies(info_dict)
  1303. if cookies:
  1304. res['Cookie'] = cookies
  1305. if 'X-Forwarded-For' not in res:
  1306. x_forwarded_for_ip = info_dict.get('__x_forwarded_for_ip')
  1307. if x_forwarded_for_ip:
  1308. res['X-Forwarded-For'] = x_forwarded_for_ip
  1309. return res
  1310. def _calc_cookies(self, info_dict):
  1311. pr = sanitized_Request(info_dict['url'])
  1312. self.cookiejar.add_cookie_header(pr)
  1313. return pr.get_header('Cookie')
  1314. def process_video_result(self, info_dict, download=True):
  1315. assert info_dict.get('_type', 'video') == 'video'
  1316. if 'id' not in info_dict:
  1317. raise ExtractorError('Missing "id" field in extractor result')
  1318. if 'title' not in info_dict:
  1319. raise ExtractorError('Missing "title" field in extractor result')
  1320. def report_force_conversion(field, field_not, conversion):
  1321. self.report_warning(
  1322. '"%s" field is not %s - forcing %s conversion, there is an error in extractor'
  1323. % (field, field_not, conversion))
  1324. def sanitize_string_field(info, string_field):
  1325. field = info.get(string_field)
  1326. if field is None or isinstance(field, compat_str):
  1327. return
  1328. report_force_conversion(string_field, 'a string', 'string')
  1329. info[string_field] = compat_str(field)
  1330. def sanitize_numeric_fields(info):
  1331. for numeric_field in self._NUMERIC_FIELDS:
  1332. field = info.get(numeric_field)
  1333. if field is None or isinstance(field, compat_numeric_types):
  1334. continue
  1335. report_force_conversion(numeric_field, 'numeric', 'int')
  1336. info[numeric_field] = int_or_none(field)
  1337. sanitize_string_field(info_dict, 'id')
  1338. sanitize_numeric_fields(info_dict)
  1339. if 'playlist' not in info_dict:
  1340. # It isn't part of a playlist
  1341. info_dict['playlist'] = None
  1342. info_dict['playlist_index'] = None
  1343. thumbnails = info_dict.get('thumbnails')
  1344. if thumbnails is None:
  1345. thumbnail = info_dict.get('thumbnail')
  1346. if thumbnail:
  1347. info_dict['thumbnails'] = thumbnails = [{'url': thumbnail}]
  1348. if thumbnails:
  1349. thumbnails.sort(key=lambda t: (
  1350. t.get('preference') if t.get('preference') is not None else -1,
  1351. t.get('width') if t.get('width') is not None else -1,
  1352. t.get('height') if t.get('height') is not None else -1,
  1353. t.get('id') if t.get('id') is not None else '', t.get('url')))
  1354. for i, t in enumerate(thumbnails):
  1355. t['url'] = sanitize_url(t['url'])
  1356. if t.get('width') and t.get('height'):
  1357. t['resolution'] = '%dx%d' % (t['width'], t['height'])
  1358. if t.get('id') is None:
  1359. t['id'] = '%d' % i
  1360. if self.params.get('list_thumbnails'):
  1361. self.list_thumbnails(info_dict)
  1362. return
  1363. thumbnail = info_dict.get('thumbnail')
  1364. if thumbnail:
  1365. info_dict['thumbnail'] = sanitize_url(thumbnail)
  1366. elif thumbnails:
  1367. info_dict['thumbnail'] = thumbnails[-1]['url']
  1368. if 'display_id' not in info_dict and 'id' in info_dict:
  1369. info_dict['display_id'] = info_dict['id']
  1370. for ts_key, date_key in (
  1371. ('timestamp', 'upload_date'),
  1372. ('release_timestamp', 'release_date'),
  1373. ):
  1374. if info_dict.get(date_key) is None and info_dict.get(ts_key) is not None:
  1375. # Working around out-of-range timestamp values (e.g. negative ones on Windows,
  1376. # see http://bugs.python.org/issue1646728)
  1377. try:
  1378. upload_date = datetime.datetime.utcfromtimestamp(info_dict[ts_key])
  1379. info_dict[date_key] = compat_str(upload_date.strftime('%Y%m%d'))
  1380. except (ValueError, OverflowError, OSError):
  1381. pass
  1382. # Auto generate title fields corresponding to the *_number fields when missing
  1383. # in order to always have clean titles. This is very common for TV series.
  1384. for field in ('chapter', 'season', 'episode'):
  1385. if info_dict.get('%s_number' % field) is not None and not info_dict.get(field):
  1386. info_dict[field] = '%s %d' % (field.capitalize(), info_dict['%s_number' % field])
  1387. for cc_kind in ('subtitles', 'automatic_captions'):
  1388. cc = info_dict.get(cc_kind)
  1389. if cc:
  1390. for _, subtitle in cc.items():
  1391. for subtitle_format in subtitle:
  1392. if subtitle_format.get('url'):
  1393. subtitle_format['url'] = sanitize_url(subtitle_format['url'])
  1394. if subtitle_format.get('ext') is None:
  1395. subtitle_format['ext'] = determine_ext(subtitle_format['url']).lower()
  1396. automatic_captions = info_dict.get('automatic_captions')
  1397. subtitles = info_dict.get('subtitles')
  1398. if self.params.get('listsubtitles', False):
  1399. if 'automatic_captions' in info_dict:
  1400. self.list_subtitles(
  1401. info_dict['id'], automatic_captions, 'automatic captions')
  1402. self.list_subtitles(info_dict['id'], subtitles, 'subtitles')
  1403. return
  1404. info_dict['requested_subtitles'] = self.process_subtitles(
  1405. info_dict['id'], subtitles, automatic_captions)
  1406. # We now pick which formats have to be downloaded
  1407. if info_dict.get('formats') is None:
  1408. # There's only one format available
  1409. formats = [info_dict]
  1410. else:
  1411. formats = info_dict['formats']
  1412. def is_wellformed(f):
  1413. url = f.get('url')
  1414. if not url:
  1415. self.report_warning(
  1416. '"url" field is missing or empty - skipping format, '
  1417. 'there is an error in extractor')
  1418. return False
  1419. if isinstance(url, bytes):
  1420. sanitize_string_field(f, 'url')
  1421. return True
  1422. # Filter out malformed formats for better extraction robustness
  1423. formats = list(filter(is_wellformed, formats or []))
  1424. if not formats:
  1425. raise ExtractorError('No video formats found!')
  1426. formats_dict = {}
  1427. # We check that all the formats have the format and format_id fields
  1428. for i, format in enumerate(formats):
  1429. sanitize_string_field(format, 'format_id')
  1430. sanitize_numeric_fields(format)
  1431. format['url'] = sanitize_url(format['url'])
  1432. if not format.get('format_id'):
  1433. format['format_id'] = compat_str(i)
  1434. else:
  1435. # Sanitize format_id from characters used in format selector expression
  1436. format['format_id'] = re.sub(r'[\s,/+\[\]()]', '_', format['format_id'])
  1437. format_id = format['format_id']
  1438. if format_id not in formats_dict:
  1439. formats_dict[format_id] = []
  1440. formats_dict[format_id].append(format)
  1441. # Make sure all formats have unique format_id
  1442. for format_id, ambiguous_formats in formats_dict.items():
  1443. if len(ambiguous_formats) > 1:
  1444. for i, format in enumerate(ambiguous_formats):
  1445. format['format_id'] = '%s-%d' % (format_id, i)
  1446. for i, format in enumerate(formats):
  1447. if format.get('format') is None:
  1448. format['format'] = '{id} - {res}{note}'.format(
  1449. id=format['format_id'],
  1450. res=self.format_resolution(format),
  1451. note=' ({0})'.format(format['format_note']) if format.get('format_note') is not None else '',
  1452. )
  1453. # Automatically determine file extension if missing
  1454. if format.get('ext') is None:
  1455. format['ext'] = determine_ext(format['url']).lower()
  1456. # Automatically determine protocol if missing (useful for format
  1457. # selection purposes)
  1458. if format.get('protocol') is None:
  1459. format['protocol'] = determine_protocol(format)
  1460. # Add HTTP headers, so that external programs can use them from the
  1461. # json output
  1462. full_format_info = info_dict.copy()
  1463. full_format_info.update(format)
  1464. format['http_headers'] = self._calc_headers(full_format_info)
  1465. # Remove private housekeeping stuff
  1466. if '__x_forwarded_for_ip' in info_dict:
  1467. del info_dict['__x_forwarded_for_ip']
  1468. # TODO Central sorting goes here
  1469. if formats[0] is not info_dict:
  1470. # only set the 'formats' fields if the original info_dict list them
  1471. # otherwise we end up with a circular reference, the first (and unique)
  1472. # element in the 'formats' field in info_dict is info_dict itself,
  1473. # which can't be exported to json
  1474. info_dict['formats'] = formats
  1475. if self.params.get('listformats'):
  1476. self.list_formats(info_dict)
  1477. return
  1478. req_format = self.params.get('format')
  1479. if req_format is None:
  1480. req_format = self._default_format_spec(info_dict, download=download)
  1481. if self.params.get('verbose'):
  1482. self._write_string('[debug] Default format spec: %s\n' % req_format)
  1483. format_selector = self.build_format_selector(req_format)
  1484. # While in format selection we may need to have an access to the original
  1485. # format set in order to calculate some metrics or do some processing.
  1486. # For now we need to be able to guess whether original formats provided
  1487. # by extractor are incomplete or not (i.e. whether extractor provides only
  1488. # video-only or audio-only formats) for proper formats selection for
  1489. # extractors with such incomplete formats (see
  1490. # https://github.com/ytdl-org/youtube-dl/pull/5556).
  1491. # Since formats may be filtered during format selection and may not match
  1492. # the original formats the results may be incorrect. Thus original formats
  1493. # or pre-calculated metrics should be passed to format selection routines
  1494. # as well.
  1495. # We will pass a context object containing all necessary additional data
  1496. # instead of just formats.
  1497. # This fixes incorrect format selection issue (see
  1498. # https://github.com/ytdl-org/youtube-dl/issues/10083).
  1499. incomplete_formats = (
  1500. # All formats are video-only or
  1501. all(f.get('vcodec') != 'none' and f.get('acodec') == 'none' for f in formats)
  1502. # all formats are audio-only
  1503. or all(f.get('vcodec') == 'none' and f.get('acodec') != 'none' for f in formats))
  1504. ctx = {
  1505. 'formats': formats,
  1506. 'incomplete_formats': incomplete_formats,
  1507. }
  1508. formats_to_download = list(format_selector(ctx))
  1509. if not formats_to_download:
  1510. raise ExtractorError('requested format not available',
  1511. expected=True)
  1512. if download:
  1513. if len(formats_to_download) > 1:
  1514. self.to_screen('[info] %s: downloading video in %s formats' % (info_dict['id'], len(formats_to_download)))
  1515. for format in formats_to_download:
  1516. new_info = dict(info_dict)
  1517. new_info.update(format)
  1518. self.process_info(new_info)
  1519. # We update the info dict with the best quality format (backwards compatibility)
  1520. info_dict.update(formats_to_download[-1])
  1521. return info_dict
  1522. def process_subtitles(self, video_id, normal_subtitles, automatic_captions):
  1523. """Select the requested subtitles and their format"""
  1524. available_subs = {}
  1525. if normal_subtitles and self.params.get('writesubtitles'):
  1526. available_subs.update(normal_subtitles)
  1527. if automatic_captions and self.params.get('writeautomaticsub'):
  1528. for lang, cap_info in automatic_captions.items():
  1529. if lang not in available_subs:
  1530. available_subs[lang] = cap_info
  1531. if (not self.params.get('writesubtitles') and not
  1532. self.params.get('writeautomaticsub') or not
  1533. available_subs):
  1534. return None
  1535. if self.params.get('allsubtitles', False):
  1536. requested_langs = available_subs.keys()
  1537. else:
  1538. if self.params.get('subtitleslangs', False):
  1539. requested_langs = self.params.get('subtitleslangs')
  1540. elif 'en' in available_subs:
  1541. requested_langs = ['en']
  1542. else:
  1543. requested_langs = [list(available_subs.keys())[0]]
  1544. formats_query = self.params.get('subtitlesformat', 'best')
  1545. formats_preference = formats_query.split('/') if formats_query else []
  1546. subs = {}
  1547. for lang in requested_langs:
  1548. formats = available_subs.get(lang)
  1549. if formats is None:
  1550. self.report_warning('%s subtitles not available for %s' % (lang, video_id))
  1551. continue
  1552. for ext in formats_preference:
  1553. if ext == 'best':
  1554. f = formats[-1]
  1555. break
  1556. matches = list(filter(lambda f: f['ext'] == ext, formats))
  1557. if matches:
  1558. f = matches[-1]
  1559. break
  1560. else:
  1561. f = formats[-1]
  1562. self.report_warning(
  1563. 'No subtitle format found matching "%s" for language %s, '
  1564. 'using %s' % (formats_query, lang, f['ext']))
  1565. subs[lang] = f
  1566. return subs
  1567. def __forced_printings(self, info_dict, filename, incomplete):
  1568. def print_mandatory(field):
  1569. if (self.params.get('force%s' % field, False)
  1570. and (not incomplete or info_dict.get(field) is not None)):
  1571. self.to_stdout(info_dict[field])
  1572. def print_optional(field):
  1573. if (self.params.get('force%s' % field, False)
  1574. and info_dict.get(field) is not None):
  1575. self.to_stdout(info_dict[field])
  1576. print_mandatory('title')
  1577. print_mandatory('id')
  1578. if self.params.get('forceurl', False) and not incomplete:
  1579. if info_dict.get('requested_formats') is not None:
  1580. for f in info_dict['requested_formats']:
  1581. self.to_stdout(f['url'] + f.get('play_path', ''))
  1582. else:
  1583. # For RTMP URLs, also include the playpath
  1584. self.to_stdout(info_dict['url'] + info_dict.get('play_path', ''))
  1585. print_optional('thumbnail')
  1586. print_optional('description')
  1587. if self.params.get('forcefilename', False) and filename is not None:
  1588. self.to_stdout(filename)
  1589. if self.params.get('forceduration', False) and info_dict.get('duration') is not None:
  1590. self.to_stdout(formatSeconds(info_dict['duration']))
  1591. print_mandatory('format')
  1592. if self.params.get('forcejson', False):
  1593. self.to_stdout(json.dumps(info_dict))
  1594. def process_info(self, info_dict):
  1595. """Process a single resolved IE result."""
  1596. assert info_dict.get('_type', 'video') == 'video'
  1597. max_downloads = int_or_none(self.params.get('max_downloads')) or float('inf')
  1598. if self._num_downloads >= max_downloads:
  1599. raise MaxDownloadsReached()
  1600. # TODO: backward compatibility, to be removed
  1601. info_dict['fulltitle'] = info_dict['title']
  1602. if 'format' not in info_dict:
  1603. info_dict['format'] = info_dict['ext']
  1604. reason = self._match_entry(info_dict, incomplete=False)
  1605. if reason is not None:
  1606. self.to_screen('[download] ' + reason)
  1607. return
  1608. self._num_downloads += 1
  1609. info_dict['_filename'] = filename = self.prepare_filename(info_dict)
  1610. # Forced printings
  1611. self.__forced_printings(info_dict, filename, incomplete=False)
  1612. # Do nothing else if in simulate mode
  1613. if self.params.get('simulate', False):
  1614. return
  1615. if filename is None:
  1616. return
  1617. def ensure_dir_exists(path):
  1618. try:
  1619. dn = os.path.dirname(path)
  1620. if dn and not os.path.exists(dn):
  1621. os.makedirs(dn)
  1622. return True
  1623. except (OSError, IOError) as err:
  1624. if isinstance(err, OSError) and err.errno == errno.EEXIST:
  1625. return True
  1626. self.report_error('unable to create directory ' + error_to_compat_str(err))
  1627. return False
  1628. if not ensure_dir_exists(sanitize_path(encodeFilename(filename))):
  1629. return
  1630. if self.params.get('writedescription', False):
  1631. descfn = replace_extension(filename, 'description', info_dict.get('ext'))
  1632. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(descfn)):
  1633. self.to_screen('[info] Video description is already present')
  1634. elif info_dict.get('description') is None:
  1635. self.report_warning('There\'s no description to write.')
  1636. else:
  1637. try:
  1638. self.to_screen('[info] Writing video description to: ' + descfn)
  1639. with io.open(encodeFilename(descfn), 'w', encoding='utf-8') as descfile:
  1640. descfile.write(info_dict['description'])
  1641. except (OSError, IOError):
  1642. self.report_error('Cannot write description file ' + descfn)
  1643. return
  1644. if self.params.get('writeannotations', False):
  1645. annofn = replace_extension(filename, 'annotations.xml', info_dict.get('ext'))
  1646. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(annofn)):
  1647. self.to_screen('[info] Video annotations are already present')
  1648. elif not info_dict.get('annotations'):
  1649. self.report_warning('There are no annotations to write.')
  1650. else:
  1651. try:
  1652. self.to_screen('[info] Writing video annotations to: ' + annofn)
  1653. with io.open(encodeFilename(annofn), 'w', encoding='utf-8') as annofile:
  1654. annofile.write(info_dict['annotations'])
  1655. except (KeyError, TypeError):
  1656. self.report_warning('There are no annotations to write.')
  1657. except (OSError, IOError):
  1658. self.report_error('Cannot write annotations file: ' + annofn)
  1659. return
  1660. subtitles_are_requested = any([self.params.get('writesubtitles', False),
  1661. self.params.get('writeautomaticsub')])
  1662. if subtitles_are_requested and info_dict.get('requested_subtitles'):
  1663. # subtitles download errors are already managed as troubles in relevant IE
  1664. # that way it will silently go on when used with unsupporting IE
  1665. subtitles = info_dict['requested_subtitles']
  1666. ie = self.get_info_extractor(info_dict['extractor_key'])
  1667. for sub_lang, sub_info in subtitles.items():
  1668. sub_format = sub_info['ext']
  1669. sub_filename = subtitles_filename(filename, sub_lang, sub_format, info_dict.get('ext'))
  1670. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(sub_filename)):
  1671. self.to_screen('[info] Video subtitle %s.%s is already present' % (sub_lang, sub_format))
  1672. else:
  1673. self.to_screen('[info] Writing video subtitles to: ' + sub_filename)
  1674. if sub_info.get('data') is not None:
  1675. try:
  1676. # Use newline='' to prevent conversion of newline characters
  1677. # See https://github.com/ytdl-org/youtube-dl/issues/10268
  1678. with io.open(encodeFilename(sub_filename), 'w', encoding='utf-8', newline='') as subfile:
  1679. subfile.write(sub_info['data'])
  1680. except (OSError, IOError):
  1681. self.report_error('Cannot write subtitles file ' + sub_filename)
  1682. return
  1683. else:
  1684. try:
  1685. sub_data = ie._request_webpage(
  1686. sub_info['url'], info_dict['id'], note=False).read()
  1687. with io.open(encodeFilename(sub_filename), 'wb') as subfile:
  1688. subfile.write(sub_data)
  1689. except (ExtractorError, IOError, OSError, ValueError) as err:
  1690. self.report_warning('Unable to download subtitle for "%s": %s' %
  1691. (sub_lang, error_to_compat_str(err)))
  1692. continue
  1693. if self.params.get('writeinfojson', False):
  1694. infofn = replace_extension(filename, 'info.json', info_dict.get('ext'))
  1695. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(infofn)):
  1696. self.to_screen('[info] Video description metadata is already present')
  1697. else:
  1698. self.to_screen('[info] Writing video description metadata as JSON to: ' + infofn)
  1699. try:
  1700. write_json_file(self.filter_requested_info(info_dict), infofn)
  1701. except (OSError, IOError):
  1702. self.report_error('Cannot write metadata to JSON file ' + infofn)
  1703. return
  1704. self._write_thumbnails(info_dict, filename)
  1705. if not self.params.get('skip_download', False):
  1706. try:
  1707. def checked_get_suitable_downloader(info_dict, params):
  1708. ed_args = params.get('external_downloader_args')
  1709. dler = get_suitable_downloader(info_dict, params)
  1710. if ed_args and not params.get('external_downloader_args'):
  1711. # external_downloader_args was cleared because external_downloader was rejected
  1712. self.report_warning('Requested external downloader cannot be used: '
  1713. 'ignoring --external-downloader-args.')
  1714. return dler
  1715. def dl(name, info):
  1716. fd = checked_get_suitable_downloader(info, self.params)(self, self.params)
  1717. for ph in self._progress_hooks:
  1718. fd.add_progress_hook(ph)
  1719. if self.params.get('verbose'):
  1720. self.to_screen('[debug] Invoking downloader on %r' % info.get('url'))
  1721. return fd.download(name, info)
  1722. if info_dict.get('requested_formats') is not None:
  1723. downloaded = []
  1724. success = True
  1725. merger = FFmpegMergerPP(self)
  1726. if not merger.available:
  1727. postprocessors = []
  1728. self.report_warning('You have requested multiple '
  1729. 'formats but ffmpeg or avconv are not installed.'
  1730. ' The formats won\'t be merged.')
  1731. else:
  1732. postprocessors = [merger]
  1733. def compatible_formats(formats):
  1734. video, audio = formats
  1735. # Check extension
  1736. video_ext, audio_ext = video.get('ext'), audio.get('ext')
  1737. if video_ext and audio_ext:
  1738. COMPATIBLE_EXTS = (
  1739. ('mp3', 'mp4', 'm4a', 'm4p', 'm4b', 'm4r', 'm4v', 'ismv', 'isma'),
  1740. ('webm')
  1741. )
  1742. for exts in COMPATIBLE_EXTS:
  1743. if video_ext in exts and audio_ext in exts:
  1744. return True
  1745. # TODO: Check acodec/vcodec
  1746. return False
  1747. filename_real_ext = os.path.splitext(filename)[1][1:]
  1748. filename_wo_ext = (
  1749. os.path.splitext(filename)[0]
  1750. if filename_real_ext == info_dict['ext']
  1751. else filename)
  1752. requested_formats = info_dict['requested_formats']
  1753. if self.params.get('merge_output_format') is None and not compatible_formats(requested_formats):
  1754. info_dict['ext'] = 'mkv'
  1755. self.report_warning(
  1756. 'Requested formats are incompatible for merge and will be merged into mkv.')
  1757. # Ensure filename always has a correct extension for successful merge
  1758. filename = '%s.%s' % (filename_wo_ext, info_dict['ext'])
  1759. if os.path.exists(encodeFilename(filename)):
  1760. self.to_screen(
  1761. '[download] %s has already been downloaded and '
  1762. 'merged' % filename)
  1763. else:
  1764. for f in requested_formats:
  1765. new_info = dict(info_dict)
  1766. new_info.update(f)
  1767. fname = prepend_extension(
  1768. self.prepare_filename(new_info),
  1769. 'f%s' % f['format_id'], new_info['ext'])
  1770. if not ensure_dir_exists(fname):
  1771. return
  1772. downloaded.append(fname)
  1773. partial_success = dl(fname, new_info)
  1774. success = success and partial_success
  1775. info_dict['__postprocessors'] = postprocessors
  1776. info_dict['__files_to_merge'] = downloaded
  1777. else:
  1778. # Just a single file
  1779. success = dl(filename, info_dict)
  1780. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  1781. self.report_error('unable to download video data: %s' % error_to_compat_str(err))
  1782. return
  1783. except (OSError, IOError) as err:
  1784. raise UnavailableVideoError(err)
  1785. except (ContentTooShortError, ) as err:
  1786. self.report_error('content too short (expected %s bytes and served %s)' % (err.expected, err.downloaded))
  1787. return
  1788. if success and filename != '-':
  1789. # Fixup content
  1790. fixup_policy = self.params.get('fixup')
  1791. if fixup_policy is None:
  1792. fixup_policy = 'detect_or_warn'
  1793. INSTALL_FFMPEG_MESSAGE = 'Install ffmpeg or avconv to fix this automatically.'
  1794. stretched_ratio = info_dict.get('stretched_ratio')
  1795. if stretched_ratio is not None and stretched_ratio != 1:
  1796. if fixup_policy == 'warn':
  1797. self.report_warning('%s: Non-uniform pixel ratio (%s)' % (
  1798. info_dict['id'], stretched_ratio))
  1799. elif fixup_policy == 'detect_or_warn':
  1800. stretched_pp = FFmpegFixupStretchedPP(self)
  1801. if stretched_pp.available:
  1802. info_dict.setdefault('__postprocessors', [])
  1803. info_dict['__postprocessors'].append(stretched_pp)
  1804. else:
  1805. self.report_warning(
  1806. '%s: Non-uniform pixel ratio (%s). %s'
  1807. % (info_dict['id'], stretched_ratio, INSTALL_FFMPEG_MESSAGE))
  1808. else:
  1809. assert fixup_policy in ('ignore', 'never')
  1810. if (info_dict.get('requested_formats') is None
  1811. and info_dict.get('container') == 'm4a_dash'):
  1812. if fixup_policy == 'warn':
  1813. self.report_warning(
  1814. '%s: writing DASH m4a. '
  1815. 'Only some players support this container.'
  1816. % info_dict['id'])
  1817. elif fixup_policy == 'detect_or_warn':
  1818. fixup_pp = FFmpegFixupM4aPP(self)
  1819. if fixup_pp.available:
  1820. info_dict.setdefault('__postprocessors', [])
  1821. info_dict['__postprocessors'].append(fixup_pp)
  1822. else:
  1823. self.report_warning(
  1824. '%s: writing DASH m4a. '
  1825. 'Only some players support this container. %s'
  1826. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1827. else:
  1828. assert fixup_policy in ('ignore', 'never')
  1829. if (info_dict.get('protocol') == 'm3u8_native'
  1830. or info_dict.get('protocol') == 'm3u8'
  1831. and self.params.get('hls_prefer_native')):
  1832. if fixup_policy == 'warn':
  1833. self.report_warning('%s: malformed AAC bitstream detected.' % (
  1834. info_dict['id']))
  1835. elif fixup_policy == 'detect_or_warn':
  1836. fixup_pp = FFmpegFixupM3u8PP(self)
  1837. if fixup_pp.available:
  1838. info_dict.setdefault('__postprocessors', [])
  1839. info_dict['__postprocessors'].append(fixup_pp)
  1840. else:
  1841. self.report_warning(
  1842. '%s: malformed AAC bitstream detected. %s'
  1843. % (info_dict['id'], INSTALL_FFMPEG_MESSAGE))
  1844. else:
  1845. assert fixup_policy in ('ignore', 'never')
  1846. try:
  1847. self.post_process(filename, info_dict)
  1848. except (PostProcessingError) as err:
  1849. self.report_error('postprocessing: %s' % error_to_compat_str(err))
  1850. return
  1851. self.record_download_archive(info_dict)
  1852. # avoid possible nugatory search for further items (PR #26638)
  1853. if self._num_downloads >= max_downloads:
  1854. raise MaxDownloadsReached()
  1855. def download(self, url_list):
  1856. """Download a given list of URLs."""
  1857. outtmpl = self.params.get('outtmpl', DEFAULT_OUTTMPL)
  1858. if (len(url_list) > 1
  1859. and outtmpl != '-'
  1860. and '%' not in outtmpl
  1861. and self.params.get('max_downloads') != 1):
  1862. raise SameFileError(outtmpl)
  1863. for url in url_list:
  1864. try:
  1865. # It also downloads the videos
  1866. res = self.extract_info(
  1867. url, force_generic_extractor=self.params.get('force_generic_extractor', False))
  1868. except UnavailableVideoError:
  1869. self.report_error('unable to download video')
  1870. except MaxDownloadsReached:
  1871. self.to_screen('[info] Maximum number of downloaded files reached.')
  1872. raise
  1873. else:
  1874. if self.params.get('dump_single_json', False):
  1875. self.to_stdout(json.dumps(res))
  1876. return self._download_retcode
  1877. def download_with_info_file(self, info_filename):
  1878. with contextlib.closing(fileinput.FileInput(
  1879. [info_filename], mode='r',
  1880. openhook=fileinput.hook_encoded('utf-8'))) as f:
  1881. # FileInput doesn't have a read method, we can't call json.load
  1882. info = self.filter_requested_info(json.loads('\n'.join(f)))
  1883. try:
  1884. self.process_ie_result(info, download=True)
  1885. except DownloadError:
  1886. webpage_url = info.get('webpage_url')
  1887. if webpage_url is not None:
  1888. self.report_warning('The info failed to download, trying with "%s"' % webpage_url)
  1889. return self.download([webpage_url])
  1890. else:
  1891. raise
  1892. return self._download_retcode
  1893. @staticmethod
  1894. def filter_requested_info(info_dict):
  1895. return dict(
  1896. (k, v) for k, v in info_dict.items()
  1897. if k not in ['requested_formats', 'requested_subtitles'])
  1898. def post_process(self, filename, ie_info):
  1899. """Run all the postprocessors on the given file."""
  1900. info = dict(ie_info)
  1901. info['filepath'] = filename
  1902. pps_chain = []
  1903. if ie_info.get('__postprocessors') is not None:
  1904. pps_chain.extend(ie_info['__postprocessors'])
  1905. pps_chain.extend(self._pps)
  1906. for pp in pps_chain:
  1907. files_to_delete = []
  1908. try:
  1909. files_to_delete, info = pp.run(info)
  1910. except PostProcessingError as e:
  1911. self.report_error(e.msg)
  1912. if files_to_delete and not self.params.get('keepvideo', False):
  1913. for old_filename in files_to_delete:
  1914. self.to_screen('Deleting original file %s (pass -k to keep)' % old_filename)
  1915. try:
  1916. os.remove(encodeFilename(old_filename))
  1917. except (IOError, OSError):
  1918. self.report_warning('Unable to remove downloaded original file')
  1919. def _make_archive_id(self, info_dict):
  1920. video_id = info_dict.get('id')
  1921. if not video_id:
  1922. return
  1923. # Future-proof against any change in case
  1924. # and backwards compatibility with prior versions
  1925. extractor = info_dict.get('extractor_key') or info_dict.get('ie_key') # key in a playlist
  1926. if extractor is None:
  1927. url = str_or_none(info_dict.get('url'))
  1928. if not url:
  1929. return
  1930. # Try to find matching extractor for the URL and take its ie_key
  1931. for ie in self._ies:
  1932. if ie.suitable(url):
  1933. extractor = ie.ie_key()
  1934. break
  1935. else:
  1936. return
  1937. return extractor.lower() + ' ' + video_id
  1938. def in_download_archive(self, info_dict):
  1939. fn = self.params.get('download_archive')
  1940. if fn is None:
  1941. return False
  1942. vid_id = self._make_archive_id(info_dict)
  1943. if not vid_id:
  1944. return False # Incomplete video information
  1945. try:
  1946. with locked_file(fn, 'r', encoding='utf-8') as archive_file:
  1947. for line in archive_file:
  1948. if line.strip() == vid_id:
  1949. return True
  1950. except IOError as ioe:
  1951. if ioe.errno != errno.ENOENT:
  1952. raise
  1953. return False
  1954. def record_download_archive(self, info_dict):
  1955. fn = self.params.get('download_archive')
  1956. if fn is None:
  1957. return
  1958. vid_id = self._make_archive_id(info_dict)
  1959. assert vid_id
  1960. with locked_file(fn, 'a', encoding='utf-8') as archive_file:
  1961. archive_file.write(vid_id + '\n')
  1962. @staticmethod
  1963. def format_resolution(format, default='unknown'):
  1964. if format.get('vcodec') == 'none':
  1965. return 'audio only'
  1966. if format.get('resolution') is not None:
  1967. return format['resolution']
  1968. if format.get('height') is not None:
  1969. if format.get('width') is not None:
  1970. res = '%sx%s' % (format['width'], format['height'])
  1971. else:
  1972. res = '%sp' % format['height']
  1973. elif format.get('width') is not None:
  1974. res = '%dx?' % format['width']
  1975. else:
  1976. res = default
  1977. return res
  1978. def _format_note(self, fdict):
  1979. res = ''
  1980. if fdict.get('ext') in ['f4f', 'f4m']:
  1981. res += '(unsupported) '
  1982. if fdict.get('language'):
  1983. if res:
  1984. res += ' '
  1985. res += '[%s] ' % fdict['language']
  1986. if fdict.get('format_note') is not None:
  1987. res += fdict['format_note'] + ' '
  1988. if fdict.get('tbr') is not None:
  1989. res += '%4dk ' % fdict['tbr']
  1990. if fdict.get('container') is not None:
  1991. if res:
  1992. res += ', '
  1993. res += '%s container' % fdict['container']
  1994. if (fdict.get('vcodec') is not None
  1995. and fdict.get('vcodec') != 'none'):
  1996. if res:
  1997. res += ', '
  1998. res += fdict['vcodec']
  1999. if fdict.get('vbr') is not None:
  2000. res += '@'
  2001. elif fdict.get('vbr') is not None and fdict.get('abr') is not None:
  2002. res += 'video@'
  2003. if fdict.get('vbr') is not None:
  2004. res += '%4dk' % fdict['vbr']
  2005. if fdict.get('fps') is not None:
  2006. if res:
  2007. res += ', '
  2008. res += '%sfps' % fdict['fps']
  2009. if fdict.get('acodec') is not None:
  2010. if res:
  2011. res += ', '
  2012. if fdict['acodec'] == 'none':
  2013. res += 'video only'
  2014. else:
  2015. res += '%-5s' % fdict['acodec']
  2016. elif fdict.get('abr') is not None:
  2017. if res:
  2018. res += ', '
  2019. res += 'audio'
  2020. if fdict.get('abr') is not None:
  2021. res += '@%3dk' % fdict['abr']
  2022. if fdict.get('asr') is not None:
  2023. res += ' (%5dHz)' % fdict['asr']
  2024. if fdict.get('filesize') is not None:
  2025. if res:
  2026. res += ', '
  2027. res += format_bytes(fdict['filesize'])
  2028. elif fdict.get('filesize_approx') is not None:
  2029. if res:
  2030. res += ', '
  2031. res += '~' + format_bytes(fdict['filesize_approx'])
  2032. return res
  2033. def list_formats(self, info_dict):
  2034. formats = info_dict.get('formats', [info_dict])
  2035. table = [
  2036. [f['format_id'], f['ext'], self.format_resolution(f), self._format_note(f)]
  2037. for f in formats
  2038. if f.get('preference') is None or f['preference'] >= -1000]
  2039. if len(formats) > 1:
  2040. table[-1][-1] += (' ' if table[-1][-1] else '') + '(best)'
  2041. header_line = ['format code', 'extension', 'resolution', 'note']
  2042. self.to_screen(
  2043. '[info] Available formats for %s:\n%s' %
  2044. (info_dict['id'], render_table(header_line, table)))
  2045. def list_thumbnails(self, info_dict):
  2046. thumbnails = info_dict.get('thumbnails')
  2047. if not thumbnails:
  2048. self.to_screen('[info] No thumbnails present for %s' % info_dict['id'])
  2049. return
  2050. self.to_screen(
  2051. '[info] Thumbnails for %s:' % info_dict['id'])
  2052. self.to_screen(render_table(
  2053. ['ID', 'width', 'height', 'URL'],
  2054. [[t['id'], t.get('width', 'unknown'), t.get('height', 'unknown'), t['url']] for t in thumbnails]))
  2055. def list_subtitles(self, video_id, subtitles, name='subtitles'):
  2056. if not subtitles:
  2057. self.to_screen('%s has no %s' % (video_id, name))
  2058. return
  2059. self.to_screen(
  2060. 'Available %s for %s:' % (name, video_id))
  2061. self.to_screen(render_table(
  2062. ['Language', 'formats'],
  2063. [[lang, ', '.join(f['ext'] for f in reversed(formats))]
  2064. for lang, formats in subtitles.items()]))
  2065. def urlopen(self, req):
  2066. """ Start an HTTP download """
  2067. if isinstance(req, compat_basestring):
  2068. req = sanitized_Request(req)
  2069. return self._opener.open(req, timeout=self._socket_timeout)
  2070. def print_debug_header(self):
  2071. if not self.params.get('verbose'):
  2072. return
  2073. if type('') is not compat_str:
  2074. # Python 2.6 on SLES11 SP1 (https://github.com/ytdl-org/youtube-dl/issues/3326)
  2075. self.report_warning(
  2076. 'Your Python is broken! Update to a newer and supported version')
  2077. stdout_encoding = getattr(
  2078. sys.stdout, 'encoding', 'missing (%s)' % type(sys.stdout).__name__)
  2079. encoding_str = (
  2080. '[debug] Encodings: locale %s, fs %s, out %s, pref %s\n' % (
  2081. locale.getpreferredencoding(),
  2082. sys.getfilesystemencoding(),
  2083. stdout_encoding,
  2084. self.get_encoding()))
  2085. write_string(encoding_str, encoding=None)
  2086. self._write_string('[debug] youtube-dl version ' + __version__ + '\n')
  2087. if _LAZY_LOADER:
  2088. self._write_string('[debug] Lazy loading extractors enabled' + '\n')
  2089. try:
  2090. sp = subprocess.Popen(
  2091. ['git', 'rev-parse', '--short', 'HEAD'],
  2092. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  2093. cwd=os.path.dirname(os.path.abspath(__file__)))
  2094. out, err = process_communicate_or_kill(sp)
  2095. out = out.decode().strip()
  2096. if re.match('[0-9a-f]+', out):
  2097. self._write_string('[debug] Git HEAD: ' + out + '\n')
  2098. except Exception:
  2099. try:
  2100. sys.exc_clear()
  2101. except Exception:
  2102. pass
  2103. def python_implementation():
  2104. impl_name = platform.python_implementation()
  2105. if impl_name == 'PyPy' and hasattr(sys, 'pypy_version_info'):
  2106. return impl_name + ' version %d.%d.%d' % sys.pypy_version_info[:3]
  2107. return impl_name
  2108. self._write_string('[debug] Python version %s (%s) - %s\n' % (
  2109. platform.python_version(), python_implementation(),
  2110. platform_name()))
  2111. exe_versions = FFmpegPostProcessor.get_versions(self)
  2112. exe_versions['rtmpdump'] = rtmpdump_version()
  2113. exe_versions['phantomjs'] = PhantomJSwrapper._version()
  2114. exe_str = ', '.join(
  2115. '%s %s' % (exe, v)
  2116. for exe, v in sorted(exe_versions.items())
  2117. if v
  2118. )
  2119. if not exe_str:
  2120. exe_str = 'none'
  2121. self._write_string('[debug] exe versions: %s\n' % exe_str)
  2122. proxy_map = {}
  2123. for handler in self._opener.handlers:
  2124. if hasattr(handler, 'proxies'):
  2125. proxy_map.update(handler.proxies)
  2126. self._write_string('[debug] Proxy map: ' + compat_str(proxy_map) + '\n')
  2127. if self.params.get('call_home', False):
  2128. ipaddr = self.urlopen('https://yt-dl.org/ip').read().decode('utf-8')
  2129. self._write_string('[debug] Public IP address: %s\n' % ipaddr)
  2130. latest_version = self.urlopen(
  2131. 'https://yt-dl.org/latest/version').read().decode('utf-8')
  2132. if version_tuple(latest_version) > version_tuple(__version__):
  2133. self.report_warning(
  2134. 'You are using an outdated version (newest version: %s)! '
  2135. 'See https://yt-dl.org/update if you need help updating.' %
  2136. latest_version)
  2137. def _setup_opener(self):
  2138. timeout_val = self.params.get('socket_timeout')
  2139. self._socket_timeout = 600 if timeout_val is None else float(timeout_val)
  2140. opts_cookiefile = self.params.get('cookiefile')
  2141. opts_proxy = self.params.get('proxy')
  2142. if opts_cookiefile is None:
  2143. self.cookiejar = compat_cookiejar.CookieJar()
  2144. else:
  2145. opts_cookiefile = expand_path(opts_cookiefile)
  2146. self.cookiejar = YoutubeDLCookieJar(opts_cookiefile)
  2147. if os.access(opts_cookiefile, os.R_OK):
  2148. self.cookiejar.load(ignore_discard=True, ignore_expires=True)
  2149. cookie_processor = YoutubeDLCookieProcessor(self.cookiejar)
  2150. if opts_proxy is not None:
  2151. if opts_proxy == '':
  2152. proxies = {}
  2153. else:
  2154. proxies = {'http': opts_proxy, 'https': opts_proxy}
  2155. else:
  2156. proxies = compat_urllib_request.getproxies()
  2157. # Set HTTPS proxy to HTTP one if given (https://github.com/ytdl-org/youtube-dl/issues/805)
  2158. if 'http' in proxies and 'https' not in proxies:
  2159. proxies['https'] = proxies['http']
  2160. proxy_handler = PerRequestProxyHandler(proxies)
  2161. debuglevel = 1 if self.params.get('debug_printtraffic') else 0
  2162. https_handler = make_HTTPS_handler(self.params, debuglevel=debuglevel)
  2163. ydlh = YoutubeDLHandler(self.params, debuglevel=debuglevel)
  2164. redirect_handler = YoutubeDLRedirectHandler()
  2165. data_handler = compat_urllib_request_DataHandler()
  2166. # When passing our own FileHandler instance, build_opener won't add the
  2167. # default FileHandler and allows us to disable the file protocol, which
  2168. # can be used for malicious purposes (see
  2169. # https://github.com/ytdl-org/youtube-dl/issues/8227)
  2170. file_handler = compat_urllib_request.FileHandler()
  2171. def file_open(*args, **kwargs):
  2172. raise compat_urllib_error.URLError('file:// scheme is explicitly disabled in youtube-dl for security reasons')
  2173. file_handler.file_open = file_open
  2174. opener = compat_urllib_request.build_opener(
  2175. proxy_handler, https_handler, cookie_processor, ydlh, redirect_handler, data_handler, file_handler)
  2176. # Delete the default user-agent header, which would otherwise apply in
  2177. # cases where our custom HTTP handler doesn't come into play
  2178. # (See https://github.com/ytdl-org/youtube-dl/issues/1309 for details)
  2179. opener.addheaders = []
  2180. self._opener = opener
  2181. def encode(self, s):
  2182. if isinstance(s, bytes):
  2183. return s # Already encoded
  2184. try:
  2185. return s.encode(self.get_encoding())
  2186. except UnicodeEncodeError as err:
  2187. err.reason = err.reason + '. Check your system encoding configuration or use the --encoding option.'
  2188. raise
  2189. def get_encoding(self):
  2190. encoding = self.params.get('encoding')
  2191. if encoding is None:
  2192. encoding = preferredencoding()
  2193. return encoding
  2194. def _write_thumbnails(self, info_dict, filename):
  2195. if self.params.get('writethumbnail', False):
  2196. thumbnails = info_dict.get('thumbnails')
  2197. if thumbnails:
  2198. thumbnails = [thumbnails[-1]]
  2199. elif self.params.get('write_all_thumbnails', False):
  2200. thumbnails = info_dict.get('thumbnails')
  2201. else:
  2202. return
  2203. if not thumbnails:
  2204. # No thumbnails present, so return immediately
  2205. return
  2206. for t in thumbnails:
  2207. thumb_ext = determine_ext(t['url'], 'jpg')
  2208. suffix = '_%s' % t['id'] if len(thumbnails) > 1 else ''
  2209. thumb_display_id = '%s ' % t['id'] if len(thumbnails) > 1 else ''
  2210. t['filename'] = thumb_filename = replace_extension(filename + suffix, thumb_ext, info_dict.get('ext'))
  2211. if self.params.get('nooverwrites', False) and os.path.exists(encodeFilename(thumb_filename)):
  2212. self.to_screen('[%s] %s: Thumbnail %sis already present' %
  2213. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2214. else:
  2215. self.to_screen('[%s] %s: Downloading thumbnail %s...' %
  2216. (info_dict['extractor'], info_dict['id'], thumb_display_id))
  2217. try:
  2218. uf = self.urlopen(t['url'])
  2219. with open(encodeFilename(thumb_filename), 'wb') as thumbf:
  2220. shutil.copyfileobj(uf, thumbf)
  2221. self.to_screen('[%s] %s: Writing thumbnail %sto: %s' %
  2222. (info_dict['extractor'], info_dict['id'], thumb_display_id, thumb_filename))
  2223. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  2224. self.report_warning('Unable to download thumbnail "%s": %s' %
  2225. (t['url'], error_to_compat_str(err)))