1
0

YoutubeDL.py 112 KB

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