youtube.py 143 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import json
  5. import os.path
  6. import random
  7. import re
  8. import time
  9. import traceback
  10. from .common import InfoExtractor, SearchInfoExtractor
  11. from ..jsinterp import JSInterpreter
  12. from ..swfinterp import SWFInterpreter
  13. from ..compat import (
  14. compat_chr,
  15. compat_HTTPError,
  16. compat_kwargs,
  17. compat_parse_qs,
  18. compat_urllib_parse_unquote,
  19. compat_urllib_parse_unquote_plus,
  20. compat_urllib_parse_urlencode,
  21. compat_urllib_parse_urlparse,
  22. compat_urlparse,
  23. compat_str,
  24. )
  25. from ..utils import (
  26. bool_or_none,
  27. clean_html,
  28. dict_get,
  29. error_to_compat_str,
  30. ExtractorError,
  31. float_or_none,
  32. get_element_by_attribute,
  33. get_element_by_id,
  34. int_or_none,
  35. mimetype2ext,
  36. orderedSet,
  37. parse_codecs,
  38. parse_duration,
  39. qualities,
  40. remove_quotes,
  41. remove_start,
  42. smuggle_url,
  43. str_or_none,
  44. str_to_int,
  45. try_get,
  46. unescapeHTML,
  47. unified_strdate,
  48. unsmuggle_url,
  49. uppercase_escape,
  50. url_or_none,
  51. urlencode_postdata,
  52. )
  53. class YoutubeBaseInfoExtractor(InfoExtractor):
  54. """Provide base functions for Youtube extractors"""
  55. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  56. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  57. _LOOKUP_URL = 'https://accounts.google.com/_/signin/sl/lookup'
  58. _CHALLENGE_URL = 'https://accounts.google.com/_/signin/sl/challenge'
  59. _TFA_URL = 'https://accounts.google.com/_/signin/challenge?hl=en&TL={0}'
  60. _NETRC_MACHINE = 'youtube'
  61. # If True it will raise an error if no login info is provided
  62. _LOGIN_REQUIRED = False
  63. _PLAYLIST_ID_RE = r'(?:PL|LL|EC|UU|FL|RD|UL|TL|OLAK5uy_)[0-9A-Za-z-_]{10,}'
  64. def _set_language(self):
  65. self._set_cookie(
  66. '.youtube.com', 'PREF', 'f1=50000000&hl=en',
  67. # YouTube sets the expire time to about two months
  68. expire_time=time.time() + 2 * 30 * 24 * 3600)
  69. def _ids_to_results(self, ids):
  70. return [
  71. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  72. for vid_id in ids]
  73. def _login(self):
  74. """
  75. Attempt to log in to YouTube.
  76. True is returned if successful or skipped.
  77. False is returned if login failed.
  78. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  79. """
  80. username, password = self._get_login_info()
  81. # No authentication to be performed
  82. if username is None:
  83. if self._LOGIN_REQUIRED and self._downloader.params.get('cookiefile') is None:
  84. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  85. return True
  86. login_page = self._download_webpage(
  87. self._LOGIN_URL, None,
  88. note='Downloading login page',
  89. errnote='unable to fetch login page', fatal=False)
  90. if login_page is False:
  91. return
  92. login_form = self._hidden_inputs(login_page)
  93. def req(url, f_req, note, errnote):
  94. data = login_form.copy()
  95. data.update({
  96. 'pstMsg': 1,
  97. 'checkConnection': 'youtube',
  98. 'checkedDomains': 'youtube',
  99. 'hl': 'en',
  100. 'deviceinfo': '[null,null,null,[],null,"US",null,null,[],"GlifWebSignIn",null,[null,null,[]]]',
  101. 'f.req': json.dumps(f_req),
  102. 'flowName': 'GlifWebSignIn',
  103. 'flowEntry': 'ServiceLogin',
  104. # TODO: reverse actual botguard identifier generation algo
  105. 'bgRequest': '["identifier",""]',
  106. })
  107. return self._download_json(
  108. url, None, note=note, errnote=errnote,
  109. transform_source=lambda s: re.sub(r'^[^[]*', '', s),
  110. fatal=False,
  111. data=urlencode_postdata(data), headers={
  112. 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8',
  113. 'Google-Accounts-XSRF': 1,
  114. })
  115. def warn(message):
  116. self._downloader.report_warning(message)
  117. lookup_req = [
  118. username,
  119. None, [], None, 'US', None, None, 2, False, True,
  120. [
  121. None, None,
  122. [2, 1, None, 1,
  123. 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn',
  124. None, [], 4],
  125. 1, [None, None, []], None, None, None, True
  126. ],
  127. username,
  128. ]
  129. lookup_results = req(
  130. self._LOOKUP_URL, lookup_req,
  131. 'Looking up account info', 'Unable to look up account info')
  132. if lookup_results is False:
  133. return False
  134. user_hash = try_get(lookup_results, lambda x: x[0][2], compat_str)
  135. if not user_hash:
  136. warn('Unable to extract user hash')
  137. return False
  138. challenge_req = [
  139. user_hash,
  140. None, 1, None, [1, None, None, None, [password, None, True]],
  141. [
  142. None, None, [2, 1, None, 1, 'https://accounts.google.com/ServiceLogin?passive=true&continue=https%3A%2F%2Fwww.youtube.com%2Fsignin%3Fnext%3D%252F%26action_handle_signin%3Dtrue%26hl%3Den%26app%3Ddesktop%26feature%3Dsign_in_button&hl=en&service=youtube&uilel=3&requestPath=%2FServiceLogin&Page=PasswordSeparationSignIn', None, [], 4],
  143. 1, [None, None, []], None, None, None, True
  144. ]]
  145. challenge_results = req(
  146. self._CHALLENGE_URL, challenge_req,
  147. 'Logging in', 'Unable to log in')
  148. if challenge_results is False:
  149. return
  150. login_res = try_get(challenge_results, lambda x: x[0][5], list)
  151. if login_res:
  152. login_msg = try_get(login_res, lambda x: x[5], compat_str)
  153. warn(
  154. 'Unable to login: %s' % 'Invalid password'
  155. if login_msg == 'INCORRECT_ANSWER_ENTERED' else login_msg)
  156. return False
  157. res = try_get(challenge_results, lambda x: x[0][-1], list)
  158. if not res:
  159. warn('Unable to extract result entry')
  160. return False
  161. login_challenge = try_get(res, lambda x: x[0][0], list)
  162. if login_challenge:
  163. challenge_str = try_get(login_challenge, lambda x: x[2], compat_str)
  164. if challenge_str == 'TWO_STEP_VERIFICATION':
  165. # SEND_SUCCESS - TFA code has been successfully sent to phone
  166. # QUOTA_EXCEEDED - reached the limit of TFA codes
  167. status = try_get(login_challenge, lambda x: x[5], compat_str)
  168. if status == 'QUOTA_EXCEEDED':
  169. warn('Exceeded the limit of TFA codes, try later')
  170. return False
  171. tl = try_get(challenge_results, lambda x: x[1][2], compat_str)
  172. if not tl:
  173. warn('Unable to extract TL')
  174. return False
  175. tfa_code = self._get_tfa_info('2-step verification code')
  176. if not tfa_code:
  177. warn(
  178. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  179. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  180. return False
  181. tfa_code = remove_start(tfa_code, 'G-')
  182. tfa_req = [
  183. user_hash, None, 2, None,
  184. [
  185. 9, None, None, None, None, None, None, None,
  186. [None, tfa_code, True, 2]
  187. ]]
  188. tfa_results = req(
  189. self._TFA_URL.format(tl), tfa_req,
  190. 'Submitting TFA code', 'Unable to submit TFA code')
  191. if tfa_results is False:
  192. return False
  193. tfa_res = try_get(tfa_results, lambda x: x[0][5], list)
  194. if tfa_res:
  195. tfa_msg = try_get(tfa_res, lambda x: x[5], compat_str)
  196. warn(
  197. 'Unable to finish TFA: %s' % 'Invalid TFA code'
  198. if tfa_msg == 'INCORRECT_ANSWER_ENTERED' else tfa_msg)
  199. return False
  200. check_cookie_url = try_get(
  201. tfa_results, lambda x: x[0][-1][2], compat_str)
  202. else:
  203. CHALLENGES = {
  204. 'LOGIN_CHALLENGE': "This device isn't recognized. For your security, Google wants to make sure it's really you.",
  205. 'USERNAME_RECOVERY': 'Please provide additional information to aid in the recovery process.',
  206. 'REAUTH': "There is something unusual about your activity. For your security, Google wants to make sure it's really you.",
  207. }
  208. challenge = CHALLENGES.get(
  209. challenge_str,
  210. '%s returned error %s.' % (self.IE_NAME, challenge_str))
  211. warn('%s\nGo to https://accounts.google.com/, login and solve a challenge.' % challenge)
  212. return False
  213. else:
  214. check_cookie_url = try_get(res, lambda x: x[2], compat_str)
  215. if not check_cookie_url:
  216. warn('Unable to extract CheckCookie URL')
  217. return False
  218. check_cookie_results = self._download_webpage(
  219. check_cookie_url, None, 'Checking cookie', fatal=False)
  220. if check_cookie_results is False:
  221. return False
  222. if 'https://myaccount.google.com/' not in check_cookie_results:
  223. warn('Unable to log in')
  224. return False
  225. return True
  226. def _download_webpage_handle(self, *args, **kwargs):
  227. query = kwargs.get('query', {}).copy()
  228. query['disable_polymer'] = 'true'
  229. kwargs['query'] = query
  230. return super(YoutubeBaseInfoExtractor, self)._download_webpage_handle(
  231. *args, **compat_kwargs(kwargs))
  232. def _real_initialize(self):
  233. if self._downloader is None:
  234. return
  235. self._set_language()
  236. if not self._login():
  237. return
  238. class YoutubeEntryListBaseInfoExtractor(YoutubeBaseInfoExtractor):
  239. # Extract entries from page with "Load more" button
  240. def _entries(self, page, playlist_id):
  241. more_widget_html = content_html = page
  242. for page_num in itertools.count(1):
  243. for entry in self._process_page(content_html):
  244. yield entry
  245. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  246. if not mobj:
  247. break
  248. count = 0
  249. retries = 3
  250. while count <= retries:
  251. try:
  252. # Downloading page may result in intermittent 5xx HTTP error
  253. # that is usually worked around with a retry
  254. more = self._download_json(
  255. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  256. 'Downloading page #%s%s'
  257. % (page_num, ' (retry #%d)' % count if count else ''),
  258. transform_source=uppercase_escape)
  259. break
  260. except ExtractorError as e:
  261. if isinstance(e.cause, compat_HTTPError) and e.cause.code in (500, 503):
  262. count += 1
  263. if count <= retries:
  264. continue
  265. raise
  266. content_html = more['content_html']
  267. if not content_html.strip():
  268. # Some webpages show a "Load more" button but they don't
  269. # have more videos
  270. break
  271. more_widget_html = more['load_more_widget_html']
  272. class YoutubePlaylistBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  273. def _process_page(self, content):
  274. for video_id, video_title in self.extract_videos_from_page(content):
  275. yield self.url_result(video_id, 'Youtube', video_id, video_title)
  276. def extract_videos_from_page(self, page):
  277. ids_in_page = []
  278. titles_in_page = []
  279. for mobj in re.finditer(self._VIDEO_RE, page):
  280. # The link with index 0 is not the first video of the playlist (not sure if still actual)
  281. if 'index' in mobj.groupdict() and mobj.group('id') == '0':
  282. continue
  283. video_id = mobj.group('id')
  284. video_title = unescapeHTML(mobj.group('title'))
  285. if video_title:
  286. video_title = video_title.strip()
  287. try:
  288. idx = ids_in_page.index(video_id)
  289. if video_title and not titles_in_page[idx]:
  290. titles_in_page[idx] = video_title
  291. except ValueError:
  292. ids_in_page.append(video_id)
  293. titles_in_page.append(video_title)
  294. return zip(ids_in_page, titles_in_page)
  295. class YoutubePlaylistsBaseInfoExtractor(YoutubeEntryListBaseInfoExtractor):
  296. def _process_page(self, content):
  297. for playlist_id in orderedSet(re.findall(
  298. r'<h3[^>]+class="[^"]*yt-lockup-title[^"]*"[^>]*><a[^>]+href="/?playlist\?list=([0-9A-Za-z-_]{10,})"',
  299. content)):
  300. yield self.url_result(
  301. 'https://www.youtube.com/playlist?list=%s' % playlist_id, 'YoutubePlaylist')
  302. def _real_extract(self, url):
  303. playlist_id = self._match_id(url)
  304. webpage = self._download_webpage(url, playlist_id)
  305. title = self._og_search_title(webpage, fatal=False)
  306. return self.playlist_result(self._entries(webpage, playlist_id), playlist_id, title)
  307. class YoutubeIE(YoutubeBaseInfoExtractor):
  308. IE_DESC = 'YouTube.com'
  309. _VALID_URL = r"""(?x)^
  310. (
  311. (?:https?://|//) # http(s):// or protocol-independent URL
  312. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  313. (?:www\.)?deturl\.com/www\.youtube\.com/|
  314. (?:www\.)?pwnyoutube\.com/|
  315. (?:www\.)?hooktube\.com/|
  316. (?:www\.)?yourepeat\.com/|
  317. tube\.majestyc\.net/|
  318. # Invidious instances taken from https://github.com/omarroth/invidious/wiki/Invidious-Instances
  319. (?:(?:www|dev)\.)?invidio\.us/|
  320. (?:(?:www|no)\.)?invidiou\.sh/|
  321. (?:(?:www|fi|de)\.)?invidious\.snopyta\.org/|
  322. (?:www\.)?invidious\.kabi\.tk/|
  323. (?:www\.)?invidious\.enkirton\.net/|
  324. (?:www\.)?invidious\.13ad\.de/|
  325. (?:www\.)?invidious\.mastodon\.host/|
  326. (?:www\.)?tube\.poal\.co/|
  327. (?:www\.)?vid\.wxzm\.sx/|
  328. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  329. (?:.*?\#/)? # handle anchor (#/) redirect urls
  330. (?: # the various things that can precede the ID:
  331. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  332. |(?: # or the v= param in all its forms
  333. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  334. (?:\?|\#!?) # the params delimiter ? or # or #!
  335. (?:.*?[&;])?? # any other preceding param (like /?s=tuff&v=xxxx or ?s=tuff&amp;v=V36LpHqtcDY)
  336. v=
  337. )
  338. ))
  339. |(?:
  340. youtu\.be| # just youtu.be/xxxx
  341. vid\.plus| # or vid.plus/xxxx
  342. zwearz\.com/watch| # or zwearz.com/watch/xxxx
  343. )/
  344. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  345. )
  346. )? # all until now is optional -> you can pass the naked ID
  347. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  348. (?!.*?\blist=
  349. (?:
  350. %(playlist_id)s| # combined list/video URLs are handled by the playlist IE
  351. WL # WL are handled by the watch later IE
  352. )
  353. )
  354. (?(1).+)? # if we found the ID, everything can follow
  355. $""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  356. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  357. _formats = {
  358. '5': {'ext': 'flv', 'width': 400, 'height': 240, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  359. '6': {'ext': 'flv', 'width': 450, 'height': 270, 'acodec': 'mp3', 'abr': 64, 'vcodec': 'h263'},
  360. '13': {'ext': '3gp', 'acodec': 'aac', 'vcodec': 'mp4v'},
  361. '17': {'ext': '3gp', 'width': 176, 'height': 144, 'acodec': 'aac', 'abr': 24, 'vcodec': 'mp4v'},
  362. '18': {'ext': 'mp4', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 96, 'vcodec': 'h264'},
  363. '22': {'ext': 'mp4', 'width': 1280, 'height': 720, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  364. '34': {'ext': 'flv', 'width': 640, 'height': 360, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  365. '35': {'ext': 'flv', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  366. # itag 36 videos are either 320x180 (BaW_jenozKc) or 320x240 (__2ABJjxzNo), abr varies as well
  367. '36': {'ext': '3gp', 'width': 320, 'acodec': 'aac', 'vcodec': 'mp4v'},
  368. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  369. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072, 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264'},
  370. '43': {'ext': 'webm', 'width': 640, 'height': 360, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  371. '44': {'ext': 'webm', 'width': 854, 'height': 480, 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8'},
  372. '45': {'ext': 'webm', 'width': 1280, 'height': 720, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  373. '46': {'ext': 'webm', 'width': 1920, 'height': 1080, 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8'},
  374. '59': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  375. '78': {'ext': 'mp4', 'width': 854, 'height': 480, 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264'},
  376. # 3D videos
  377. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  378. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -20},
  379. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  380. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'acodec': 'aac', 'abr': 192, 'vcodec': 'h264', 'preference': -20},
  381. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 128, 'vcodec': 'vp8', 'preference': -20},
  382. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  383. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'acodec': 'vorbis', 'abr': 192, 'vcodec': 'vp8', 'preference': -20},
  384. # Apple HTTP Live Streaming
  385. '91': {'ext': 'mp4', 'height': 144, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  386. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  387. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  388. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 128, 'vcodec': 'h264', 'preference': -10},
  389. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  390. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 256, 'vcodec': 'h264', 'preference': -10},
  391. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 48, 'vcodec': 'h264', 'preference': -10},
  392. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'acodec': 'aac', 'abr': 24, 'vcodec': 'h264', 'preference': -10},
  393. # DASH mp4 video
  394. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'h264'},
  395. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'h264'},
  396. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  397. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264'},
  398. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264'},
  399. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'vcodec': 'h264'}, # Height can vary (https://github.com/ytdl-org/youtube-dl/issues/4559)
  400. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'vcodec': 'h264'},
  401. '212': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'h264'},
  402. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'h264'},
  403. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  404. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'h264', 'fps': 60},
  405. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'h264'},
  406. # Dash mp4 audio
  407. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 48, 'container': 'm4a_dash'},
  408. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 128, 'container': 'm4a_dash'},
  409. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'abr': 256, 'container': 'm4a_dash'},
  410. '256': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  411. '258': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'container': 'm4a_dash'},
  412. '325': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'dtse', 'container': 'm4a_dash'},
  413. '328': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'ec-3', 'container': 'm4a_dash'},
  414. # Dash webm
  415. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  416. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  417. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  418. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  419. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  420. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp8'},
  421. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'container': 'webm', 'vcodec': 'vp9'},
  422. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  423. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  424. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  425. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  426. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  427. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  428. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  429. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  430. # itag 272 videos are either 3840x2160 (e.g. RtoitU2A-3E) or 7680x4320 (sLprVF6d7Ug)
  431. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  432. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  433. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  434. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  435. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9'},
  436. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'vcodec': 'vp9', 'fps': 60},
  437. # Dash webm audio
  438. '171': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 128},
  439. '172': {'ext': 'webm', 'acodec': 'vorbis', 'format_note': 'DASH audio', 'abr': 256},
  440. # Dash webm audio with opus inside
  441. '249': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50},
  442. '250': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70},
  443. '251': {'ext': 'webm', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160},
  444. # RTMP (unnamed)
  445. '_rtmp': {'protocol': 'rtmp'},
  446. # av01 video only formats sometimes served with "unknown" codecs
  447. '394': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  448. '395': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  449. '396': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  450. '397': {'acodec': 'none', 'vcodec': 'av01.0.05M.08'},
  451. }
  452. _SUBTITLE_FORMATS = ('srv1', 'srv2', 'srv3', 'ttml', 'vtt')
  453. _GEO_BYPASS = False
  454. IE_NAME = 'youtube'
  455. _TESTS = [
  456. {
  457. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&t=1s&end=9',
  458. 'info_dict': {
  459. 'id': 'BaW_jenozKc',
  460. 'ext': 'mp4',
  461. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  462. 'uploader': 'Philipp Hagemeister',
  463. 'uploader_id': 'phihag',
  464. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
  465. 'channel_id': 'UCLqxVugv74EIW3VWh2NOa3Q',
  466. 'channel_url': r're:https?://(?:www\.)?youtube\.com/channel/UCLqxVugv74EIW3VWh2NOa3Q',
  467. 'upload_date': '20121002',
  468. 'description': 'test chars: "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
  469. 'categories': ['Science & Technology'],
  470. 'tags': ['youtube-dl'],
  471. 'duration': 10,
  472. 'view_count': int,
  473. 'like_count': int,
  474. 'dislike_count': int,
  475. 'start_time': 1,
  476. 'end_time': 9,
  477. }
  478. },
  479. {
  480. 'url': 'https://www.youtube.com/watch?v=UxxajLWwzqY',
  481. 'note': 'Test generic use_cipher_signature video (#897)',
  482. 'info_dict': {
  483. 'id': 'UxxajLWwzqY',
  484. 'ext': 'mp4',
  485. 'upload_date': '20120506',
  486. 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
  487. 'alt_title': 'I Love It (feat. Charli XCX)',
  488. 'description': 'md5:f3ceb5ef83a08d95b9d146f973157cc8',
  489. 'tags': ['Icona Pop i love it', 'sweden', 'pop music', 'big beat records', 'big beat', 'charli',
  490. 'xcx', 'charli xcx', 'girls', 'hbo', 'i love it', "i don't care", 'icona', 'pop',
  491. 'iconic ep', 'iconic', 'love', 'it'],
  492. 'duration': 180,
  493. 'uploader': 'Icona Pop',
  494. 'uploader_id': 'IconaPop',
  495. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IconaPop',
  496. 'creator': 'Icona Pop',
  497. 'track': 'I Love It (feat. Charli XCX)',
  498. 'artist': 'Icona Pop',
  499. }
  500. },
  501. {
  502. 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
  503. 'note': 'Test VEVO video with age protection (#956)',
  504. 'info_dict': {
  505. 'id': '07FYdnEawAQ',
  506. 'ext': 'mp4',
  507. 'upload_date': '20130703',
  508. 'title': 'Justin Timberlake - Tunnel Vision (Official Music Video) (Explicit)',
  509. 'alt_title': 'Tunnel Vision',
  510. 'description': 'md5:07dab3356cde4199048e4c7cd93471e1',
  511. 'duration': 419,
  512. 'uploader': 'justintimberlakeVEVO',
  513. 'uploader_id': 'justintimberlakeVEVO',
  514. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/justintimberlakeVEVO',
  515. 'creator': 'Justin Timberlake',
  516. 'track': 'Tunnel Vision',
  517. 'artist': 'Justin Timberlake',
  518. 'age_limit': 18,
  519. }
  520. },
  521. {
  522. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  523. 'note': 'Embed-only video (#1746)',
  524. 'info_dict': {
  525. 'id': 'yZIXLfi8CZQ',
  526. 'ext': 'mp4',
  527. 'upload_date': '20120608',
  528. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  529. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  530. 'uploader': 'SET India',
  531. 'uploader_id': 'setindia',
  532. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/setindia',
  533. 'age_limit': 18,
  534. }
  535. },
  536. {
  537. 'url': 'https://www.youtube.com/watch?v=BaW_jenozKc&v=UxxajLWwzqY',
  538. 'note': 'Use the first video ID in the URL',
  539. 'info_dict': {
  540. 'id': 'BaW_jenozKc',
  541. 'ext': 'mp4',
  542. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  543. 'uploader': 'Philipp Hagemeister',
  544. 'uploader_id': 'phihag',
  545. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/phihag',
  546. 'upload_date': '20121002',
  547. 'description': 'test chars: "\'/\\ä↭𝕐\ntest URL: https://github.com/rg3/youtube-dl/issues/1892\n\nThis is a test video for youtube-dl.\n\nFor more information, contact phihag@phihag.de .',
  548. 'categories': ['Science & Technology'],
  549. 'tags': ['youtube-dl'],
  550. 'duration': 10,
  551. 'view_count': int,
  552. 'like_count': int,
  553. 'dislike_count': int,
  554. },
  555. 'params': {
  556. 'skip_download': True,
  557. },
  558. },
  559. {
  560. 'url': 'https://www.youtube.com/watch?v=a9LDPn-MO4I',
  561. 'note': '256k DASH audio (format 141) via DASH manifest',
  562. 'info_dict': {
  563. 'id': 'a9LDPn-MO4I',
  564. 'ext': 'm4a',
  565. 'upload_date': '20121002',
  566. 'uploader_id': '8KVIDEO',
  567. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/8KVIDEO',
  568. 'description': '',
  569. 'uploader': '8KVIDEO',
  570. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  571. },
  572. 'params': {
  573. 'youtube_include_dash_manifest': True,
  574. 'format': '141',
  575. },
  576. 'skip': 'format 141 not served anymore',
  577. },
  578. # DASH manifest with encrypted signature
  579. {
  580. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  581. 'info_dict': {
  582. 'id': 'IB3lcPjvWLA',
  583. 'ext': 'm4a',
  584. 'title': 'Afrojack, Spree Wilson - The Spark (Official Music Video) ft. Spree Wilson',
  585. 'description': 'md5:8f5e2b82460520b619ccac1f509d43bf',
  586. 'duration': 244,
  587. 'uploader': 'AfrojackVEVO',
  588. 'uploader_id': 'AfrojackVEVO',
  589. 'upload_date': '20131011',
  590. },
  591. 'params': {
  592. 'youtube_include_dash_manifest': True,
  593. 'format': '141/bestaudio[ext=m4a]',
  594. },
  595. },
  596. # JS player signature function name containing $
  597. {
  598. 'url': 'https://www.youtube.com/watch?v=nfWlot6h_JM',
  599. 'info_dict': {
  600. 'id': 'nfWlot6h_JM',
  601. 'ext': 'm4a',
  602. 'title': 'Taylor Swift - Shake It Off',
  603. 'description': 'md5:bec2185232c05479482cb5a9b82719bf',
  604. 'duration': 242,
  605. 'uploader': 'TaylorSwiftVEVO',
  606. 'uploader_id': 'TaylorSwiftVEVO',
  607. 'upload_date': '20140818',
  608. 'creator': 'Taylor Swift',
  609. },
  610. 'params': {
  611. 'youtube_include_dash_manifest': True,
  612. 'format': '141/bestaudio[ext=m4a]',
  613. },
  614. },
  615. # Controversy video
  616. {
  617. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  618. 'info_dict': {
  619. 'id': 'T4XJQO3qol8',
  620. 'ext': 'mp4',
  621. 'duration': 219,
  622. 'upload_date': '20100909',
  623. 'uploader': 'Amazing Atheist',
  624. 'uploader_id': 'TheAmazingAtheist',
  625. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheAmazingAtheist',
  626. 'title': 'Burning Everyone\'s Koran',
  627. 'description': 'SUBSCRIBE: http://www.youtube.com/saturninefilms\n\nEven Obama has taken a stand against freedom on this issue: http://www.huffingtonpost.com/2010/09/09/obama-gma-interview-quran_n_710282.html',
  628. }
  629. },
  630. # Normal age-gate video (No vevo, embed allowed)
  631. {
  632. 'url': 'https://youtube.com/watch?v=HtVdAasjOgU',
  633. 'info_dict': {
  634. 'id': 'HtVdAasjOgU',
  635. 'ext': 'mp4',
  636. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  637. 'description': r're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  638. 'duration': 142,
  639. 'uploader': 'The Witcher',
  640. 'uploader_id': 'WitcherGame',
  641. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/WitcherGame',
  642. 'upload_date': '20140605',
  643. 'age_limit': 18,
  644. },
  645. },
  646. # Age-gate video with encrypted signature
  647. {
  648. 'url': 'https://www.youtube.com/watch?v=6kLq3WMV1nU',
  649. 'info_dict': {
  650. 'id': '6kLq3WMV1nU',
  651. 'ext': 'mp4',
  652. 'title': 'Dedication To My Ex (Miss That) (Lyric Video)',
  653. 'description': 'md5:33765bb339e1b47e7e72b5490139bb41',
  654. 'duration': 246,
  655. 'uploader': 'LloydVEVO',
  656. 'uploader_id': 'LloydVEVO',
  657. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/LloydVEVO',
  658. 'upload_date': '20110629',
  659. 'age_limit': 18,
  660. },
  661. },
  662. # video_info is None (https://github.com/ytdl-org/youtube-dl/issues/4421)
  663. # YouTube Red ad is not captured for creator
  664. {
  665. 'url': '__2ABJjxzNo',
  666. 'info_dict': {
  667. 'id': '__2ABJjxzNo',
  668. 'ext': 'mp4',
  669. 'duration': 266,
  670. 'upload_date': '20100430',
  671. 'uploader_id': 'deadmau5',
  672. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/deadmau5',
  673. 'creator': 'deadmau5',
  674. 'description': 'md5:12c56784b8032162bb936a5f76d55360',
  675. 'uploader': 'deadmau5',
  676. 'title': 'Deadmau5 - Some Chords (HD)',
  677. 'alt_title': 'Some Chords',
  678. },
  679. 'expected_warnings': [
  680. 'DASH manifest missing',
  681. ]
  682. },
  683. # Olympics (https://github.com/ytdl-org/youtube-dl/issues/4431)
  684. {
  685. 'url': 'lqQg6PlCWgI',
  686. 'info_dict': {
  687. 'id': 'lqQg6PlCWgI',
  688. 'ext': 'mp4',
  689. 'duration': 6085,
  690. 'upload_date': '20150827',
  691. 'uploader_id': 'olympic',
  692. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/olympic',
  693. 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
  694. 'uploader': 'Olympic',
  695. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  696. },
  697. 'params': {
  698. 'skip_download': 'requires avconv',
  699. }
  700. },
  701. # Non-square pixels
  702. {
  703. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  704. 'info_dict': {
  705. 'id': '_b-2C3KPAM0',
  706. 'ext': 'mp4',
  707. 'stretched_ratio': 16 / 9.,
  708. 'duration': 85,
  709. 'upload_date': '20110310',
  710. 'uploader_id': 'AllenMeow',
  711. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/AllenMeow',
  712. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  713. 'uploader': '孫ᄋᄅ',
  714. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  715. },
  716. },
  717. # url_encoded_fmt_stream_map is empty string
  718. {
  719. 'url': 'qEJwOuvDf7I',
  720. 'info_dict': {
  721. 'id': 'qEJwOuvDf7I',
  722. 'ext': 'webm',
  723. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  724. 'description': '',
  725. 'upload_date': '20150404',
  726. 'uploader_id': 'spbelect',
  727. 'uploader': 'Наблюдатели Петербурга',
  728. },
  729. 'params': {
  730. 'skip_download': 'requires avconv',
  731. },
  732. 'skip': 'This live event has ended.',
  733. },
  734. # Extraction from multiple DASH manifests (https://github.com/ytdl-org/youtube-dl/pull/6097)
  735. {
  736. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  737. 'info_dict': {
  738. 'id': 'FIl7x6_3R5Y',
  739. 'ext': 'webm',
  740. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  741. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  742. 'duration': 220,
  743. 'upload_date': '20150625',
  744. 'uploader_id': 'dorappi2000',
  745. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/dorappi2000',
  746. 'uploader': 'dorappi2000',
  747. 'formats': 'mincount:31',
  748. },
  749. 'skip': 'not actual anymore',
  750. },
  751. # DASH manifest with segment_list
  752. {
  753. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  754. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  755. 'info_dict': {
  756. 'id': 'CsmdDsKjzN8',
  757. 'ext': 'mp4',
  758. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  759. 'uploader': 'Airtek',
  760. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  761. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  762. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  763. },
  764. 'params': {
  765. 'youtube_include_dash_manifest': True,
  766. 'format': '135', # bestvideo
  767. },
  768. 'skip': 'This live event has ended.',
  769. },
  770. {
  771. # Multifeed videos (multiple cameras), URL is for Main Camera
  772. 'url': 'https://www.youtube.com/watch?v=jqWvoWXjCVs',
  773. 'info_dict': {
  774. 'id': 'jqWvoWXjCVs',
  775. 'title': 'teamPGP: Rocket League Noob Stream',
  776. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  777. },
  778. 'playlist': [{
  779. 'info_dict': {
  780. 'id': 'jqWvoWXjCVs',
  781. 'ext': 'mp4',
  782. 'title': 'teamPGP: Rocket League Noob Stream (Main Camera)',
  783. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  784. 'duration': 7335,
  785. 'upload_date': '20150721',
  786. 'uploader': 'Beer Games Beer',
  787. 'uploader_id': 'beergamesbeer',
  788. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  789. 'license': 'Standard YouTube License',
  790. },
  791. }, {
  792. 'info_dict': {
  793. 'id': '6h8e8xoXJzg',
  794. 'ext': 'mp4',
  795. 'title': 'teamPGP: Rocket League Noob Stream (kreestuh)',
  796. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  797. 'duration': 7337,
  798. 'upload_date': '20150721',
  799. 'uploader': 'Beer Games Beer',
  800. 'uploader_id': 'beergamesbeer',
  801. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  802. 'license': 'Standard YouTube License',
  803. },
  804. }, {
  805. 'info_dict': {
  806. 'id': 'PUOgX5z9xZw',
  807. 'ext': 'mp4',
  808. 'title': 'teamPGP: Rocket League Noob Stream (grizzle)',
  809. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  810. 'duration': 7337,
  811. 'upload_date': '20150721',
  812. 'uploader': 'Beer Games Beer',
  813. 'uploader_id': 'beergamesbeer',
  814. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  815. 'license': 'Standard YouTube License',
  816. },
  817. }, {
  818. 'info_dict': {
  819. 'id': 'teuwxikvS5k',
  820. 'ext': 'mp4',
  821. 'title': 'teamPGP: Rocket League Noob Stream (zim)',
  822. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  823. 'duration': 7334,
  824. 'upload_date': '20150721',
  825. 'uploader': 'Beer Games Beer',
  826. 'uploader_id': 'beergamesbeer',
  827. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/beergamesbeer',
  828. 'license': 'Standard YouTube License',
  829. },
  830. }],
  831. 'params': {
  832. 'skip_download': True,
  833. },
  834. 'skip': 'This video is not available.',
  835. },
  836. {
  837. # Multifeed video with comma in title (see https://github.com/ytdl-org/youtube-dl/issues/8536)
  838. 'url': 'https://www.youtube.com/watch?v=gVfLd0zydlo',
  839. 'info_dict': {
  840. 'id': 'gVfLd0zydlo',
  841. 'title': 'DevConf.cz 2016 Day 2 Workshops 1 14:00 - 15:30',
  842. },
  843. 'playlist_count': 2,
  844. 'skip': 'Not multifeed anymore',
  845. },
  846. {
  847. 'url': 'https://vid.plus/FlRa-iH7PGw',
  848. 'only_matching': True,
  849. },
  850. {
  851. 'url': 'https://zwearz.com/watch/9lWxNJF-ufM/electra-woman-dyna-girl-official-trailer-grace-helbig.html',
  852. 'only_matching': True,
  853. },
  854. {
  855. # Title with JS-like syntax "};" (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  856. # Also tests cut-off URL expansion in video description (see
  857. # https://github.com/ytdl-org/youtube-dl/issues/1892,
  858. # https://github.com/ytdl-org/youtube-dl/issues/8164)
  859. 'url': 'https://www.youtube.com/watch?v=lsguqyKfVQg',
  860. 'info_dict': {
  861. 'id': 'lsguqyKfVQg',
  862. 'ext': 'mp4',
  863. 'title': '{dark walk}; Loki/AC/Dishonored; collab w/Elflover21',
  864. 'alt_title': 'Dark Walk - Position Music',
  865. 'description': 'md5:8085699c11dc3f597ce0410b0dcbb34a',
  866. 'duration': 133,
  867. 'upload_date': '20151119',
  868. 'uploader_id': 'IronSoulElf',
  869. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/IronSoulElf',
  870. 'uploader': 'IronSoulElf',
  871. 'creator': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
  872. 'track': 'Dark Walk - Position Music',
  873. 'artist': 'Todd Haberman, Daniel Law Heath and Aaron Kaplan',
  874. 'album': 'Position Music - Production Music Vol. 143 - Dark Walk',
  875. },
  876. 'params': {
  877. 'skip_download': True,
  878. },
  879. },
  880. {
  881. # Tags with '};' (see https://github.com/ytdl-org/youtube-dl/issues/7468)
  882. 'url': 'https://www.youtube.com/watch?v=Ms7iBXnlUO8',
  883. 'only_matching': True,
  884. },
  885. {
  886. # Video with yt:stretch=17:0
  887. 'url': 'https://www.youtube.com/watch?v=Q39EVAstoRM',
  888. 'info_dict': {
  889. 'id': 'Q39EVAstoRM',
  890. 'ext': 'mp4',
  891. 'title': 'Clash Of Clans#14 Dicas De Ataque Para CV 4',
  892. 'description': 'md5:ee18a25c350637c8faff806845bddee9',
  893. 'upload_date': '20151107',
  894. 'uploader_id': 'UCCr7TALkRbo3EtFzETQF1LA',
  895. 'uploader': 'CH GAMER DROID',
  896. },
  897. 'params': {
  898. 'skip_download': True,
  899. },
  900. 'skip': 'This video does not exist.',
  901. },
  902. {
  903. # Video licensed under Creative Commons
  904. 'url': 'https://www.youtube.com/watch?v=M4gD1WSo5mA',
  905. 'info_dict': {
  906. 'id': 'M4gD1WSo5mA',
  907. 'ext': 'mp4',
  908. 'title': 'md5:e41008789470fc2533a3252216f1c1d1',
  909. 'description': 'md5:a677553cf0840649b731a3024aeff4cc',
  910. 'duration': 721,
  911. 'upload_date': '20150127',
  912. 'uploader_id': 'BerkmanCenter',
  913. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/BerkmanCenter',
  914. 'uploader': 'The Berkman Klein Center for Internet & Society',
  915. 'license': 'Creative Commons Attribution license (reuse allowed)',
  916. },
  917. 'params': {
  918. 'skip_download': True,
  919. },
  920. },
  921. {
  922. # Channel-like uploader_url
  923. 'url': 'https://www.youtube.com/watch?v=eQcmzGIKrzg',
  924. 'info_dict': {
  925. 'id': 'eQcmzGIKrzg',
  926. 'ext': 'mp4',
  927. 'title': 'Democratic Socialism and Foreign Policy | Bernie Sanders',
  928. 'description': 'md5:dda0d780d5a6e120758d1711d062a867',
  929. 'duration': 4060,
  930. 'upload_date': '20151119',
  931. 'uploader': 'Bernie Sanders',
  932. 'uploader_id': 'UCH1dpzjCEiGAt8CXkryhkZg',
  933. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCH1dpzjCEiGAt8CXkryhkZg',
  934. 'license': 'Creative Commons Attribution license (reuse allowed)',
  935. },
  936. 'params': {
  937. 'skip_download': True,
  938. },
  939. },
  940. {
  941. 'url': 'https://www.youtube.com/watch?feature=player_embedded&amp;amp;v=V36LpHqtcDY',
  942. 'only_matching': True,
  943. },
  944. {
  945. # YouTube Red paid video (https://github.com/ytdl-org/youtube-dl/issues/10059)
  946. 'url': 'https://www.youtube.com/watch?v=i1Ko8UG-Tdo',
  947. 'only_matching': True,
  948. },
  949. {
  950. # Rental video preview
  951. 'url': 'https://www.youtube.com/watch?v=yYr8q0y5Jfg',
  952. 'info_dict': {
  953. 'id': 'uGpuVWrhIzE',
  954. 'ext': 'mp4',
  955. 'title': 'Piku - Trailer',
  956. 'description': 'md5:c36bd60c3fd6f1954086c083c72092eb',
  957. 'upload_date': '20150811',
  958. 'uploader': 'FlixMatrix',
  959. 'uploader_id': 'FlixMatrixKaravan',
  960. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/FlixMatrixKaravan',
  961. 'license': 'Standard YouTube License',
  962. },
  963. 'params': {
  964. 'skip_download': True,
  965. },
  966. 'skip': 'This video is not available.',
  967. },
  968. {
  969. # YouTube Red video with episode data
  970. 'url': 'https://www.youtube.com/watch?v=iqKdEhx-dD4',
  971. 'info_dict': {
  972. 'id': 'iqKdEhx-dD4',
  973. 'ext': 'mp4',
  974. 'title': 'Isolation - Mind Field (Ep 1)',
  975. 'description': 'md5:46a29be4ceffa65b92d277b93f463c0f',
  976. 'duration': 2085,
  977. 'upload_date': '20170118',
  978. 'uploader': 'Vsauce',
  979. 'uploader_id': 'Vsauce',
  980. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/Vsauce',
  981. 'series': 'Mind Field',
  982. 'season_number': 1,
  983. 'episode_number': 1,
  984. },
  985. 'params': {
  986. 'skip_download': True,
  987. },
  988. 'expected_warnings': [
  989. 'Skipping DASH manifest',
  990. ],
  991. },
  992. {
  993. # The following content has been identified by the YouTube community
  994. # as inappropriate or offensive to some audiences.
  995. 'url': 'https://www.youtube.com/watch?v=6SJNVb0GnPI',
  996. 'info_dict': {
  997. 'id': '6SJNVb0GnPI',
  998. 'ext': 'mp4',
  999. 'title': 'Race Differences in Intelligence',
  1000. 'description': 'md5:5d161533167390427a1f8ee89a1fc6f1',
  1001. 'duration': 965,
  1002. 'upload_date': '20140124',
  1003. 'uploader': 'New Century Foundation',
  1004. 'uploader_id': 'UCEJYpZGqgUob0zVVEaLhvVg',
  1005. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCEJYpZGqgUob0zVVEaLhvVg',
  1006. },
  1007. 'params': {
  1008. 'skip_download': True,
  1009. },
  1010. },
  1011. {
  1012. # itag 212
  1013. 'url': '1t24XAntNCY',
  1014. 'only_matching': True,
  1015. },
  1016. {
  1017. # geo restricted to JP
  1018. 'url': 'sJL6WA-aGkQ',
  1019. 'only_matching': True,
  1020. },
  1021. {
  1022. 'url': 'https://www.youtube.com/watch?v=MuAGGZNfUkU&list=RDMM',
  1023. 'only_matching': True,
  1024. },
  1025. {
  1026. 'url': 'https://invidio.us/watch?v=BaW_jenozKc',
  1027. 'only_matching': True,
  1028. },
  1029. {
  1030. # DRM protected
  1031. 'url': 'https://www.youtube.com/watch?v=s7_qI6_mIXc',
  1032. 'only_matching': True,
  1033. },
  1034. {
  1035. # Video with unsupported adaptive stream type formats
  1036. 'url': 'https://www.youtube.com/watch?v=Z4Vy8R84T1U',
  1037. 'info_dict': {
  1038. 'id': 'Z4Vy8R84T1U',
  1039. 'ext': 'mp4',
  1040. 'title': 'saman SMAN 53 Jakarta(Sancety) opening COFFEE4th at SMAN 53 Jakarta',
  1041. 'description': 'md5:d41d8cd98f00b204e9800998ecf8427e',
  1042. 'duration': 433,
  1043. 'upload_date': '20130923',
  1044. 'uploader': 'Amelia Putri Harwita',
  1045. 'uploader_id': 'UCpOxM49HJxmC1qCalXyB3_Q',
  1046. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCpOxM49HJxmC1qCalXyB3_Q',
  1047. 'formats': 'maxcount:10',
  1048. },
  1049. 'params': {
  1050. 'skip_download': True,
  1051. 'youtube_include_dash_manifest': False,
  1052. },
  1053. },
  1054. {
  1055. # Youtube Music Auto-generated description
  1056. 'url': 'https://music.youtube.com/watch?v=MgNrAu2pzNs',
  1057. 'info_dict': {
  1058. 'id': 'MgNrAu2pzNs',
  1059. 'ext': 'mp4',
  1060. 'title': 'Voyeur Girl',
  1061. 'description': 'md5:7ae382a65843d6df2685993e90a8628f',
  1062. 'upload_date': '20190312',
  1063. 'uploader': 'Various Artists - Topic',
  1064. 'uploader_id': 'UCVWKBi1ELZn0QX2CBLSkiyw',
  1065. 'artist': 'Stephen',
  1066. 'track': 'Voyeur Girl',
  1067. 'album': 'it\'s too much love to know my dear',
  1068. 'release_date': '20190313',
  1069. 'release_year': 2019,
  1070. },
  1071. 'params': {
  1072. 'skip_download': True,
  1073. },
  1074. },
  1075. {
  1076. # Youtube Music Auto-generated description
  1077. # Retrieve 'artist' field from 'Artist:' in video description
  1078. # when it is present on youtube music video
  1079. 'url': 'https://www.youtube.com/watch?v=k0jLE7tTwjY',
  1080. 'info_dict': {
  1081. 'id': 'k0jLE7tTwjY',
  1082. 'ext': 'mp4',
  1083. 'title': 'Latch Feat. Sam Smith',
  1084. 'description': 'md5:3cb1e8101a7c85fcba9b4fb41b951335',
  1085. 'upload_date': '20150110',
  1086. 'uploader': 'Various Artists - Topic',
  1087. 'uploader_id': 'UCNkEcmYdjrH4RqtNgh7BZ9w',
  1088. 'artist': 'Disclosure',
  1089. 'track': 'Latch Feat. Sam Smith',
  1090. 'album': 'Latch Featuring Sam Smith',
  1091. 'release_date': '20121008',
  1092. 'release_year': 2012,
  1093. },
  1094. 'params': {
  1095. 'skip_download': True,
  1096. },
  1097. },
  1098. {
  1099. # Youtube Music Auto-generated description
  1100. # handle multiple artists on youtube music video
  1101. 'url': 'https://www.youtube.com/watch?v=74qn0eJSjpA',
  1102. 'info_dict': {
  1103. 'id': '74qn0eJSjpA',
  1104. 'ext': 'mp4',
  1105. 'title': 'Eastside',
  1106. 'description': 'md5:290516bb73dcbfab0dcc4efe6c3de5f2',
  1107. 'upload_date': '20180710',
  1108. 'uploader': 'Benny Blanco - Topic',
  1109. 'uploader_id': 'UCzqz_ksRu_WkIzmivMdIS7A',
  1110. 'artist': 'benny blanco, Halsey, Khalid',
  1111. 'track': 'Eastside',
  1112. 'album': 'Eastside',
  1113. 'release_date': '20180713',
  1114. 'release_year': 2018,
  1115. },
  1116. 'params': {
  1117. 'skip_download': True,
  1118. },
  1119. },
  1120. {
  1121. # Youtube Music Auto-generated description
  1122. # handle youtube music video with release_year and no release_date
  1123. 'url': 'https://www.youtube.com/watch?v=-hcAI0g-f5M',
  1124. 'info_dict': {
  1125. 'id': '-hcAI0g-f5M',
  1126. 'ext': 'mp4',
  1127. 'title': 'Put It On Me',
  1128. 'description': 'md5:93c55acc682ae7b0c668f2e34e1c069e',
  1129. 'upload_date': '20180426',
  1130. 'uploader': 'Matt Maeson - Topic',
  1131. 'uploader_id': 'UCnEkIGqtGcQMLk73Kp-Q5LQ',
  1132. 'artist': 'Matt Maeson',
  1133. 'track': 'Put It On Me',
  1134. 'album': 'The Hearse',
  1135. 'release_date': None,
  1136. 'release_year': 2018,
  1137. },
  1138. 'params': {
  1139. 'skip_download': True,
  1140. },
  1141. },
  1142. ]
  1143. def __init__(self, *args, **kwargs):
  1144. super(YoutubeIE, self).__init__(*args, **kwargs)
  1145. self._player_cache = {}
  1146. def report_video_info_webpage_download(self, video_id):
  1147. """Report attempt to download video info webpage."""
  1148. self.to_screen('%s: Downloading video info webpage' % video_id)
  1149. def report_information_extraction(self, video_id):
  1150. """Report attempt to extract video information."""
  1151. self.to_screen('%s: Extracting video information' % video_id)
  1152. def report_unavailable_format(self, video_id, format):
  1153. """Report extracted video URL."""
  1154. self.to_screen('%s: Format %s not available' % (video_id, format))
  1155. def report_rtmp_download(self):
  1156. """Indicate the download will use the RTMP protocol."""
  1157. self.to_screen('RTMP download detected')
  1158. def _signature_cache_id(self, example_sig):
  1159. """ Return a string representation of a signature """
  1160. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  1161. def _extract_signature_function(self, video_id, player_url, example_sig):
  1162. id_m = re.match(
  1163. r'.*?-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player(?:-new)?|(?:/[a-z]{2,3}_[A-Z]{2})?/base)?\.(?P<ext>[a-z]+)$',
  1164. player_url)
  1165. if not id_m:
  1166. raise ExtractorError('Cannot identify player %r' % player_url)
  1167. player_type = id_m.group('ext')
  1168. player_id = id_m.group('id')
  1169. # Read from filesystem cache
  1170. func_id = '%s_%s_%s' % (
  1171. player_type, player_id, self._signature_cache_id(example_sig))
  1172. assert os.path.basename(func_id) == func_id
  1173. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  1174. if cache_spec is not None:
  1175. return lambda s: ''.join(s[i] for i in cache_spec)
  1176. download_note = (
  1177. 'Downloading player %s' % player_url
  1178. if self._downloader.params.get('verbose') else
  1179. 'Downloading %s player %s' % (player_type, player_id)
  1180. )
  1181. if player_type == 'js':
  1182. code = self._download_webpage(
  1183. player_url, video_id,
  1184. note=download_note,
  1185. errnote='Download of %s failed' % player_url)
  1186. res = self._parse_sig_js(code)
  1187. elif player_type == 'swf':
  1188. urlh = self._request_webpage(
  1189. player_url, video_id,
  1190. note=download_note,
  1191. errnote='Download of %s failed' % player_url)
  1192. code = urlh.read()
  1193. res = self._parse_sig_swf(code)
  1194. else:
  1195. assert False, 'Invalid player type %r' % player_type
  1196. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1197. cache_res = res(test_string)
  1198. cache_spec = [ord(c) for c in cache_res]
  1199. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  1200. return res
  1201. def _print_sig_code(self, func, example_sig):
  1202. def gen_sig_code(idxs):
  1203. def _genslice(start, end, step):
  1204. starts = '' if start == 0 else str(start)
  1205. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  1206. steps = '' if step == 1 else (':%d' % step)
  1207. return 's[%s%s%s]' % (starts, ends, steps)
  1208. step = None
  1209. # Quelch pyflakes warnings - start will be set when step is set
  1210. start = '(Never used)'
  1211. for i, prev in zip(idxs[1:], idxs[:-1]):
  1212. if step is not None:
  1213. if i - prev == step:
  1214. continue
  1215. yield _genslice(start, prev, step)
  1216. step = None
  1217. continue
  1218. if i - prev in [-1, 1]:
  1219. step = i - prev
  1220. start = prev
  1221. continue
  1222. else:
  1223. yield 's[%d]' % prev
  1224. if step is None:
  1225. yield 's[%d]' % i
  1226. else:
  1227. yield _genslice(start, i, step)
  1228. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  1229. cache_res = func(test_string)
  1230. cache_spec = [ord(c) for c in cache_res]
  1231. expr_code = ' + '.join(gen_sig_code(cache_spec))
  1232. signature_id_tuple = '(%s)' % (
  1233. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  1234. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  1235. ' return %s\n') % (signature_id_tuple, expr_code)
  1236. self.to_screen('Extracted signature function:\n' + code)
  1237. def _parse_sig_js(self, jscode):
  1238. funcname = self._search_regex(
  1239. (r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1240. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*encodeURIComponent\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1241. r'(?P<sig>[a-zA-Z0-9$]+)\s*=\s*function\(\s*a\s*\)\s*{\s*a\s*=\s*a\.split\(\s*""\s*\)',
  1242. # Obsolete patterns
  1243. r'(["\'])signature\1\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1244. r'\.sig\|\|(?P<sig>[a-zA-Z0-9$]+)\(',
  1245. r'yt\.akamaized\.net/\)\s*\|\|\s*.*?\s*[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?:encodeURIComponent\s*\()?\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1246. r'\b[cs]\s*&&\s*[adf]\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1247. r'\b[a-zA-Z0-9]+\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1248. r'\bc\s*&&\s*a\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1249. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\(',
  1250. r'\bc\s*&&\s*[a-zA-Z0-9]+\.set\([^,]+\s*,\s*\([^)]*\)\s*\(\s*(?P<sig>[a-zA-Z0-9$]+)\('),
  1251. jscode, 'Initial JS player signature function name', group='sig')
  1252. jsi = JSInterpreter(jscode)
  1253. initial_function = jsi.extract_function(funcname)
  1254. return lambda s: initial_function([s])
  1255. def _parse_sig_swf(self, file_contents):
  1256. swfi = SWFInterpreter(file_contents)
  1257. TARGET_CLASSNAME = 'SignatureDecipher'
  1258. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  1259. initial_function = swfi.extract_function(searched_class, 'decipher')
  1260. return lambda s: initial_function([s])
  1261. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  1262. """Turn the encrypted s field into a working signature"""
  1263. if player_url is None:
  1264. raise ExtractorError('Cannot decrypt signature without player_url')
  1265. if player_url.startswith('//'):
  1266. player_url = 'https:' + player_url
  1267. elif not re.match(r'https?://', player_url):
  1268. player_url = compat_urlparse.urljoin(
  1269. 'https://www.youtube.com', player_url)
  1270. try:
  1271. player_id = (player_url, self._signature_cache_id(s))
  1272. if player_id not in self._player_cache:
  1273. func = self._extract_signature_function(
  1274. video_id, player_url, s
  1275. )
  1276. self._player_cache[player_id] = func
  1277. func = self._player_cache[player_id]
  1278. if self._downloader.params.get('youtube_print_sig_code'):
  1279. self._print_sig_code(func, s)
  1280. return func(s)
  1281. except Exception as e:
  1282. tb = traceback.format_exc()
  1283. raise ExtractorError(
  1284. 'Signature extraction failed: ' + tb, cause=e)
  1285. def _get_subtitles(self, video_id, webpage):
  1286. try:
  1287. subs_doc = self._download_xml(
  1288. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  1289. video_id, note=False)
  1290. except ExtractorError as err:
  1291. self._downloader.report_warning('unable to download video subtitles: %s' % error_to_compat_str(err))
  1292. return {}
  1293. sub_lang_list = {}
  1294. for track in subs_doc.findall('track'):
  1295. lang = track.attrib['lang_code']
  1296. if lang in sub_lang_list:
  1297. continue
  1298. sub_formats = []
  1299. for ext in self._SUBTITLE_FORMATS:
  1300. params = compat_urllib_parse_urlencode({
  1301. 'lang': lang,
  1302. 'v': video_id,
  1303. 'fmt': ext,
  1304. 'name': track.attrib['name'].encode('utf-8'),
  1305. })
  1306. sub_formats.append({
  1307. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  1308. 'ext': ext,
  1309. })
  1310. sub_lang_list[lang] = sub_formats
  1311. if not sub_lang_list:
  1312. self._downloader.report_warning('video doesn\'t have subtitles')
  1313. return {}
  1314. return sub_lang_list
  1315. def _get_ytplayer_config(self, video_id, webpage):
  1316. patterns = (
  1317. # User data may contain arbitrary character sequences that may affect
  1318. # JSON extraction with regex, e.g. when '};' is contained the second
  1319. # regex won't capture the whole JSON. Yet working around by trying more
  1320. # concrete regex first keeping in mind proper quoted string handling
  1321. # to be implemented in future that will replace this workaround (see
  1322. # https://github.com/ytdl-org/youtube-dl/issues/7468,
  1323. # https://github.com/ytdl-org/youtube-dl/pull/7599)
  1324. r';ytplayer\.config\s*=\s*({.+?});ytplayer',
  1325. r';ytplayer\.config\s*=\s*({.+?});',
  1326. )
  1327. config = self._search_regex(
  1328. patterns, webpage, 'ytplayer.config', default=None)
  1329. if config:
  1330. return self._parse_json(
  1331. uppercase_escape(config), video_id, fatal=False)
  1332. def _get_automatic_captions(self, video_id, webpage):
  1333. """We need the webpage for getting the captions url, pass it as an
  1334. argument to speed up the process."""
  1335. self.to_screen('%s: Looking for automatic captions' % video_id)
  1336. player_config = self._get_ytplayer_config(video_id, webpage)
  1337. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  1338. if not player_config:
  1339. self._downloader.report_warning(err_msg)
  1340. return {}
  1341. try:
  1342. args = player_config['args']
  1343. caption_url = args.get('ttsurl')
  1344. if caption_url:
  1345. timestamp = args['timestamp']
  1346. # We get the available subtitles
  1347. list_params = compat_urllib_parse_urlencode({
  1348. 'type': 'list',
  1349. 'tlangs': 1,
  1350. 'asrs': 1,
  1351. })
  1352. list_url = caption_url + '&' + list_params
  1353. caption_list = self._download_xml(list_url, video_id)
  1354. original_lang_node = caption_list.find('track')
  1355. if original_lang_node is None:
  1356. self._downloader.report_warning('Video doesn\'t have automatic captions')
  1357. return {}
  1358. original_lang = original_lang_node.attrib['lang_code']
  1359. caption_kind = original_lang_node.attrib.get('kind', '')
  1360. sub_lang_list = {}
  1361. for lang_node in caption_list.findall('target'):
  1362. sub_lang = lang_node.attrib['lang_code']
  1363. sub_formats = []
  1364. for ext in self._SUBTITLE_FORMATS:
  1365. params = compat_urllib_parse_urlencode({
  1366. 'lang': original_lang,
  1367. 'tlang': sub_lang,
  1368. 'fmt': ext,
  1369. 'ts': timestamp,
  1370. 'kind': caption_kind,
  1371. })
  1372. sub_formats.append({
  1373. 'url': caption_url + '&' + params,
  1374. 'ext': ext,
  1375. })
  1376. sub_lang_list[sub_lang] = sub_formats
  1377. return sub_lang_list
  1378. def make_captions(sub_url, sub_langs):
  1379. parsed_sub_url = compat_urllib_parse_urlparse(sub_url)
  1380. caption_qs = compat_parse_qs(parsed_sub_url.query)
  1381. captions = {}
  1382. for sub_lang in sub_langs:
  1383. sub_formats = []
  1384. for ext in self._SUBTITLE_FORMATS:
  1385. caption_qs.update({
  1386. 'tlang': [sub_lang],
  1387. 'fmt': [ext],
  1388. })
  1389. sub_url = compat_urlparse.urlunparse(parsed_sub_url._replace(
  1390. query=compat_urllib_parse_urlencode(caption_qs, True)))
  1391. sub_formats.append({
  1392. 'url': sub_url,
  1393. 'ext': ext,
  1394. })
  1395. captions[sub_lang] = sub_formats
  1396. return captions
  1397. # New captions format as of 22.06.2017
  1398. player_response = args.get('player_response')
  1399. if player_response and isinstance(player_response, compat_str):
  1400. player_response = self._parse_json(
  1401. player_response, video_id, fatal=False)
  1402. if player_response:
  1403. renderer = player_response['captions']['playerCaptionsTracklistRenderer']
  1404. base_url = renderer['captionTracks'][0]['baseUrl']
  1405. sub_lang_list = []
  1406. for lang in renderer['translationLanguages']:
  1407. lang_code = lang.get('languageCode')
  1408. if lang_code:
  1409. sub_lang_list.append(lang_code)
  1410. return make_captions(base_url, sub_lang_list)
  1411. # Some videos don't provide ttsurl but rather caption_tracks and
  1412. # caption_translation_languages (e.g. 20LmZk1hakA)
  1413. # Does not used anymore as of 22.06.2017
  1414. caption_tracks = args['caption_tracks']
  1415. caption_translation_languages = args['caption_translation_languages']
  1416. caption_url = compat_parse_qs(caption_tracks.split(',')[0])['u'][0]
  1417. sub_lang_list = []
  1418. for lang in caption_translation_languages.split(','):
  1419. lang_qs = compat_parse_qs(compat_urllib_parse_unquote_plus(lang))
  1420. sub_lang = lang_qs.get('lc', [None])[0]
  1421. if sub_lang:
  1422. sub_lang_list.append(sub_lang)
  1423. return make_captions(caption_url, sub_lang_list)
  1424. # An extractor error can be raise by the download process if there are
  1425. # no automatic captions but there are subtitles
  1426. except (KeyError, IndexError, ExtractorError):
  1427. self._downloader.report_warning(err_msg)
  1428. return {}
  1429. def _mark_watched(self, video_id, video_info, player_response):
  1430. playback_url = url_or_none(try_get(
  1431. player_response,
  1432. lambda x: x['playbackTracking']['videostatsPlaybackUrl']['baseUrl']) or try_get(
  1433. video_info, lambda x: x['videostats_playback_base_url'][0]))
  1434. if not playback_url:
  1435. return
  1436. parsed_playback_url = compat_urlparse.urlparse(playback_url)
  1437. qs = compat_urlparse.parse_qs(parsed_playback_url.query)
  1438. # cpn generation algorithm is reverse engineered from base.js.
  1439. # In fact it works even with dummy cpn.
  1440. CPN_ALPHABET = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_'
  1441. cpn = ''.join((CPN_ALPHABET[random.randint(0, 256) & 63] for _ in range(0, 16)))
  1442. qs.update({
  1443. 'ver': ['2'],
  1444. 'cpn': [cpn],
  1445. })
  1446. playback_url = compat_urlparse.urlunparse(
  1447. parsed_playback_url._replace(query=compat_urllib_parse_urlencode(qs, True)))
  1448. self._download_webpage(
  1449. playback_url, video_id, 'Marking watched',
  1450. 'Unable to mark watched', fatal=False)
  1451. @staticmethod
  1452. def _extract_urls(webpage):
  1453. # Embedded YouTube player
  1454. entries = [
  1455. unescapeHTML(mobj.group('url'))
  1456. for mobj in re.finditer(r'''(?x)
  1457. (?:
  1458. <iframe[^>]+?src=|
  1459. data-video-url=|
  1460. <embed[^>]+?src=|
  1461. embedSWF\(?:\s*|
  1462. <object[^>]+data=|
  1463. new\s+SWFObject\(
  1464. )
  1465. (["\'])
  1466. (?P<url>(?:https?:)?//(?:www\.)?youtube(?:-nocookie)?\.com/
  1467. (?:embed|v|p)/[0-9A-Za-z_-]{11}.*?)
  1468. \1''', webpage)]
  1469. # lazyYT YouTube embed
  1470. entries.extend(list(map(
  1471. unescapeHTML,
  1472. re.findall(r'class="lazyYT" data-youtube-id="([^"]+)"', webpage))))
  1473. # Wordpress "YouTube Video Importer" plugin
  1474. matches = re.findall(r'''(?x)<div[^>]+
  1475. class=(?P<q1>[\'"])[^\'"]*\byvii_single_video_player\b[^\'"]*(?P=q1)[^>]+
  1476. data-video_id=(?P<q2>[\'"])([^\'"]+)(?P=q2)''', webpage)
  1477. entries.extend(m[-1] for m in matches)
  1478. return entries
  1479. @staticmethod
  1480. def _extract_url(webpage):
  1481. urls = YoutubeIE._extract_urls(webpage)
  1482. return urls[0] if urls else None
  1483. @classmethod
  1484. def extract_id(cls, url):
  1485. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  1486. if mobj is None:
  1487. raise ExtractorError('Invalid URL: %s' % url)
  1488. video_id = mobj.group(2)
  1489. return video_id
  1490. def _extract_annotations(self, video_id):
  1491. return self._download_webpage(
  1492. 'https://www.youtube.com/annotations_invideo', video_id,
  1493. note='Downloading annotations',
  1494. errnote='Unable to download video annotations', fatal=False,
  1495. query={
  1496. 'features': 1,
  1497. 'legacy': 1,
  1498. 'video_id': video_id,
  1499. })
  1500. @staticmethod
  1501. def _extract_chapters(description, duration):
  1502. if not description:
  1503. return None
  1504. chapter_lines = re.findall(
  1505. r'(?:^|<br\s*/>)([^<]*<a[^>]+onclick=["\']yt\.www\.watch\.player\.seekTo[^>]+>(\d{1,2}:\d{1,2}(?::\d{1,2})?)</a>[^>]*)(?=$|<br\s*/>)',
  1506. description)
  1507. if not chapter_lines:
  1508. return None
  1509. chapters = []
  1510. for next_num, (chapter_line, time_point) in enumerate(
  1511. chapter_lines, start=1):
  1512. start_time = parse_duration(time_point)
  1513. if start_time is None:
  1514. continue
  1515. if start_time > duration:
  1516. break
  1517. end_time = (duration if next_num == len(chapter_lines)
  1518. else parse_duration(chapter_lines[next_num][1]))
  1519. if end_time is None:
  1520. continue
  1521. if end_time > duration:
  1522. end_time = duration
  1523. if start_time > end_time:
  1524. break
  1525. chapter_title = re.sub(
  1526. r'<a[^>]+>[^<]+</a>', '', chapter_line).strip(' \t-')
  1527. chapter_title = re.sub(r'\s+', ' ', chapter_title)
  1528. chapters.append({
  1529. 'start_time': start_time,
  1530. 'end_time': end_time,
  1531. 'title': chapter_title,
  1532. })
  1533. return chapters
  1534. def _real_extract(self, url):
  1535. url, smuggled_data = unsmuggle_url(url, {})
  1536. proto = (
  1537. 'http' if self._downloader.params.get('prefer_insecure', False)
  1538. else 'https')
  1539. start_time = None
  1540. end_time = None
  1541. parsed_url = compat_urllib_parse_urlparse(url)
  1542. for component in [parsed_url.fragment, parsed_url.query]:
  1543. query = compat_parse_qs(component)
  1544. if start_time is None and 't' in query:
  1545. start_time = parse_duration(query['t'][0])
  1546. if start_time is None and 'start' in query:
  1547. start_time = parse_duration(query['start'][0])
  1548. if end_time is None and 'end' in query:
  1549. end_time = parse_duration(query['end'][0])
  1550. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1551. mobj = re.search(self._NEXT_URL_RE, url)
  1552. if mobj:
  1553. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  1554. video_id = self.extract_id(url)
  1555. # Get video webpage
  1556. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  1557. video_webpage = self._download_webpage(url, video_id)
  1558. # Attempt to extract SWF player URL
  1559. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1560. if mobj is not None:
  1561. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1562. else:
  1563. player_url = None
  1564. dash_mpds = []
  1565. def add_dash_mpd(video_info):
  1566. dash_mpd = video_info.get('dashmpd')
  1567. if dash_mpd and dash_mpd[0] not in dash_mpds:
  1568. dash_mpds.append(dash_mpd[0])
  1569. def add_dash_mpd_pr(pl_response):
  1570. dash_mpd = url_or_none(try_get(
  1571. pl_response, lambda x: x['streamingData']['dashManifestUrl'],
  1572. compat_str))
  1573. if dash_mpd and dash_mpd not in dash_mpds:
  1574. dash_mpds.append(dash_mpd)
  1575. is_live = None
  1576. view_count = None
  1577. def extract_view_count(v_info):
  1578. return int_or_none(try_get(v_info, lambda x: x['view_count'][0]))
  1579. def extract_token(v_info):
  1580. return dict_get(v_info, ('account_playback_token', 'accountPlaybackToken', 'token'))
  1581. player_response = {}
  1582. # Get video info
  1583. embed_webpage = None
  1584. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1585. age_gate = True
  1586. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1587. # this can be viewed without login into Youtube
  1588. url = proto + '://www.youtube.com/embed/%s' % video_id
  1589. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  1590. data = compat_urllib_parse_urlencode({
  1591. 'video_id': video_id,
  1592. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1593. 'sts': self._search_regex(
  1594. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  1595. })
  1596. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  1597. video_info_webpage = self._download_webpage(
  1598. video_info_url, video_id,
  1599. note='Refetching age-gated info webpage',
  1600. errnote='unable to download video info webpage')
  1601. video_info = compat_parse_qs(video_info_webpage)
  1602. add_dash_mpd(video_info)
  1603. else:
  1604. age_gate = False
  1605. video_info = None
  1606. sts = None
  1607. # Try looking directly into the video webpage
  1608. ytplayer_config = self._get_ytplayer_config(video_id, video_webpage)
  1609. if ytplayer_config:
  1610. args = ytplayer_config['args']
  1611. if args.get('url_encoded_fmt_stream_map') or args.get('hlsvp'):
  1612. # Convert to the same format returned by compat_parse_qs
  1613. video_info = dict((k, [v]) for k, v in args.items())
  1614. add_dash_mpd(video_info)
  1615. # Rental video is not rented but preview is available (e.g.
  1616. # https://www.youtube.com/watch?v=yYr8q0y5Jfg,
  1617. # https://github.com/ytdl-org/youtube-dl/issues/10532)
  1618. if not video_info and args.get('ypc_vid'):
  1619. return self.url_result(
  1620. args['ypc_vid'], YoutubeIE.ie_key(), video_id=args['ypc_vid'])
  1621. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1622. is_live = True
  1623. sts = ytplayer_config.get('sts')
  1624. if not player_response:
  1625. pl_response = str_or_none(args.get('player_response'))
  1626. if pl_response:
  1627. pl_response = self._parse_json(pl_response, video_id, fatal=False)
  1628. if isinstance(pl_response, dict):
  1629. player_response = pl_response
  1630. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1631. add_dash_mpd_pr(player_response)
  1632. # We also try looking in get_video_info since it may contain different dashmpd
  1633. # URL that points to a DASH manifest with possibly different itag set (some itags
  1634. # are missing from DASH manifest pointed by webpage's dashmpd, some - from DASH
  1635. # manifest pointed by get_video_info's dashmpd).
  1636. # The general idea is to take a union of itags of both DASH manifests (for example
  1637. # video with such 'manifest behavior' see https://github.com/ytdl-org/youtube-dl/issues/6093)
  1638. self.report_video_info_webpage_download(video_id)
  1639. for el in ('embedded', 'detailpage', 'vevo', ''):
  1640. query = {
  1641. 'video_id': video_id,
  1642. 'ps': 'default',
  1643. 'eurl': '',
  1644. 'gl': 'US',
  1645. 'hl': 'en',
  1646. }
  1647. if el:
  1648. query['el'] = el
  1649. if sts:
  1650. query['sts'] = sts
  1651. video_info_webpage = self._download_webpage(
  1652. '%s://www.youtube.com/get_video_info' % proto,
  1653. video_id, note=False,
  1654. errnote='unable to download video info webpage',
  1655. fatal=False, query=query)
  1656. if not video_info_webpage:
  1657. continue
  1658. get_video_info = compat_parse_qs(video_info_webpage)
  1659. if not player_response:
  1660. pl_response = get_video_info.get('player_response', [None])[0]
  1661. if isinstance(pl_response, dict):
  1662. player_response = pl_response
  1663. add_dash_mpd_pr(player_response)
  1664. add_dash_mpd(get_video_info)
  1665. if view_count is None:
  1666. view_count = extract_view_count(get_video_info)
  1667. if not video_info:
  1668. video_info = get_video_info
  1669. get_token = extract_token(get_video_info)
  1670. if get_token:
  1671. # Different get_video_info requests may report different results, e.g.
  1672. # some may report video unavailability, but some may serve it without
  1673. # any complaint (see https://github.com/ytdl-org/youtube-dl/issues/7362,
  1674. # the original webpage as well as el=info and el=embedded get_video_info
  1675. # requests report video unavailability due to geo restriction while
  1676. # el=detailpage succeeds and returns valid data). This is probably
  1677. # due to YouTube measures against IP ranges of hosting providers.
  1678. # Working around by preferring the first succeeded video_info containing
  1679. # the token if no such video_info yet was found.
  1680. token = extract_token(video_info)
  1681. if not token:
  1682. video_info = get_video_info
  1683. break
  1684. def extract_unavailable_message():
  1685. return self._html_search_regex(
  1686. r'(?s)<h1[^>]+id="unavailable-message"[^>]*>(.+?)</h1>',
  1687. video_webpage, 'unavailable message', default=None)
  1688. if not video_info:
  1689. unavailable_message = extract_unavailable_message()
  1690. if not unavailable_message:
  1691. unavailable_message = 'Unable to extract video data'
  1692. raise ExtractorError(
  1693. 'YouTube said: %s' % unavailable_message, expected=True, video_id=video_id)
  1694. video_details = try_get(
  1695. player_response, lambda x: x['videoDetails'], dict) or {}
  1696. # title
  1697. if 'title' in video_info:
  1698. video_title = video_info['title'][0]
  1699. elif 'title' in player_response:
  1700. video_title = video_details['title']
  1701. else:
  1702. self._downloader.report_warning('Unable to extract video title')
  1703. video_title = '_'
  1704. # description
  1705. description_original = video_description = get_element_by_id("eow-description", video_webpage)
  1706. if video_description:
  1707. def replace_url(m):
  1708. redir_url = compat_urlparse.urljoin(url, m.group(1))
  1709. parsed_redir_url = compat_urllib_parse_urlparse(redir_url)
  1710. if re.search(r'^(?:www\.)?(?:youtube(?:-nocookie)?\.com|youtu\.be)$', parsed_redir_url.netloc) and parsed_redir_url.path == '/redirect':
  1711. qs = compat_parse_qs(parsed_redir_url.query)
  1712. q = qs.get('q')
  1713. if q and q[0]:
  1714. return q[0]
  1715. return redir_url
  1716. description_original = video_description = re.sub(r'''(?x)
  1717. <a\s+
  1718. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1719. (?:title|href)="([^"]+)"\s+
  1720. (?:[a-zA-Z-]+="[^"]*"\s+)*?
  1721. class="[^"]*"[^>]*>
  1722. [^<]+\.{3}\s*
  1723. </a>
  1724. ''', replace_url, video_description)
  1725. video_description = clean_html(video_description)
  1726. else:
  1727. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1728. if fd_mobj:
  1729. video_description = unescapeHTML(fd_mobj.group(1))
  1730. else:
  1731. video_description = ''
  1732. if not smuggled_data.get('force_singlefeed', False):
  1733. if not self._downloader.params.get('noplaylist'):
  1734. multifeed_metadata_list = try_get(
  1735. player_response,
  1736. lambda x: x['multicamera']['playerLegacyMulticameraRenderer']['metadataList'],
  1737. compat_str) or try_get(
  1738. video_info, lambda x: x['multifeed_metadata_list'][0], compat_str)
  1739. if multifeed_metadata_list:
  1740. entries = []
  1741. feed_ids = []
  1742. for feed in multifeed_metadata_list.split(','):
  1743. # Unquote should take place before split on comma (,) since textual
  1744. # fields may contain comma as well (see
  1745. # https://github.com/ytdl-org/youtube-dl/issues/8536)
  1746. feed_data = compat_parse_qs(compat_urllib_parse_unquote_plus(feed))
  1747. entries.append({
  1748. '_type': 'url_transparent',
  1749. 'ie_key': 'Youtube',
  1750. 'url': smuggle_url(
  1751. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1752. {'force_singlefeed': True}),
  1753. 'title': '%s (%s)' % (video_title, feed_data['title'][0]),
  1754. })
  1755. feed_ids.append(feed_data['id'][0])
  1756. self.to_screen(
  1757. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1758. % (', '.join(feed_ids), video_id))
  1759. return self.playlist_result(entries, video_id, video_title, video_description)
  1760. else:
  1761. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1762. if view_count is None:
  1763. view_count = extract_view_count(video_info)
  1764. if view_count is None and video_details:
  1765. view_count = int_or_none(video_details.get('viewCount'))
  1766. if is_live is None:
  1767. is_live = bool_or_none(video_details.get('isLive'))
  1768. # Check for "rental" videos
  1769. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1770. raise ExtractorError('"rental" videos not supported. See https://github.com/ytdl-org/youtube-dl/issues/359 for more information.', expected=True)
  1771. def _extract_filesize(media_url):
  1772. return int_or_none(self._search_regex(
  1773. r'\bclen[=/](\d+)', media_url, 'filesize', default=None))
  1774. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1775. self.report_rtmp_download()
  1776. formats = [{
  1777. 'format_id': '_rtmp',
  1778. 'protocol': 'rtmp',
  1779. 'url': video_info['conn'][0],
  1780. 'player_url': player_url,
  1781. }]
  1782. elif not is_live and (len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1):
  1783. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1784. if 'rtmpe%3Dyes' in encoded_url_map:
  1785. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/ytdl-org/youtube-dl/issues/343 for more information.', expected=True)
  1786. formats_spec = {}
  1787. fmt_list = video_info.get('fmt_list', [''])[0]
  1788. if fmt_list:
  1789. for fmt in fmt_list.split(','):
  1790. spec = fmt.split('/')
  1791. if len(spec) > 1:
  1792. width_height = spec[1].split('x')
  1793. if len(width_height) == 2:
  1794. formats_spec[spec[0]] = {
  1795. 'resolution': spec[1],
  1796. 'width': int_or_none(width_height[0]),
  1797. 'height': int_or_none(width_height[1]),
  1798. }
  1799. q = qualities(['small', 'medium', 'hd720'])
  1800. streaming_formats = try_get(player_response, lambda x: x['streamingData']['formats'], list)
  1801. if streaming_formats:
  1802. for fmt in streaming_formats:
  1803. itag = str_or_none(fmt.get('itag'))
  1804. if not itag:
  1805. continue
  1806. quality = fmt.get('quality')
  1807. quality_label = fmt.get('qualityLabel') or quality
  1808. formats_spec[itag] = {
  1809. 'asr': int_or_none(fmt.get('audioSampleRate')),
  1810. 'filesize': int_or_none(fmt.get('contentLength')),
  1811. 'format_note': quality_label,
  1812. 'fps': int_or_none(fmt.get('fps')),
  1813. 'height': int_or_none(fmt.get('height')),
  1814. 'quality': q(quality),
  1815. # bitrate for itag 43 is always 2147483647
  1816. 'tbr': float_or_none(fmt.get('averageBitrate') or fmt.get('bitrate'), 1000) if itag != '43' else None,
  1817. 'width': int_or_none(fmt.get('width')),
  1818. }
  1819. formats = []
  1820. for url_data_str in encoded_url_map.split(','):
  1821. url_data = compat_parse_qs(url_data_str)
  1822. if 'itag' not in url_data or 'url' not in url_data or url_data.get('drm_families'):
  1823. continue
  1824. stream_type = int_or_none(try_get(url_data, lambda x: x['stream_type'][0]))
  1825. # Unsupported FORMAT_STREAM_TYPE_OTF
  1826. if stream_type == 3:
  1827. continue
  1828. format_id = url_data['itag'][0]
  1829. url = url_data['url'][0]
  1830. if 's' in url_data or self._downloader.params.get('youtube_include_dash_manifest', True):
  1831. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1832. jsplayer_url_json = self._search_regex(
  1833. ASSETS_RE,
  1834. embed_webpage if age_gate else video_webpage,
  1835. 'JS player URL (1)', default=None)
  1836. if not jsplayer_url_json and not age_gate:
  1837. # We need the embed website after all
  1838. if embed_webpage is None:
  1839. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1840. embed_webpage = self._download_webpage(
  1841. embed_url, video_id, 'Downloading embed webpage')
  1842. jsplayer_url_json = self._search_regex(
  1843. ASSETS_RE, embed_webpage, 'JS player URL')
  1844. player_url = json.loads(jsplayer_url_json)
  1845. if player_url is None:
  1846. player_url_json = self._search_regex(
  1847. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1848. video_webpage, 'age gate player URL')
  1849. player_url = json.loads(player_url_json)
  1850. if 'sig' in url_data:
  1851. url += '&signature=' + url_data['sig'][0]
  1852. elif 's' in url_data:
  1853. encrypted_sig = url_data['s'][0]
  1854. if self._downloader.params.get('verbose'):
  1855. if player_url is None:
  1856. player_version = 'unknown'
  1857. player_desc = 'unknown'
  1858. else:
  1859. if player_url.endswith('swf'):
  1860. player_version = self._search_regex(
  1861. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  1862. 'flash player', fatal=False)
  1863. player_desc = 'flash player %s' % player_version
  1864. else:
  1865. player_version = self._search_regex(
  1866. [r'html5player-([^/]+?)(?:/html5player(?:-new)?)?\.js',
  1867. r'(?:www|player(?:_ias)?)-([^/]+)(?:/[a-z]{2,3}_[A-Z]{2})?/base\.js'],
  1868. player_url,
  1869. 'html5 player', fatal=False)
  1870. player_desc = 'html5 player %s' % player_version
  1871. parts_sizes = self._signature_cache_id(encrypted_sig)
  1872. self.to_screen('{%s} signature length %s, %s' %
  1873. (format_id, parts_sizes, player_desc))
  1874. signature = self._decrypt_signature(
  1875. encrypted_sig, video_id, player_url, age_gate)
  1876. sp = try_get(url_data, lambda x: x['sp'][0], compat_str) or 'signature'
  1877. url += '&%s=%s' % (sp, signature)
  1878. if 'ratebypass' not in url:
  1879. url += '&ratebypass=yes'
  1880. dct = {
  1881. 'format_id': format_id,
  1882. 'url': url,
  1883. 'player_url': player_url,
  1884. }
  1885. if format_id in self._formats:
  1886. dct.update(self._formats[format_id])
  1887. if format_id in formats_spec:
  1888. dct.update(formats_spec[format_id])
  1889. # Some itags are not included in DASH manifest thus corresponding formats will
  1890. # lack metadata (see https://github.com/ytdl-org/youtube-dl/pull/5993).
  1891. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1892. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1893. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1894. filesize = int_or_none(url_data.get(
  1895. 'clen', [None])[0]) or _extract_filesize(url)
  1896. quality = url_data.get('quality', [None])[0]
  1897. more_fields = {
  1898. 'filesize': filesize,
  1899. 'tbr': float_or_none(url_data.get('bitrate', [None])[0], 1000),
  1900. 'width': width,
  1901. 'height': height,
  1902. 'fps': int_or_none(url_data.get('fps', [None])[0]),
  1903. 'format_note': url_data.get('quality_label', [None])[0] or quality,
  1904. 'quality': q(quality),
  1905. }
  1906. for key, value in more_fields.items():
  1907. if value:
  1908. dct[key] = value
  1909. type_ = url_data.get('type', [None])[0]
  1910. if type_:
  1911. type_split = type_.split(';')
  1912. kind_ext = type_split[0].split('/')
  1913. if len(kind_ext) == 2:
  1914. kind, _ = kind_ext
  1915. dct['ext'] = mimetype2ext(type_split[0])
  1916. if kind in ('audio', 'video'):
  1917. codecs = None
  1918. for mobj in re.finditer(
  1919. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  1920. if mobj.group('key') == 'codecs':
  1921. codecs = mobj.group('val')
  1922. break
  1923. if codecs:
  1924. dct.update(parse_codecs(codecs))
  1925. if dct.get('acodec') == 'none' or dct.get('vcodec') == 'none':
  1926. dct['downloader_options'] = {
  1927. # Youtube throttles chunks >~10M
  1928. 'http_chunk_size': 10485760,
  1929. }
  1930. formats.append(dct)
  1931. else:
  1932. manifest_url = (
  1933. url_or_none(try_get(
  1934. player_response,
  1935. lambda x: x['streamingData']['hlsManifestUrl'],
  1936. compat_str))
  1937. or url_or_none(try_get(
  1938. video_info, lambda x: x['hlsvp'][0], compat_str)))
  1939. if manifest_url:
  1940. formats = []
  1941. m3u8_formats = self._extract_m3u8_formats(
  1942. manifest_url, video_id, 'mp4', fatal=False)
  1943. for a_format in m3u8_formats:
  1944. itag = self._search_regex(
  1945. r'/itag/(\d+)/', a_format['url'], 'itag', default=None)
  1946. if itag:
  1947. a_format['format_id'] = itag
  1948. if itag in self._formats:
  1949. dct = self._formats[itag].copy()
  1950. dct.update(a_format)
  1951. a_format = dct
  1952. a_format['player_url'] = player_url
  1953. # Accept-Encoding header causes failures in live streams on Youtube and Youtube Gaming
  1954. a_format.setdefault('http_headers', {})['Youtubedl-no-compression'] = 'True'
  1955. formats.append(a_format)
  1956. else:
  1957. error_message = clean_html(video_info.get('reason', [None])[0])
  1958. if not error_message:
  1959. error_message = extract_unavailable_message()
  1960. if error_message:
  1961. raise ExtractorError(error_message, expected=True)
  1962. raise ExtractorError('no conn, hlsvp, hlsManifestUrl or url_encoded_fmt_stream_map information found in video info')
  1963. # uploader
  1964. video_uploader = try_get(
  1965. video_info, lambda x: x['author'][0],
  1966. compat_str) or str_or_none(video_details.get('author'))
  1967. if video_uploader:
  1968. video_uploader = compat_urllib_parse_unquote_plus(video_uploader)
  1969. else:
  1970. self._downloader.report_warning('unable to extract uploader name')
  1971. # uploader_id
  1972. video_uploader_id = None
  1973. video_uploader_url = None
  1974. mobj = re.search(
  1975. r'<link itemprop="url" href="(?P<uploader_url>https?://www\.youtube\.com/(?:user|channel)/(?P<uploader_id>[^"]+))">',
  1976. video_webpage)
  1977. if mobj is not None:
  1978. video_uploader_id = mobj.group('uploader_id')
  1979. video_uploader_url = mobj.group('uploader_url')
  1980. else:
  1981. self._downloader.report_warning('unable to extract uploader nickname')
  1982. channel_id = (
  1983. str_or_none(video_details.get('channelId'))
  1984. or self._html_search_meta(
  1985. 'channelId', video_webpage, 'channel id', default=None)
  1986. or self._search_regex(
  1987. r'data-channel-external-id=(["\'])(?P<id>(?:(?!\1).)+)\1',
  1988. video_webpage, 'channel id', default=None, group='id'))
  1989. channel_url = 'http://www.youtube.com/channel/%s' % channel_id if channel_id else None
  1990. # thumbnail image
  1991. # We try first to get a high quality image:
  1992. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1993. video_webpage, re.DOTALL)
  1994. if m_thumb is not None:
  1995. video_thumbnail = m_thumb.group(1)
  1996. elif 'thumbnail_url' not in video_info:
  1997. self._downloader.report_warning('unable to extract video thumbnail')
  1998. video_thumbnail = None
  1999. else: # don't panic if we can't find it
  2000. video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
  2001. # upload date
  2002. upload_date = self._html_search_meta(
  2003. 'datePublished', video_webpage, 'upload date', default=None)
  2004. if not upload_date:
  2005. upload_date = self._search_regex(
  2006. [r'(?s)id="eow-date.*?>(.*?)</span>',
  2007. r'(?:id="watch-uploader-info".*?>.*?|["\']simpleText["\']\s*:\s*["\'])(?:Published|Uploaded|Streamed live|Started) on (.+?)[<"\']'],
  2008. video_webpage, 'upload date', default=None)
  2009. upload_date = unified_strdate(upload_date)
  2010. video_license = self._html_search_regex(
  2011. r'<h4[^>]+class="title"[^>]*>\s*License\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li',
  2012. video_webpage, 'license', default=None)
  2013. m_music = re.search(
  2014. r'''(?x)
  2015. <h4[^>]+class="title"[^>]*>\s*Music\s*</h4>\s*
  2016. <ul[^>]*>\s*
  2017. <li>(?P<title>.+?)
  2018. by (?P<creator>.+?)
  2019. (?:
  2020. \(.+?\)|
  2021. <a[^>]*
  2022. (?:
  2023. \bhref=["\']/red[^>]*>| # drop possible
  2024. >\s*Listen ad-free with YouTube Red # YouTube Red ad
  2025. )
  2026. .*?
  2027. )?</li
  2028. ''',
  2029. video_webpage)
  2030. if m_music:
  2031. video_alt_title = remove_quotes(unescapeHTML(m_music.group('title')))
  2032. video_creator = clean_html(m_music.group('creator'))
  2033. else:
  2034. video_alt_title = video_creator = None
  2035. def extract_meta(field):
  2036. return self._html_search_regex(
  2037. r'<h4[^>]+class="title"[^>]*>\s*%s\s*</h4>\s*<ul[^>]*>\s*<li>(.+?)</li>\s*' % field,
  2038. video_webpage, field, default=None)
  2039. track = extract_meta('Song')
  2040. artist = extract_meta('Artist')
  2041. album = extract_meta('Album')
  2042. # Youtube Music Auto-generated description
  2043. release_date = release_year = None
  2044. if video_description:
  2045. mobj = re.search(r'(?s)Provided to YouTube by [^\n]+\n+(?P<track>[^·]+)·(?P<artist>[^\n]+)\n+(?P<album>[^\n]+)(?:.+?℗\s*(?P<release_year>\d{4})(?!\d))?(?:.+?Released on\s*:\s*(?P<release_date>\d{4}-\d{2}-\d{2}))?(.+?\nArtist\s*:\s*(?P<clean_artist>[^\n]+))?', video_description)
  2046. if mobj:
  2047. if not track:
  2048. track = mobj.group('track').strip()
  2049. if not artist:
  2050. artist = mobj.group('clean_artist') or ', '.join(a.strip() for a in mobj.group('artist').split('·'))
  2051. if not album:
  2052. album = mobj.group('album'.strip())
  2053. release_year = mobj.group('release_year')
  2054. release_date = mobj.group('release_date')
  2055. if release_date:
  2056. release_date = release_date.replace('-', '')
  2057. if not release_year:
  2058. release_year = int(release_date[:4])
  2059. if release_year:
  2060. release_year = int(release_year)
  2061. m_episode = re.search(
  2062. r'<div[^>]+id="watch7-headline"[^>]*>\s*<span[^>]*>.*?>(?P<series>[^<]+)</a></b>\s*S(?P<season>\d+)\s*•\s*E(?P<episode>\d+)</span>',
  2063. video_webpage)
  2064. if m_episode:
  2065. series = unescapeHTML(m_episode.group('series'))
  2066. season_number = int(m_episode.group('season'))
  2067. episode_number = int(m_episode.group('episode'))
  2068. else:
  2069. series = season_number = episode_number = None
  2070. m_cat_container = self._search_regex(
  2071. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  2072. video_webpage, 'categories', default=None)
  2073. if m_cat_container:
  2074. category = self._html_search_regex(
  2075. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  2076. default=None)
  2077. video_categories = None if category is None else [category]
  2078. else:
  2079. video_categories = None
  2080. video_tags = [
  2081. unescapeHTML(m.group('content'))
  2082. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  2083. def _extract_count(count_name):
  2084. return str_to_int(self._search_regex(
  2085. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  2086. % re.escape(count_name),
  2087. video_webpage, count_name, default=None))
  2088. like_count = _extract_count('like')
  2089. dislike_count = _extract_count('dislike')
  2090. if view_count is None:
  2091. view_count = str_to_int(self._search_regex(
  2092. r'<[^>]+class=["\']watch-view-count[^>]+>\s*([\d,\s]+)', video_webpage,
  2093. 'view count', default=None))
  2094. average_rating = (
  2095. float_or_none(video_details.get('averageRating'))
  2096. or try_get(video_info, lambda x: float_or_none(x['avg_rating'][0])))
  2097. # subtitles
  2098. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  2099. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  2100. video_duration = try_get(
  2101. video_info, lambda x: int_or_none(x['length_seconds'][0]))
  2102. if not video_duration:
  2103. video_duration = int_or_none(video_details.get('lengthSeconds'))
  2104. if not video_duration:
  2105. video_duration = parse_duration(self._html_search_meta(
  2106. 'duration', video_webpage, 'video duration'))
  2107. # annotations
  2108. video_annotations = None
  2109. if self._downloader.params.get('writeannotations', False):
  2110. video_annotations = self._extract_annotations(video_id)
  2111. chapters = self._extract_chapters(description_original, video_duration)
  2112. # Look for the DASH manifest
  2113. if self._downloader.params.get('youtube_include_dash_manifest', True):
  2114. dash_mpd_fatal = True
  2115. for mpd_url in dash_mpds:
  2116. dash_formats = {}
  2117. try:
  2118. def decrypt_sig(mobj):
  2119. s = mobj.group(1)
  2120. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  2121. return '/signature/%s' % dec_s
  2122. mpd_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, mpd_url)
  2123. for df in self._extract_mpd_formats(
  2124. mpd_url, video_id, fatal=dash_mpd_fatal,
  2125. formats_dict=self._formats):
  2126. if not df.get('filesize'):
  2127. df['filesize'] = _extract_filesize(df['url'])
  2128. # Do not overwrite DASH format found in some previous DASH manifest
  2129. if df['format_id'] not in dash_formats:
  2130. dash_formats[df['format_id']] = df
  2131. # Additional DASH manifests may end up in HTTP Error 403 therefore
  2132. # allow them to fail without bug report message if we already have
  2133. # some DASH manifest succeeded. This is temporary workaround to reduce
  2134. # burst of bug reports until we figure out the reason and whether it
  2135. # can be fixed at all.
  2136. dash_mpd_fatal = False
  2137. except (ExtractorError, KeyError) as e:
  2138. self.report_warning(
  2139. 'Skipping DASH manifest: %r' % e, video_id)
  2140. if dash_formats:
  2141. # Remove the formats we found through non-DASH, they
  2142. # contain less info and it can be wrong, because we use
  2143. # fixed values (for example the resolution). See
  2144. # https://github.com/ytdl-org/youtube-dl/issues/5774 for an
  2145. # example.
  2146. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  2147. formats.extend(dash_formats.values())
  2148. # Check for malformed aspect ratio
  2149. stretched_m = re.search(
  2150. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  2151. video_webpage)
  2152. if stretched_m:
  2153. w = float(stretched_m.group('w'))
  2154. h = float(stretched_m.group('h'))
  2155. # yt:stretch may hold invalid ratio data (e.g. for Q39EVAstoRM ratio is 17:0).
  2156. # We will only process correct ratios.
  2157. if w > 0 and h > 0:
  2158. ratio = w / h
  2159. for f in formats:
  2160. if f.get('vcodec') != 'none':
  2161. f['stretched_ratio'] = ratio
  2162. if not formats:
  2163. token = extract_token(video_info)
  2164. if not token:
  2165. if 'reason' in video_info:
  2166. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  2167. regions_allowed = self._html_search_meta(
  2168. 'regionsAllowed', video_webpage, default=None)
  2169. countries = regions_allowed.split(',') if regions_allowed else None
  2170. self.raise_geo_restricted(
  2171. msg=video_info['reason'][0], countries=countries)
  2172. reason = video_info['reason'][0]
  2173. if 'Invalid parameters' in reason:
  2174. unavailable_message = extract_unavailable_message()
  2175. if unavailable_message:
  2176. reason = unavailable_message
  2177. raise ExtractorError(
  2178. 'YouTube said: %s' % reason,
  2179. expected=True, video_id=video_id)
  2180. else:
  2181. raise ExtractorError(
  2182. '"token" parameter not in video info for unknown reason',
  2183. video_id=video_id)
  2184. if not formats and (video_info.get('license_info') or try_get(player_response, lambda x: x['streamingData']['licenseInfos'])):
  2185. raise ExtractorError('This video is DRM protected.', expected=True)
  2186. self._sort_formats(formats)
  2187. self.mark_watched(video_id, video_info, player_response)
  2188. return {
  2189. 'id': video_id,
  2190. 'uploader': video_uploader,
  2191. 'uploader_id': video_uploader_id,
  2192. 'uploader_url': video_uploader_url,
  2193. 'channel_id': channel_id,
  2194. 'channel_url': channel_url,
  2195. 'upload_date': upload_date,
  2196. 'license': video_license,
  2197. 'creator': video_creator or artist,
  2198. 'title': video_title,
  2199. 'alt_title': video_alt_title or track,
  2200. 'thumbnail': video_thumbnail,
  2201. 'description': video_description,
  2202. 'categories': video_categories,
  2203. 'tags': video_tags,
  2204. 'subtitles': video_subtitles,
  2205. 'automatic_captions': automatic_captions,
  2206. 'duration': video_duration,
  2207. 'age_limit': 18 if age_gate else 0,
  2208. 'annotations': video_annotations,
  2209. 'chapters': chapters,
  2210. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  2211. 'view_count': view_count,
  2212. 'like_count': like_count,
  2213. 'dislike_count': dislike_count,
  2214. 'average_rating': average_rating,
  2215. 'formats': formats,
  2216. 'is_live': is_live,
  2217. 'start_time': start_time,
  2218. 'end_time': end_time,
  2219. 'series': series,
  2220. 'season_number': season_number,
  2221. 'episode_number': episode_number,
  2222. 'track': track,
  2223. 'artist': artist,
  2224. 'album': album,
  2225. 'release_date': release_date,
  2226. 'release_year': release_year,
  2227. }
  2228. class YoutubePlaylistIE(YoutubePlaylistBaseInfoExtractor):
  2229. IE_DESC = 'YouTube.com playlists'
  2230. _VALID_URL = r"""(?x)(?:
  2231. (?:https?://)?
  2232. (?:\w+\.)?
  2233. (?:
  2234. (?:
  2235. youtube\.com|
  2236. invidio\.us
  2237. )
  2238. /
  2239. (?:
  2240. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/(?:videoseries|[0-9A-Za-z_-]{11}))
  2241. \? (?:.*?[&;])*? (?:p|a|list)=
  2242. | p/
  2243. )|
  2244. youtu\.be/[0-9A-Za-z_-]{11}\?.*?\blist=
  2245. )
  2246. (
  2247. (?:PL|LL|EC|UU|FL|RD|UL|TL|OLAK5uy_)?[0-9A-Za-z-_]{10,}
  2248. # Top tracks, they can also include dots
  2249. |(?:MC)[\w\.]*
  2250. )
  2251. .*
  2252. |
  2253. (%(playlist_id)s)
  2254. )""" % {'playlist_id': YoutubeBaseInfoExtractor._PLAYLIST_ID_RE}
  2255. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  2256. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})(?:&amp;(?:[^"]*?index=(?P<index>\d+))?(?:[^>]+>(?P<title>[^<]+))?)?'
  2257. IE_NAME = 'youtube:playlist'
  2258. _TESTS = [{
  2259. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  2260. 'info_dict': {
  2261. 'title': 'ytdl test PL',
  2262. 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  2263. },
  2264. 'playlist_count': 3,
  2265. }, {
  2266. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  2267. 'info_dict': {
  2268. 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  2269. 'title': 'YDL_Empty_List',
  2270. },
  2271. 'playlist_count': 0,
  2272. 'skip': 'This playlist is private',
  2273. }, {
  2274. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  2275. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2276. 'info_dict': {
  2277. 'title': '29C3: Not my department',
  2278. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  2279. },
  2280. 'playlist_count': 95,
  2281. }, {
  2282. 'note': 'issue #673',
  2283. 'url': 'PLBB231211A4F62143',
  2284. 'info_dict': {
  2285. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  2286. 'id': 'PLBB231211A4F62143',
  2287. },
  2288. 'playlist_mincount': 26,
  2289. }, {
  2290. 'note': 'Large playlist',
  2291. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  2292. 'info_dict': {
  2293. 'title': 'Uploads from Cauchemar',
  2294. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  2295. },
  2296. 'playlist_mincount': 799,
  2297. }, {
  2298. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2299. 'info_dict': {
  2300. 'title': 'YDL_safe_search',
  2301. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  2302. },
  2303. 'playlist_count': 2,
  2304. 'skip': 'This playlist is private',
  2305. }, {
  2306. 'note': 'embedded',
  2307. 'url': 'https://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2308. 'playlist_count': 4,
  2309. 'info_dict': {
  2310. 'title': 'JODA15',
  2311. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  2312. }
  2313. }, {
  2314. 'url': 'http://www.youtube.com/embed/_xDOZElKyNU?list=PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2315. 'playlist_mincount': 485,
  2316. 'info_dict': {
  2317. 'title': '2017 華語最新單曲 (2/24更新)',
  2318. 'id': 'PLsyOSbh5bs16vubvKePAQ1x3PhKavfBIl',
  2319. }
  2320. }, {
  2321. 'note': 'Embedded SWF player',
  2322. 'url': 'https://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  2323. 'playlist_count': 4,
  2324. 'info_dict': {
  2325. 'title': 'JODA7',
  2326. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  2327. }
  2328. }, {
  2329. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  2330. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  2331. 'info_dict': {
  2332. 'title': 'Uploads from Interstellar Movie',
  2333. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  2334. },
  2335. 'playlist_mincount': 21,
  2336. }, {
  2337. # Playlist URL that does not actually serve a playlist
  2338. 'url': 'https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4',
  2339. 'info_dict': {
  2340. 'id': 'FqZTN594JQw',
  2341. 'ext': 'webm',
  2342. 'title': "Smiley's People 01 detective, Adventure Series, Action",
  2343. 'uploader': 'STREEM',
  2344. 'uploader_id': 'UCyPhqAZgwYWZfxElWVbVJng',
  2345. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/channel/UCyPhqAZgwYWZfxElWVbVJng',
  2346. 'upload_date': '20150526',
  2347. 'license': 'Standard YouTube License',
  2348. 'description': 'md5:507cdcb5a49ac0da37a920ece610be80',
  2349. 'categories': ['People & Blogs'],
  2350. 'tags': list,
  2351. 'view_count': int,
  2352. 'like_count': int,
  2353. 'dislike_count': int,
  2354. },
  2355. 'params': {
  2356. 'skip_download': True,
  2357. },
  2358. 'add_ie': [YoutubeIE.ie_key()],
  2359. }, {
  2360. 'url': 'https://youtu.be/yeWKywCrFtk?list=PL2qgrgXsNUG5ig9cat4ohreBjYLAPC0J5',
  2361. 'info_dict': {
  2362. 'id': 'yeWKywCrFtk',
  2363. 'ext': 'mp4',
  2364. 'title': 'Small Scale Baler and Braiding Rugs',
  2365. 'uploader': 'Backus-Page House Museum',
  2366. 'uploader_id': 'backuspagemuseum',
  2367. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/backuspagemuseum',
  2368. 'upload_date': '20161008',
  2369. 'license': 'Standard YouTube License',
  2370. 'description': 'md5:800c0c78d5eb128500bffd4f0b4f2e8a',
  2371. 'categories': ['Nonprofits & Activism'],
  2372. 'tags': list,
  2373. 'like_count': int,
  2374. 'dislike_count': int,
  2375. },
  2376. 'params': {
  2377. 'noplaylist': True,
  2378. 'skip_download': True,
  2379. },
  2380. }, {
  2381. # https://github.com/ytdl-org/youtube-dl/issues/21844
  2382. 'url': 'https://www.youtube.com/playlist?list=PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2383. 'info_dict': {
  2384. 'title': 'Data Analysis with Dr Mike Pound',
  2385. 'id': 'PLzH6n4zXuckpfMu_4Ff8E7Z1behQks5ba',
  2386. 'uploader_id': 'Computerphile',
  2387. 'uploader': 'Computerphile',
  2388. },
  2389. 'playlist_mincount': 11,
  2390. }, {
  2391. 'url': 'https://youtu.be/uWyaPkt-VOI?list=PL9D9FC436B881BA21',
  2392. 'only_matching': True,
  2393. }, {
  2394. 'url': 'TLGGrESM50VT6acwMjAyMjAxNw',
  2395. 'only_matching': True,
  2396. }, {
  2397. # music album playlist
  2398. 'url': 'OLAK5uy_m4xAFdmMC5rX3Ji3g93pQe3hqLZw_9LhM',
  2399. 'only_matching': True,
  2400. }, {
  2401. 'url': 'https://invidio.us/playlist?list=PLDIoUOhQQPlXr63I_vwF9GD8sAKh77dWU',
  2402. 'only_matching': True,
  2403. }]
  2404. def _real_initialize(self):
  2405. self._login()
  2406. def _extract_mix(self, playlist_id):
  2407. # The mixes are generated from a single video
  2408. # the id of the playlist is just 'RD' + video_id
  2409. ids = []
  2410. last_id = playlist_id[-11:]
  2411. for n in itertools.count(1):
  2412. url = 'https://youtube.com/watch?v=%s&list=%s' % (last_id, playlist_id)
  2413. webpage = self._download_webpage(
  2414. url, playlist_id, 'Downloading page {0} of Youtube mix'.format(n))
  2415. new_ids = orderedSet(re.findall(
  2416. r'''(?xs)data-video-username=".*?".*?
  2417. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  2418. webpage))
  2419. # Fetch new pages until all the videos are repeated, it seems that
  2420. # there are always 51 unique videos.
  2421. new_ids = [_id for _id in new_ids if _id not in ids]
  2422. if not new_ids:
  2423. break
  2424. ids.extend(new_ids)
  2425. last_id = ids[-1]
  2426. url_results = self._ids_to_results(ids)
  2427. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  2428. title_span = (
  2429. search_title('playlist-title')
  2430. or search_title('title long-title')
  2431. or search_title('title'))
  2432. title = clean_html(title_span)
  2433. return self.playlist_result(url_results, playlist_id, title)
  2434. def _extract_playlist(self, playlist_id):
  2435. url = self._TEMPLATE_URL % playlist_id
  2436. page = self._download_webpage(url, playlist_id)
  2437. # the yt-alert-message now has tabindex attribute (see https://github.com/ytdl-org/youtube-dl/issues/11604)
  2438. for match in re.findall(r'<div class="yt-alert-message"[^>]*>([^<]+)</div>', page):
  2439. match = match.strip()
  2440. # Check if the playlist exists or is private
  2441. mobj = re.match(r'[^<]*(?:The|This) playlist (?P<reason>does not exist|is private)[^<]*', match)
  2442. if mobj:
  2443. reason = mobj.group('reason')
  2444. message = 'This playlist %s' % reason
  2445. if 'private' in reason:
  2446. message += ', use --username or --netrc to access it'
  2447. message += '.'
  2448. raise ExtractorError(message, expected=True)
  2449. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  2450. raise ExtractorError(
  2451. 'Invalid parameters. Maybe URL is incorrect.',
  2452. expected=True)
  2453. elif re.match(r'[^<]*Choose your language[^<]*', match):
  2454. continue
  2455. else:
  2456. self.report_warning('Youtube gives an alert message: ' + match)
  2457. playlist_title = self._html_search_regex(
  2458. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  2459. page, 'title', default=None)
  2460. _UPLOADER_BASE = r'class=["\']pl-header-details[^>]+>\s*<li>\s*<a[^>]+\bhref='
  2461. uploader = self._search_regex(
  2462. r'%s["\']/(?:user|channel)/[^>]+>([^<]+)' % _UPLOADER_BASE,
  2463. page, 'uploader', default=None)
  2464. mobj = re.search(
  2465. r'%s(["\'])(?P<path>/(?:user|channel)/(?P<uploader_id>.+?))\1' % _UPLOADER_BASE,
  2466. page)
  2467. if mobj:
  2468. uploader_id = mobj.group('uploader_id')
  2469. uploader_url = compat_urlparse.urljoin(url, mobj.group('path'))
  2470. else:
  2471. uploader_id = uploader_url = None
  2472. has_videos = True
  2473. if not playlist_title:
  2474. try:
  2475. # Some playlist URLs don't actually serve a playlist (e.g.
  2476. # https://www.youtube.com/watch?v=FqZTN594JQw&list=PLMYEtVRpaqY00V9W81Cwmzp6N6vZqfUKD4)
  2477. next(self._entries(page, playlist_id))
  2478. except StopIteration:
  2479. has_videos = False
  2480. playlist = self.playlist_result(
  2481. self._entries(page, playlist_id), playlist_id, playlist_title)
  2482. playlist.update({
  2483. 'uploader': uploader,
  2484. 'uploader_id': uploader_id,
  2485. 'uploader_url': uploader_url,
  2486. })
  2487. return has_videos, playlist
  2488. def _check_download_just_video(self, url, playlist_id):
  2489. # Check if it's a video-specific URL
  2490. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  2491. video_id = query_dict.get('v', [None])[0] or self._search_regex(
  2492. r'(?:(?:^|//)youtu\.be/|youtube\.com/embed/(?!videoseries))([0-9A-Za-z_-]{11})', url,
  2493. 'video id', default=None)
  2494. if video_id:
  2495. if self._downloader.params.get('noplaylist'):
  2496. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  2497. return video_id, self.url_result(video_id, 'Youtube', video_id=video_id)
  2498. else:
  2499. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  2500. return video_id, None
  2501. return None, None
  2502. def _real_extract(self, url):
  2503. # Extract playlist id
  2504. mobj = re.match(self._VALID_URL, url)
  2505. if mobj is None:
  2506. raise ExtractorError('Invalid URL: %s' % url)
  2507. playlist_id = mobj.group(1) or mobj.group(2)
  2508. video_id, video = self._check_download_just_video(url, playlist_id)
  2509. if video:
  2510. return video
  2511. if playlist_id.startswith(('RD', 'UL', 'PU')):
  2512. # Mixes require a custom extraction process
  2513. return self._extract_mix(playlist_id)
  2514. has_videos, playlist = self._extract_playlist(playlist_id)
  2515. if has_videos or not video_id:
  2516. return playlist
  2517. # Some playlist URLs don't actually serve a playlist (see
  2518. # https://github.com/ytdl-org/youtube-dl/issues/10537).
  2519. # Fallback to plain video extraction if there is a video id
  2520. # along with playlist id.
  2521. return self.url_result(video_id, 'Youtube', video_id=video_id)
  2522. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  2523. IE_DESC = 'YouTube.com channels'
  2524. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com|(?:www\.)?invidio\.us)/channel/(?P<id>[0-9A-Za-z_-]+)'
  2525. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  2526. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  2527. IE_NAME = 'youtube:channel'
  2528. _TESTS = [{
  2529. 'note': 'paginated channel',
  2530. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  2531. 'playlist_mincount': 91,
  2532. 'info_dict': {
  2533. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  2534. 'title': 'Uploads from lex will',
  2535. }
  2536. }, {
  2537. 'note': 'Age restricted channel',
  2538. # from https://www.youtube.com/user/DeusExOfficial
  2539. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  2540. 'playlist_mincount': 64,
  2541. 'info_dict': {
  2542. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  2543. 'title': 'Uploads from Deus Ex',
  2544. },
  2545. }, {
  2546. 'url': 'https://invidio.us/channel/UC23qupoDRn9YOAVzeoxjOQA',
  2547. 'only_matching': True,
  2548. }]
  2549. @classmethod
  2550. def suitable(cls, url):
  2551. return (False if YoutubePlaylistsIE.suitable(url) or YoutubeLiveIE.suitable(url)
  2552. else super(YoutubeChannelIE, cls).suitable(url))
  2553. def _build_template_url(self, url, channel_id):
  2554. return self._TEMPLATE_URL % channel_id
  2555. def _real_extract(self, url):
  2556. channel_id = self._match_id(url)
  2557. url = self._build_template_url(url, channel_id)
  2558. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  2559. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  2560. # otherwise fallback on channel by page extraction
  2561. channel_page = self._download_webpage(
  2562. url + '?view=57', channel_id,
  2563. 'Downloading channel page', fatal=False)
  2564. if channel_page is False:
  2565. channel_playlist_id = False
  2566. else:
  2567. channel_playlist_id = self._html_search_meta(
  2568. 'channelId', channel_page, 'channel id', default=None)
  2569. if not channel_playlist_id:
  2570. channel_url = self._html_search_meta(
  2571. ('al:ios:url', 'twitter:app:url:iphone', 'twitter:app:url:ipad'),
  2572. channel_page, 'channel url', default=None)
  2573. if channel_url:
  2574. channel_playlist_id = self._search_regex(
  2575. r'vnd\.youtube://user/([0-9A-Za-z_-]+)',
  2576. channel_url, 'channel id', default=None)
  2577. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  2578. playlist_id = 'UU' + channel_playlist_id[2:]
  2579. return self.url_result(
  2580. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  2581. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  2582. autogenerated = re.search(r'''(?x)
  2583. class="[^"]*?(?:
  2584. channel-header-autogenerated-label|
  2585. yt-channel-title-autogenerated
  2586. )[^"]*"''', channel_page) is not None
  2587. if autogenerated:
  2588. # The videos are contained in a single page
  2589. # the ajax pages can't be used, they are empty
  2590. entries = [
  2591. self.url_result(
  2592. video_id, 'Youtube', video_id=video_id,
  2593. video_title=video_title)
  2594. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  2595. return self.playlist_result(entries, channel_id)
  2596. try:
  2597. next(self._entries(channel_page, channel_id))
  2598. except StopIteration:
  2599. alert_message = self._html_search_regex(
  2600. r'(?s)<div[^>]+class=(["\']).*?\byt-alert-message\b.*?\1[^>]*>(?P<alert>[^<]+)</div>',
  2601. channel_page, 'alert', default=None, group='alert')
  2602. if alert_message:
  2603. raise ExtractorError('Youtube said: %s' % alert_message, expected=True)
  2604. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  2605. class YoutubeUserIE(YoutubeChannelIE):
  2606. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  2607. _VALID_URL = r'(?:(?:https?://(?:\w+\.)?youtube\.com/(?:(?P<user>user|c)/)?(?!(?:attribution_link|watch|results|shared)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)(?P<id>[A-Za-z0-9_-]+)'
  2608. _TEMPLATE_URL = 'https://www.youtube.com/%s/%s/videos'
  2609. IE_NAME = 'youtube:user'
  2610. _TESTS = [{
  2611. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  2612. 'playlist_mincount': 320,
  2613. 'info_dict': {
  2614. 'id': 'UUfX55Sx5hEFjoC3cNs6mCUQ',
  2615. 'title': 'Uploads from The Linux Foundation',
  2616. }
  2617. }, {
  2618. # Only available via https://www.youtube.com/c/12minuteathlete/videos
  2619. # but not https://www.youtube.com/user/12minuteathlete/videos
  2620. 'url': 'https://www.youtube.com/c/12minuteathlete/videos',
  2621. 'playlist_mincount': 249,
  2622. 'info_dict': {
  2623. 'id': 'UUVjM-zV6_opMDx7WYxnjZiQ',
  2624. 'title': 'Uploads from 12 Minute Athlete',
  2625. }
  2626. }, {
  2627. 'url': 'ytuser:phihag',
  2628. 'only_matching': True,
  2629. }, {
  2630. 'url': 'https://www.youtube.com/c/gametrailers',
  2631. 'only_matching': True,
  2632. }, {
  2633. 'url': 'https://www.youtube.com/gametrailers',
  2634. 'only_matching': True,
  2635. }, {
  2636. # This channel is not available, geo restricted to JP
  2637. 'url': 'https://www.youtube.com/user/kananishinoSMEJ/videos',
  2638. 'only_matching': True,
  2639. }]
  2640. @classmethod
  2641. def suitable(cls, url):
  2642. # Don't return True if the url can be extracted with other youtube
  2643. # extractor, the regex would is too permissive and it would match.
  2644. other_yt_ies = iter(klass for (name, klass) in globals().items() if name.startswith('Youtube') and name.endswith('IE') and klass is not cls)
  2645. if any(ie.suitable(url) for ie in other_yt_ies):
  2646. return False
  2647. else:
  2648. return super(YoutubeUserIE, cls).suitable(url)
  2649. def _build_template_url(self, url, channel_id):
  2650. mobj = re.match(self._VALID_URL, url)
  2651. return self._TEMPLATE_URL % (mobj.group('user') or 'user', mobj.group('id'))
  2652. class YoutubeLiveIE(YoutubeBaseInfoExtractor):
  2653. IE_DESC = 'YouTube.com live streams'
  2654. _VALID_URL = r'(?P<base_url>https?://(?:\w+\.)?youtube\.com/(?:(?:user|channel|c)/)?(?P<id>[^/]+))/live'
  2655. IE_NAME = 'youtube:live'
  2656. _TESTS = [{
  2657. 'url': 'https://www.youtube.com/user/TheYoungTurks/live',
  2658. 'info_dict': {
  2659. 'id': 'a48o2S1cPoo',
  2660. 'ext': 'mp4',
  2661. 'title': 'The Young Turks - Live Main Show',
  2662. 'uploader': 'The Young Turks',
  2663. 'uploader_id': 'TheYoungTurks',
  2664. 'uploader_url': r're:https?://(?:www\.)?youtube\.com/user/TheYoungTurks',
  2665. 'upload_date': '20150715',
  2666. 'license': 'Standard YouTube License',
  2667. 'description': 'md5:438179573adcdff3c97ebb1ee632b891',
  2668. 'categories': ['News & Politics'],
  2669. 'tags': ['Cenk Uygur (TV Program Creator)', 'The Young Turks (Award-Winning Work)', 'Talk Show (TV Genre)'],
  2670. 'like_count': int,
  2671. 'dislike_count': int,
  2672. },
  2673. 'params': {
  2674. 'skip_download': True,
  2675. },
  2676. }, {
  2677. 'url': 'https://www.youtube.com/channel/UC1yBKRuGpC1tSM73A0ZjYjQ/live',
  2678. 'only_matching': True,
  2679. }, {
  2680. 'url': 'https://www.youtube.com/c/CommanderVideoHq/live',
  2681. 'only_matching': True,
  2682. }, {
  2683. 'url': 'https://www.youtube.com/TheYoungTurks/live',
  2684. 'only_matching': True,
  2685. }]
  2686. def _real_extract(self, url):
  2687. mobj = re.match(self._VALID_URL, url)
  2688. channel_id = mobj.group('id')
  2689. base_url = mobj.group('base_url')
  2690. webpage = self._download_webpage(url, channel_id, fatal=False)
  2691. if webpage:
  2692. page_type = self._og_search_property(
  2693. 'type', webpage, 'page type', default='')
  2694. video_id = self._html_search_meta(
  2695. 'videoId', webpage, 'video id', default=None)
  2696. if page_type.startswith('video') and video_id and re.match(
  2697. r'^[0-9A-Za-z_-]{11}$', video_id):
  2698. return self.url_result(video_id, YoutubeIE.ie_key())
  2699. return self.url_result(base_url)
  2700. class YoutubePlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  2701. IE_DESC = 'YouTube.com user/channel playlists'
  2702. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/(?:user|channel)/(?P<id>[^/]+)/playlists'
  2703. IE_NAME = 'youtube:playlists'
  2704. _TESTS = [{
  2705. 'url': 'https://www.youtube.com/user/ThirstForScience/playlists',
  2706. 'playlist_mincount': 4,
  2707. 'info_dict': {
  2708. 'id': 'ThirstForScience',
  2709. 'title': 'Thirst for Science',
  2710. },
  2711. }, {
  2712. # with "Load more" button
  2713. 'url': 'https://www.youtube.com/user/igorkle1/playlists?view=1&sort=dd',
  2714. 'playlist_mincount': 70,
  2715. 'info_dict': {
  2716. 'id': 'igorkle1',
  2717. 'title': 'Игорь Клейнер',
  2718. },
  2719. }, {
  2720. 'url': 'https://www.youtube.com/channel/UCiU1dHvZObB2iP6xkJ__Icw/playlists',
  2721. 'playlist_mincount': 17,
  2722. 'info_dict': {
  2723. 'id': 'UCiU1dHvZObB2iP6xkJ__Icw',
  2724. 'title': 'Chem Player',
  2725. },
  2726. }]
  2727. class YoutubeSearchBaseInfoExtractor(YoutubePlaylistBaseInfoExtractor):
  2728. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})(?:[^"]*"[^>]+\btitle="(?P<title>[^"]+))?'
  2729. class YoutubeSearchIE(SearchInfoExtractor, YoutubeSearchBaseInfoExtractor):
  2730. IE_DESC = 'YouTube.com searches'
  2731. # there doesn't appear to be a real limit, for example if you search for
  2732. # 'python' you get more than 8.000.000 results
  2733. _MAX_RESULTS = float('inf')
  2734. IE_NAME = 'youtube:search'
  2735. _SEARCH_KEY = 'ytsearch'
  2736. _EXTRA_QUERY_ARGS = {}
  2737. _TESTS = []
  2738. def _get_n_results(self, query, n):
  2739. """Get a specified number of results for a query"""
  2740. videos = []
  2741. limit = n
  2742. url_query = {
  2743. 'search_query': query.encode('utf-8'),
  2744. }
  2745. url_query.update(self._EXTRA_QUERY_ARGS)
  2746. result_url = 'https://www.youtube.com/results?' + compat_urllib_parse_urlencode(url_query)
  2747. for pagenum in itertools.count(1):
  2748. data = self._download_json(
  2749. result_url, video_id='query "%s"' % query,
  2750. note='Downloading page %s' % pagenum,
  2751. errnote='Unable to download API page',
  2752. query={'spf': 'navigate'})
  2753. html_content = data[1]['body']['content']
  2754. if 'class="search-message' in html_content:
  2755. raise ExtractorError(
  2756. '[youtube] No video results', expected=True)
  2757. new_videos = list(self._process_page(html_content))
  2758. videos += new_videos
  2759. if not new_videos or len(videos) > limit:
  2760. break
  2761. next_link = self._html_search_regex(
  2762. r'href="(/results\?[^"]*\bsp=[^"]+)"[^>]*>\s*<span[^>]+class="[^"]*\byt-uix-button-content\b[^"]*"[^>]*>Next',
  2763. html_content, 'next link', default=None)
  2764. if next_link is None:
  2765. break
  2766. result_url = compat_urlparse.urljoin('https://www.youtube.com/', next_link)
  2767. if len(videos) > n:
  2768. videos = videos[:n]
  2769. return self.playlist_result(videos, query)
  2770. class YoutubeSearchDateIE(YoutubeSearchIE):
  2771. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  2772. _SEARCH_KEY = 'ytsearchdate'
  2773. IE_DESC = 'YouTube.com searches, newest videos first'
  2774. _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
  2775. class YoutubeSearchURLIE(YoutubeSearchBaseInfoExtractor):
  2776. IE_DESC = 'YouTube.com search URLs'
  2777. IE_NAME = 'youtube:search_url'
  2778. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?(?:search_query|q)=(?P<query>[^&]+)(?:[&]|$)'
  2779. _TESTS = [{
  2780. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  2781. 'playlist_mincount': 5,
  2782. 'info_dict': {
  2783. 'title': 'youtube-dl test video',
  2784. }
  2785. }, {
  2786. 'url': 'https://www.youtube.com/results?q=test&sp=EgQIBBgB',
  2787. 'only_matching': True,
  2788. }]
  2789. def _real_extract(self, url):
  2790. mobj = re.match(self._VALID_URL, url)
  2791. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  2792. webpage = self._download_webpage(url, query)
  2793. return self.playlist_result(self._process_page(webpage), playlist_title=query)
  2794. class YoutubeShowIE(YoutubePlaylistsBaseInfoExtractor):
  2795. IE_DESC = 'YouTube.com (multi-season) shows'
  2796. _VALID_URL = r'https?://(?:www\.)?youtube\.com/show/(?P<id>[^?#]*)'
  2797. IE_NAME = 'youtube:show'
  2798. _TESTS = [{
  2799. 'url': 'https://www.youtube.com/show/airdisasters',
  2800. 'playlist_mincount': 5,
  2801. 'info_dict': {
  2802. 'id': 'airdisasters',
  2803. 'title': 'Air Disasters',
  2804. }
  2805. }]
  2806. def _real_extract(self, url):
  2807. playlist_id = self._match_id(url)
  2808. return super(YoutubeShowIE, self)._real_extract(
  2809. 'https://www.youtube.com/show/%s/playlists' % playlist_id)
  2810. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  2811. """
  2812. Base class for feed extractors
  2813. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  2814. """
  2815. _LOGIN_REQUIRED = True
  2816. @property
  2817. def IE_NAME(self):
  2818. return 'youtube:%s' % self._FEED_NAME
  2819. def _real_initialize(self):
  2820. self._login()
  2821. def _entries(self, page):
  2822. # The extraction process is the same as for playlists, but the regex
  2823. # for the video ids doesn't contain an index
  2824. ids = []
  2825. more_widget_html = content_html = page
  2826. for page_num in itertools.count(1):
  2827. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  2828. # 'recommended' feed has infinite 'load more' and each new portion spins
  2829. # the same videos in (sometimes) slightly different order, so we'll check
  2830. # for unicity and break when portion has no new videos
  2831. new_ids = list(filter(lambda video_id: video_id not in ids, orderedSet(matches)))
  2832. if not new_ids:
  2833. break
  2834. ids.extend(new_ids)
  2835. for entry in self._ids_to_results(new_ids):
  2836. yield entry
  2837. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  2838. if not mobj:
  2839. break
  2840. more = self._download_json(
  2841. 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  2842. 'Downloading page #%s' % page_num,
  2843. transform_source=uppercase_escape)
  2844. content_html = more['content_html']
  2845. more_widget_html = more['load_more_widget_html']
  2846. def _real_extract(self, url):
  2847. page = self._download_webpage(
  2848. 'https://www.youtube.com/feed/%s' % self._FEED_NAME,
  2849. self._PLAYLIST_TITLE)
  2850. return self.playlist_result(
  2851. self._entries(page), playlist_title=self._PLAYLIST_TITLE)
  2852. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  2853. IE_NAME = 'youtube:watchlater'
  2854. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  2855. _VALID_URL = r'https?://(?:www\.)?youtube\.com/(?:feed/watch_later|(?:playlist|watch)\?(?:.+&)?list=WL)|:ytwatchlater'
  2856. _TESTS = [{
  2857. 'url': 'https://www.youtube.com/playlist?list=WL',
  2858. 'only_matching': True,
  2859. }, {
  2860. 'url': 'https://www.youtube.com/watch?v=bCNU9TrbiRk&index=1&list=WL',
  2861. 'only_matching': True,
  2862. }]
  2863. def _real_extract(self, url):
  2864. _, video = self._check_download_just_video(url, 'WL')
  2865. if video:
  2866. return video
  2867. _, playlist = self._extract_playlist('WL')
  2868. return playlist
  2869. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  2870. IE_NAME = 'youtube:favorites'
  2871. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  2872. _VALID_URL = r'https?://(?:www\.)?youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  2873. _LOGIN_REQUIRED = True
  2874. def _real_extract(self, url):
  2875. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  2876. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  2877. return self.url_result(playlist_id, 'YoutubePlaylist')
  2878. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  2879. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  2880. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  2881. _FEED_NAME = 'recommended'
  2882. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  2883. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  2884. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  2885. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  2886. _FEED_NAME = 'subscriptions'
  2887. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  2888. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  2889. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  2890. _VALID_URL = r'https?://(?:www\.)?youtube\.com/feed/history|:ythistory'
  2891. _FEED_NAME = 'history'
  2892. _PLAYLIST_TITLE = 'Youtube History'
  2893. class YoutubeTruncatedURLIE(InfoExtractor):
  2894. IE_NAME = 'youtube:truncated_url'
  2895. IE_DESC = False # Do not list
  2896. _VALID_URL = r'''(?x)
  2897. (?:https?://)?
  2898. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  2899. (?:watch\?(?:
  2900. feature=[a-z_]+|
  2901. annotation_id=annotation_[^&]+|
  2902. x-yt-cl=[0-9]+|
  2903. hl=[^&]*|
  2904. t=[0-9]+
  2905. )?
  2906. |
  2907. attribution_link\?a=[^&]+
  2908. )
  2909. $
  2910. '''
  2911. _TESTS = [{
  2912. 'url': 'https://www.youtube.com/watch?annotation_id=annotation_3951667041',
  2913. 'only_matching': True,
  2914. }, {
  2915. 'url': 'https://www.youtube.com/watch?',
  2916. 'only_matching': True,
  2917. }, {
  2918. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  2919. 'only_matching': True,
  2920. }, {
  2921. 'url': 'https://www.youtube.com/watch?feature=foo',
  2922. 'only_matching': True,
  2923. }, {
  2924. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  2925. 'only_matching': True,
  2926. }, {
  2927. 'url': 'https://www.youtube.com/watch?t=2372',
  2928. 'only_matching': True,
  2929. }]
  2930. def _real_extract(self, url):
  2931. raise ExtractorError(
  2932. 'Did you forget to quote the URL? Remember that & is a meta '
  2933. 'character in most shells, so you want to put the URL in quotes, '
  2934. 'like youtube-dl '
  2935. '"https://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  2936. ' or simply youtube-dl BaW_jenozKc .',
  2937. expected=True)
  2938. class YoutubeTruncatedIDIE(InfoExtractor):
  2939. IE_NAME = 'youtube:truncated_id'
  2940. IE_DESC = False # Do not list
  2941. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  2942. _TESTS = [{
  2943. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  2944. 'only_matching': True,
  2945. }]
  2946. def _real_extract(self, url):
  2947. video_id = self._match_id(url)
  2948. raise ExtractorError(
  2949. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  2950. expected=True)