YoutubeDL.py 114 KB

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