youtube.py 131 KB

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