common.py 157 KB

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