2
0

common.py 108 KB

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