common.py 131 KB

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