common.py 141 KB

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