YoutubeDL.py 113 KB

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