common.py 94 KB

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