common.py 131 KB

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