common.py 113 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469
  1. from __future__ import unicode_literals
  2. import base64
  3. import datetime
  4. import hashlib
  5. import json
  6. import netrc
  7. import os
  8. import random
  9. import re
  10. import socket
  11. import sys
  12. import time
  13. import math
  14. from ..compat import (
  15. compat_cookiejar,
  16. compat_cookies,
  17. compat_etree_fromstring,
  18. compat_getpass,
  19. compat_http_client,
  20. compat_os_name,
  21. compat_str,
  22. compat_urllib_error,
  23. compat_urllib_parse_unquote,
  24. compat_urllib_parse_urlencode,
  25. compat_urllib_request,
  26. compat_urlparse,
  27. )
  28. from ..downloader.f4m import remove_encrypted_media
  29. from ..utils import (
  30. NO_DEFAULT,
  31. age_restricted,
  32. base_url,
  33. bug_reports_message,
  34. clean_html,
  35. compiled_regex_type,
  36. determine_ext,
  37. determine_protocol,
  38. error_to_compat_str,
  39. ExtractorError,
  40. extract_attributes,
  41. fix_xml_ampersands,
  42. float_or_none,
  43. GeoRestrictedError,
  44. GeoUtils,
  45. int_or_none,
  46. js_to_json,
  47. mimetype2ext,
  48. orderedSet,
  49. parse_codecs,
  50. parse_duration,
  51. parse_iso8601,
  52. parse_m3u8_attributes,
  53. RegexNotFoundError,
  54. sanitized_Request,
  55. sanitize_filename,
  56. unescapeHTML,
  57. unified_strdate,
  58. unified_timestamp,
  59. update_Request,
  60. update_url_query,
  61. urljoin,
  62. url_basename,
  63. xpath_element,
  64. xpath_text,
  65. xpath_with_ns,
  66. )
  67. class InfoExtractor(object):
  68. """Information Extractor class.
  69. Information extractors are the classes that, given a URL, extract
  70. information about the video (or videos) the URL refers to. This
  71. information includes the real video URL, the video title, author and
  72. others. The information is stored in a dictionary which is then
  73. passed to the YoutubeDL. The YoutubeDL processes this
  74. information possibly downloading the video to the file system, among
  75. other possible outcomes.
  76. The type field determines the type of the result.
  77. By far the most common value (and the default if _type is missing) is
  78. "video", which indicates a single video.
  79. For a video, the dictionaries must include the following fields:
  80. id: Video identifier.
  81. title: Video title, unescaped.
  82. Additionally, it must contain either a formats entry or a url one:
  83. formats: A list of dictionaries for each format available, ordered
  84. from worst to best quality.
  85. Potential fields:
  86. * url Mandatory. The URL of the video file
  87. * manifest_url
  88. The URL of the manifest file in case of
  89. fragmented media (DASH, hls, hds)
  90. * ext Will be calculated from URL if missing
  91. * format A human-readable description of the format
  92. ("mp4 container with h264/opus").
  93. Calculated from the format_id, width, height.
  94. and format_note fields if missing.
  95. * format_id A short description of the format
  96. ("mp4_h264_opus" or "19").
  97. Technically optional, but strongly recommended.
  98. * format_note Additional info about the format
  99. ("3D" or "DASH video")
  100. * width Width of the video, if known
  101. * height Height of the video, if known
  102. * resolution Textual description of width and height
  103. * tbr Average bitrate of audio and video in KBit/s
  104. * abr Average audio bitrate in KBit/s
  105. * acodec Name of the audio codec in use
  106. * asr Audio sampling rate in Hertz
  107. * vbr Average video bitrate in KBit/s
  108. * fps Frame rate
  109. * vcodec Name of the video codec in use
  110. * container Name of the container format
  111. * filesize The number of bytes, if known in advance
  112. * filesize_approx An estimate for the number of bytes
  113. * player_url SWF Player URL (used for rtmpdump).
  114. * protocol The protocol that will be used for the actual
  115. download, lower-case.
  116. "http", "https", "rtsp", "rtmp", "rtmpe",
  117. "m3u8", "m3u8_native" or "http_dash_segments".
  118. * fragment_base_url
  119. Base URL for fragments. Each fragment's path
  120. value (if present) will be relative to
  121. this URL.
  122. * fragments A list of fragments of a fragmented media.
  123. Each fragment entry must contain either an url
  124. or a path. If an url is present it should be
  125. considered by a client. Otherwise both path and
  126. fragment_base_url must be present. Here is
  127. the list of all potential fields:
  128. * "url" - fragment's URL
  129. * "path" - fragment's path relative to
  130. fragment_base_url
  131. * "duration" (optional, int or float)
  132. * "filesize" (optional, int)
  133. * preference Order number of this format. If this field is
  134. present and not None, the formats get sorted
  135. by this field, regardless of all other values.
  136. -1 for default (order by other properties),
  137. -2 or smaller for less than default.
  138. < -1000 to hide the format (if there is
  139. another one which is strictly better)
  140. * language Language code, e.g. "de" or "en-US".
  141. * language_preference Is this in the language mentioned in
  142. the URL?
  143. 10 if it's what the URL is about,
  144. -1 for default (don't know),
  145. -10 otherwise, other values reserved for now.
  146. * quality Order number of the video quality of this
  147. format, irrespective of the file format.
  148. -1 for default (order by other properties),
  149. -2 or smaller for less than default.
  150. * source_preference Order number for this video source
  151. (quality takes higher priority)
  152. -1 for default (order by other properties),
  153. -2 or smaller for less than default.
  154. * http_headers A dictionary of additional HTTP headers
  155. to add to the request.
  156. * stretched_ratio If given and not 1, indicates that the
  157. video's pixels are not square.
  158. width : height ratio as float.
  159. * no_resume The server does not support resuming the
  160. (HTTP or RTMP) download. Boolean.
  161. url: Final video URL.
  162. ext: Video filename extension.
  163. format: The video format, defaults to ext (used for --get-format)
  164. player_url: SWF Player URL (used for rtmpdump).
  165. The following fields are optional:
  166. alt_title: A secondary title of the video.
  167. display_id An alternative identifier for the video, not necessarily
  168. unique, but available before title. Typically, id is
  169. something like "4234987", title "Dancing naked mole rats",
  170. and display_id "dancing-naked-mole-rats"
  171. thumbnails: A list of dictionaries, with the following entries:
  172. * "id" (optional, string) - Thumbnail format ID
  173. * "url"
  174. * "preference" (optional, int) - quality of the image
  175. * "width" (optional, int)
  176. * "height" (optional, int)
  177. * "resolution" (optional, string "{width}x{height"},
  178. deprecated)
  179. * "filesize" (optional, int)
  180. thumbnail: Full URL to a video thumbnail image.
  181. description: Full video description.
  182. uploader: Full name of the video uploader.
  183. license: License name the video is licensed under.
  184. creator: The creator of the video.
  185. release_date: The date (YYYYMMDD) when the video was released.
  186. timestamp: UNIX timestamp of the moment the video became available.
  187. upload_date: Video upload date (YYYYMMDD).
  188. If not explicitly set, calculated from timestamp.
  189. uploader_id: Nickname or id of the video uploader.
  190. uploader_url: Full URL to a personal webpage of the video uploader.
  191. location: Physical location where the video was filmed.
  192. subtitles: The available subtitles as a dictionary in the format
  193. {tag: subformats}. "tag" is usually a language code, and
  194. "subformats" is a list sorted from lower to higher
  195. preference, each element is a dictionary with the "ext"
  196. entry and one of:
  197. * "data": The subtitles file contents
  198. * "url": A URL pointing to the subtitles file
  199. "ext" will be calculated from URL if missing
  200. automatic_captions: Like 'subtitles', used by the YoutubeIE for
  201. automatically generated captions
  202. duration: Length of the video in seconds, as an integer or float.
  203. view_count: How many users have watched the video on the platform.
  204. like_count: Number of positive ratings of the video
  205. dislike_count: Number of negative ratings of the video
  206. repost_count: Number of reposts of the video
  207. average_rating: Average rating give by users, the scale used depends on the webpage
  208. comment_count: Number of comments on the video
  209. comments: A list of comments, each with one or more of the following
  210. properties (all but one of text or html optional):
  211. * "author" - human-readable name of the comment author
  212. * "author_id" - user ID of the comment author
  213. * "id" - Comment ID
  214. * "html" - Comment as HTML
  215. * "text" - Plain text of the comment
  216. * "timestamp" - UNIX timestamp of comment
  217. * "parent" - ID of the comment this one is replying to.
  218. Set to "root" to indicate that this is a
  219. comment to the original video.
  220. age_limit: Age restriction for the video, as an integer (years)
  221. webpage_url: The URL to the video webpage, if given to youtube-dl it
  222. should allow to get the same result again. (It will be set
  223. by YoutubeDL if it's missing)
  224. categories: A list of categories that the video falls in, for example
  225. ["Sports", "Berlin"]
  226. tags: A list of tags assigned to the video, e.g. ["sweden", "pop music"]
  227. is_live: True, False, or None (=unknown). Whether this video is a
  228. live stream that goes on instead of a fixed-length video.
  229. start_time: Time in seconds where the reproduction should start, as
  230. specified in the URL.
  231. end_time: Time in seconds where the reproduction should end, as
  232. specified in the URL.
  233. The following fields should only be used when the video belongs to some logical
  234. chapter or section:
  235. chapter: Name or title of the chapter the video belongs to.
  236. chapter_number: Number of the chapter the video belongs to, as an integer.
  237. chapter_id: Id of the chapter the video belongs to, as a unicode string.
  238. The following fields should only be used when the video is an episode of some
  239. series, programme or podcast:
  240. series: Title of the series or programme the video episode belongs to.
  241. season: Title of the season the video episode belongs to.
  242. season_number: Number of the season the video episode belongs to, as an integer.
  243. season_id: Id of the season the video episode belongs to, as a unicode string.
  244. episode: Title of the video episode. Unlike mandatory video title field,
  245. this field should denote the exact title of the video episode
  246. without any kind of decoration.
  247. episode_number: Number of the video episode within a season, as an integer.
  248. episode_id: Id of the video episode, as a unicode string.
  249. The following fields should only be used when the media is a track or a part of
  250. a music album:
  251. track: Title of the track.
  252. track_number: Number of the track within an album or a disc, as an integer.
  253. track_id: Id of the track (useful in case of custom indexing, e.g. 6.iii),
  254. as a unicode string.
  255. artist: Artist(s) of the track.
  256. genre: Genre(s) of the track.
  257. album: Title of the album the track belongs to.
  258. album_type: Type of the album (e.g. "Demo", "Full-length", "Split", "Compilation", etc).
  259. album_artist: List of all artists appeared on the album (e.g.
  260. "Ash Borer / Fell Voices" or "Various Artists", useful for splits
  261. and compilations).
  262. disc_number: Number of the disc or other physical medium the track belongs to,
  263. as an integer.
  264. release_year: Year (YYYY) when the album was released.
  265. Unless mentioned otherwise, the fields should be Unicode strings.
  266. Unless mentioned otherwise, None is equivalent to absence of information.
  267. _type "playlist" indicates multiple videos.
  268. There must be a key "entries", which is a list, an iterable, or a PagedList
  269. object, each element of which is a valid dictionary by this specification.
  270. Additionally, playlists can have "title", "description" and "id" attributes
  271. with the same semantics as videos (see above).
  272. _type "multi_video" indicates that there are multiple videos that
  273. form a single show, for examples multiple acts of an opera or TV episode.
  274. It must have an entries key like a playlist and contain all the keys
  275. required for a video at the same time.
  276. _type "url" indicates that the video must be extracted from another
  277. location, possibly by a different extractor. Its only required key is:
  278. "url" - the next URL to extract.
  279. The key "ie_key" can be set to the class name (minus the trailing "IE",
  280. e.g. "Youtube") if the extractor class is known in advance.
  281. Additionally, the dictionary may have any properties of the resolved entity
  282. known in advance, for example "title" if the title of the referred video is
  283. known ahead of time.
  284. _type "url_transparent" entities have the same specification as "url", but
  285. indicate that the given additional information is more precise than the one
  286. associated with the resolved URL.
  287. This is useful when a site employs a video service that hosts the video and
  288. its technical metadata, but that video service does not embed a useful
  289. title, description etc.
  290. Subclasses of this one should re-define the _real_initialize() and
  291. _real_extract() methods and define a _VALID_URL regexp.
  292. Probably, they should also be added to the list of extractors.
  293. _GEO_BYPASS attribute may be set to False in order to disable
  294. geo restriction bypass mechanisms for a particular extractor.
  295. Though it won't disable explicit geo restriction bypass based on
  296. country code provided with geo_bypass_country. (experimental)
  297. _GEO_COUNTRIES attribute may contain a list of presumably geo unrestricted
  298. countries for this extractor. One of these countries will be used by
  299. geo restriction bypass mechanism right away in order to bypass
  300. geo restriction, of course, if the mechanism is not disabled. (experimental)
  301. NB: both these geo attributes are experimental and may change in future
  302. or be completely removed.
  303. Finally, the _WORKING attribute should be set to False for broken IEs
  304. in order to warn the users and skip the tests.
  305. """
  306. _ready = False
  307. _downloader = None
  308. _x_forwarded_for_ip = None
  309. _GEO_BYPASS = True
  310. _GEO_COUNTRIES = None
  311. _WORKING = True
  312. def __init__(self, downloader=None):
  313. """Constructor. Receives an optional downloader."""
  314. self._ready = False
  315. self._x_forwarded_for_ip = None
  316. self.set_downloader(downloader)
  317. @classmethod
  318. def suitable(cls, url):
  319. """Receives a URL and returns True if suitable for this IE."""
  320. # This does not use has/getattr intentionally - we want to know whether
  321. # we have cached the regexp for *this* class, whereas getattr would also
  322. # match the superclass
  323. if '_VALID_URL_RE' not in cls.__dict__:
  324. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  325. return cls._VALID_URL_RE.match(url) is not None
  326. @classmethod
  327. def _match_id(cls, url):
  328. if '_VALID_URL_RE' not in cls.__dict__:
  329. cls._VALID_URL_RE = re.compile(cls._VALID_URL)
  330. m = cls._VALID_URL_RE.match(url)
  331. assert m
  332. return m.group('id')
  333. @classmethod
  334. def working(cls):
  335. """Getter method for _WORKING."""
  336. return cls._WORKING
  337. def initialize(self):
  338. """Initializes an instance (authentication, etc)."""
  339. self._initialize_geo_bypass(self._GEO_COUNTRIES)
  340. if not self._ready:
  341. self._real_initialize()
  342. self._ready = True
  343. def _initialize_geo_bypass(self, countries):
  344. """
  345. Initialize geo restriction bypass mechanism.
  346. This method is used to initialize geo bypass mechanism based on faking
  347. X-Forwarded-For HTTP header. A random country from provided country list
  348. is selected and a random IP belonging to this country is generated. This
  349. IP will be passed as X-Forwarded-For HTTP header in all subsequent
  350. HTTP requests.
  351. This method will be used for initial geo bypass mechanism initialization
  352. during the instance initialization with _GEO_COUNTRIES.
  353. You may also manually call it from extractor's code if geo countries
  354. information is not available beforehand (e.g. obtained during
  355. extraction) or due to some another reason.
  356. """
  357. if not self._x_forwarded_for_ip:
  358. country_code = self._downloader.params.get('geo_bypass_country', None)
  359. # If there is no explicit country for geo bypass specified and
  360. # the extractor is known to be geo restricted let's fake IP
  361. # as X-Forwarded-For right away.
  362. if (not country_code and
  363. self._GEO_BYPASS and
  364. self._downloader.params.get('geo_bypass', True) and
  365. countries):
  366. country_code = random.choice(countries)
  367. if country_code:
  368. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country_code)
  369. if self._downloader.params.get('verbose', False):
  370. self._downloader.to_stdout(
  371. '[debug] Using fake IP %s (%s) as X-Forwarded-For.'
  372. % (self._x_forwarded_for_ip, country_code.upper()))
  373. def extract(self, url):
  374. """Extracts URL information and returns it in list of dicts."""
  375. try:
  376. for _ in range(2):
  377. try:
  378. self.initialize()
  379. ie_result = self._real_extract(url)
  380. if self._x_forwarded_for_ip:
  381. ie_result['__x_forwarded_for_ip'] = self._x_forwarded_for_ip
  382. return ie_result
  383. except GeoRestrictedError as e:
  384. if self.__maybe_fake_ip_and_retry(e.countries):
  385. continue
  386. raise
  387. except ExtractorError:
  388. raise
  389. except compat_http_client.IncompleteRead as e:
  390. raise ExtractorError('A network error has occurred.', cause=e, expected=True)
  391. except (KeyError, StopIteration) as e:
  392. raise ExtractorError('An extractor error has occurred.', cause=e)
  393. def __maybe_fake_ip_and_retry(self, countries):
  394. if (not self._downloader.params.get('geo_bypass_country', None) and
  395. self._GEO_BYPASS and
  396. self._downloader.params.get('geo_bypass', True) and
  397. not self._x_forwarded_for_ip and
  398. countries):
  399. country_code = random.choice(countries)
  400. self._x_forwarded_for_ip = GeoUtils.random_ipv4(country_code)
  401. if self._x_forwarded_for_ip:
  402. self.report_warning(
  403. 'Video is geo restricted. Retrying extraction with fake IP %s (%s) as X-Forwarded-For.'
  404. % (self._x_forwarded_for_ip, country_code.upper()))
  405. return True
  406. return False
  407. def set_downloader(self, downloader):
  408. """Sets the downloader for this IE."""
  409. self._downloader = downloader
  410. def _real_initialize(self):
  411. """Real initialization process. Redefine in subclasses."""
  412. pass
  413. def _real_extract(self, url):
  414. """Real extraction process. Redefine in subclasses."""
  415. pass
  416. @classmethod
  417. def ie_key(cls):
  418. """A string for getting the InfoExtractor with get_info_extractor"""
  419. return compat_str(cls.__name__[:-2])
  420. @property
  421. def IE_NAME(self):
  422. return compat_str(type(self).__name__[:-2])
  423. def _request_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, data=None, headers={}, query={}):
  424. """ Returns the response handle """
  425. if note is None:
  426. self.report_download_webpage(video_id)
  427. elif note is not False:
  428. if video_id is None:
  429. self.to_screen('%s' % (note,))
  430. else:
  431. self.to_screen('%s: %s' % (video_id, note))
  432. if isinstance(url_or_request, compat_urllib_request.Request):
  433. url_or_request = update_Request(
  434. url_or_request, data=data, headers=headers, query=query)
  435. else:
  436. if query:
  437. url_or_request = update_url_query(url_or_request, query)
  438. if data is not None or headers:
  439. url_or_request = sanitized_Request(url_or_request, data, headers)
  440. try:
  441. return self._downloader.urlopen(url_or_request)
  442. except (compat_urllib_error.URLError, compat_http_client.HTTPException, socket.error) as err:
  443. if errnote is False:
  444. return False
  445. if errnote is None:
  446. errnote = 'Unable to download webpage'
  447. errmsg = '%s: %s' % (errnote, error_to_compat_str(err))
  448. if fatal:
  449. raise ExtractorError(errmsg, sys.exc_info()[2], cause=err)
  450. else:
  451. self._downloader.report_warning(errmsg)
  452. return False
  453. def _download_webpage_handle(self, url_or_request, video_id, note=None, errnote=None, fatal=True, encoding=None, data=None, headers={}, query={}):
  454. """ Returns a tuple (page content as string, URL handle) """
  455. # Strip hashes from the URL (#1038)
  456. if isinstance(url_or_request, (compat_str, str)):
  457. url_or_request = url_or_request.partition('#')[0]
  458. # Some sites check X-Forwarded-For HTTP header in order to figure out
  459. # the origin of the client behind proxy. This allows bypassing geo
  460. # restriction by faking this header's value to IP that belongs to some
  461. # geo unrestricted country. We will do so once we encounter any
  462. # geo restriction error.
  463. if self._x_forwarded_for_ip:
  464. if 'X-Forwarded-For' not in headers:
  465. headers['X-Forwarded-For'] = self._x_forwarded_for_ip
  466. urlh = self._request_webpage(url_or_request, video_id, note, errnote, fatal, data=data, headers=headers, query=query)
  467. if urlh is False:
  468. assert not fatal
  469. return False
  470. content = self._webpage_read_content(urlh, url_or_request, video_id, note, errnote, fatal, encoding=encoding)
  471. return (content, urlh)
  472. @staticmethod
  473. def _guess_encoding_from_content(content_type, webpage_bytes):
  474. m = re.match(r'[a-zA-Z0-9_.-]+/[a-zA-Z0-9_.-]+\s*;\s*charset=(.+)', content_type)
  475. if m:
  476. encoding = m.group(1)
  477. else:
  478. m = re.search(br'<meta[^>]+charset=[\'"]?([^\'")]+)[ /\'">]',
  479. webpage_bytes[:1024])
  480. if m:
  481. encoding = m.group(1).decode('ascii')
  482. elif webpage_bytes.startswith(b'\xff\xfe'):
  483. encoding = 'utf-16'
  484. else:
  485. encoding = 'utf-8'
  486. return encoding
  487. def _webpage_read_content(self, urlh, url_or_request, video_id, note=None, errnote=None, fatal=True, prefix=None, encoding=None):
  488. content_type = urlh.headers.get('Content-Type', '')
  489. webpage_bytes = urlh.read()
  490. if prefix is not None:
  491. webpage_bytes = prefix + webpage_bytes
  492. if not encoding:
  493. encoding = self._guess_encoding_from_content(content_type, webpage_bytes)
  494. if self._downloader.params.get('dump_intermediate_pages', False):
  495. try:
  496. url = url_or_request.get_full_url()
  497. except AttributeError:
  498. url = url_or_request
  499. self.to_screen('Dumping request to ' + url)
  500. dump = base64.b64encode(webpage_bytes).decode('ascii')
  501. self._downloader.to_screen(dump)
  502. if self._downloader.params.get('write_pages', False):
  503. try:
  504. url = url_or_request.get_full_url()
  505. except AttributeError:
  506. url = url_or_request
  507. basen = '%s_%s' % (video_id, url)
  508. if len(basen) > 240:
  509. h = '___' + hashlib.md5(basen.encode('utf-8')).hexdigest()
  510. basen = basen[:240 - len(h)] + h
  511. raw_filename = basen + '.dump'
  512. filename = sanitize_filename(raw_filename, restricted=True)
  513. self.to_screen('Saving request to ' + filename)
  514. # Working around MAX_PATH limitation on Windows (see
  515. # http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx)
  516. if compat_os_name == 'nt':
  517. absfilepath = os.path.abspath(filename)
  518. if len(absfilepath) > 259:
  519. filename = '\\\\?\\' + absfilepath
  520. with open(filename, 'wb') as outf:
  521. outf.write(webpage_bytes)
  522. try:
  523. content = webpage_bytes.decode(encoding, 'replace')
  524. except LookupError:
  525. content = webpage_bytes.decode('utf-8', 'replace')
  526. if ('<title>Access to this site is blocked</title>' in content and
  527. 'Websense' in content[:512]):
  528. msg = 'Access to this webpage has been blocked by Websense filtering software in your network.'
  529. blocked_iframe = self._html_search_regex(
  530. r'<iframe src="([^"]+)"', content,
  531. 'Websense information URL', default=None)
  532. if blocked_iframe:
  533. msg += ' Visit %s for more details' % blocked_iframe
  534. raise ExtractorError(msg, expected=True)
  535. if '<title>The URL you requested has been blocked</title>' in content[:512]:
  536. msg = (
  537. 'Access to this webpage has been blocked by Indian censorship. '
  538. 'Use a VPN or proxy server (with --proxy) to route around it.')
  539. block_msg = self._html_search_regex(
  540. r'</h1><p>(.*?)</p>',
  541. content, 'block message', default=None)
  542. if block_msg:
  543. msg += ' (Message: "%s")' % block_msg.replace('\n', ' ')
  544. raise ExtractorError(msg, expected=True)
  545. return content
  546. def _download_webpage(self, url_or_request, video_id, note=None, errnote=None, fatal=True, tries=1, timeout=5, encoding=None, data=None, headers={}, query={}):
  547. """ Returns the data of the page as a string """
  548. success = False
  549. try_count = 0
  550. while success is False:
  551. try:
  552. res = self._download_webpage_handle(url_or_request, video_id, note, errnote, fatal, encoding=encoding, data=data, headers=headers, query=query)
  553. success = True
  554. except compat_http_client.IncompleteRead as e:
  555. try_count += 1
  556. if try_count >= tries:
  557. raise e
  558. self._sleep(timeout, video_id)
  559. if res is False:
  560. return res
  561. else:
  562. content, _ = res
  563. return content
  564. def _download_xml(self, url_or_request, video_id,
  565. note='Downloading XML', errnote='Unable to download XML',
  566. transform_source=None, fatal=True, encoding=None, data=None, headers={}, query={}):
  567. """Return the xml as an xml.etree.ElementTree.Element"""
  568. xml_string = self._download_webpage(
  569. url_or_request, video_id, note, errnote, fatal=fatal, encoding=encoding, data=data, headers=headers, query=query)
  570. if xml_string is False:
  571. return xml_string
  572. if transform_source:
  573. xml_string = transform_source(xml_string)
  574. return compat_etree_fromstring(xml_string.encode('utf-8'))
  575. def _download_json(self, url_or_request, video_id,
  576. note='Downloading JSON metadata',
  577. errnote='Unable to download JSON metadata',
  578. transform_source=None,
  579. fatal=True, encoding=None, data=None, headers={}, query={}):
  580. json_string = self._download_webpage(
  581. url_or_request, video_id, note, errnote, fatal=fatal,
  582. encoding=encoding, data=data, headers=headers, query=query)
  583. if (not fatal) and json_string is False:
  584. return None
  585. return self._parse_json(
  586. json_string, video_id, transform_source=transform_source, fatal=fatal)
  587. def _parse_json(self, json_string, video_id, transform_source=None, fatal=True):
  588. if transform_source:
  589. json_string = transform_source(json_string)
  590. try:
  591. return json.loads(json_string)
  592. except ValueError as ve:
  593. errmsg = '%s: Failed to parse JSON ' % video_id
  594. if fatal:
  595. raise ExtractorError(errmsg, cause=ve)
  596. else:
  597. self.report_warning(errmsg + str(ve))
  598. def report_warning(self, msg, video_id=None):
  599. idstr = '' if video_id is None else '%s: ' % video_id
  600. self._downloader.report_warning(
  601. '[%s] %s%s' % (self.IE_NAME, idstr, msg))
  602. def to_screen(self, msg):
  603. """Print msg to screen, prefixing it with '[ie_name]'"""
  604. self._downloader.to_screen('[%s] %s' % (self.IE_NAME, msg))
  605. def report_extraction(self, id_or_name):
  606. """Report information extraction."""
  607. self.to_screen('%s: Extracting information' % id_or_name)
  608. def report_download_webpage(self, video_id):
  609. """Report webpage download."""
  610. self.to_screen('%s: Downloading webpage' % video_id)
  611. def report_age_confirmation(self):
  612. """Report attempt to confirm age."""
  613. self.to_screen('Confirming age')
  614. def report_login(self):
  615. """Report attempt to log in."""
  616. self.to_screen('Logging in')
  617. @staticmethod
  618. def raise_login_required(msg='This video is only available for registered users'):
  619. raise ExtractorError(
  620. '%s. Use --username and --password or --netrc to provide account credentials.' % msg,
  621. expected=True)
  622. @staticmethod
  623. def raise_geo_restricted(msg='This video is not available from your location due to geo restriction', countries=None):
  624. raise GeoRestrictedError(msg, countries=countries)
  625. # Methods for following #608
  626. @staticmethod
  627. def url_result(url, ie=None, video_id=None, video_title=None):
  628. """Returns a URL that points to a page that should be processed"""
  629. # TODO: ie should be the class used for getting the info
  630. video_info = {'_type': 'url',
  631. 'url': url,
  632. 'ie_key': ie}
  633. if video_id is not None:
  634. video_info['id'] = video_id
  635. if video_title is not None:
  636. video_info['title'] = video_title
  637. return video_info
  638. def playlist_from_matches(self, matches, video_id, video_title, getter=None, ie=None):
  639. urlrs = orderedSet(
  640. self.url_result(self._proto_relative_url(getter(m) if getter else m), ie)
  641. for m in matches)
  642. return self.playlist_result(
  643. urlrs, playlist_id=video_id, playlist_title=video_title)
  644. @staticmethod
  645. def playlist_result(entries, playlist_id=None, playlist_title=None, playlist_description=None):
  646. """Returns a playlist"""
  647. video_info = {'_type': 'playlist',
  648. 'entries': entries}
  649. if playlist_id:
  650. video_info['id'] = playlist_id
  651. if playlist_title:
  652. video_info['title'] = playlist_title
  653. if playlist_description:
  654. video_info['description'] = playlist_description
  655. return video_info
  656. def _search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  657. """
  658. Perform a regex search on the given string, using a single or a list of
  659. patterns returning the first matching group.
  660. In case of failure return a default value or raise a WARNING or a
  661. RegexNotFoundError, depending on fatal, specifying the field name.
  662. """
  663. if isinstance(pattern, (str, compat_str, compiled_regex_type)):
  664. mobj = re.search(pattern, string, flags)
  665. else:
  666. for p in pattern:
  667. mobj = re.search(p, string, flags)
  668. if mobj:
  669. break
  670. if not self._downloader.params.get('no_color') and compat_os_name != 'nt' and sys.stderr.isatty():
  671. _name = '\033[0;34m%s\033[0m' % name
  672. else:
  673. _name = name
  674. if mobj:
  675. if group is None:
  676. # return the first matching group
  677. return next(g for g in mobj.groups() if g is not None)
  678. else:
  679. return mobj.group(group)
  680. elif default is not NO_DEFAULT:
  681. return default
  682. elif fatal:
  683. raise RegexNotFoundError('Unable to extract %s' % _name)
  684. else:
  685. self._downloader.report_warning('unable to extract %s' % _name + bug_reports_message())
  686. return None
  687. def _html_search_regex(self, pattern, string, name, default=NO_DEFAULT, fatal=True, flags=0, group=None):
  688. """
  689. Like _search_regex, but strips HTML tags and unescapes entities.
  690. """
  691. res = self._search_regex(pattern, string, name, default, fatal, flags, group)
  692. if res:
  693. return clean_html(res).strip()
  694. else:
  695. return res
  696. def _get_netrc_login_info(self, netrc_machine=None):
  697. username = None
  698. password = None
  699. netrc_machine = netrc_machine or self._NETRC_MACHINE
  700. if self._downloader.params.get('usenetrc', False):
  701. try:
  702. info = netrc.netrc().authenticators(netrc_machine)
  703. if info is not None:
  704. username = info[0]
  705. password = info[2]
  706. else:
  707. raise netrc.NetrcParseError(
  708. 'No authenticators for %s' % netrc_machine)
  709. except (IOError, netrc.NetrcParseError) as err:
  710. self._downloader.report_warning(
  711. 'parsing .netrc: %s' % error_to_compat_str(err))
  712. return username, password
  713. def _get_login_info(self, username_option='username', password_option='password', netrc_machine=None):
  714. """
  715. Get the login info as (username, password)
  716. First look for the manually specified credentials using username_option
  717. and password_option as keys in params dictionary. If no such credentials
  718. available look in the netrc file using the netrc_machine or _NETRC_MACHINE
  719. value.
  720. If there's no info available, return (None, None)
  721. """
  722. if self._downloader is None:
  723. return (None, None)
  724. downloader_params = self._downloader.params
  725. # Attempt to use provided username and password or .netrc data
  726. if downloader_params.get(username_option) is not None:
  727. username = downloader_params[username_option]
  728. password = downloader_params[password_option]
  729. else:
  730. username, password = self._get_netrc_login_info(netrc_machine)
  731. return username, password
  732. def _get_tfa_info(self, note='two-factor verification code'):
  733. """
  734. Get the two-factor authentication info
  735. TODO - asking the user will be required for sms/phone verify
  736. currently just uses the command line option
  737. If there's no info available, return None
  738. """
  739. if self._downloader is None:
  740. return None
  741. downloader_params = self._downloader.params
  742. if downloader_params.get('twofactor') is not None:
  743. return downloader_params['twofactor']
  744. return compat_getpass('Type %s and press [Return]: ' % note)
  745. # Helper functions for extracting OpenGraph info
  746. @staticmethod
  747. def _og_regexes(prop):
  748. content_re = r'content=(?:"([^"]+?)"|\'([^\']+?)\'|\s*([^\s"\'=<>`]+?))'
  749. property_re = (r'(?:name|property)=(?:\'og:%(prop)s\'|"og:%(prop)s"|\s*og:%(prop)s\b)'
  750. % {'prop': re.escape(prop)})
  751. template = r'<meta[^>]+?%s[^>]+?%s'
  752. return [
  753. template % (property_re, content_re),
  754. template % (content_re, property_re),
  755. ]
  756. @staticmethod
  757. def _meta_regex(prop):
  758. return r'''(?isx)<meta
  759. (?=[^>]+(?:itemprop|name|property|id|http-equiv)=(["\']?)%s\1)
  760. [^>]+?content=(["\'])(?P<content>.*?)\2''' % re.escape(prop)
  761. def _og_search_property(self, prop, html, name=None, **kargs):
  762. if not isinstance(prop, (list, tuple)):
  763. prop = [prop]
  764. if name is None:
  765. name = 'OpenGraph %s' % prop[0]
  766. og_regexes = []
  767. for p in prop:
  768. og_regexes.extend(self._og_regexes(p))
  769. escaped = self._search_regex(og_regexes, html, name, flags=re.DOTALL, **kargs)
  770. if escaped is None:
  771. return None
  772. return unescapeHTML(escaped)
  773. def _og_search_thumbnail(self, html, **kargs):
  774. return self._og_search_property('image', html, 'thumbnail URL', fatal=False, **kargs)
  775. def _og_search_description(self, html, **kargs):
  776. return self._og_search_property('description', html, fatal=False, **kargs)
  777. def _og_search_title(self, html, **kargs):
  778. return self._og_search_property('title', html, **kargs)
  779. def _og_search_video_url(self, html, name='video url', secure=True, **kargs):
  780. regexes = self._og_regexes('video') + self._og_regexes('video:url')
  781. if secure:
  782. regexes = self._og_regexes('video:secure_url') + regexes
  783. return self._html_search_regex(regexes, html, name, **kargs)
  784. def _og_search_url(self, html, **kargs):
  785. return self._og_search_property('url', html, **kargs)
  786. def _html_search_meta(self, name, html, display_name=None, fatal=False, **kwargs):
  787. if not isinstance(name, (list, tuple)):
  788. name = [name]
  789. if display_name is None:
  790. display_name = name[0]
  791. return self._html_search_regex(
  792. [self._meta_regex(n) for n in name],
  793. html, display_name, fatal=fatal, group='content', **kwargs)
  794. def _dc_search_uploader(self, html):
  795. return self._html_search_meta('dc.creator', html, 'uploader')
  796. def _rta_search(self, html):
  797. # See http://www.rtalabel.org/index.php?content=howtofaq#single
  798. if re.search(r'(?ix)<meta\s+name="rating"\s+'
  799. r' content="RTA-5042-1996-1400-1577-RTA"',
  800. html):
  801. return 18
  802. return 0
  803. def _media_rating_search(self, html):
  804. # See http://www.tjg-designs.com/WP/metadata-code-examples-adding-metadata-to-your-web-pages/
  805. rating = self._html_search_meta('rating', html)
  806. if not rating:
  807. return None
  808. RATING_TABLE = {
  809. 'safe for kids': 0,
  810. 'general': 8,
  811. '14 years': 14,
  812. 'mature': 17,
  813. 'restricted': 19,
  814. }
  815. return RATING_TABLE.get(rating.lower())
  816. def _family_friendly_search(self, html):
  817. # See http://schema.org/VideoObject
  818. family_friendly = self._html_search_meta('isFamilyFriendly', html)
  819. if not family_friendly:
  820. return None
  821. RATING_TABLE = {
  822. '1': 0,
  823. 'true': 0,
  824. '0': 18,
  825. 'false': 18,
  826. }
  827. return RATING_TABLE.get(family_friendly.lower())
  828. def _twitter_search_player(self, html):
  829. return self._html_search_meta('twitter:player', html,
  830. 'twitter card player')
  831. def _search_json_ld(self, html, video_id, expected_type=None, **kwargs):
  832. json_ld = self._search_regex(
  833. r'(?s)<script[^>]+type=(["\'])application/ld\+json\1[^>]*>(?P<json_ld>.+?)</script>',
  834. html, 'JSON-LD', group='json_ld', **kwargs)
  835. default = kwargs.get('default', NO_DEFAULT)
  836. if not json_ld:
  837. return default if default is not NO_DEFAULT else {}
  838. # JSON-LD may be malformed and thus `fatal` should be respected.
  839. # At the same time `default` may be passed that assumes `fatal=False`
  840. # for _search_regex. Let's simulate the same behavior here as well.
  841. fatal = kwargs.get('fatal', True) if default == NO_DEFAULT else False
  842. return self._json_ld(json_ld, video_id, fatal=fatal, expected_type=expected_type)
  843. def _json_ld(self, json_ld, video_id, fatal=True, expected_type=None):
  844. if isinstance(json_ld, compat_str):
  845. json_ld = self._parse_json(json_ld, video_id, fatal=fatal)
  846. if not json_ld:
  847. return {}
  848. info = {}
  849. if not isinstance(json_ld, (list, tuple, dict)):
  850. return info
  851. if isinstance(json_ld, dict):
  852. json_ld = [json_ld]
  853. for e in json_ld:
  854. if e.get('@context') == 'http://schema.org':
  855. item_type = e.get('@type')
  856. if expected_type is not None and expected_type != item_type:
  857. return info
  858. if item_type == 'TVEpisode':
  859. info.update({
  860. 'episode': unescapeHTML(e.get('name')),
  861. 'episode_number': int_or_none(e.get('episodeNumber')),
  862. 'description': unescapeHTML(e.get('description')),
  863. })
  864. part_of_season = e.get('partOfSeason')
  865. if isinstance(part_of_season, dict) and part_of_season.get('@type') == 'TVSeason':
  866. info['season_number'] = int_or_none(part_of_season.get('seasonNumber'))
  867. part_of_series = e.get('partOfSeries') or e.get('partOfTVSeries')
  868. if isinstance(part_of_series, dict) and part_of_series.get('@type') == 'TVSeries':
  869. info['series'] = unescapeHTML(part_of_series.get('name'))
  870. elif item_type == 'Article':
  871. info.update({
  872. 'timestamp': parse_iso8601(e.get('datePublished')),
  873. 'title': unescapeHTML(e.get('headline')),
  874. 'description': unescapeHTML(e.get('articleBody')),
  875. })
  876. elif item_type == 'VideoObject':
  877. info.update({
  878. 'url': e.get('contentUrl'),
  879. 'title': unescapeHTML(e.get('name')),
  880. 'description': unescapeHTML(e.get('description')),
  881. 'thumbnail': e.get('thumbnailUrl') or e.get('thumbnailURL'),
  882. 'duration': parse_duration(e.get('duration')),
  883. 'timestamp': unified_timestamp(e.get('uploadDate')),
  884. 'filesize': float_or_none(e.get('contentSize')),
  885. 'tbr': int_or_none(e.get('bitrate')),
  886. 'width': int_or_none(e.get('width')),
  887. 'height': int_or_none(e.get('height')),
  888. })
  889. break
  890. return dict((k, v) for k, v in info.items() if v is not None)
  891. @staticmethod
  892. def _hidden_inputs(html):
  893. html = re.sub(r'<!--(?:(?!<!--).)*-->', '', html)
  894. hidden_inputs = {}
  895. for input in re.findall(r'(?i)(<input[^>]+>)', html):
  896. attrs = extract_attributes(input)
  897. if not input:
  898. continue
  899. if attrs.get('type') not in ('hidden', 'submit'):
  900. continue
  901. name = attrs.get('name') or attrs.get('id')
  902. value = attrs.get('value')
  903. if name and value is not None:
  904. hidden_inputs[name] = value
  905. return hidden_inputs
  906. def _form_hidden_inputs(self, form_id, html):
  907. form = self._search_regex(
  908. r'(?is)<form[^>]+?id=(["\'])%s\1[^>]*>(?P<form>.+?)</form>' % form_id,
  909. html, '%s form' % form_id, group='form')
  910. return self._hidden_inputs(form)
  911. def _sort_formats(self, formats, field_preference=None):
  912. if not formats:
  913. raise ExtractorError('No video formats found')
  914. for f in formats:
  915. # Automatically determine tbr when missing based on abr and vbr (improves
  916. # formats sorting in some cases)
  917. if 'tbr' not in f and f.get('abr') is not None and f.get('vbr') is not None:
  918. f['tbr'] = f['abr'] + f['vbr']
  919. def _formats_key(f):
  920. # TODO remove the following workaround
  921. from ..utils import determine_ext
  922. if not f.get('ext') and 'url' in f:
  923. f['ext'] = determine_ext(f['url'])
  924. if isinstance(field_preference, (list, tuple)):
  925. return tuple(
  926. f.get(field)
  927. if f.get(field) is not None
  928. else ('' if field == 'format_id' else -1)
  929. for field in field_preference)
  930. preference = f.get('preference')
  931. if preference is None:
  932. preference = 0
  933. if f.get('ext') in ['f4f', 'f4m']: # Not yet supported
  934. preference -= 0.5
  935. protocol = f.get('protocol') or determine_protocol(f)
  936. proto_preference = 0 if protocol in ['http', 'https'] else (-0.5 if protocol == 'rtsp' else -0.1)
  937. if f.get('vcodec') == 'none': # audio only
  938. preference -= 50
  939. if self._downloader.params.get('prefer_free_formats'):
  940. ORDER = ['aac', 'mp3', 'm4a', 'webm', 'ogg', 'opus']
  941. else:
  942. ORDER = ['webm', 'opus', 'ogg', 'mp3', 'aac', 'm4a']
  943. ext_preference = 0
  944. try:
  945. audio_ext_preference = ORDER.index(f['ext'])
  946. except ValueError:
  947. audio_ext_preference = -1
  948. else:
  949. if f.get('acodec') == 'none': # video only
  950. preference -= 40
  951. if self._downloader.params.get('prefer_free_formats'):
  952. ORDER = ['flv', 'mp4', 'webm']
  953. else:
  954. ORDER = ['webm', 'flv', 'mp4']
  955. try:
  956. ext_preference = ORDER.index(f['ext'])
  957. except ValueError:
  958. ext_preference = -1
  959. audio_ext_preference = 0
  960. return (
  961. preference,
  962. f.get('language_preference') if f.get('language_preference') is not None else -1,
  963. f.get('quality') if f.get('quality') is not None else -1,
  964. f.get('tbr') if f.get('tbr') is not None else -1,
  965. f.get('filesize') if f.get('filesize') is not None else -1,
  966. f.get('vbr') if f.get('vbr') is not None else -1,
  967. f.get('height') if f.get('height') is not None else -1,
  968. f.get('width') if f.get('width') is not None else -1,
  969. proto_preference,
  970. ext_preference,
  971. f.get('abr') if f.get('abr') is not None else -1,
  972. audio_ext_preference,
  973. f.get('fps') if f.get('fps') is not None else -1,
  974. f.get('filesize_approx') if f.get('filesize_approx') is not None else -1,
  975. f.get('source_preference') if f.get('source_preference') is not None else -1,
  976. f.get('format_id') if f.get('format_id') is not None else '',
  977. )
  978. formats.sort(key=_formats_key)
  979. def _check_formats(self, formats, video_id):
  980. if formats:
  981. formats[:] = filter(
  982. lambda f: self._is_valid_url(
  983. f['url'], video_id,
  984. item='%s video format' % f.get('format_id') if f.get('format_id') else 'video'),
  985. formats)
  986. @staticmethod
  987. def _remove_duplicate_formats(formats):
  988. format_urls = set()
  989. unique_formats = []
  990. for f in formats:
  991. if f['url'] not in format_urls:
  992. format_urls.add(f['url'])
  993. unique_formats.append(f)
  994. formats[:] = unique_formats
  995. def _is_valid_url(self, url, video_id, item='video', headers={}):
  996. url = self._proto_relative_url(url, scheme='http:')
  997. # For now assume non HTTP(S) URLs always valid
  998. if not (url.startswith('http://') or url.startswith('https://')):
  999. return True
  1000. try:
  1001. self._request_webpage(url, video_id, 'Checking %s URL' % item, headers=headers)
  1002. return True
  1003. except ExtractorError as e:
  1004. if isinstance(e.cause, compat_urllib_error.URLError):
  1005. self.to_screen(
  1006. '%s: %s URL is invalid, skipping' % (video_id, item))
  1007. return False
  1008. raise
  1009. def http_scheme(self):
  1010. """ Either "http:" or "https:", depending on the user's preferences """
  1011. return (
  1012. 'http:'
  1013. if self._downloader.params.get('prefer_insecure', False)
  1014. else 'https:')
  1015. def _proto_relative_url(self, url, scheme=None):
  1016. if url is None:
  1017. return url
  1018. if url.startswith('//'):
  1019. if scheme is None:
  1020. scheme = self.http_scheme()
  1021. return scheme + url
  1022. else:
  1023. return url
  1024. def _sleep(self, timeout, video_id, msg_template=None):
  1025. if msg_template is None:
  1026. msg_template = '%(video_id)s: Waiting for %(timeout)s seconds'
  1027. msg = msg_template % {'video_id': video_id, 'timeout': timeout}
  1028. self.to_screen(msg)
  1029. time.sleep(timeout)
  1030. def _extract_f4m_formats(self, manifest_url, video_id, preference=None, f4m_id=None,
  1031. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1032. fatal=True, m3u8_id=None):
  1033. manifest = self._download_xml(
  1034. manifest_url, video_id, 'Downloading f4m manifest',
  1035. 'Unable to download f4m manifest',
  1036. # Some manifests may be malformed, e.g. prosiebensat1 generated manifests
  1037. # (see https://github.com/rg3/youtube-dl/issues/6215#issuecomment-121704244)
  1038. transform_source=transform_source,
  1039. fatal=fatal)
  1040. if manifest is False:
  1041. return []
  1042. return self._parse_f4m_formats(
  1043. manifest, manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  1044. transform_source=transform_source, fatal=fatal, m3u8_id=m3u8_id)
  1045. def _parse_f4m_formats(self, manifest, manifest_url, video_id, preference=None, f4m_id=None,
  1046. transform_source=lambda s: fix_xml_ampersands(s).strip(),
  1047. fatal=True, m3u8_id=None):
  1048. # currently youtube-dl cannot decode the playerVerificationChallenge as Akamai uses Adobe Alchemy
  1049. akamai_pv = manifest.find('{http://ns.adobe.com/f4m/1.0}pv-2.0')
  1050. if akamai_pv is not None and ';' in akamai_pv.text:
  1051. playerVerificationChallenge = akamai_pv.text.split(';')[0]
  1052. if playerVerificationChallenge.strip() != '':
  1053. return []
  1054. formats = []
  1055. manifest_version = '1.0'
  1056. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/1.0}media')
  1057. if not media_nodes:
  1058. manifest_version = '2.0'
  1059. media_nodes = manifest.findall('{http://ns.adobe.com/f4m/2.0}media')
  1060. # Remove unsupported DRM protected media from final formats
  1061. # rendition (see https://github.com/rg3/youtube-dl/issues/8573).
  1062. media_nodes = remove_encrypted_media(media_nodes)
  1063. if not media_nodes:
  1064. return formats
  1065. base_url = xpath_text(
  1066. manifest, ['{http://ns.adobe.com/f4m/1.0}baseURL', '{http://ns.adobe.com/f4m/2.0}baseURL'],
  1067. 'base URL', default=None)
  1068. if base_url:
  1069. base_url = base_url.strip()
  1070. bootstrap_info = xpath_element(
  1071. manifest, ['{http://ns.adobe.com/f4m/1.0}bootstrapInfo', '{http://ns.adobe.com/f4m/2.0}bootstrapInfo'],
  1072. 'bootstrap info', default=None)
  1073. vcodec = None
  1074. mime_type = xpath_text(
  1075. manifest, ['{http://ns.adobe.com/f4m/1.0}mimeType', '{http://ns.adobe.com/f4m/2.0}mimeType'],
  1076. 'base URL', default=None)
  1077. if mime_type and mime_type.startswith('audio/'):
  1078. vcodec = 'none'
  1079. for i, media_el in enumerate(media_nodes):
  1080. tbr = int_or_none(media_el.attrib.get('bitrate'))
  1081. width = int_or_none(media_el.attrib.get('width'))
  1082. height = int_or_none(media_el.attrib.get('height'))
  1083. format_id = '-'.join(filter(None, [f4m_id, compat_str(i if tbr is None else tbr)]))
  1084. # If <bootstrapInfo> is present, the specified f4m is a
  1085. # stream-level manifest, and only set-level manifests may refer to
  1086. # external resources. See section 11.4 and section 4 of F4M spec
  1087. if bootstrap_info is None:
  1088. media_url = None
  1089. # @href is introduced in 2.0, see section 11.6 of F4M spec
  1090. if manifest_version == '2.0':
  1091. media_url = media_el.attrib.get('href')
  1092. if media_url is None:
  1093. media_url = media_el.attrib.get('url')
  1094. if not media_url:
  1095. continue
  1096. manifest_url = (
  1097. media_url if media_url.startswith('http://') or media_url.startswith('https://')
  1098. else ((base_url or '/'.join(manifest_url.split('/')[:-1])) + '/' + media_url))
  1099. # If media_url is itself a f4m manifest do the recursive extraction
  1100. # since bitrates in parent manifest (this one) and media_url manifest
  1101. # may differ leading to inability to resolve the format by requested
  1102. # bitrate in f4m downloader
  1103. ext = determine_ext(manifest_url)
  1104. if ext == 'f4m':
  1105. f4m_formats = self._extract_f4m_formats(
  1106. manifest_url, video_id, preference=preference, f4m_id=f4m_id,
  1107. transform_source=transform_source, fatal=fatal)
  1108. # Sometimes stream-level manifest contains single media entry that
  1109. # does not contain any quality metadata (e.g. http://matchtv.ru/#live-player).
  1110. # At the same time parent's media entry in set-level manifest may
  1111. # contain it. We will copy it from parent in such cases.
  1112. if len(f4m_formats) == 1:
  1113. f = f4m_formats[0]
  1114. f.update({
  1115. 'tbr': f.get('tbr') or tbr,
  1116. 'width': f.get('width') or width,
  1117. 'height': f.get('height') or height,
  1118. 'format_id': f.get('format_id') if not tbr else format_id,
  1119. 'vcodec': vcodec,
  1120. })
  1121. formats.extend(f4m_formats)
  1122. continue
  1123. elif ext == 'm3u8':
  1124. formats.extend(self._extract_m3u8_formats(
  1125. manifest_url, video_id, 'mp4', preference=preference,
  1126. m3u8_id=m3u8_id, fatal=fatal))
  1127. continue
  1128. formats.append({
  1129. 'format_id': format_id,
  1130. 'url': manifest_url,
  1131. 'manifest_url': manifest_url,
  1132. 'ext': 'flv' if bootstrap_info is not None else None,
  1133. 'tbr': tbr,
  1134. 'width': width,
  1135. 'height': height,
  1136. 'vcodec': vcodec,
  1137. 'preference': preference,
  1138. })
  1139. return formats
  1140. def _m3u8_meta_format(self, m3u8_url, ext=None, preference=None, m3u8_id=None):
  1141. return {
  1142. 'format_id': '-'.join(filter(None, [m3u8_id, 'meta'])),
  1143. 'url': m3u8_url,
  1144. 'ext': ext,
  1145. 'protocol': 'm3u8',
  1146. 'preference': preference - 100 if preference else -100,
  1147. 'resolution': 'multiple',
  1148. 'format_note': 'Quality selection URL',
  1149. }
  1150. def _extract_m3u8_formats(self, m3u8_url, video_id, ext=None,
  1151. entry_protocol='m3u8', preference=None,
  1152. m3u8_id=None, note=None, errnote=None,
  1153. fatal=True, live=False):
  1154. res = self._download_webpage_handle(
  1155. m3u8_url, video_id,
  1156. note=note or 'Downloading m3u8 information',
  1157. errnote=errnote or 'Failed to download m3u8 information',
  1158. fatal=fatal)
  1159. if res is False:
  1160. return []
  1161. m3u8_doc, urlh = res
  1162. m3u8_url = urlh.geturl()
  1163. if '#EXT-X-FAXS-CM:' in m3u8_doc: # Adobe Flash Access
  1164. return []
  1165. formats = [self._m3u8_meta_format(m3u8_url, ext, preference, m3u8_id)]
  1166. format_url = lambda u: (
  1167. u
  1168. if re.match(r'^https?://', u)
  1169. else compat_urlparse.urljoin(m3u8_url, u))
  1170. # We should try extracting formats only from master playlists [1], i.e.
  1171. # playlists that describe available qualities. On the other hand media
  1172. # playlists [2] should be returned as is since they contain just the media
  1173. # without qualities renditions.
  1174. # Fortunately, master playlist can be easily distinguished from media
  1175. # playlist based on particular tags availability. As of [1, 2] master
  1176. # playlist tags MUST NOT appear in a media playist and vice versa.
  1177. # As of [3] #EXT-X-TARGETDURATION tag is REQUIRED for every media playlist
  1178. # and MUST NOT appear in master playlist thus we can clearly detect media
  1179. # playlist with this criterion.
  1180. # 1. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.4
  1181. # 2. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3
  1182. # 3. https://tools.ietf.org/html/draft-pantos-http-live-streaming-17#section-4.3.3.1
  1183. if '#EXT-X-TARGETDURATION' in m3u8_doc: # media playlist, return as is
  1184. return [{
  1185. 'url': m3u8_url,
  1186. 'format_id': m3u8_id,
  1187. 'ext': ext,
  1188. 'protocol': entry_protocol,
  1189. 'preference': preference,
  1190. }]
  1191. audio_in_video_stream = {}
  1192. last_info = {}
  1193. last_media = {}
  1194. for line in m3u8_doc.splitlines():
  1195. if line.startswith('#EXT-X-STREAM-INF:'):
  1196. last_info = parse_m3u8_attributes(line)
  1197. elif line.startswith('#EXT-X-MEDIA:'):
  1198. media = parse_m3u8_attributes(line)
  1199. media_type = media.get('TYPE')
  1200. if media_type in ('VIDEO', 'AUDIO'):
  1201. group_id = media.get('GROUP-ID')
  1202. media_url = media.get('URI')
  1203. if media_url:
  1204. format_id = []
  1205. for v in (group_id, media.get('NAME')):
  1206. if v:
  1207. format_id.append(v)
  1208. f = {
  1209. 'format_id': '-'.join(format_id),
  1210. 'url': format_url(media_url),
  1211. 'language': media.get('LANGUAGE'),
  1212. 'ext': ext,
  1213. 'protocol': entry_protocol,
  1214. 'preference': preference,
  1215. }
  1216. if media_type == 'AUDIO':
  1217. f['vcodec'] = 'none'
  1218. if group_id and not audio_in_video_stream.get(group_id):
  1219. audio_in_video_stream[group_id] = False
  1220. formats.append(f)
  1221. else:
  1222. # When there is no URI in EXT-X-MEDIA let this tag's
  1223. # data be used by regular URI lines below
  1224. last_media = media
  1225. if media_type == 'AUDIO' and group_id:
  1226. audio_in_video_stream[group_id] = True
  1227. elif line.startswith('#') or not line.strip():
  1228. continue
  1229. else:
  1230. tbr = int_or_none(last_info.get('AVERAGE-BANDWIDTH') or last_info.get('BANDWIDTH'), scale=1000)
  1231. format_id = []
  1232. if m3u8_id:
  1233. format_id.append(m3u8_id)
  1234. # Despite specification does not mention NAME attribute for
  1235. # EXT-X-STREAM-INF it still sometimes may be present
  1236. stream_name = last_info.get('NAME') or last_media.get('NAME')
  1237. # Bandwidth of live streams may differ over time thus making
  1238. # format_id unpredictable. So it's better to keep provided
  1239. # format_id intact.
  1240. if not live:
  1241. format_id.append(stream_name if stream_name else '%d' % (tbr if tbr else len(formats)))
  1242. manifest_url = format_url(line.strip())
  1243. f = {
  1244. 'format_id': '-'.join(format_id),
  1245. 'url': manifest_url,
  1246. 'manifest_url': manifest_url,
  1247. 'tbr': tbr,
  1248. 'ext': ext,
  1249. 'fps': float_or_none(last_info.get('FRAME-RATE')),
  1250. 'protocol': entry_protocol,
  1251. 'preference': preference,
  1252. }
  1253. resolution = last_info.get('RESOLUTION')
  1254. if resolution:
  1255. mobj = re.search(r'(?P<width>\d+)[xX](?P<height>\d+)', resolution)
  1256. if mobj:
  1257. f['width'] = int(mobj.group('width'))
  1258. f['height'] = int(mobj.group('height'))
  1259. # Unified Streaming Platform
  1260. mobj = re.search(
  1261. r'audio.*?(?:%3D|=)(\d+)(?:-video.*?(?:%3D|=)(\d+))?', f['url'])
  1262. if mobj:
  1263. abr, vbr = mobj.groups()
  1264. abr, vbr = float_or_none(abr, 1000), float_or_none(vbr, 1000)
  1265. f.update({
  1266. 'vbr': vbr,
  1267. 'abr': abr,
  1268. })
  1269. f.update(parse_codecs(last_info.get('CODECS')))
  1270. if audio_in_video_stream.get(last_info.get('AUDIO')) is False and f['vcodec'] != 'none':
  1271. # TODO: update acodec for audio only formats with the same GROUP-ID
  1272. f['acodec'] = 'none'
  1273. formats.append(f)
  1274. last_info = {}
  1275. last_media = {}
  1276. return formats
  1277. @staticmethod
  1278. def _xpath_ns(path, namespace=None):
  1279. if not namespace:
  1280. return path
  1281. out = []
  1282. for c in path.split('/'):
  1283. if not c or c == '.':
  1284. out.append(c)
  1285. else:
  1286. out.append('{%s}%s' % (namespace, c))
  1287. return '/'.join(out)
  1288. def _extract_smil_formats(self, smil_url, video_id, fatal=True, f4m_params=None, transform_source=None):
  1289. smil = self._download_smil(smil_url, video_id, fatal=fatal, transform_source=transform_source)
  1290. if smil is False:
  1291. assert not fatal
  1292. return []
  1293. namespace = self._parse_smil_namespace(smil)
  1294. return self._parse_smil_formats(
  1295. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1296. def _extract_smil_info(self, smil_url, video_id, fatal=True, f4m_params=None):
  1297. smil = self._download_smil(smil_url, video_id, fatal=fatal)
  1298. if smil is False:
  1299. return {}
  1300. return self._parse_smil(smil, smil_url, video_id, f4m_params=f4m_params)
  1301. def _download_smil(self, smil_url, video_id, fatal=True, transform_source=None):
  1302. return self._download_xml(
  1303. smil_url, video_id, 'Downloading SMIL file',
  1304. 'Unable to download SMIL file', fatal=fatal, transform_source=transform_source)
  1305. def _parse_smil(self, smil, smil_url, video_id, f4m_params=None):
  1306. namespace = self._parse_smil_namespace(smil)
  1307. formats = self._parse_smil_formats(
  1308. smil, smil_url, video_id, namespace=namespace, f4m_params=f4m_params)
  1309. subtitles = self._parse_smil_subtitles(smil, namespace=namespace)
  1310. video_id = os.path.splitext(url_basename(smil_url))[0]
  1311. title = None
  1312. description = None
  1313. upload_date = None
  1314. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1315. name = meta.attrib.get('name')
  1316. content = meta.attrib.get('content')
  1317. if not name or not content:
  1318. continue
  1319. if not title and name == 'title':
  1320. title = content
  1321. elif not description and name in ('description', 'abstract'):
  1322. description = content
  1323. elif not upload_date and name == 'date':
  1324. upload_date = unified_strdate(content)
  1325. thumbnails = [{
  1326. 'id': image.get('type'),
  1327. 'url': image.get('src'),
  1328. 'width': int_or_none(image.get('width')),
  1329. 'height': int_or_none(image.get('height')),
  1330. } for image in smil.findall(self._xpath_ns('.//image', namespace)) if image.get('src')]
  1331. return {
  1332. 'id': video_id,
  1333. 'title': title or video_id,
  1334. 'description': description,
  1335. 'upload_date': upload_date,
  1336. 'thumbnails': thumbnails,
  1337. 'formats': formats,
  1338. 'subtitles': subtitles,
  1339. }
  1340. def _parse_smil_namespace(self, smil):
  1341. return self._search_regex(
  1342. r'(?i)^{([^}]+)?}smil$', smil.tag, 'namespace', default=None)
  1343. def _parse_smil_formats(self, smil, smil_url, video_id, namespace=None, f4m_params=None, transform_rtmp_url=None):
  1344. base = smil_url
  1345. for meta in smil.findall(self._xpath_ns('./head/meta', namespace)):
  1346. b = meta.get('base') or meta.get('httpBase')
  1347. if b:
  1348. base = b
  1349. break
  1350. formats = []
  1351. rtmp_count = 0
  1352. http_count = 0
  1353. m3u8_count = 0
  1354. srcs = []
  1355. media = smil.findall(self._xpath_ns('.//video', namespace)) + smil.findall(self._xpath_ns('.//audio', namespace))
  1356. for medium in media:
  1357. src = medium.get('src')
  1358. if not src or src in srcs:
  1359. continue
  1360. srcs.append(src)
  1361. bitrate = float_or_none(medium.get('system-bitrate') or medium.get('systemBitrate'), 1000)
  1362. filesize = int_or_none(medium.get('size') or medium.get('fileSize'))
  1363. width = int_or_none(medium.get('width'))
  1364. height = int_or_none(medium.get('height'))
  1365. proto = medium.get('proto')
  1366. ext = medium.get('ext')
  1367. src_ext = determine_ext(src)
  1368. streamer = medium.get('streamer') or base
  1369. if proto == 'rtmp' or streamer.startswith('rtmp'):
  1370. rtmp_count += 1
  1371. formats.append({
  1372. 'url': streamer,
  1373. 'play_path': src,
  1374. 'ext': 'flv',
  1375. 'format_id': 'rtmp-%d' % (rtmp_count if bitrate is None else bitrate),
  1376. 'tbr': bitrate,
  1377. 'filesize': filesize,
  1378. 'width': width,
  1379. 'height': height,
  1380. })
  1381. if transform_rtmp_url:
  1382. streamer, src = transform_rtmp_url(streamer, src)
  1383. formats[-1].update({
  1384. 'url': streamer,
  1385. 'play_path': src,
  1386. })
  1387. continue
  1388. src_url = src if src.startswith('http') else compat_urlparse.urljoin(base, src)
  1389. src_url = src_url.strip()
  1390. if proto == 'm3u8' or src_ext == 'm3u8':
  1391. m3u8_formats = self._extract_m3u8_formats(
  1392. src_url, video_id, ext or 'mp4', m3u8_id='hls', fatal=False)
  1393. if len(m3u8_formats) == 1:
  1394. m3u8_count += 1
  1395. m3u8_formats[0].update({
  1396. 'format_id': 'hls-%d' % (m3u8_count if bitrate is None else bitrate),
  1397. 'tbr': bitrate,
  1398. 'width': width,
  1399. 'height': height,
  1400. })
  1401. formats.extend(m3u8_formats)
  1402. continue
  1403. if src_ext == 'f4m':
  1404. f4m_url = src_url
  1405. if not f4m_params:
  1406. f4m_params = {
  1407. 'hdcore': '3.2.0',
  1408. 'plugin': 'flowplayer-3.2.0.1',
  1409. }
  1410. f4m_url += '&' if '?' in f4m_url else '?'
  1411. f4m_url += compat_urllib_parse_urlencode(f4m_params)
  1412. formats.extend(self._extract_f4m_formats(f4m_url, video_id, f4m_id='hds', fatal=False))
  1413. continue
  1414. if src_url.startswith('http') and self._is_valid_url(src, video_id):
  1415. http_count += 1
  1416. formats.append({
  1417. 'url': src_url,
  1418. 'ext': ext or src_ext or 'flv',
  1419. 'format_id': 'http-%d' % (bitrate or http_count),
  1420. 'tbr': bitrate,
  1421. 'filesize': filesize,
  1422. 'width': width,
  1423. 'height': height,
  1424. })
  1425. continue
  1426. return formats
  1427. def _parse_smil_subtitles(self, smil, namespace=None, subtitles_lang='en'):
  1428. urls = []
  1429. subtitles = {}
  1430. for num, textstream in enumerate(smil.findall(self._xpath_ns('.//textstream', namespace))):
  1431. src = textstream.get('src')
  1432. if not src or src in urls:
  1433. continue
  1434. urls.append(src)
  1435. ext = textstream.get('ext') or mimetype2ext(textstream.get('type')) or determine_ext(src)
  1436. lang = textstream.get('systemLanguage') or textstream.get('systemLanguageName') or textstream.get('lang') or subtitles_lang
  1437. subtitles.setdefault(lang, []).append({
  1438. 'url': src,
  1439. 'ext': ext,
  1440. })
  1441. return subtitles
  1442. def _extract_xspf_playlist(self, playlist_url, playlist_id, fatal=True):
  1443. xspf = self._download_xml(
  1444. playlist_url, playlist_id, 'Downloading xpsf playlist',
  1445. 'Unable to download xspf manifest', fatal=fatal)
  1446. if xspf is False:
  1447. return []
  1448. return self._parse_xspf(xspf, playlist_id)
  1449. def _parse_xspf(self, playlist, playlist_id):
  1450. NS_MAP = {
  1451. 'xspf': 'http://xspf.org/ns/0/',
  1452. 's1': 'http://static.streamone.nl/player/ns/0',
  1453. }
  1454. entries = []
  1455. for track in playlist.findall(xpath_with_ns('./xspf:trackList/xspf:track', NS_MAP)):
  1456. title = xpath_text(
  1457. track, xpath_with_ns('./xspf:title', NS_MAP), 'title', default=playlist_id)
  1458. description = xpath_text(
  1459. track, xpath_with_ns('./xspf:annotation', NS_MAP), 'description')
  1460. thumbnail = xpath_text(
  1461. track, xpath_with_ns('./xspf:image', NS_MAP), 'thumbnail')
  1462. duration = float_or_none(
  1463. xpath_text(track, xpath_with_ns('./xspf:duration', NS_MAP), 'duration'), 1000)
  1464. formats = [{
  1465. 'url': location.text,
  1466. 'format_id': location.get(xpath_with_ns('s1:label', NS_MAP)),
  1467. 'width': int_or_none(location.get(xpath_with_ns('s1:width', NS_MAP))),
  1468. 'height': int_or_none(location.get(xpath_with_ns('s1:height', NS_MAP))),
  1469. } for location in track.findall(xpath_with_ns('./xspf:location', NS_MAP))]
  1470. self._sort_formats(formats)
  1471. entries.append({
  1472. 'id': playlist_id,
  1473. 'title': title,
  1474. 'description': description,
  1475. 'thumbnail': thumbnail,
  1476. 'duration': duration,
  1477. 'formats': formats,
  1478. })
  1479. return entries
  1480. def _extract_mpd_formats(self, mpd_url, video_id, mpd_id=None, note=None, errnote=None, fatal=True, formats_dict={}):
  1481. res = self._download_webpage_handle(
  1482. mpd_url, video_id,
  1483. note=note or 'Downloading MPD manifest',
  1484. errnote=errnote or 'Failed to download MPD manifest',
  1485. fatal=fatal)
  1486. if res is False:
  1487. return []
  1488. mpd, urlh = res
  1489. mpd_base_url = base_url(urlh.geturl())
  1490. return self._parse_mpd_formats(
  1491. compat_etree_fromstring(mpd.encode('utf-8')), mpd_id, mpd_base_url,
  1492. formats_dict=formats_dict, mpd_url=mpd_url)
  1493. def _parse_mpd_formats(self, mpd_doc, mpd_id=None, mpd_base_url='', formats_dict={}, mpd_url=None):
  1494. """
  1495. Parse formats from MPD manifest.
  1496. References:
  1497. 1. MPEG-DASH Standard, ISO/IEC 23009-1:2014(E),
  1498. http://standards.iso.org/ittf/PubliclyAvailableStandards/c065274_ISO_IEC_23009-1_2014.zip
  1499. 2. https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP
  1500. """
  1501. if mpd_doc.get('type') == 'dynamic':
  1502. return []
  1503. namespace = self._search_regex(r'(?i)^{([^}]+)?}MPD$', mpd_doc.tag, 'namespace', default=None)
  1504. def _add_ns(path):
  1505. return self._xpath_ns(path, namespace)
  1506. def is_drm_protected(element):
  1507. return element.find(_add_ns('ContentProtection')) is not None
  1508. def extract_multisegment_info(element, ms_parent_info):
  1509. ms_info = ms_parent_info.copy()
  1510. # As per [1, 5.3.9.2.2] SegmentList and SegmentTemplate share some
  1511. # common attributes and elements. We will only extract relevant
  1512. # for us.
  1513. def extract_common(source):
  1514. segment_timeline = source.find(_add_ns('SegmentTimeline'))
  1515. if segment_timeline is not None:
  1516. s_e = segment_timeline.findall(_add_ns('S'))
  1517. if s_e:
  1518. ms_info['total_number'] = 0
  1519. ms_info['s'] = []
  1520. for s in s_e:
  1521. r = int(s.get('r', 0))
  1522. ms_info['total_number'] += 1 + r
  1523. ms_info['s'].append({
  1524. 't': int(s.get('t', 0)),
  1525. # @d is mandatory (see [1, 5.3.9.6.2, Table 17, page 60])
  1526. 'd': int(s.attrib['d']),
  1527. 'r': r,
  1528. })
  1529. start_number = source.get('startNumber')
  1530. if start_number:
  1531. ms_info['start_number'] = int(start_number)
  1532. timescale = source.get('timescale')
  1533. if timescale:
  1534. ms_info['timescale'] = int(timescale)
  1535. segment_duration = source.get('duration')
  1536. if segment_duration:
  1537. ms_info['segment_duration'] = int(segment_duration)
  1538. def extract_Initialization(source):
  1539. initialization = source.find(_add_ns('Initialization'))
  1540. if initialization is not None:
  1541. ms_info['initialization_url'] = initialization.attrib['sourceURL']
  1542. segment_list = element.find(_add_ns('SegmentList'))
  1543. if segment_list is not None:
  1544. extract_common(segment_list)
  1545. extract_Initialization(segment_list)
  1546. segment_urls_e = segment_list.findall(_add_ns('SegmentURL'))
  1547. if segment_urls_e:
  1548. ms_info['segment_urls'] = [segment.attrib['media'] for segment in segment_urls_e]
  1549. else:
  1550. segment_template = element.find(_add_ns('SegmentTemplate'))
  1551. if segment_template is not None:
  1552. extract_common(segment_template)
  1553. media = segment_template.get('media')
  1554. if media:
  1555. ms_info['media'] = media
  1556. initialization = segment_template.get('initialization')
  1557. if initialization:
  1558. ms_info['initialization'] = initialization
  1559. else:
  1560. extract_Initialization(segment_template)
  1561. return ms_info
  1562. mpd_duration = parse_duration(mpd_doc.get('mediaPresentationDuration'))
  1563. formats = []
  1564. for period in mpd_doc.findall(_add_ns('Period')):
  1565. period_duration = parse_duration(period.get('duration')) or mpd_duration
  1566. period_ms_info = extract_multisegment_info(period, {
  1567. 'start_number': 1,
  1568. 'timescale': 1,
  1569. })
  1570. for adaptation_set in period.findall(_add_ns('AdaptationSet')):
  1571. if is_drm_protected(adaptation_set):
  1572. continue
  1573. adaption_set_ms_info = extract_multisegment_info(adaptation_set, period_ms_info)
  1574. for representation in adaptation_set.findall(_add_ns('Representation')):
  1575. if is_drm_protected(representation):
  1576. continue
  1577. representation_attrib = adaptation_set.attrib.copy()
  1578. representation_attrib.update(representation.attrib)
  1579. # According to [1, 5.3.7.2, Table 9, page 41], @mimeType is mandatory
  1580. mime_type = representation_attrib['mimeType']
  1581. content_type = mime_type.split('/')[0]
  1582. if content_type == 'text':
  1583. # TODO implement WebVTT downloading
  1584. pass
  1585. elif content_type == 'video' or content_type == 'audio':
  1586. base_url = ''
  1587. for element in (representation, adaptation_set, period, mpd_doc):
  1588. base_url_e = element.find(_add_ns('BaseURL'))
  1589. if base_url_e is not None:
  1590. base_url = base_url_e.text + base_url
  1591. if re.match(r'^https?://', base_url):
  1592. break
  1593. if mpd_base_url and not re.match(r'^https?://', base_url):
  1594. if not mpd_base_url.endswith('/') and not base_url.startswith('/'):
  1595. mpd_base_url += '/'
  1596. base_url = mpd_base_url + base_url
  1597. representation_id = representation_attrib.get('id')
  1598. lang = representation_attrib.get('lang')
  1599. url_el = representation.find(_add_ns('BaseURL'))
  1600. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength') if url_el is not None else None)
  1601. bandwidth = int_or_none(representation_attrib.get('bandwidth'))
  1602. f = {
  1603. 'format_id': '%s-%s' % (mpd_id, representation_id) if mpd_id else representation_id,
  1604. 'url': base_url,
  1605. 'manifest_url': mpd_url,
  1606. 'ext': mimetype2ext(mime_type),
  1607. 'width': int_or_none(representation_attrib.get('width')),
  1608. 'height': int_or_none(representation_attrib.get('height')),
  1609. 'tbr': int_or_none(bandwidth, 1000),
  1610. 'asr': int_or_none(representation_attrib.get('audioSamplingRate')),
  1611. 'fps': int_or_none(representation_attrib.get('frameRate')),
  1612. 'language': lang if lang not in ('mul', 'und', 'zxx', 'mis') else None,
  1613. 'format_note': 'DASH %s' % content_type,
  1614. 'filesize': filesize,
  1615. }
  1616. f.update(parse_codecs(representation_attrib.get('codecs')))
  1617. representation_ms_info = extract_multisegment_info(representation, adaption_set_ms_info)
  1618. def prepare_template(template_name, identifiers):
  1619. t = representation_ms_info[template_name]
  1620. t = t.replace('$RepresentationID$', representation_id)
  1621. t = re.sub(r'\$(%s)\$' % '|'.join(identifiers), r'%(\1)d', t)
  1622. t = re.sub(r'\$(%s)%%([^$]+)\$' % '|'.join(identifiers), r'%(\1)\2', t)
  1623. t.replace('$$', '$')
  1624. return t
  1625. # @initialization is a regular template like @media one
  1626. # so it should be handled just the same way (see
  1627. # https://github.com/rg3/youtube-dl/issues/11605)
  1628. if 'initialization' in representation_ms_info:
  1629. initialization_template = prepare_template(
  1630. 'initialization',
  1631. # As per [1, 5.3.9.4.2, Table 15, page 54] $Number$ and
  1632. # $Time$ shall not be included for @initialization thus
  1633. # only $Bandwidth$ remains
  1634. ('Bandwidth', ))
  1635. representation_ms_info['initialization_url'] = initialization_template % {
  1636. 'Bandwidth': bandwidth,
  1637. }
  1638. if 'segment_urls' not in representation_ms_info and 'media' in representation_ms_info:
  1639. media_template = prepare_template('media', ('Number', 'Bandwidth', 'Time'))
  1640. # As per [1, 5.3.9.4.4, Table 16, page 55] $Number$ and $Time$
  1641. # can't be used at the same time
  1642. if '%(Number' in media_template and 's' not in representation_ms_info:
  1643. segment_duration = None
  1644. if 'total_number' not in representation_ms_info and 'segment_duration':
  1645. segment_duration = float_or_none(representation_ms_info['segment_duration'], representation_ms_info['timescale'])
  1646. representation_ms_info['total_number'] = int(math.ceil(float(period_duration) / segment_duration))
  1647. representation_ms_info['fragments'] = [{
  1648. 'url': media_template % {
  1649. 'Number': segment_number,
  1650. 'Bandwidth': bandwidth,
  1651. },
  1652. 'duration': segment_duration,
  1653. } for segment_number in range(
  1654. representation_ms_info['start_number'],
  1655. representation_ms_info['total_number'] + representation_ms_info['start_number'])]
  1656. else:
  1657. # $Number*$ or $Time$ in media template with S list available
  1658. # Example $Number*$: http://www.svtplay.se/klipp/9023742/stopptid-om-bjorn-borg
  1659. # Example $Time$: https://play.arkena.com/embed/avp/v2/player/media/b41dda37-d8e7-4d3f-b1b5-9a9db578bdfe/1/129411
  1660. representation_ms_info['fragments'] = []
  1661. segment_time = 0
  1662. segment_d = None
  1663. segment_number = representation_ms_info['start_number']
  1664. def add_segment_url():
  1665. segment_url = media_template % {
  1666. 'Time': segment_time,
  1667. 'Bandwidth': bandwidth,
  1668. 'Number': segment_number,
  1669. }
  1670. representation_ms_info['fragments'].append({
  1671. 'url': segment_url,
  1672. 'duration': float_or_none(segment_d, representation_ms_info['timescale']),
  1673. })
  1674. for num, s in enumerate(representation_ms_info['s']):
  1675. segment_time = s.get('t') or segment_time
  1676. segment_d = s['d']
  1677. add_segment_url()
  1678. segment_number += 1
  1679. for r in range(s.get('r', 0)):
  1680. segment_time += segment_d
  1681. add_segment_url()
  1682. segment_number += 1
  1683. segment_time += segment_d
  1684. elif 'segment_urls' in representation_ms_info and 's' in representation_ms_info:
  1685. # No media template
  1686. # Example: https://www.youtube.com/watch?v=iXZV5uAYMJI
  1687. # or any YouTube dashsegments video
  1688. fragments = []
  1689. segment_index = 0
  1690. timescale = representation_ms_info['timescale']
  1691. for s in representation_ms_info['s']:
  1692. duration = float_or_none(s['d'], timescale)
  1693. for r in range(s.get('r', 0) + 1):
  1694. fragments.append({
  1695. 'url': representation_ms_info['segment_urls'][segment_index],
  1696. 'duration': duration,
  1697. })
  1698. segment_index += 1
  1699. representation_ms_info['fragments'] = fragments
  1700. # NB: MPD manifest may contain direct URLs to unfragmented media.
  1701. # No fragments key is present in this case.
  1702. if 'fragments' in representation_ms_info:
  1703. f.update({
  1704. 'fragments': [],
  1705. 'protocol': 'http_dash_segments',
  1706. })
  1707. if 'initialization_url' in representation_ms_info:
  1708. initialization_url = representation_ms_info['initialization_url']
  1709. if not f.get('url'):
  1710. f['url'] = initialization_url
  1711. f['fragments'].append({'url': initialization_url})
  1712. f['fragments'].extend(representation_ms_info['fragments'])
  1713. for fragment in f['fragments']:
  1714. fragment['url'] = urljoin(base_url, fragment['url'])
  1715. try:
  1716. existing_format = next(
  1717. fo for fo in formats
  1718. if fo['format_id'] == representation_id)
  1719. except StopIteration:
  1720. full_info = formats_dict.get(representation_id, {}).copy()
  1721. full_info.update(f)
  1722. formats.append(full_info)
  1723. else:
  1724. existing_format.update(f)
  1725. else:
  1726. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  1727. return formats
  1728. def _extract_ism_formats(self, ism_url, video_id, ism_id=None, note=None, errnote=None, fatal=True):
  1729. res = self._download_webpage_handle(
  1730. ism_url, video_id,
  1731. note=note or 'Downloading ISM manifest',
  1732. errnote=errnote or 'Failed to download ISM manifest',
  1733. fatal=fatal)
  1734. if res is False:
  1735. return []
  1736. ism, urlh = res
  1737. return self._parse_ism_formats(
  1738. compat_etree_fromstring(ism.encode('utf-8')), urlh.geturl(), ism_id)
  1739. def _parse_ism_formats(self, ism_doc, ism_url, ism_id=None):
  1740. if ism_doc.get('IsLive') == 'TRUE' or ism_doc.find('Protection') is not None:
  1741. return []
  1742. duration = int(ism_doc.attrib['Duration'])
  1743. timescale = int_or_none(ism_doc.get('TimeScale')) or 10000000
  1744. formats = []
  1745. for stream in ism_doc.findall('StreamIndex'):
  1746. stream_type = stream.get('Type')
  1747. if stream_type not in ('video', 'audio'):
  1748. continue
  1749. url_pattern = stream.attrib['Url']
  1750. stream_timescale = int_or_none(stream.get('TimeScale')) or timescale
  1751. stream_name = stream.get('Name')
  1752. for track in stream.findall('QualityLevel'):
  1753. fourcc = track.get('FourCC')
  1754. # TODO: add support for WVC1 and WMAP
  1755. if fourcc not in ('H264', 'AVC1', 'AACL'):
  1756. self.report_warning('%s is not a supported codec' % fourcc)
  1757. continue
  1758. tbr = int(track.attrib['Bitrate']) // 1000
  1759. width = int_or_none(track.get('MaxWidth'))
  1760. height = int_or_none(track.get('MaxHeight'))
  1761. sampling_rate = int_or_none(track.get('SamplingRate'))
  1762. track_url_pattern = re.sub(r'{[Bb]itrate}', track.attrib['Bitrate'], url_pattern)
  1763. track_url_pattern = compat_urlparse.urljoin(ism_url, track_url_pattern)
  1764. fragments = []
  1765. fragment_ctx = {
  1766. 'time': 0,
  1767. }
  1768. stream_fragments = stream.findall('c')
  1769. for stream_fragment_index, stream_fragment in enumerate(stream_fragments):
  1770. fragment_ctx['time'] = int_or_none(stream_fragment.get('t')) or fragment_ctx['time']
  1771. fragment_repeat = int_or_none(stream_fragment.get('r')) or 1
  1772. fragment_ctx['duration'] = int_or_none(stream_fragment.get('d'))
  1773. if not fragment_ctx['duration']:
  1774. try:
  1775. next_fragment_time = int(stream_fragment[stream_fragment_index + 1].attrib['t'])
  1776. except IndexError:
  1777. next_fragment_time = duration
  1778. fragment_ctx['duration'] = (next_fragment_time - fragment_ctx['time']) / fragment_repeat
  1779. for _ in range(fragment_repeat):
  1780. fragments.append({
  1781. 'url': re.sub(r'{start[ _]time}', compat_str(fragment_ctx['time']), track_url_pattern),
  1782. 'duration': fragment_ctx['duration'] / stream_timescale,
  1783. })
  1784. fragment_ctx['time'] += fragment_ctx['duration']
  1785. format_id = []
  1786. if ism_id:
  1787. format_id.append(ism_id)
  1788. if stream_name:
  1789. format_id.append(stream_name)
  1790. format_id.append(compat_str(tbr))
  1791. formats.append({
  1792. 'format_id': '-'.join(format_id),
  1793. 'url': ism_url,
  1794. 'manifest_url': ism_url,
  1795. 'ext': 'ismv' if stream_type == 'video' else 'isma',
  1796. 'width': width,
  1797. 'height': height,
  1798. 'tbr': tbr,
  1799. 'asr': sampling_rate,
  1800. 'vcodec': 'none' if stream_type == 'audio' else fourcc,
  1801. 'acodec': 'none' if stream_type == 'video' else fourcc,
  1802. 'protocol': 'ism',
  1803. 'fragments': fragments,
  1804. '_download_params': {
  1805. 'duration': duration,
  1806. 'timescale': stream_timescale,
  1807. 'width': width or 0,
  1808. 'height': height or 0,
  1809. 'fourcc': fourcc,
  1810. 'codec_private_data': track.get('CodecPrivateData'),
  1811. 'sampling_rate': sampling_rate,
  1812. 'channels': int_or_none(track.get('Channels', 2)),
  1813. 'bits_per_sample': int_or_none(track.get('BitsPerSample', 16)),
  1814. 'nal_unit_length_field': int_or_none(track.get('NALUnitLengthField', 4)),
  1815. },
  1816. })
  1817. return formats
  1818. def _parse_html5_media_entries(self, base_url, webpage, video_id, m3u8_id=None, m3u8_entry_protocol='m3u8', mpd_id=None, preference=None):
  1819. def absolute_url(video_url):
  1820. return compat_urlparse.urljoin(base_url, video_url)
  1821. def parse_content_type(content_type):
  1822. if not content_type:
  1823. return {}
  1824. ctr = re.search(r'(?P<mimetype>[^/]+/[^;]+)(?:;\s*codecs="?(?P<codecs>[^"]+))?', content_type)
  1825. if ctr:
  1826. mimetype, codecs = ctr.groups()
  1827. f = parse_codecs(codecs)
  1828. f['ext'] = mimetype2ext(mimetype)
  1829. return f
  1830. return {}
  1831. def _media_formats(src, cur_media_type):
  1832. full_url = absolute_url(src)
  1833. ext = determine_ext(full_url)
  1834. if ext == 'm3u8':
  1835. is_plain_url = False
  1836. formats = self._extract_m3u8_formats(
  1837. full_url, video_id, ext='mp4',
  1838. entry_protocol=m3u8_entry_protocol, m3u8_id=m3u8_id,
  1839. preference=preference)
  1840. elif ext == 'mpd':
  1841. is_plain_url = False
  1842. formats = self._extract_mpd_formats(
  1843. full_url, video_id, mpd_id=mpd_id)
  1844. else:
  1845. is_plain_url = True
  1846. formats = [{
  1847. 'url': full_url,
  1848. 'vcodec': 'none' if cur_media_type == 'audio' else None,
  1849. }]
  1850. return is_plain_url, formats
  1851. entries = []
  1852. media_tags = [(media_tag, media_type, '')
  1853. for media_tag, media_type
  1854. in re.findall(r'(?s)(<(video|audio)[^>]*/>)', webpage)]
  1855. media_tags.extend(re.findall(
  1856. # We only allow video|audio followed by a whitespace or '>'.
  1857. # Allowing more characters may end up in significant slow down (see
  1858. # https://github.com/rg3/youtube-dl/issues/11979, example URL:
  1859. # http://www.porntrex.com/maps/videositemap.xml).
  1860. r'(?s)(<(?P<tag>video|audio)(?:\s+[^>]*)?>)(.*?)</(?P=tag)>', webpage))
  1861. for media_tag, media_type, media_content in media_tags:
  1862. media_info = {
  1863. 'formats': [],
  1864. 'subtitles': {},
  1865. }
  1866. media_attributes = extract_attributes(media_tag)
  1867. src = media_attributes.get('src')
  1868. if src:
  1869. _, formats = _media_formats(src, media_type)
  1870. media_info['formats'].extend(formats)
  1871. media_info['thumbnail'] = media_attributes.get('poster')
  1872. if media_content:
  1873. for source_tag in re.findall(r'<source[^>]+>', media_content):
  1874. source_attributes = extract_attributes(source_tag)
  1875. src = source_attributes.get('src')
  1876. if not src:
  1877. continue
  1878. is_plain_url, formats = _media_formats(src, media_type)
  1879. if is_plain_url:
  1880. f = parse_content_type(source_attributes.get('type'))
  1881. f.update(formats[0])
  1882. media_info['formats'].append(f)
  1883. else:
  1884. media_info['formats'].extend(formats)
  1885. for track_tag in re.findall(r'<track[^>]+>', media_content):
  1886. track_attributes = extract_attributes(track_tag)
  1887. kind = track_attributes.get('kind')
  1888. if not kind or kind in ('subtitles', 'captions'):
  1889. src = track_attributes.get('src')
  1890. if not src:
  1891. continue
  1892. lang = track_attributes.get('srclang') or track_attributes.get('lang') or track_attributes.get('label')
  1893. media_info['subtitles'].setdefault(lang, []).append({
  1894. 'url': absolute_url(src),
  1895. })
  1896. if media_info['formats'] or media_info['subtitles']:
  1897. entries.append(media_info)
  1898. return entries
  1899. def _extract_akamai_formats(self, manifest_url, video_id, hosts={}):
  1900. formats = []
  1901. hdcore_sign = 'hdcore=3.7.0'
  1902. f4m_url = re.sub(r'(https?://[^/+])/i/', r'\1/z/', manifest_url).replace('/master.m3u8', '/manifest.f4m')
  1903. hds_host = hosts.get('hds')
  1904. if hds_host:
  1905. f4m_url = re.sub(r'(https?://)[^/]+', r'\1' + hds_host, f4m_url)
  1906. if 'hdcore=' not in f4m_url:
  1907. f4m_url += ('&' if '?' in f4m_url else '?') + hdcore_sign
  1908. f4m_formats = self._extract_f4m_formats(
  1909. f4m_url, video_id, f4m_id='hds', fatal=False)
  1910. for entry in f4m_formats:
  1911. entry.update({'extra_param_to_segment_url': hdcore_sign})
  1912. formats.extend(f4m_formats)
  1913. m3u8_url = re.sub(r'(https?://[^/]+)/z/', r'\1/i/', manifest_url).replace('/manifest.f4m', '/master.m3u8')
  1914. hls_host = hosts.get('hls')
  1915. if hls_host:
  1916. m3u8_url = re.sub(r'(https?://)[^/]+', r'\1' + hls_host, m3u8_url)
  1917. formats.extend(self._extract_m3u8_formats(
  1918. m3u8_url, video_id, 'mp4', 'm3u8_native',
  1919. m3u8_id='hls', fatal=False))
  1920. return formats
  1921. def _extract_wowza_formats(self, url, video_id, m3u8_entry_protocol='m3u8_native', skip_protocols=[]):
  1922. url = re.sub(r'/(?:manifest|playlist|jwplayer)\.(?:m3u8|f4m|mpd|smil)', '', url)
  1923. url_base = self._search_regex(r'(?:https?|rtmp|rtsp)(://[^?]+)', url, 'format url')
  1924. http_base_url = 'http' + url_base
  1925. formats = []
  1926. if 'm3u8' not in skip_protocols:
  1927. formats.extend(self._extract_m3u8_formats(
  1928. http_base_url + '/playlist.m3u8', video_id, 'mp4',
  1929. m3u8_entry_protocol, m3u8_id='hls', fatal=False))
  1930. if 'f4m' not in skip_protocols:
  1931. formats.extend(self._extract_f4m_formats(
  1932. http_base_url + '/manifest.f4m',
  1933. video_id, f4m_id='hds', fatal=False))
  1934. if 'dash' not in skip_protocols:
  1935. formats.extend(self._extract_mpd_formats(
  1936. http_base_url + '/manifest.mpd',
  1937. video_id, mpd_id='dash', fatal=False))
  1938. if re.search(r'(?:/smil:|\.smil)', url_base):
  1939. if 'smil' not in skip_protocols:
  1940. rtmp_formats = self._extract_smil_formats(
  1941. http_base_url + '/jwplayer.smil',
  1942. video_id, fatal=False)
  1943. for rtmp_format in rtmp_formats:
  1944. rtsp_format = rtmp_format.copy()
  1945. rtsp_format['url'] = '%s/%s' % (rtmp_format['url'], rtmp_format['play_path'])
  1946. del rtsp_format['play_path']
  1947. del rtsp_format['ext']
  1948. rtsp_format.update({
  1949. 'url': rtsp_format['url'].replace('rtmp://', 'rtsp://'),
  1950. 'format_id': rtmp_format['format_id'].replace('rtmp', 'rtsp'),
  1951. 'protocol': 'rtsp',
  1952. })
  1953. formats.extend([rtmp_format, rtsp_format])
  1954. else:
  1955. for protocol in ('rtmp', 'rtsp'):
  1956. if protocol not in skip_protocols:
  1957. formats.append({
  1958. 'url': protocol + url_base,
  1959. 'format_id': protocol,
  1960. 'protocol': protocol,
  1961. })
  1962. return formats
  1963. @staticmethod
  1964. def _find_jwplayer_data(webpage):
  1965. mobj = re.search(
  1966. r'jwplayer\((?P<quote>[\'"])[^\'" ]+(?P=quote)\)\.setup\s*\((?P<options>[^)]+)\)',
  1967. webpage)
  1968. if mobj:
  1969. return mobj.group('options')
  1970. def _extract_jwplayer_data(self, webpage, video_id, *args, **kwargs):
  1971. jwplayer_data = self._parse_json(
  1972. self._find_jwplayer_data(webpage), video_id,
  1973. transform_source=js_to_json)
  1974. return self._parse_jwplayer_data(
  1975. jwplayer_data, video_id, *args, **kwargs)
  1976. def _parse_jwplayer_data(self, jwplayer_data, video_id=None, require_title=True,
  1977. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  1978. # JWPlayer backward compatibility: flattened playlists
  1979. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/api/config.js#L81-L96
  1980. if 'playlist' not in jwplayer_data:
  1981. jwplayer_data = {'playlist': [jwplayer_data]}
  1982. entries = []
  1983. # JWPlayer backward compatibility: single playlist item
  1984. # https://github.com/jwplayer/jwplayer/blob/v7.7.0/src/js/playlist/playlist.js#L10
  1985. if not isinstance(jwplayer_data['playlist'], list):
  1986. jwplayer_data['playlist'] = [jwplayer_data['playlist']]
  1987. for video_data in jwplayer_data['playlist']:
  1988. # JWPlayer backward compatibility: flattened sources
  1989. # https://github.com/jwplayer/jwplayer/blob/v7.4.3/src/js/playlist/item.js#L29-L35
  1990. if 'sources' not in video_data:
  1991. video_data['sources'] = [video_data]
  1992. this_video_id = video_id or video_data['mediaid']
  1993. formats = self._parse_jwplayer_formats(
  1994. video_data['sources'], video_id=this_video_id, m3u8_id=m3u8_id,
  1995. mpd_id=mpd_id, rtmp_params=rtmp_params, base_url=base_url)
  1996. self._sort_formats(formats)
  1997. subtitles = {}
  1998. tracks = video_data.get('tracks')
  1999. if tracks and isinstance(tracks, list):
  2000. for track in tracks:
  2001. if track.get('kind') != 'captions':
  2002. continue
  2003. track_url = urljoin(base_url, track.get('file'))
  2004. if not track_url:
  2005. continue
  2006. subtitles.setdefault(track.get('label') or 'en', []).append({
  2007. 'url': self._proto_relative_url(track_url)
  2008. })
  2009. entries.append({
  2010. 'id': this_video_id,
  2011. 'title': video_data['title'] if require_title else video_data.get('title'),
  2012. 'description': video_data.get('description'),
  2013. 'thumbnail': self._proto_relative_url(video_data.get('image')),
  2014. 'timestamp': int_or_none(video_data.get('pubdate')),
  2015. 'duration': float_or_none(jwplayer_data.get('duration') or video_data.get('duration')),
  2016. 'subtitles': subtitles,
  2017. 'formats': formats,
  2018. })
  2019. if len(entries) == 1:
  2020. return entries[0]
  2021. else:
  2022. return self.playlist_result(entries)
  2023. def _parse_jwplayer_formats(self, jwplayer_sources_data, video_id=None,
  2024. m3u8_id=None, mpd_id=None, rtmp_params=None, base_url=None):
  2025. formats = []
  2026. for source in jwplayer_sources_data:
  2027. source_url = self._proto_relative_url(source['file'])
  2028. if base_url:
  2029. source_url = compat_urlparse.urljoin(base_url, source_url)
  2030. source_type = source.get('type') or ''
  2031. ext = mimetype2ext(source_type) or determine_ext(source_url)
  2032. if source_type == 'hls' or ext == 'm3u8':
  2033. formats.extend(self._extract_m3u8_formats(
  2034. source_url, video_id, 'mp4', entry_protocol='m3u8_native',
  2035. m3u8_id=m3u8_id, fatal=False))
  2036. elif ext == 'mpd':
  2037. formats.extend(self._extract_mpd_formats(
  2038. source_url, video_id, mpd_id=mpd_id, fatal=False))
  2039. elif ext == 'smil':
  2040. formats.extend(self._extract_smil_formats(
  2041. source_url, video_id, fatal=False))
  2042. # https://github.com/jwplayer/jwplayer/blob/master/src/js/providers/default.js#L67
  2043. elif source_type.startswith('audio') or ext in (
  2044. 'oga', 'aac', 'mp3', 'mpeg', 'vorbis'):
  2045. formats.append({
  2046. 'url': source_url,
  2047. 'vcodec': 'none',
  2048. 'ext': ext,
  2049. })
  2050. else:
  2051. height = int_or_none(source.get('height'))
  2052. if height is None:
  2053. # Often no height is provided but there is a label in
  2054. # format like "1080p", "720p SD", or 1080.
  2055. height = int_or_none(self._search_regex(
  2056. r'^(\d{3,4})[pP]?(?:\b|$)', compat_str(source.get('label') or ''),
  2057. 'height', default=None))
  2058. a_format = {
  2059. 'url': source_url,
  2060. 'width': int_or_none(source.get('width')),
  2061. 'height': height,
  2062. 'tbr': int_or_none(source.get('bitrate')),
  2063. 'ext': ext,
  2064. }
  2065. if source_url.startswith('rtmp'):
  2066. a_format['ext'] = 'flv'
  2067. # See com/longtailvideo/jwplayer/media/RTMPMediaProvider.as
  2068. # of jwplayer.flash.swf
  2069. rtmp_url_parts = re.split(
  2070. r'((?:mp4|mp3|flv):)', source_url, 1)
  2071. if len(rtmp_url_parts) == 3:
  2072. rtmp_url, prefix, play_path = rtmp_url_parts
  2073. a_format.update({
  2074. 'url': rtmp_url,
  2075. 'play_path': prefix + play_path,
  2076. })
  2077. if rtmp_params:
  2078. a_format.update(rtmp_params)
  2079. formats.append(a_format)
  2080. return formats
  2081. def _live_title(self, name):
  2082. """ Generate the title for a live video """
  2083. now = datetime.datetime.now()
  2084. now_str = now.strftime('%Y-%m-%d %H:%M')
  2085. return name + ' ' + now_str
  2086. def _int(self, v, name, fatal=False, **kwargs):
  2087. res = int_or_none(v, **kwargs)
  2088. if 'get_attr' in kwargs:
  2089. print(getattr(v, kwargs['get_attr']))
  2090. if res is None:
  2091. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  2092. if fatal:
  2093. raise ExtractorError(msg)
  2094. else:
  2095. self._downloader.report_warning(msg)
  2096. return res
  2097. def _float(self, v, name, fatal=False, **kwargs):
  2098. res = float_or_none(v, **kwargs)
  2099. if res is None:
  2100. msg = 'Failed to extract %s: Could not parse value %r' % (name, v)
  2101. if fatal:
  2102. raise ExtractorError(msg)
  2103. else:
  2104. self._downloader.report_warning(msg)
  2105. return res
  2106. def _set_cookie(self, domain, name, value, expire_time=None):
  2107. cookie = compat_cookiejar.Cookie(
  2108. 0, name, value, None, None, domain, None,
  2109. None, '/', True, False, expire_time, '', None, None, None)
  2110. self._downloader.cookiejar.set_cookie(cookie)
  2111. def _get_cookies(self, url):
  2112. """ Return a compat_cookies.SimpleCookie with the cookies for the url """
  2113. req = sanitized_Request(url)
  2114. self._downloader.cookiejar.add_cookie_header(req)
  2115. return compat_cookies.SimpleCookie(req.get_header('Cookie'))
  2116. def get_testcases(self, include_onlymatching=False):
  2117. t = getattr(self, '_TEST', None)
  2118. if t:
  2119. assert not hasattr(self, '_TESTS'), \
  2120. '%s has _TEST and _TESTS' % type(self).__name__
  2121. tests = [t]
  2122. else:
  2123. tests = getattr(self, '_TESTS', [])
  2124. for t in tests:
  2125. if not include_onlymatching and t.get('only_matching', False):
  2126. continue
  2127. t['name'] = type(self).__name__[:-len('IE')]
  2128. yield t
  2129. def is_suitable(self, age_limit):
  2130. """ Test whether the extractor is generally suitable for the given
  2131. age limit (i.e. pornographic sites are not, all others usually are) """
  2132. any_restricted = False
  2133. for tc in self.get_testcases(include_onlymatching=False):
  2134. if tc.get('playlist', []):
  2135. tc = tc['playlist'][0]
  2136. is_restricted = age_restricted(
  2137. tc.get('info_dict', {}).get('age_limit'), age_limit)
  2138. if not is_restricted:
  2139. return True
  2140. any_restricted = any_restricted or is_restricted
  2141. return not any_restricted
  2142. def extract_subtitles(self, *args, **kwargs):
  2143. if (self._downloader.params.get('writesubtitles', False) or
  2144. self._downloader.params.get('listsubtitles')):
  2145. return self._get_subtitles(*args, **kwargs)
  2146. return {}
  2147. def _get_subtitles(self, *args, **kwargs):
  2148. raise NotImplementedError('This method must be implemented by subclasses')
  2149. @staticmethod
  2150. def _merge_subtitle_items(subtitle_list1, subtitle_list2):
  2151. """ Merge subtitle items for one language. Items with duplicated URLs
  2152. will be dropped. """
  2153. list1_urls = set([item['url'] for item in subtitle_list1])
  2154. ret = list(subtitle_list1)
  2155. ret.extend([item for item in subtitle_list2 if item['url'] not in list1_urls])
  2156. return ret
  2157. @classmethod
  2158. def _merge_subtitles(cls, subtitle_dict1, subtitle_dict2):
  2159. """ Merge two subtitle dictionaries, language by language. """
  2160. ret = dict(subtitle_dict1)
  2161. for lang in subtitle_dict2:
  2162. ret[lang] = cls._merge_subtitle_items(subtitle_dict1.get(lang, []), subtitle_dict2[lang])
  2163. return ret
  2164. def extract_automatic_captions(self, *args, **kwargs):
  2165. if (self._downloader.params.get('writeautomaticsub', False) or
  2166. self._downloader.params.get('listsubtitles')):
  2167. return self._get_automatic_captions(*args, **kwargs)
  2168. return {}
  2169. def _get_automatic_captions(self, *args, **kwargs):
  2170. raise NotImplementedError('This method must be implemented by subclasses')
  2171. def mark_watched(self, *args, **kwargs):
  2172. if (self._downloader.params.get('mark_watched', False) and
  2173. (self._get_login_info()[0] is not None or
  2174. self._downloader.params.get('cookiefile') is not None)):
  2175. self._mark_watched(*args, **kwargs)
  2176. def _mark_watched(self, *args, **kwargs):
  2177. raise NotImplementedError('This method must be implemented by subclasses')
  2178. def geo_verification_headers(self):
  2179. headers = {}
  2180. geo_verification_proxy = self._downloader.params.get('geo_verification_proxy')
  2181. if geo_verification_proxy:
  2182. headers['Ytdl-request-proxy'] = geo_verification_proxy
  2183. return headers
  2184. def _generic_id(self, url):
  2185. return compat_urllib_parse_unquote(os.path.splitext(url.rstrip('/').split('/')[-1])[0])
  2186. def _generic_title(self, url):
  2187. return compat_urllib_parse_unquote(os.path.splitext(url_basename(url))[0])
  2188. class SearchInfoExtractor(InfoExtractor):
  2189. """
  2190. Base class for paged search queries extractors.
  2191. They accept URLs in the format _SEARCH_KEY(|all|[0-9]):{query}
  2192. Instances should define _SEARCH_KEY and _MAX_RESULTS.
  2193. """
  2194. @classmethod
  2195. def _make_valid_url(cls):
  2196. return r'%s(?P<prefix>|[1-9][0-9]*|all):(?P<query>[\s\S]+)' % cls._SEARCH_KEY
  2197. @classmethod
  2198. def suitable(cls, url):
  2199. return re.match(cls._make_valid_url(), url) is not None
  2200. def _real_extract(self, query):
  2201. mobj = re.match(self._make_valid_url(), query)
  2202. if mobj is None:
  2203. raise ExtractorError('Invalid search query "%s"' % query)
  2204. prefix = mobj.group('prefix')
  2205. query = mobj.group('query')
  2206. if prefix == '':
  2207. return self._get_n_results(query, 1)
  2208. elif prefix == 'all':
  2209. return self._get_n_results(query, self._MAX_RESULTS)
  2210. else:
  2211. n = int(prefix)
  2212. if n <= 0:
  2213. raise ExtractorError('invalid download number %s for query "%s"' % (n, query))
  2214. elif n > self._MAX_RESULTS:
  2215. self._downloader.report_warning('%s returns max %i results (you requested %i)' % (self._SEARCH_KEY, self._MAX_RESULTS, n))
  2216. n = self._MAX_RESULTS
  2217. return self._get_n_results(query, n)
  2218. def _get_n_results(self, query, n):
  2219. """Get a specified number of results for a query"""
  2220. raise NotImplementedError('This method must be implemented by subclasses')
  2221. @property
  2222. def SEARCH_KEY(self):
  2223. return self._SEARCH_KEY