youtube.py 92 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058
  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import itertools
  4. import json
  5. import os.path
  6. import re
  7. import time
  8. import traceback
  9. from .common import InfoExtractor, SearchInfoExtractor
  10. from ..jsinterp import JSInterpreter
  11. from ..swfinterp import SWFInterpreter
  12. from ..compat import (
  13. compat_chr,
  14. compat_parse_qs,
  15. compat_urllib_parse,
  16. compat_urllib_parse_unquote,
  17. compat_urllib_parse_unquote_plus,
  18. compat_urllib_parse_urlparse,
  19. compat_urllib_request,
  20. compat_urlparse,
  21. compat_str,
  22. )
  23. from ..utils import (
  24. clean_html,
  25. encode_dict,
  26. ExtractorError,
  27. float_or_none,
  28. get_element_by_attribute,
  29. get_element_by_id,
  30. int_or_none,
  31. orderedSet,
  32. parse_duration,
  33. remove_start,
  34. smuggle_url,
  35. str_to_int,
  36. unescapeHTML,
  37. unified_strdate,
  38. unsmuggle_url,
  39. uppercase_escape,
  40. ISO3166Utils,
  41. )
  42. class YoutubeBaseInfoExtractor(InfoExtractor):
  43. """Provide base functions for Youtube extractors"""
  44. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  45. _TWOFACTOR_URL = 'https://accounts.google.com/signin/challenge'
  46. _NETRC_MACHINE = 'youtube'
  47. # If True it will raise an error if no login info is provided
  48. _LOGIN_REQUIRED = False
  49. def _set_language(self):
  50. self._set_cookie(
  51. '.youtube.com', 'PREF', 'f1=50000000&hl=en',
  52. # YouTube sets the expire time to about two months
  53. expire_time=time.time() + 2 * 30 * 24 * 3600)
  54. def _ids_to_results(self, ids):
  55. return [
  56. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  57. for vid_id in ids]
  58. def _login(self):
  59. """
  60. Attempt to log in to YouTube.
  61. True is returned if successful or skipped.
  62. False is returned if login failed.
  63. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  64. """
  65. (username, password) = self._get_login_info()
  66. # No authentication to be performed
  67. if username is None:
  68. if self._LOGIN_REQUIRED:
  69. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  70. return True
  71. login_page = self._download_webpage(
  72. self._LOGIN_URL, None,
  73. note='Downloading login page',
  74. errnote='unable to fetch login page', fatal=False)
  75. if login_page is False:
  76. return
  77. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  78. login_page, 'Login GALX parameter')
  79. # Log in
  80. login_form_strs = {
  81. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  82. 'Email': username,
  83. 'GALX': galx,
  84. 'Passwd': password,
  85. 'PersistentCookie': 'yes',
  86. '_utf8': '霱',
  87. 'bgresponse': 'js_disabled',
  88. 'checkConnection': '',
  89. 'checkedDomains': 'youtube',
  90. 'dnConn': '',
  91. 'pstMsg': '0',
  92. 'rmShown': '1',
  93. 'secTok': '',
  94. 'signIn': 'Sign in',
  95. 'timeStmp': '',
  96. 'service': 'youtube',
  97. 'uilel': '3',
  98. 'hl': 'en_US',
  99. }
  100. login_data = compat_urllib_parse.urlencode(encode_dict(login_form_strs)).encode('ascii')
  101. req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  102. login_results = self._download_webpage(
  103. req, None,
  104. note='Logging in', errnote='unable to log in', fatal=False)
  105. if login_results is False:
  106. return False
  107. if re.search(r'id="errormsg_0_Passwd"', login_results) is not None:
  108. raise ExtractorError('Please use your account password and a two-factor code instead of an application-specific password.', expected=True)
  109. # Two-Factor
  110. # TODO add SMS and phone call support - these require making a request and then prompting the user
  111. if re.search(r'(?i)<form[^>]* id="challenge"', login_results) is not None:
  112. tfa_code = self._get_tfa_info('2-step verification code')
  113. if not tfa_code:
  114. self._downloader.report_warning(
  115. 'Two-factor authentication required. Provide it either interactively or with --twofactor <code>'
  116. '(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  117. return False
  118. tfa_code = remove_start(tfa_code, 'G-')
  119. tfa_form_strs = self._form_hidden_inputs('challenge', login_results)
  120. tfa_form_strs.update({
  121. 'Pin': tfa_code,
  122. 'TrustDevice': 'on',
  123. })
  124. tfa_data = compat_urllib_parse.urlencode(encode_dict(tfa_form_strs)).encode('ascii')
  125. tfa_req = compat_urllib_request.Request(self._TWOFACTOR_URL, tfa_data)
  126. tfa_results = self._download_webpage(
  127. tfa_req, None,
  128. note='Submitting TFA code', errnote='unable to submit tfa', fatal=False)
  129. if tfa_results is False:
  130. return False
  131. if re.search(r'(?i)<form[^>]* id="challenge"', tfa_results) is not None:
  132. self._downloader.report_warning('Two-factor code expired or invalid. Please try again, or use a one-use backup code instead.')
  133. return False
  134. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', tfa_results) is not None:
  135. self._downloader.report_warning('unable to log in - did the page structure change?')
  136. return False
  137. if re.search(r'smsauth-interstitial-reviewsettings', tfa_results) is not None:
  138. self._downloader.report_warning('Your Google account has a security notice. Please log in on your web browser, resolve the notice, and try again.')
  139. return False
  140. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  141. self._downloader.report_warning('unable to log in: bad username or password')
  142. return False
  143. return True
  144. def _real_initialize(self):
  145. if self._downloader is None:
  146. return
  147. self._set_language()
  148. if not self._login():
  149. return
  150. class YoutubePlaylistBaseInfoExtractor(InfoExtractor):
  151. # Extract the video ids from the playlist pages
  152. def _entries(self, page, playlist_id):
  153. more_widget_html = content_html = page
  154. for page_num in itertools.count(1):
  155. for video_id, video_title in self.extract_videos_from_page(content_html):
  156. yield self.url_result(
  157. video_id, 'Youtube', video_id=video_id,
  158. video_title=video_title)
  159. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  160. if not mobj:
  161. break
  162. more = self._download_json(
  163. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  164. 'Downloading page #%s' % page_num,
  165. transform_source=uppercase_escape)
  166. content_html = more['content_html']
  167. if not content_html.strip():
  168. # Some webpages show a "Load more" button but they don't
  169. # have more videos
  170. break
  171. more_widget_html = more['load_more_widget_html']
  172. def extract_videos_from_page(self, page):
  173. ids_in_page = []
  174. titles_in_page = []
  175. for mobj in re.finditer(self._VIDEO_RE, page):
  176. # The link with index 0 is not the first video of the playlist (not sure if still actual)
  177. if 'index' in mobj.groupdict() and mobj.group('id') == '0':
  178. continue
  179. video_id = mobj.group('id')
  180. video_title = unescapeHTML(mobj.group('title'))
  181. if video_title:
  182. video_title = video_title.strip()
  183. try:
  184. idx = ids_in_page.index(video_id)
  185. if video_title and not titles_in_page[idx]:
  186. titles_in_page[idx] = video_title
  187. except ValueError:
  188. ids_in_page.append(video_id)
  189. titles_in_page.append(video_title)
  190. return zip(ids_in_page, titles_in_page)
  191. class YoutubePlaylistsBaseInfoExtractor(InfoExtractor):
  192. def _real_extract(self, url):
  193. playlist_id = self._match_id(url)
  194. webpage = self._download_webpage(url, playlist_id)
  195. entries = [
  196. self.url_result(compat_urlparse.urljoin(url, playlist), 'YoutubePlaylist')
  197. for playlist in re.findall(r'href="(/playlist\?list=.+?)"', webpage)]
  198. title = self._og_search_title(webpage, fatal=False)
  199. return self.playlist_result(entries, playlist_id, title)
  200. class YoutubeIE(YoutubeBaseInfoExtractor):
  201. IE_DESC = 'YouTube.com'
  202. _VALID_URL = r"""(?x)^
  203. (
  204. (?:https?://|//) # http(s):// or protocol-independent URL
  205. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  206. (?:www\.)?deturl\.com/www\.youtube\.com/|
  207. (?:www\.)?pwnyoutube\.com/|
  208. (?:www\.)?yourepeat\.com/|
  209. tube\.majestyc\.net/|
  210. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  211. (?:.*?\#/)? # handle anchor (#/) redirect urls
  212. (?: # the various things that can precede the ID:
  213. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  214. |(?: # or the v= param in all its forms
  215. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  216. (?:\?|\#!?) # the params delimiter ? or # or #!
  217. (?:.*?&)?? # any other preceding param (like /?s=tuff&v=xxxx)
  218. v=
  219. )
  220. ))
  221. |(?:
  222. youtu\.be| # just youtu.be/xxxx
  223. vid\.plus # or vid.plus/xxxx
  224. )/
  225. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  226. )
  227. )? # all until now is optional -> you can pass the naked ID
  228. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  229. (?!.*?&list=) # combined list/video URLs are handled by the playlist IE
  230. (?(1).+)? # if we found the ID, everything can follow
  231. $"""
  232. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  233. _formats = {
  234. '5': {'ext': 'flv', 'width': 400, 'height': 240},
  235. '6': {'ext': 'flv', 'width': 450, 'height': 270},
  236. '13': {'ext': '3gp'},
  237. '17': {'ext': '3gp', 'width': 176, 'height': 144},
  238. '18': {'ext': 'mp4', 'width': 640, 'height': 360},
  239. '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
  240. '34': {'ext': 'flv', 'width': 640, 'height': 360},
  241. '35': {'ext': 'flv', 'width': 854, 'height': 480},
  242. '36': {'ext': '3gp', 'width': 320, 'height': 240},
  243. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
  244. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
  245. '43': {'ext': 'webm', 'width': 640, 'height': 360},
  246. '44': {'ext': 'webm', 'width': 854, 'height': 480},
  247. '45': {'ext': 'webm', 'width': 1280, 'height': 720},
  248. '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
  249. '59': {'ext': 'mp4', 'width': 854, 'height': 480},
  250. '78': {'ext': 'mp4', 'width': 854, 'height': 480},
  251. # 3d videos
  252. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
  253. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
  254. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
  255. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
  256. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
  257. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
  258. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
  259. # Apple HTTP Live Streaming
  260. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  261. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
  262. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
  263. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
  264. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
  265. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  266. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
  267. # DASH mp4 video
  268. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  269. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  270. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  271. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  272. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  273. '138': {'ext': 'mp4', 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40}, # Height can vary (https://github.com/rg3/youtube-dl/issues/4559)
  274. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  275. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  276. '298': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'h264'},
  277. '299': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'h264'},
  278. '266': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'vcodec': 'h264'},
  279. # Dash mp4 audio
  280. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'vcodec': 'none', 'abr': 48, 'preference': -50, 'container': 'm4a_dash'},
  281. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'vcodec': 'none', 'abr': 128, 'preference': -50, 'container': 'm4a_dash'},
  282. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'acodec': 'aac', 'vcodec': 'none', 'abr': 256, 'preference': -50, 'container': 'm4a_dash'},
  283. # Dash webm
  284. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  285. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  286. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  287. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  288. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  289. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'vp8', 'preference': -40},
  290. '278': {'ext': 'webm', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'container': 'webm', 'vcodec': 'vp9'},
  291. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  292. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  293. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  294. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  295. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  296. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  297. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  298. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  299. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  300. '302': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'vp9'},
  301. '303': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'vp9'},
  302. '308': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'vp9'},
  303. '313': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'vcodec': 'vp9'},
  304. '315': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40, 'fps': 60, 'vcodec': 'vp9'},
  305. # Dash webm audio
  306. '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
  307. '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
  308. # Dash webm audio with opus inside
  309. '249': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 50, 'preference': -50},
  310. '250': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 70, 'preference': -50},
  311. '251': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'acodec': 'opus', 'abr': 160, 'preference': -50},
  312. # RTMP (unnamed)
  313. '_rtmp': {'protocol': 'rtmp'},
  314. }
  315. IE_NAME = 'youtube'
  316. _TESTS = [
  317. {
  318. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKcj&t=1s&end=9',
  319. 'info_dict': {
  320. 'id': 'BaW_jenozKc',
  321. 'ext': 'mp4',
  322. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  323. 'uploader': 'Philipp Hagemeister',
  324. 'uploader_id': 'phihag',
  325. 'upload_date': '20121002',
  326. '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 .',
  327. 'categories': ['Science & Technology'],
  328. 'tags': ['youtube-dl'],
  329. 'like_count': int,
  330. 'dislike_count': int,
  331. 'start_time': 1,
  332. 'end_time': 9,
  333. }
  334. },
  335. {
  336. 'url': 'http://www.youtube.com/watch?v=UxxajLWwzqY',
  337. 'note': 'Test generic use_cipher_signature video (#897)',
  338. 'info_dict': {
  339. 'id': 'UxxajLWwzqY',
  340. 'ext': 'mp4',
  341. 'upload_date': '20120506',
  342. 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
  343. 'description': 'md5:782e8651347686cba06e58f71ab51773',
  344. 'tags': ['Icona Pop i love it', 'sweden', 'pop music', 'big beat records', 'big beat', 'charli',
  345. 'xcx', 'charli xcx', 'girls', 'hbo', 'i love it', "i don't care", 'icona', 'pop',
  346. 'iconic ep', 'iconic', 'love', 'it'],
  347. 'uploader': 'Icona Pop',
  348. 'uploader_id': 'IconaPop',
  349. }
  350. },
  351. {
  352. 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
  353. 'note': 'Test VEVO video with age protection (#956)',
  354. 'info_dict': {
  355. 'id': '07FYdnEawAQ',
  356. 'ext': 'mp4',
  357. 'upload_date': '20130703',
  358. 'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
  359. 'description': 'md5:64249768eec3bc4276236606ea996373',
  360. 'uploader': 'justintimberlakeVEVO',
  361. 'uploader_id': 'justintimberlakeVEVO',
  362. 'age_limit': 18,
  363. }
  364. },
  365. {
  366. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  367. 'note': 'Embed-only video (#1746)',
  368. 'info_dict': {
  369. 'id': 'yZIXLfi8CZQ',
  370. 'ext': 'mp4',
  371. 'upload_date': '20120608',
  372. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  373. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  374. 'uploader': 'SET India',
  375. 'uploader_id': 'setindia'
  376. }
  377. },
  378. {
  379. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKcj&v=UxxajLWwzqY',
  380. 'note': 'Use the first video ID in the URL',
  381. 'info_dict': {
  382. 'id': 'BaW_jenozKc',
  383. 'ext': 'mp4',
  384. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  385. 'uploader': 'Philipp Hagemeister',
  386. 'uploader_id': 'phihag',
  387. 'upload_date': '20121002',
  388. '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 .',
  389. 'categories': ['Science & Technology'],
  390. 'tags': ['youtube-dl'],
  391. 'like_count': int,
  392. 'dislike_count': int,
  393. },
  394. 'params': {
  395. 'skip_download': True,
  396. },
  397. },
  398. {
  399. 'url': 'http://www.youtube.com/watch?v=a9LDPn-MO4I',
  400. 'note': '256k DASH audio (format 141) via DASH manifest',
  401. 'info_dict': {
  402. 'id': 'a9LDPn-MO4I',
  403. 'ext': 'm4a',
  404. 'upload_date': '20121002',
  405. 'uploader_id': '8KVIDEO',
  406. 'description': '',
  407. 'uploader': '8KVIDEO',
  408. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  409. },
  410. 'params': {
  411. 'youtube_include_dash_manifest': True,
  412. 'format': '141',
  413. },
  414. },
  415. # DASH manifest with encrypted signature
  416. {
  417. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  418. 'info_dict': {
  419. 'id': 'IB3lcPjvWLA',
  420. 'ext': 'm4a',
  421. 'title': 'Afrojack, Spree Wilson - The Spark ft. Spree Wilson',
  422. 'description': 'md5:12e7067fa6735a77bdcbb58cb1187d2d',
  423. 'uploader': 'AfrojackVEVO',
  424. 'uploader_id': 'AfrojackVEVO',
  425. 'upload_date': '20131011',
  426. },
  427. 'params': {
  428. 'youtube_include_dash_manifest': True,
  429. 'format': '141',
  430. },
  431. },
  432. # JS player signature function name containing $
  433. {
  434. 'url': 'https://www.youtube.com/watch?v=nfWlot6h_JM',
  435. 'info_dict': {
  436. 'id': 'nfWlot6h_JM',
  437. 'ext': 'm4a',
  438. 'title': 'Taylor Swift - Shake It Off',
  439. 'description': 'md5:95f66187cd7c8b2c13eb78e1223b63c3',
  440. 'uploader': 'TaylorSwiftVEVO',
  441. 'uploader_id': 'TaylorSwiftVEVO',
  442. 'upload_date': '20140818',
  443. },
  444. 'params': {
  445. 'youtube_include_dash_manifest': True,
  446. 'format': '141',
  447. },
  448. },
  449. # Controversy video
  450. {
  451. 'url': 'https://www.youtube.com/watch?v=T4XJQO3qol8',
  452. 'info_dict': {
  453. 'id': 'T4XJQO3qol8',
  454. 'ext': 'mp4',
  455. 'upload_date': '20100909',
  456. 'uploader': 'The Amazing Atheist',
  457. 'uploader_id': 'TheAmazingAtheist',
  458. 'title': 'Burning Everyone\'s Koran',
  459. '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',
  460. }
  461. },
  462. # Normal age-gate video (No vevo, embed allowed)
  463. {
  464. 'url': 'http://youtube.com/watch?v=HtVdAasjOgU',
  465. 'info_dict': {
  466. 'id': 'HtVdAasjOgU',
  467. 'ext': 'mp4',
  468. 'title': 'The Witcher 3: Wild Hunt - The Sword Of Destiny Trailer',
  469. 'description': 're:(?s).{100,}About the Game\n.*?The Witcher 3: Wild Hunt.{100,}',
  470. 'uploader': 'The Witcher',
  471. 'uploader_id': 'WitcherGame',
  472. 'upload_date': '20140605',
  473. 'age_limit': 18,
  474. },
  475. },
  476. # Age-gate video with encrypted signature
  477. {
  478. 'url': 'http://www.youtube.com/watch?v=6kLq3WMV1nU',
  479. 'info_dict': {
  480. 'id': '6kLq3WMV1nU',
  481. 'ext': 'mp4',
  482. 'title': 'Dedication To My Ex (Miss That) (Lyric Video)',
  483. 'description': 'md5:33765bb339e1b47e7e72b5490139bb41',
  484. 'uploader': 'LloydVEVO',
  485. 'uploader_id': 'LloydVEVO',
  486. 'upload_date': '20110629',
  487. 'age_limit': 18,
  488. },
  489. },
  490. # video_info is None (https://github.com/rg3/youtube-dl/issues/4421)
  491. {
  492. 'url': '__2ABJjxzNo',
  493. 'info_dict': {
  494. 'id': '__2ABJjxzNo',
  495. 'ext': 'mp4',
  496. 'upload_date': '20100430',
  497. 'uploader_id': 'deadmau5',
  498. 'description': 'md5:12c56784b8032162bb936a5f76d55360',
  499. 'uploader': 'deadmau5',
  500. 'title': 'Deadmau5 - Some Chords (HD)',
  501. },
  502. 'expected_warnings': [
  503. 'DASH manifest missing',
  504. ]
  505. },
  506. # Olympics (https://github.com/rg3/youtube-dl/issues/4431)
  507. {
  508. 'url': 'lqQg6PlCWgI',
  509. 'info_dict': {
  510. 'id': 'lqQg6PlCWgI',
  511. 'ext': 'mp4',
  512. 'upload_date': '20120724',
  513. 'uploader_id': 'olympic',
  514. 'description': 'HO09 - Women - GER-AUS - Hockey - 31 July 2012 - London 2012 Olympic Games',
  515. 'uploader': 'Olympics',
  516. 'title': 'Hockey - Women - GER-AUS - London 2012 Olympic Games',
  517. },
  518. 'params': {
  519. 'skip_download': 'requires avconv',
  520. }
  521. },
  522. # Non-square pixels
  523. {
  524. 'url': 'https://www.youtube.com/watch?v=_b-2C3KPAM0',
  525. 'info_dict': {
  526. 'id': '_b-2C3KPAM0',
  527. 'ext': 'mp4',
  528. 'stretched_ratio': 16 / 9.,
  529. 'upload_date': '20110310',
  530. 'uploader_id': 'AllenMeow',
  531. 'description': 'made by Wacom from Korea | 字幕&加油添醋 by TY\'s Allen | 感謝heylisa00cavey1001同學熱情提供梗及翻譯',
  532. 'uploader': '孫艾倫',
  533. 'title': '[A-made] 變態妍字幕版 太妍 我就是這樣的人',
  534. },
  535. },
  536. # url_encoded_fmt_stream_map is empty string
  537. {
  538. 'url': 'qEJwOuvDf7I',
  539. 'info_dict': {
  540. 'id': 'qEJwOuvDf7I',
  541. 'ext': 'webm',
  542. 'title': 'Обсуждение судебной практики по выборам 14 сентября 2014 года в Санкт-Петербурге',
  543. 'description': '',
  544. 'upload_date': '20150404',
  545. 'uploader_id': 'spbelect',
  546. 'uploader': 'Наблюдатели Петербурга',
  547. },
  548. 'params': {
  549. 'skip_download': 'requires avconv',
  550. }
  551. },
  552. # Extraction from multiple DASH manifests (https://github.com/rg3/youtube-dl/pull/6097)
  553. {
  554. 'url': 'https://www.youtube.com/watch?v=FIl7x6_3R5Y',
  555. 'info_dict': {
  556. 'id': 'FIl7x6_3R5Y',
  557. 'ext': 'mp4',
  558. 'title': 'md5:7b81415841e02ecd4313668cde88737a',
  559. 'description': 'md5:116377fd2963b81ec4ce64b542173306',
  560. 'upload_date': '20150625',
  561. 'uploader_id': 'dorappi2000',
  562. 'uploader': 'dorappi2000',
  563. 'formats': 'mincount:33',
  564. },
  565. },
  566. # DASH manifest with segment_list
  567. {
  568. 'url': 'https://www.youtube.com/embed/CsmdDsKjzN8',
  569. 'md5': '8ce563a1d667b599d21064e982ab9e31',
  570. 'info_dict': {
  571. 'id': 'CsmdDsKjzN8',
  572. 'ext': 'mp4',
  573. 'upload_date': '20150501', # According to '<meta itemprop="datePublished"', but in other places it's 20150510
  574. 'uploader': 'Airtek',
  575. 'description': 'Retransmisión en directo de la XVIII media maratón de Zaragoza.',
  576. 'uploader_id': 'UCzTzUmjXxxacNnL8I3m4LnQ',
  577. 'title': 'Retransmisión XVIII Media maratón Zaragoza 2015',
  578. },
  579. 'params': {
  580. 'youtube_include_dash_manifest': True,
  581. 'format': '135', # bestvideo
  582. }
  583. },
  584. {
  585. # Multifeed videos (multiple cameras), URL is for Main Camera
  586. 'url': 'https://www.youtube.com/watch?v=jqWvoWXjCVs',
  587. 'info_dict': {
  588. 'id': 'jqWvoWXjCVs',
  589. 'title': 'teamPGP: Rocket League Noob Stream',
  590. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  591. },
  592. 'playlist': [{
  593. 'info_dict': {
  594. 'id': 'jqWvoWXjCVs',
  595. 'ext': 'mp4',
  596. 'title': 'teamPGP: Rocket League Noob Stream (Main Camera)',
  597. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  598. 'upload_date': '20150721',
  599. 'uploader': 'Beer Games Beer',
  600. 'uploader_id': 'beergamesbeer',
  601. },
  602. }, {
  603. 'info_dict': {
  604. 'id': '6h8e8xoXJzg',
  605. 'ext': 'mp4',
  606. 'title': 'teamPGP: Rocket League Noob Stream (kreestuh)',
  607. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  608. 'upload_date': '20150721',
  609. 'uploader': 'Beer Games Beer',
  610. 'uploader_id': 'beergamesbeer',
  611. },
  612. }, {
  613. 'info_dict': {
  614. 'id': 'PUOgX5z9xZw',
  615. 'ext': 'mp4',
  616. 'title': 'teamPGP: Rocket League Noob Stream (grizzle)',
  617. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  618. 'upload_date': '20150721',
  619. 'uploader': 'Beer Games Beer',
  620. 'uploader_id': 'beergamesbeer',
  621. },
  622. }, {
  623. 'info_dict': {
  624. 'id': 'teuwxikvS5k',
  625. 'ext': 'mp4',
  626. 'title': 'teamPGP: Rocket League Noob Stream (zim)',
  627. 'description': 'md5:dc7872fb300e143831327f1bae3af010',
  628. 'upload_date': '20150721',
  629. 'uploader': 'Beer Games Beer',
  630. 'uploader_id': 'beergamesbeer',
  631. },
  632. }],
  633. 'params': {
  634. 'skip_download': True,
  635. },
  636. },
  637. {
  638. 'url': 'http://vid.plus/FlRa-iH7PGw',
  639. 'only_matching': True,
  640. }
  641. ]
  642. def __init__(self, *args, **kwargs):
  643. super(YoutubeIE, self).__init__(*args, **kwargs)
  644. self._player_cache = {}
  645. def report_video_info_webpage_download(self, video_id):
  646. """Report attempt to download video info webpage."""
  647. self.to_screen('%s: Downloading video info webpage' % video_id)
  648. def report_information_extraction(self, video_id):
  649. """Report attempt to extract video information."""
  650. self.to_screen('%s: Extracting video information' % video_id)
  651. def report_unavailable_format(self, video_id, format):
  652. """Report extracted video URL."""
  653. self.to_screen('%s: Format %s not available' % (video_id, format))
  654. def report_rtmp_download(self):
  655. """Indicate the download will use the RTMP protocol."""
  656. self.to_screen('RTMP download detected')
  657. def _signature_cache_id(self, example_sig):
  658. """ Return a string representation of a signature """
  659. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  660. def _extract_signature_function(self, video_id, player_url, example_sig):
  661. id_m = re.match(
  662. r'.*?-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player(?:-new)?|/base)?\.(?P<ext>[a-z]+)$',
  663. player_url)
  664. if not id_m:
  665. raise ExtractorError('Cannot identify player %r' % player_url)
  666. player_type = id_m.group('ext')
  667. player_id = id_m.group('id')
  668. # Read from filesystem cache
  669. func_id = '%s_%s_%s' % (
  670. player_type, player_id, self._signature_cache_id(example_sig))
  671. assert os.path.basename(func_id) == func_id
  672. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  673. if cache_spec is not None:
  674. return lambda s: ''.join(s[i] for i in cache_spec)
  675. download_note = (
  676. 'Downloading player %s' % player_url
  677. if self._downloader.params.get('verbose') else
  678. 'Downloading %s player %s' % (player_type, player_id)
  679. )
  680. if player_type == 'js':
  681. code = self._download_webpage(
  682. player_url, video_id,
  683. note=download_note,
  684. errnote='Download of %s failed' % player_url)
  685. res = self._parse_sig_js(code)
  686. elif player_type == 'swf':
  687. urlh = self._request_webpage(
  688. player_url, video_id,
  689. note=download_note,
  690. errnote='Download of %s failed' % player_url)
  691. code = urlh.read()
  692. res = self._parse_sig_swf(code)
  693. else:
  694. assert False, 'Invalid player type %r' % player_type
  695. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  696. cache_res = res(test_string)
  697. cache_spec = [ord(c) for c in cache_res]
  698. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  699. return res
  700. def _print_sig_code(self, func, example_sig):
  701. def gen_sig_code(idxs):
  702. def _genslice(start, end, step):
  703. starts = '' if start == 0 else str(start)
  704. ends = (':%d' % (end + step)) if end + step >= 0 else ':'
  705. steps = '' if step == 1 else (':%d' % step)
  706. return 's[%s%s%s]' % (starts, ends, steps)
  707. step = None
  708. # Quelch pyflakes warnings - start will be set when step is set
  709. start = '(Never used)'
  710. for i, prev in zip(idxs[1:], idxs[:-1]):
  711. if step is not None:
  712. if i - prev == step:
  713. continue
  714. yield _genslice(start, prev, step)
  715. step = None
  716. continue
  717. if i - prev in [-1, 1]:
  718. step = i - prev
  719. start = prev
  720. continue
  721. else:
  722. yield 's[%d]' % prev
  723. if step is None:
  724. yield 's[%d]' % i
  725. else:
  726. yield _genslice(start, i, step)
  727. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  728. cache_res = func(test_string)
  729. cache_spec = [ord(c) for c in cache_res]
  730. expr_code = ' + '.join(gen_sig_code(cache_spec))
  731. signature_id_tuple = '(%s)' % (
  732. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  733. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  734. ' return %s\n') % (signature_id_tuple, expr_code)
  735. self.to_screen('Extracted signature function:\n' + code)
  736. def _parse_sig_js(self, jscode):
  737. funcname = self._search_regex(
  738. r'\.sig\|\|([a-zA-Z0-9$]+)\(', jscode,
  739. 'Initial JS player signature function name')
  740. jsi = JSInterpreter(jscode)
  741. initial_function = jsi.extract_function(funcname)
  742. return lambda s: initial_function([s])
  743. def _parse_sig_swf(self, file_contents):
  744. swfi = SWFInterpreter(file_contents)
  745. TARGET_CLASSNAME = 'SignatureDecipher'
  746. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  747. initial_function = swfi.extract_function(searched_class, 'decipher')
  748. return lambda s: initial_function([s])
  749. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  750. """Turn the encrypted s field into a working signature"""
  751. if player_url is None:
  752. raise ExtractorError('Cannot decrypt signature without player_url')
  753. if player_url.startswith('//'):
  754. player_url = 'https:' + player_url
  755. try:
  756. player_id = (player_url, self._signature_cache_id(s))
  757. if player_id not in self._player_cache:
  758. func = self._extract_signature_function(
  759. video_id, player_url, s
  760. )
  761. self._player_cache[player_id] = func
  762. func = self._player_cache[player_id]
  763. if self._downloader.params.get('youtube_print_sig_code'):
  764. self._print_sig_code(func, s)
  765. return func(s)
  766. except Exception as e:
  767. tb = traceback.format_exc()
  768. raise ExtractorError(
  769. 'Signature extraction failed: ' + tb, cause=e)
  770. def _get_subtitles(self, video_id, webpage):
  771. try:
  772. subs_doc = self._download_xml(
  773. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  774. video_id, note=False)
  775. except ExtractorError as err:
  776. self._downloader.report_warning('unable to download video subtitles: %s' % compat_str(err))
  777. return {}
  778. sub_lang_list = {}
  779. for track in subs_doc.findall('track'):
  780. lang = track.attrib['lang_code']
  781. if lang in sub_lang_list:
  782. continue
  783. sub_formats = []
  784. for ext in ['sbv', 'vtt', 'srt']:
  785. params = compat_urllib_parse.urlencode({
  786. 'lang': lang,
  787. 'v': video_id,
  788. 'fmt': ext,
  789. 'name': track.attrib['name'].encode('utf-8'),
  790. })
  791. sub_formats.append({
  792. 'url': 'https://www.youtube.com/api/timedtext?' + params,
  793. 'ext': ext,
  794. })
  795. sub_lang_list[lang] = sub_formats
  796. if not sub_lang_list:
  797. self._downloader.report_warning('video doesn\'t have subtitles')
  798. return {}
  799. return sub_lang_list
  800. def _get_automatic_captions(self, video_id, webpage):
  801. """We need the webpage for getting the captions url, pass it as an
  802. argument to speed up the process."""
  803. self.to_screen('%s: Looking for automatic captions' % video_id)
  804. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  805. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  806. if mobj is None:
  807. self._downloader.report_warning(err_msg)
  808. return {}
  809. player_config = json.loads(mobj.group(1))
  810. try:
  811. args = player_config['args']
  812. caption_url = args['ttsurl']
  813. timestamp = args['timestamp']
  814. # We get the available subtitles
  815. list_params = compat_urllib_parse.urlencode({
  816. 'type': 'list',
  817. 'tlangs': 1,
  818. 'asrs': 1,
  819. })
  820. list_url = caption_url + '&' + list_params
  821. caption_list = self._download_xml(list_url, video_id)
  822. original_lang_node = caption_list.find('track')
  823. if original_lang_node is None:
  824. self._downloader.report_warning('Video doesn\'t have automatic captions')
  825. return {}
  826. original_lang = original_lang_node.attrib['lang_code']
  827. caption_kind = original_lang_node.attrib.get('kind', '')
  828. sub_lang_list = {}
  829. for lang_node in caption_list.findall('target'):
  830. sub_lang = lang_node.attrib['lang_code']
  831. sub_formats = []
  832. for ext in ['sbv', 'vtt', 'srt']:
  833. params = compat_urllib_parse.urlencode({
  834. 'lang': original_lang,
  835. 'tlang': sub_lang,
  836. 'fmt': ext,
  837. 'ts': timestamp,
  838. 'kind': caption_kind,
  839. })
  840. sub_formats.append({
  841. 'url': caption_url + '&' + params,
  842. 'ext': ext,
  843. })
  844. sub_lang_list[sub_lang] = sub_formats
  845. return sub_lang_list
  846. # An extractor error can be raise by the download process if there are
  847. # no automatic captions but there are subtitles
  848. except (KeyError, ExtractorError):
  849. self._downloader.report_warning(err_msg)
  850. return {}
  851. @classmethod
  852. def extract_id(cls, url):
  853. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  854. if mobj is None:
  855. raise ExtractorError('Invalid URL: %s' % url)
  856. video_id = mobj.group(2)
  857. return video_id
  858. def _extract_from_m3u8(self, manifest_url, video_id):
  859. url_map = {}
  860. def _get_urls(_manifest):
  861. lines = _manifest.split('\n')
  862. urls = filter(lambda l: l and not l.startswith('#'),
  863. lines)
  864. return urls
  865. manifest = self._download_webpage(manifest_url, video_id, 'Downloading formats manifest')
  866. formats_urls = _get_urls(manifest)
  867. for format_url in formats_urls:
  868. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  869. url_map[itag] = format_url
  870. return url_map
  871. def _extract_annotations(self, video_id):
  872. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  873. return self._download_webpage(url, video_id, note='Searching for annotations.', errnote='Unable to download video annotations.')
  874. def _parse_dash_manifest(
  875. self, video_id, dash_manifest_url, player_url, age_gate, fatal=True):
  876. def decrypt_sig(mobj):
  877. s = mobj.group(1)
  878. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  879. return '/signature/%s' % dec_s
  880. dash_manifest_url = re.sub(r'/s/([a-fA-F0-9\.]+)', decrypt_sig, dash_manifest_url)
  881. dash_doc = self._download_xml(
  882. dash_manifest_url, video_id,
  883. note='Downloading DASH manifest',
  884. errnote='Could not download DASH manifest',
  885. fatal=fatal)
  886. if dash_doc is False:
  887. return []
  888. formats = []
  889. for a in dash_doc.findall('.//{urn:mpeg:DASH:schema:MPD:2011}AdaptationSet'):
  890. mime_type = a.attrib.get('mimeType')
  891. for r in a.findall('{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  892. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  893. if url_el is None:
  894. continue
  895. if mime_type == 'text/vtt':
  896. # TODO implement WebVTT downloading
  897. pass
  898. elif mime_type.startswith('audio/') or mime_type.startswith('video/'):
  899. segment_list = r.find('{urn:mpeg:DASH:schema:MPD:2011}SegmentList')
  900. format_id = r.attrib['id']
  901. video_url = url_el.text
  902. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  903. f = {
  904. 'format_id': format_id,
  905. 'url': video_url,
  906. 'width': int_or_none(r.attrib.get('width')),
  907. 'height': int_or_none(r.attrib.get('height')),
  908. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  909. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  910. 'filesize': filesize,
  911. 'fps': int_or_none(r.attrib.get('frameRate')),
  912. }
  913. if segment_list is not None:
  914. f.update({
  915. 'initialization_url': segment_list.find('{urn:mpeg:DASH:schema:MPD:2011}Initialization').attrib['sourceURL'],
  916. 'segment_urls': [segment.attrib.get('media') for segment in segment_list.findall('{urn:mpeg:DASH:schema:MPD:2011}SegmentURL')],
  917. 'protocol': 'http_dash_segments',
  918. })
  919. try:
  920. existing_format = next(
  921. fo for fo in formats
  922. if fo['format_id'] == format_id)
  923. except StopIteration:
  924. full_info = self._formats.get(format_id, {}).copy()
  925. full_info.update(f)
  926. codecs = r.attrib.get('codecs')
  927. if codecs:
  928. if full_info.get('acodec') == 'none' and 'vcodec' not in full_info:
  929. full_info['vcodec'] = codecs
  930. elif full_info.get('vcodec') == 'none' and 'acodec' not in full_info:
  931. full_info['acodec'] = codecs
  932. formats.append(full_info)
  933. else:
  934. existing_format.update(f)
  935. else:
  936. self.report_warning('Unknown MIME type %s in DASH manifest' % mime_type)
  937. return formats
  938. def _real_extract(self, url):
  939. url, smuggled_data = unsmuggle_url(url, {})
  940. proto = (
  941. 'http' if self._downloader.params.get('prefer_insecure', False)
  942. else 'https')
  943. start_time = None
  944. end_time = None
  945. parsed_url = compat_urllib_parse_urlparse(url)
  946. for component in [parsed_url.fragment, parsed_url.query]:
  947. query = compat_parse_qs(component)
  948. if start_time is None and 't' in query:
  949. start_time = parse_duration(query['t'][0])
  950. if start_time is None and 'start' in query:
  951. start_time = parse_duration(query['start'][0])
  952. if end_time is None and 'end' in query:
  953. end_time = parse_duration(query['end'][0])
  954. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  955. mobj = re.search(self._NEXT_URL_RE, url)
  956. if mobj:
  957. url = proto + '://www.youtube.com/' + compat_urllib_parse_unquote(mobj.group(1)).lstrip('/')
  958. video_id = self.extract_id(url)
  959. # Get video webpage
  960. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1&bpctr=9999999999' % video_id
  961. video_webpage = self._download_webpage(url, video_id)
  962. # Attempt to extract SWF player URL
  963. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  964. if mobj is not None:
  965. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  966. else:
  967. player_url = None
  968. dash_mpds = []
  969. def add_dash_mpd(video_info):
  970. dash_mpd = video_info.get('dashmpd')
  971. if dash_mpd and dash_mpd[0] not in dash_mpds:
  972. dash_mpds.append(dash_mpd[0])
  973. # Get video info
  974. embed_webpage = None
  975. is_live = None
  976. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  977. age_gate = True
  978. # We simulate the access to the video from www.youtube.com/v/{video_id}
  979. # this can be viewed without login into Youtube
  980. url = proto + '://www.youtube.com/embed/%s' % video_id
  981. embed_webpage = self._download_webpage(url, video_id, 'Downloading embed webpage')
  982. data = compat_urllib_parse.urlencode({
  983. 'video_id': video_id,
  984. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  985. 'sts': self._search_regex(
  986. r'"sts"\s*:\s*(\d+)', embed_webpage, 'sts', default=''),
  987. })
  988. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  989. video_info_webpage = self._download_webpage(
  990. video_info_url, video_id,
  991. note='Refetching age-gated info webpage',
  992. errnote='unable to download video info webpage')
  993. video_info = compat_parse_qs(video_info_webpage)
  994. add_dash_mpd(video_info)
  995. else:
  996. age_gate = False
  997. video_info = None
  998. # Try looking directly into the video webpage
  999. mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
  1000. if mobj:
  1001. json_code = uppercase_escape(mobj.group(1))
  1002. ytplayer_config = json.loads(json_code)
  1003. args = ytplayer_config['args']
  1004. if args.get('url_encoded_fmt_stream_map'):
  1005. # Convert to the same format returned by compat_parse_qs
  1006. video_info = dict((k, [v]) for k, v in args.items())
  1007. add_dash_mpd(video_info)
  1008. if args.get('livestream') == '1' or args.get('live_playback') == 1:
  1009. is_live = True
  1010. if not video_info or self._downloader.params.get('youtube_include_dash_manifest', True):
  1011. # We also try looking in get_video_info since it may contain different dashmpd
  1012. # URL that points to a DASH manifest with possibly different itag set (some itags
  1013. # are missing from DASH manifest pointed by webpage's dashmpd, some - from DASH
  1014. # manifest pointed by get_video_info's dashmpd).
  1015. # The general idea is to take a union of itags of both DASH manifests (for example
  1016. # video with such 'manifest behavior' see https://github.com/rg3/youtube-dl/issues/6093)
  1017. self.report_video_info_webpage_download(video_id)
  1018. for el_type in ['&el=info', '&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1019. video_info_url = (
  1020. '%s://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1021. % (proto, video_id, el_type))
  1022. video_info_webpage = self._download_webpage(
  1023. video_info_url,
  1024. video_id, note=False,
  1025. errnote='unable to download video info webpage')
  1026. get_video_info = compat_parse_qs(video_info_webpage)
  1027. if get_video_info.get('use_cipher_signature') != ['True']:
  1028. add_dash_mpd(get_video_info)
  1029. if not video_info:
  1030. video_info = get_video_info
  1031. if 'token' in get_video_info:
  1032. # Different get_video_info requests may report different results, e.g.
  1033. # some may report video unavailability, but some may serve it without
  1034. # any complaint (see https://github.com/rg3/youtube-dl/issues/7362,
  1035. # the original webpage as well as el=info and el=embedded get_video_info
  1036. # requests report video unavailability due to geo restriction while
  1037. # el=detailpage succeeds and returns valid data). This is probably
  1038. # due to YouTube measures against IP ranges of hosting providers.
  1039. # Working around by preferring the first succeeded video_info containing
  1040. # the token if no such video_info yet was found.
  1041. if 'token' not in video_info:
  1042. video_info = get_video_info
  1043. break
  1044. if 'token' not in video_info:
  1045. if 'reason' in video_info:
  1046. if 'The uploader has not made this video available in your country.' in video_info['reason']:
  1047. regions_allowed = self._html_search_meta('regionsAllowed', video_webpage, default=None)
  1048. if regions_allowed:
  1049. raise ExtractorError('YouTube said: This video is available in %s only' % (
  1050. ', '.join(map(ISO3166Utils.short2full, regions_allowed.split(',')))),
  1051. expected=True)
  1052. raise ExtractorError(
  1053. 'YouTube said: %s' % video_info['reason'][0],
  1054. expected=True, video_id=video_id)
  1055. else:
  1056. raise ExtractorError(
  1057. '"token" parameter not in video info for unknown reason',
  1058. video_id=video_id)
  1059. # title
  1060. if 'title' in video_info:
  1061. video_title = video_info['title'][0]
  1062. else:
  1063. self._downloader.report_warning('Unable to extract video title')
  1064. video_title = '_'
  1065. # description
  1066. video_description = get_element_by_id("eow-description", video_webpage)
  1067. if video_description:
  1068. video_description = re.sub(r'''(?x)
  1069. <a\s+
  1070. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1071. title="([^"]+)"\s+
  1072. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1073. class="yt-uix-redirect-link"\s*>
  1074. [^<]+
  1075. </a>
  1076. ''', r'\1', video_description)
  1077. video_description = clean_html(video_description)
  1078. else:
  1079. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1080. if fd_mobj:
  1081. video_description = unescapeHTML(fd_mobj.group(1))
  1082. else:
  1083. video_description = ''
  1084. if 'multifeed_metadata_list' in video_info and not smuggled_data.get('force_singlefeed', False):
  1085. if not self._downloader.params.get('noplaylist'):
  1086. entries = []
  1087. feed_ids = []
  1088. multifeed_metadata_list = compat_urllib_parse_unquote_plus(video_info['multifeed_metadata_list'][0])
  1089. for feed in multifeed_metadata_list.split(','):
  1090. feed_data = compat_parse_qs(feed)
  1091. entries.append({
  1092. '_type': 'url_transparent',
  1093. 'ie_key': 'Youtube',
  1094. 'url': smuggle_url(
  1095. '%s://www.youtube.com/watch?v=%s' % (proto, feed_data['id'][0]),
  1096. {'force_singlefeed': True}),
  1097. 'title': '%s (%s)' % (video_title, feed_data['title'][0]),
  1098. })
  1099. feed_ids.append(feed_data['id'][0])
  1100. self.to_screen(
  1101. 'Downloading multifeed video (%s) - add --no-playlist to just download video %s'
  1102. % (', '.join(feed_ids), video_id))
  1103. return self.playlist_result(entries, video_id, video_title, video_description)
  1104. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1105. if 'view_count' in video_info:
  1106. view_count = int(video_info['view_count'][0])
  1107. else:
  1108. view_count = None
  1109. # Check for "rental" videos
  1110. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1111. raise ExtractorError('"rental" videos not supported')
  1112. # Start extracting information
  1113. self.report_information_extraction(video_id)
  1114. # uploader
  1115. if 'author' not in video_info:
  1116. raise ExtractorError('Unable to extract uploader name')
  1117. video_uploader = compat_urllib_parse_unquote_plus(video_info['author'][0])
  1118. # uploader_id
  1119. video_uploader_id = None
  1120. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1121. if mobj is not None:
  1122. video_uploader_id = mobj.group(1)
  1123. else:
  1124. self._downloader.report_warning('unable to extract uploader nickname')
  1125. # thumbnail image
  1126. # We try first to get a high quality image:
  1127. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1128. video_webpage, re.DOTALL)
  1129. if m_thumb is not None:
  1130. video_thumbnail = m_thumb.group(1)
  1131. elif 'thumbnail_url' not in video_info:
  1132. self._downloader.report_warning('unable to extract video thumbnail')
  1133. video_thumbnail = None
  1134. else: # don't panic if we can't find it
  1135. video_thumbnail = compat_urllib_parse_unquote_plus(video_info['thumbnail_url'][0])
  1136. # upload date
  1137. upload_date = self._html_search_meta(
  1138. 'datePublished', video_webpage, 'upload date', default=None)
  1139. if not upload_date:
  1140. upload_date = self._search_regex(
  1141. [r'(?s)id="eow-date.*?>(.*?)</span>',
  1142. r'id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live|Started) on (.+?)</strong>'],
  1143. video_webpage, 'upload date', default=None)
  1144. if upload_date:
  1145. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1146. upload_date = unified_strdate(upload_date)
  1147. m_cat_container = self._search_regex(
  1148. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  1149. video_webpage, 'categories', default=None)
  1150. if m_cat_container:
  1151. category = self._html_search_regex(
  1152. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  1153. default=None)
  1154. video_categories = None if category is None else [category]
  1155. else:
  1156. video_categories = None
  1157. video_tags = [
  1158. unescapeHTML(m.group('content'))
  1159. for m in re.finditer(self._meta_regex('og:video:tag'), video_webpage)]
  1160. def _extract_count(count_name):
  1161. return str_to_int(self._search_regex(
  1162. r'-%s-button[^>]+><span[^>]+class="yt-uix-button-content"[^>]*>([\d,]+)</span>'
  1163. % re.escape(count_name),
  1164. video_webpage, count_name, default=None))
  1165. like_count = _extract_count('like')
  1166. dislike_count = _extract_count('dislike')
  1167. # subtitles
  1168. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1169. automatic_captions = self.extract_automatic_captions(video_id, video_webpage)
  1170. if 'length_seconds' not in video_info:
  1171. self._downloader.report_warning('unable to extract video duration')
  1172. video_duration = None
  1173. else:
  1174. video_duration = int(compat_urllib_parse_unquote_plus(video_info['length_seconds'][0]))
  1175. # annotations
  1176. video_annotations = None
  1177. if self._downloader.params.get('writeannotations', False):
  1178. video_annotations = self._extract_annotations(video_id)
  1179. def _map_to_format_list(urlmap):
  1180. formats = []
  1181. for itag, video_real_url in urlmap.items():
  1182. dct = {
  1183. 'format_id': itag,
  1184. 'url': video_real_url,
  1185. 'player_url': player_url,
  1186. }
  1187. if itag in self._formats:
  1188. dct.update(self._formats[itag])
  1189. formats.append(dct)
  1190. return formats
  1191. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1192. self.report_rtmp_download()
  1193. formats = [{
  1194. 'format_id': '_rtmp',
  1195. 'protocol': 'rtmp',
  1196. 'url': video_info['conn'][0],
  1197. 'player_url': player_url,
  1198. }]
  1199. elif len(video_info.get('url_encoded_fmt_stream_map', [''])[0]) >= 1 or len(video_info.get('adaptive_fmts', [''])[0]) >= 1:
  1200. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts', [''])[0]
  1201. if 'rtmpe%3Dyes' in encoded_url_map:
  1202. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1203. formats = []
  1204. for url_data_str in encoded_url_map.split(','):
  1205. url_data = compat_parse_qs(url_data_str)
  1206. if 'itag' not in url_data or 'url' not in url_data:
  1207. continue
  1208. format_id = url_data['itag'][0]
  1209. url = url_data['url'][0]
  1210. if 'sig' in url_data:
  1211. url += '&signature=' + url_data['sig'][0]
  1212. elif 's' in url_data:
  1213. encrypted_sig = url_data['s'][0]
  1214. ASSETS_RE = r'"assets":.+?"js":\s*("[^"]+")'
  1215. jsplayer_url_json = self._search_regex(
  1216. ASSETS_RE,
  1217. embed_webpage if age_gate else video_webpage,
  1218. 'JS player URL (1)', default=None)
  1219. if not jsplayer_url_json and not age_gate:
  1220. # We need the embed website after all
  1221. if embed_webpage is None:
  1222. embed_url = proto + '://www.youtube.com/embed/%s' % video_id
  1223. embed_webpage = self._download_webpage(
  1224. embed_url, video_id, 'Downloading embed webpage')
  1225. jsplayer_url_json = self._search_regex(
  1226. ASSETS_RE, embed_webpage, 'JS player URL')
  1227. player_url = json.loads(jsplayer_url_json)
  1228. if player_url is None:
  1229. player_url_json = self._search_regex(
  1230. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  1231. video_webpage, 'age gate player URL')
  1232. player_url = json.loads(player_url_json)
  1233. if self._downloader.params.get('verbose'):
  1234. if player_url is None:
  1235. player_version = 'unknown'
  1236. player_desc = 'unknown'
  1237. else:
  1238. if player_url.endswith('swf'):
  1239. player_version = self._search_regex(
  1240. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  1241. 'flash player', fatal=False)
  1242. player_desc = 'flash player %s' % player_version
  1243. else:
  1244. player_version = self._search_regex(
  1245. [r'html5player-([^/]+?)(?:/html5player(?:-new)?)?\.js', r'(?:www|player)-([^/]+)/base\.js'],
  1246. player_url,
  1247. 'html5 player', fatal=False)
  1248. player_desc = 'html5 player %s' % player_version
  1249. parts_sizes = self._signature_cache_id(encrypted_sig)
  1250. self.to_screen('{%s} signature length %s, %s' %
  1251. (format_id, parts_sizes, player_desc))
  1252. signature = self._decrypt_signature(
  1253. encrypted_sig, video_id, player_url, age_gate)
  1254. url += '&signature=' + signature
  1255. if 'ratebypass' not in url:
  1256. url += '&ratebypass=yes'
  1257. # Some itags are not included in DASH manifest thus corresponding formats will
  1258. # lack metadata (see https://github.com/rg3/youtube-dl/pull/5993).
  1259. # Trying to extract metadata from url_encoded_fmt_stream_map entry.
  1260. mobj = re.search(r'^(?P<width>\d+)[xX](?P<height>\d+)$', url_data.get('size', [''])[0])
  1261. width, height = (int(mobj.group('width')), int(mobj.group('height'))) if mobj else (None, None)
  1262. dct = {
  1263. 'format_id': format_id,
  1264. 'url': url,
  1265. 'player_url': player_url,
  1266. 'filesize': int_or_none(url_data.get('clen', [None])[0]),
  1267. 'tbr': float_or_none(url_data.get('bitrate', [None])[0], 1000),
  1268. 'width': width,
  1269. 'height': height,
  1270. 'fps': int_or_none(url_data.get('fps', [None])[0]),
  1271. 'format_note': url_data.get('quality_label', [None])[0] or url_data.get('quality', [None])[0],
  1272. }
  1273. type_ = url_data.get('type', [None])[0]
  1274. if type_:
  1275. type_split = type_.split(';')
  1276. kind_ext = type_split[0].split('/')
  1277. if len(kind_ext) == 2:
  1278. kind, ext = kind_ext
  1279. dct['ext'] = ext
  1280. if kind in ('audio', 'video'):
  1281. codecs = None
  1282. for mobj in re.finditer(
  1283. r'(?P<key>[a-zA-Z_-]+)=(?P<quote>["\']?)(?P<val>.+?)(?P=quote)(?:;|$)', type_):
  1284. if mobj.group('key') == 'codecs':
  1285. codecs = mobj.group('val')
  1286. break
  1287. if codecs:
  1288. codecs = codecs.split(',')
  1289. if len(codecs) == 2:
  1290. acodec, vcodec = codecs[0], codecs[1]
  1291. else:
  1292. acodec, vcodec = (codecs[0], 'none') if kind == 'audio' else ('none', codecs[0])
  1293. dct.update({
  1294. 'acodec': acodec,
  1295. 'vcodec': vcodec,
  1296. })
  1297. if format_id in self._formats:
  1298. dct.update(self._formats[format_id])
  1299. formats.append(dct)
  1300. elif video_info.get('hlsvp'):
  1301. manifest_url = video_info['hlsvp'][0]
  1302. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1303. formats = _map_to_format_list(url_map)
  1304. else:
  1305. raise ExtractorError('no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1306. # Look for the DASH manifest
  1307. if self._downloader.params.get('youtube_include_dash_manifest', True):
  1308. dash_mpd_fatal = True
  1309. for dash_manifest_url in dash_mpds:
  1310. dash_formats = {}
  1311. try:
  1312. for df in self._parse_dash_manifest(
  1313. video_id, dash_manifest_url, player_url, age_gate, dash_mpd_fatal):
  1314. # Do not overwrite DASH format found in some previous DASH manifest
  1315. if df['format_id'] not in dash_formats:
  1316. dash_formats[df['format_id']] = df
  1317. # Additional DASH manifests may end up in HTTP Error 403 therefore
  1318. # allow them to fail without bug report message if we already have
  1319. # some DASH manifest succeeded. This is temporary workaround to reduce
  1320. # burst of bug reports until we figure out the reason and whether it
  1321. # can be fixed at all.
  1322. dash_mpd_fatal = False
  1323. except (ExtractorError, KeyError) as e:
  1324. self.report_warning(
  1325. 'Skipping DASH manifest: %r' % e, video_id)
  1326. if dash_formats:
  1327. # Remove the formats we found through non-DASH, they
  1328. # contain less info and it can be wrong, because we use
  1329. # fixed values (for example the resolution). See
  1330. # https://github.com/rg3/youtube-dl/issues/5774 for an
  1331. # example.
  1332. formats = [f for f in formats if f['format_id'] not in dash_formats.keys()]
  1333. formats.extend(dash_formats.values())
  1334. # Check for malformed aspect ratio
  1335. stretched_m = re.search(
  1336. r'<meta\s+property="og:video:tag".*?content="yt:stretch=(?P<w>[0-9]+):(?P<h>[0-9]+)">',
  1337. video_webpage)
  1338. if stretched_m:
  1339. ratio = float(stretched_m.group('w')) / float(stretched_m.group('h'))
  1340. for f in formats:
  1341. if f.get('vcodec') != 'none':
  1342. f['stretched_ratio'] = ratio
  1343. self._sort_formats(formats)
  1344. return {
  1345. 'id': video_id,
  1346. 'uploader': video_uploader,
  1347. 'uploader_id': video_uploader_id,
  1348. 'upload_date': upload_date,
  1349. 'title': video_title,
  1350. 'thumbnail': video_thumbnail,
  1351. 'description': video_description,
  1352. 'categories': video_categories,
  1353. 'tags': video_tags,
  1354. 'subtitles': video_subtitles,
  1355. 'automatic_captions': automatic_captions,
  1356. 'duration': video_duration,
  1357. 'age_limit': 18 if age_gate else 0,
  1358. 'annotations': video_annotations,
  1359. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  1360. 'view_count': view_count,
  1361. 'like_count': like_count,
  1362. 'dislike_count': dislike_count,
  1363. 'average_rating': float_or_none(video_info.get('avg_rating', [None])[0]),
  1364. 'formats': formats,
  1365. 'is_live': is_live,
  1366. 'start_time': start_time,
  1367. 'end_time': end_time,
  1368. }
  1369. class YoutubePlaylistIE(YoutubeBaseInfoExtractor, YoutubePlaylistBaseInfoExtractor):
  1370. IE_DESC = 'YouTube.com playlists'
  1371. _VALID_URL = r"""(?x)(?:
  1372. (?:https?://)?
  1373. (?:\w+\.)?
  1374. youtube\.com/
  1375. (?:
  1376. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/videoseries)
  1377. \? (?:.*?&)*? (?:p|a|list)=
  1378. | p/
  1379. )
  1380. (
  1381. (?:PL|LL|EC|UU|FL|RD|UL)?[0-9A-Za-z-_]{10,}
  1382. # Top tracks, they can also include dots
  1383. |(?:MC)[\w\.]*
  1384. )
  1385. .*
  1386. |
  1387. ((?:PL|LL|EC|UU|FL|RD|UL)[0-9A-Za-z-_]{10,})
  1388. )"""
  1389. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  1390. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)(?:[^>]+>(?P<title>[^<]+))?'
  1391. IE_NAME = 'youtube:playlist'
  1392. _TESTS = [{
  1393. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1394. 'info_dict': {
  1395. 'title': 'ytdl test PL',
  1396. 'id': 'PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  1397. },
  1398. 'playlist_count': 3,
  1399. }, {
  1400. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1401. 'info_dict': {
  1402. 'id': 'PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  1403. 'title': 'YDL_Empty_List',
  1404. },
  1405. 'playlist_count': 0,
  1406. }, {
  1407. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  1408. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1409. 'info_dict': {
  1410. 'title': '29C3: Not my department',
  1411. 'id': 'PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  1412. },
  1413. 'playlist_count': 95,
  1414. }, {
  1415. 'note': 'issue #673',
  1416. 'url': 'PLBB231211A4F62143',
  1417. 'info_dict': {
  1418. 'title': '[OLD]Team Fortress 2 (Class-based LP)',
  1419. 'id': 'PLBB231211A4F62143',
  1420. },
  1421. 'playlist_mincount': 26,
  1422. }, {
  1423. 'note': 'Large playlist',
  1424. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  1425. 'info_dict': {
  1426. 'title': 'Uploads from Cauchemar',
  1427. 'id': 'UUBABnxM4Ar9ten8Mdjj1j0Q',
  1428. },
  1429. 'playlist_mincount': 799,
  1430. }, {
  1431. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1432. 'info_dict': {
  1433. 'title': 'YDL_safe_search',
  1434. 'id': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  1435. },
  1436. 'playlist_count': 2,
  1437. }, {
  1438. 'note': 'embedded',
  1439. 'url': 'http://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1440. 'playlist_count': 4,
  1441. 'info_dict': {
  1442. 'title': 'JODA15',
  1443. 'id': 'PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  1444. }
  1445. }, {
  1446. 'note': 'Embedded SWF player',
  1447. 'url': 'http://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  1448. 'playlist_count': 4,
  1449. 'info_dict': {
  1450. 'title': 'JODA7',
  1451. 'id': 'YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ',
  1452. }
  1453. }, {
  1454. 'note': 'Buggy playlist: the webpage has a "Load more" button but it doesn\'t have more videos',
  1455. 'url': 'https://www.youtube.com/playlist?list=UUXw-G3eDE9trcvY2sBMM_aA',
  1456. 'info_dict': {
  1457. 'title': 'Uploads from Interstellar Movie',
  1458. 'id': 'UUXw-G3eDE9trcvY2sBMM_aA',
  1459. },
  1460. 'playlist_mincout': 21,
  1461. }]
  1462. def _real_initialize(self):
  1463. self._login()
  1464. def _extract_mix(self, playlist_id):
  1465. # The mixes are generated from a single video
  1466. # the id of the playlist is just 'RD' + video_id
  1467. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1468. webpage = self._download_webpage(
  1469. url, playlist_id, 'Downloading Youtube mix')
  1470. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  1471. title_span = (
  1472. search_title('playlist-title') or
  1473. search_title('title long-title') or
  1474. search_title('title'))
  1475. title = clean_html(title_span)
  1476. ids = orderedSet(re.findall(
  1477. r'''(?xs)data-video-username=".*?".*?
  1478. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  1479. webpage))
  1480. url_results = self._ids_to_results(ids)
  1481. return self.playlist_result(url_results, playlist_id, title)
  1482. def _extract_playlist(self, playlist_id):
  1483. url = self._TEMPLATE_URL % playlist_id
  1484. page = self._download_webpage(url, playlist_id)
  1485. for match in re.findall(r'<div class="yt-alert-message">([^<]+)</div>', page):
  1486. match = match.strip()
  1487. # Check if the playlist exists or is private
  1488. if re.match(r'[^<]*(The|This) playlist (does not exist|is private)[^<]*', match):
  1489. raise ExtractorError(
  1490. 'The playlist doesn\'t exist or is private, use --username or '
  1491. '--netrc to access it.',
  1492. expected=True)
  1493. elif re.match(r'[^<]*Invalid parameters[^<]*', match):
  1494. raise ExtractorError(
  1495. 'Invalid parameters. Maybe URL is incorrect.',
  1496. expected=True)
  1497. elif re.match(r'[^<]*Choose your language[^<]*', match):
  1498. continue
  1499. else:
  1500. self.report_warning('Youtube gives an alert message: ' + match)
  1501. playlist_title = self._html_search_regex(
  1502. r'(?s)<h1 class="pl-header-title[^"]*"[^>]*>\s*(.*?)\s*</h1>',
  1503. page, 'title')
  1504. return self.playlist_result(self._entries(page, playlist_id), playlist_id, playlist_title)
  1505. def _real_extract(self, url):
  1506. # Extract playlist id
  1507. mobj = re.match(self._VALID_URL, url)
  1508. if mobj is None:
  1509. raise ExtractorError('Invalid URL: %s' % url)
  1510. playlist_id = mobj.group(1) or mobj.group(2)
  1511. # Check if it's a video-specific URL
  1512. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1513. if 'v' in query_dict:
  1514. video_id = query_dict['v'][0]
  1515. if self._downloader.params.get('noplaylist'):
  1516. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1517. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1518. else:
  1519. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1520. if playlist_id.startswith('RD') or playlist_id.startswith('UL'):
  1521. # Mixes require a custom extraction process
  1522. return self._extract_mix(playlist_id)
  1523. return self._extract_playlist(playlist_id)
  1524. class YoutubeChannelIE(YoutubePlaylistBaseInfoExtractor):
  1525. IE_DESC = 'YouTube.com channels'
  1526. _VALID_URL = r'https?://(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/(?P<id>[0-9A-Za-z_-]+)'
  1527. _TEMPLATE_URL = 'https://www.youtube.com/channel/%s/videos'
  1528. _VIDEO_RE = r'(?:title="(?P<title>[^"]+)"[^>]+)?href="/watch\?v=(?P<id>[0-9A-Za-z_-]+)&?'
  1529. IE_NAME = 'youtube:channel'
  1530. _TESTS = [{
  1531. 'note': 'paginated channel',
  1532. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  1533. 'playlist_mincount': 91,
  1534. 'info_dict': {
  1535. 'id': 'UUKfVa3S1e4PHvxWcwyMMg8w',
  1536. 'title': 'Uploads from lex will',
  1537. }
  1538. }, {
  1539. 'note': 'Age restricted channel',
  1540. # from https://www.youtube.com/user/DeusExOfficial
  1541. 'url': 'https://www.youtube.com/channel/UCs0ifCMCm1icqRbqhUINa0w',
  1542. 'playlist_mincount': 64,
  1543. 'info_dict': {
  1544. 'id': 'UUs0ifCMCm1icqRbqhUINa0w',
  1545. 'title': 'Uploads from Deus Ex',
  1546. },
  1547. }]
  1548. def _real_extract(self, url):
  1549. channel_id = self._match_id(url)
  1550. url = self._TEMPLATE_URL % channel_id
  1551. # Channel by page listing is restricted to 35 pages of 30 items, i.e. 1050 videos total (see #5778)
  1552. # Workaround by extracting as a playlist if managed to obtain channel playlist URL
  1553. # otherwise fallback on channel by page extraction
  1554. channel_page = self._download_webpage(
  1555. url + '?view=57', channel_id,
  1556. 'Downloading channel page', fatal=False)
  1557. if channel_page is False:
  1558. channel_playlist_id = False
  1559. else:
  1560. channel_playlist_id = self._html_search_meta(
  1561. 'channelId', channel_page, 'channel id', default=None)
  1562. if not channel_playlist_id:
  1563. channel_playlist_id = self._search_regex(
  1564. r'data-(?:channel-external-|yt)id="([^"]+)"',
  1565. channel_page, 'channel id', default=None)
  1566. if channel_playlist_id and channel_playlist_id.startswith('UC'):
  1567. playlist_id = 'UU' + channel_playlist_id[2:]
  1568. return self.url_result(
  1569. compat_urlparse.urljoin(url, '/playlist?list=%s' % playlist_id), 'YoutubePlaylist')
  1570. channel_page = self._download_webpage(url, channel_id, 'Downloading page #1')
  1571. autogenerated = re.search(r'''(?x)
  1572. class="[^"]*?(?:
  1573. channel-header-autogenerated-label|
  1574. yt-channel-title-autogenerated
  1575. )[^"]*"''', channel_page) is not None
  1576. if autogenerated:
  1577. # The videos are contained in a single page
  1578. # the ajax pages can't be used, they are empty
  1579. entries = [
  1580. self.url_result(
  1581. video_id, 'Youtube', video_id=video_id,
  1582. video_title=video_title)
  1583. for video_id, video_title in self.extract_videos_from_page(channel_page)]
  1584. return self.playlist_result(entries, channel_id)
  1585. return self.playlist_result(self._entries(channel_page, channel_id), channel_id)
  1586. class YoutubeUserIE(YoutubeChannelIE):
  1587. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  1588. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)(?P<id>[A-Za-z0-9_-]+)'
  1589. _TEMPLATE_URL = 'https://www.youtube.com/user/%s/videos'
  1590. IE_NAME = 'youtube:user'
  1591. _TESTS = [{
  1592. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  1593. 'playlist_mincount': 320,
  1594. 'info_dict': {
  1595. 'title': 'TheLinuxFoundation',
  1596. }
  1597. }, {
  1598. 'url': 'ytuser:phihag',
  1599. 'only_matching': True,
  1600. }]
  1601. @classmethod
  1602. def suitable(cls, url):
  1603. # Don't return True if the url can be extracted with other youtube
  1604. # extractor, the regex would is too permissive and it would match.
  1605. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1606. if any(ie.suitable(url) for ie in other_ies):
  1607. return False
  1608. else:
  1609. return super(YoutubeUserIE, cls).suitable(url)
  1610. class YoutubeUserPlaylistsIE(YoutubePlaylistsBaseInfoExtractor):
  1611. IE_DESC = 'YouTube.com user playlists'
  1612. _VALID_URL = r'https?://(?:\w+\.)?youtube\.com/user/(?P<id>[^/]+)/playlists'
  1613. IE_NAME = 'youtube:user:playlists'
  1614. _TEST = {
  1615. 'url': 'http://www.youtube.com/user/ThirstForScience/playlists',
  1616. 'playlist_mincount': 4,
  1617. 'info_dict': {
  1618. 'id': 'ThirstForScience',
  1619. 'title': 'Thirst for Science',
  1620. },
  1621. }
  1622. class YoutubeSearchIE(SearchInfoExtractor, YoutubePlaylistIE):
  1623. IE_DESC = 'YouTube.com searches'
  1624. # there doesn't appear to be a real limit, for example if you search for
  1625. # 'python' you get more than 8.000.000 results
  1626. _MAX_RESULTS = float('inf')
  1627. IE_NAME = 'youtube:search'
  1628. _SEARCH_KEY = 'ytsearch'
  1629. _EXTRA_QUERY_ARGS = {}
  1630. _TESTS = []
  1631. def _get_n_results(self, query, n):
  1632. """Get a specified number of results for a query"""
  1633. videos = []
  1634. limit = n
  1635. for pagenum in itertools.count(1):
  1636. url_query = {
  1637. 'search_query': query.encode('utf-8'),
  1638. 'page': pagenum,
  1639. 'spf': 'navigate',
  1640. }
  1641. url_query.update(self._EXTRA_QUERY_ARGS)
  1642. result_url = 'https://www.youtube.com/results?' + compat_urllib_parse.urlencode(url_query)
  1643. data = self._download_json(
  1644. result_url, video_id='query "%s"' % query,
  1645. note='Downloading page %s' % pagenum,
  1646. errnote='Unable to download API page')
  1647. html_content = data[1]['body']['content']
  1648. if 'class="search-message' in html_content:
  1649. raise ExtractorError(
  1650. '[youtube] No video results', expected=True)
  1651. new_videos = self._ids_to_results(orderedSet(re.findall(
  1652. r'href="/watch\?v=(.{11})', html_content)))
  1653. videos += new_videos
  1654. if not new_videos or len(videos) > limit:
  1655. break
  1656. if len(videos) > n:
  1657. videos = videos[:n]
  1658. return self.playlist_result(videos, query)
  1659. class YoutubeSearchDateIE(YoutubeSearchIE):
  1660. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1661. _SEARCH_KEY = 'ytsearchdate'
  1662. IE_DESC = 'YouTube.com searches, newest videos first'
  1663. _EXTRA_QUERY_ARGS = {'search_sort': 'video_date_uploaded'}
  1664. class YoutubeSearchURLIE(InfoExtractor):
  1665. IE_DESC = 'YouTube.com search URLs'
  1666. IE_NAME = 'youtube:search_url'
  1667. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
  1668. _TESTS = [{
  1669. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  1670. 'playlist_mincount': 5,
  1671. 'info_dict': {
  1672. 'title': 'youtube-dl test video',
  1673. }
  1674. }]
  1675. def _real_extract(self, url):
  1676. mobj = re.match(self._VALID_URL, url)
  1677. query = compat_urllib_parse_unquote_plus(mobj.group('query'))
  1678. webpage = self._download_webpage(url, query)
  1679. result_code = self._search_regex(
  1680. r'(?s)<ol[^>]+class="item-section"(.*?)</ol>', webpage, 'result HTML')
  1681. part_codes = re.findall(
  1682. r'(?s)<h3[^>]+class="[^"]*yt-lockup-title[^"]*"[^>]*>(.*?)</h3>', result_code)
  1683. entries = []
  1684. for part_code in part_codes:
  1685. part_title = self._html_search_regex(
  1686. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1687. part_url_snippet = self._html_search_regex(
  1688. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1689. part_url = compat_urlparse.urljoin(
  1690. 'https://www.youtube.com/', part_url_snippet)
  1691. entries.append({
  1692. '_type': 'url',
  1693. 'url': part_url,
  1694. 'title': part_title,
  1695. })
  1696. return {
  1697. '_type': 'playlist',
  1698. 'entries': entries,
  1699. 'title': query,
  1700. }
  1701. class YoutubeShowIE(InfoExtractor):
  1702. IE_DESC = 'YouTube.com (multi-season) shows'
  1703. _VALID_URL = r'https?://www\.youtube\.com/show/(?P<id>[^?#]*)'
  1704. IE_NAME = 'youtube:show'
  1705. _TESTS = [{
  1706. 'url': 'https://www.youtube.com/show/airdisasters',
  1707. 'playlist_mincount': 5,
  1708. 'info_dict': {
  1709. 'id': 'airdisasters',
  1710. 'title': 'Air Disasters',
  1711. }
  1712. }]
  1713. def _real_extract(self, url):
  1714. mobj = re.match(self._VALID_URL, url)
  1715. playlist_id = mobj.group('id')
  1716. webpage = self._download_webpage(
  1717. 'https://www.youtube.com/show/%s/playlists' % playlist_id, playlist_id, 'Downloading show webpage')
  1718. # There's one playlist for each season of the show
  1719. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1720. self.to_screen('%s: Found %s seasons' % (playlist_id, len(m_seasons)))
  1721. entries = [
  1722. self.url_result(
  1723. 'https://www.youtube.com' + season.group(1), 'YoutubePlaylist')
  1724. for season in m_seasons
  1725. ]
  1726. title = self._og_search_title(webpage, fatal=False)
  1727. return {
  1728. '_type': 'playlist',
  1729. 'id': playlist_id,
  1730. 'title': title,
  1731. 'entries': entries,
  1732. }
  1733. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1734. """
  1735. Base class for feed extractors
  1736. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1737. """
  1738. _LOGIN_REQUIRED = True
  1739. @property
  1740. def IE_NAME(self):
  1741. return 'youtube:%s' % self._FEED_NAME
  1742. def _real_initialize(self):
  1743. self._login()
  1744. def _real_extract(self, url):
  1745. page = self._download_webpage(
  1746. 'https://www.youtube.com/feed/%s' % self._FEED_NAME, self._PLAYLIST_TITLE)
  1747. # The extraction process is the same as for playlists, but the regex
  1748. # for the video ids doesn't contain an index
  1749. ids = []
  1750. more_widget_html = content_html = page
  1751. for page_num in itertools.count(1):
  1752. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  1753. # 'recommended' feed has infinite 'load more' and each new portion spins
  1754. # the same videos in (sometimes) slightly different order, so we'll check
  1755. # for unicity and break when portion has no new videos
  1756. new_ids = filter(lambda video_id: video_id not in ids, orderedSet(matches))
  1757. if not new_ids:
  1758. break
  1759. ids.extend(new_ids)
  1760. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1761. if not mobj:
  1762. break
  1763. more = self._download_json(
  1764. 'https://youtube.com/%s' % mobj.group('more'), self._PLAYLIST_TITLE,
  1765. 'Downloading page #%s' % page_num,
  1766. transform_source=uppercase_escape)
  1767. content_html = more['content_html']
  1768. more_widget_html = more['load_more_widget_html']
  1769. return self.playlist_result(
  1770. self._ids_to_results(ids), playlist_title=self._PLAYLIST_TITLE)
  1771. class YoutubeWatchLaterIE(YoutubePlaylistIE):
  1772. IE_NAME = 'youtube:watchlater'
  1773. IE_DESC = 'Youtube watch later list, ":ytwatchlater" for short (requires authentication)'
  1774. _VALID_URL = r'https?://www\.youtube\.com/(?:feed/watch_later|playlist\?list=WL)|:ytwatchlater'
  1775. _TESTS = [] # override PlaylistIE tests
  1776. def _real_extract(self, url):
  1777. return self._extract_playlist('WL')
  1778. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1779. IE_NAME = 'youtube:favorites'
  1780. IE_DESC = 'YouTube.com favourite videos, ":ytfav" for short (requires authentication)'
  1781. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1782. _LOGIN_REQUIRED = True
  1783. def _real_extract(self, url):
  1784. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1785. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  1786. return self.url_result(playlist_id, 'YoutubePlaylist')
  1787. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1788. IE_DESC = 'YouTube.com recommended videos, ":ytrec" for short (requires authentication)'
  1789. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1790. _FEED_NAME = 'recommended'
  1791. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  1792. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1793. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1794. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1795. _FEED_NAME = 'subscriptions'
  1796. _PLAYLIST_TITLE = 'Youtube Subscriptions'
  1797. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1798. IE_DESC = 'Youtube watch history, ":ythistory" for short (requires authentication)'
  1799. _VALID_URL = 'https?://www\.youtube\.com/feed/history|:ythistory'
  1800. _FEED_NAME = 'history'
  1801. _PLAYLIST_TITLE = 'Youtube History'
  1802. class YoutubeTruncatedURLIE(InfoExtractor):
  1803. IE_NAME = 'youtube:truncated_url'
  1804. IE_DESC = False # Do not list
  1805. _VALID_URL = r'''(?x)
  1806. (?:https?://)?
  1807. (?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/
  1808. (?:watch\?(?:
  1809. feature=[a-z_]+|
  1810. annotation_id=annotation_[^&]+|
  1811. x-yt-cl=[0-9]+|
  1812. hl=[^&]*|
  1813. t=[0-9]+
  1814. )?
  1815. |
  1816. attribution_link\?a=[^&]+
  1817. )
  1818. $
  1819. '''
  1820. _TESTS = [{
  1821. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  1822. 'only_matching': True,
  1823. }, {
  1824. 'url': 'http://www.youtube.com/watch?',
  1825. 'only_matching': True,
  1826. }, {
  1827. 'url': 'https://www.youtube.com/watch?x-yt-cl=84503534',
  1828. 'only_matching': True,
  1829. }, {
  1830. 'url': 'https://www.youtube.com/watch?feature=foo',
  1831. 'only_matching': True,
  1832. }, {
  1833. 'url': 'https://www.youtube.com/watch?hl=en-GB',
  1834. 'only_matching': True,
  1835. }, {
  1836. 'url': 'https://www.youtube.com/watch?t=2372',
  1837. 'only_matching': True,
  1838. }]
  1839. def _real_extract(self, url):
  1840. raise ExtractorError(
  1841. 'Did you forget to quote the URL? Remember that & is a meta '
  1842. 'character in most shells, so you want to put the URL in quotes, '
  1843. 'like youtube-dl '
  1844. '"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1845. ' or simply youtube-dl BaW_jenozKc .',
  1846. expected=True)
  1847. class YoutubeTruncatedIDIE(InfoExtractor):
  1848. IE_NAME = 'youtube:truncated_id'
  1849. IE_DESC = False # Do not list
  1850. _VALID_URL = r'https?://(?:www\.)?youtube\.com/watch\?v=(?P<id>[0-9A-Za-z_-]{1,10})$'
  1851. _TESTS = [{
  1852. 'url': 'https://www.youtube.com/watch?v=N_708QY7Ob',
  1853. 'only_matching': True,
  1854. }]
  1855. def _real_extract(self, url):
  1856. video_id = self._match_id(url)
  1857. raise ExtractorError(
  1858. 'Incomplete YouTube ID %s. URL %s looks truncated.' % (video_id, url),
  1859. expected=True)