common.py 100 KB

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