common.py 145 KB

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