YoutubeDL.py 112 KB

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