common.py 140 KB

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