common.py 156 KB

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