common.py 116 KB

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