YoutubeDL.py 121 KB

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