youtube.py 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620
  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 traceback
  8. from .common import InfoExtractor, SearchInfoExtractor
  9. from .subtitles import SubtitlesInfoExtractor
  10. from ..jsinterp import JSInterpreter
  11. from ..swfinterp import SWFInterpreter
  12. from ..utils import (
  13. compat_chr,
  14. compat_parse_qs,
  15. compat_urllib_parse,
  16. compat_urllib_request,
  17. compat_urlparse,
  18. compat_str,
  19. clean_html,
  20. get_element_by_id,
  21. get_element_by_attribute,
  22. ExtractorError,
  23. int_or_none,
  24. OnDemandPagedList,
  25. unescapeHTML,
  26. unified_strdate,
  27. orderedSet,
  28. uppercase_escape,
  29. )
  30. class YoutubeBaseInfoExtractor(InfoExtractor):
  31. """Provide base functions for Youtube extractors"""
  32. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  33. _TWOFACTOR_URL = 'https://accounts.google.com/SecondFactor'
  34. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  35. _AGE_URL = 'https://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  36. _NETRC_MACHINE = 'youtube'
  37. # If True it will raise an error if no login info is provided
  38. _LOGIN_REQUIRED = False
  39. def _set_language(self):
  40. return bool(self._download_webpage(
  41. self._LANG_URL, None,
  42. note='Setting language', errnote='unable to set language',
  43. fatal=False))
  44. def _login(self):
  45. """
  46. Attempt to log in to YouTube.
  47. True is returned if successful or skipped.
  48. False is returned if login failed.
  49. If _LOGIN_REQUIRED is set and no authentication was provided, an error is raised.
  50. """
  51. (username, password) = self._get_login_info()
  52. # No authentication to be performed
  53. if username is None:
  54. if self._LOGIN_REQUIRED:
  55. raise ExtractorError('No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  56. return True
  57. login_page = self._download_webpage(
  58. self._LOGIN_URL, None,
  59. note='Downloading login page',
  60. errnote='unable to fetch login page', fatal=False)
  61. if login_page is False:
  62. return
  63. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  64. login_page, 'Login GALX parameter')
  65. # Log in
  66. login_form_strs = {
  67. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  68. 'Email': username,
  69. 'GALX': galx,
  70. 'Passwd': password,
  71. 'PersistentCookie': 'yes',
  72. '_utf8': '霱',
  73. 'bgresponse': 'js_disabled',
  74. 'checkConnection': '',
  75. 'checkedDomains': 'youtube',
  76. 'dnConn': '',
  77. 'pstMsg': '0',
  78. 'rmShown': '1',
  79. 'secTok': '',
  80. 'signIn': 'Sign in',
  81. 'timeStmp': '',
  82. 'service': 'youtube',
  83. 'uilel': '3',
  84. 'hl': 'en_US',
  85. }
  86. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  87. # chokes on unicode
  88. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  89. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  90. req = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  91. login_results = self._download_webpage(
  92. req, None,
  93. note='Logging in', errnote='unable to log in', fatal=False)
  94. if login_results is False:
  95. return False
  96. if re.search(r'id="errormsg_0_Passwd"', login_results) is not None:
  97. raise ExtractorError('Please use your account password and a two-factor code instead of an application-specific password.', expected=True)
  98. # Two-Factor
  99. # TODO add SMS and phone call support - these require making a request and then prompting the user
  100. if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', login_results) is not None:
  101. tfa_code = self._get_tfa_info()
  102. if tfa_code is None:
  103. self._downloader.report_warning('Two-factor authentication required. Provide it with --twofactor <code>')
  104. self._downloader.report_warning('(Note that only TOTP (Google Authenticator App) codes work at this time.)')
  105. return False
  106. # Unlike the first login form, secTok and timeStmp are both required for the TFA form
  107. match = re.search(r'id="secTok"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
  108. if match is None:
  109. self._downloader.report_warning('Failed to get secTok - did the page structure change?')
  110. secTok = match.group(1)
  111. match = re.search(r'id="timeStmp"\n\s+value=\'(.+)\'/>', login_results, re.M | re.U)
  112. if match is None:
  113. self._downloader.report_warning('Failed to get timeStmp - did the page structure change?')
  114. timeStmp = match.group(1)
  115. tfa_form_strs = {
  116. 'continue': 'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  117. 'smsToken': '',
  118. 'smsUserPin': tfa_code,
  119. 'smsVerifyPin': 'Verify',
  120. 'PersistentCookie': 'yes',
  121. 'checkConnection': '',
  122. 'checkedDomains': 'youtube',
  123. 'pstMsg': '1',
  124. 'secTok': secTok,
  125. 'timeStmp': timeStmp,
  126. 'service': 'youtube',
  127. 'hl': 'en_US',
  128. }
  129. tfa_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in tfa_form_strs.items())
  130. tfa_data = compat_urllib_parse.urlencode(tfa_form).encode('ascii')
  131. tfa_req = compat_urllib_request.Request(self._TWOFACTOR_URL, tfa_data)
  132. tfa_results = self._download_webpage(
  133. tfa_req, None,
  134. note='Submitting TFA code', errnote='unable to submit tfa', fatal=False)
  135. if tfa_results is False:
  136. return False
  137. if re.search(r'(?i)<form[^>]* id="gaia_secondfactorform"', tfa_results) is not None:
  138. self._downloader.report_warning('Two-factor code expired. Please try again, or use a one-use backup code instead.')
  139. return False
  140. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', tfa_results) is not None:
  141. self._downloader.report_warning('unable to log in - did the page structure change?')
  142. return False
  143. if re.search(r'smsauth-interstitial-reviewsettings', tfa_results) is not None:
  144. self._downloader.report_warning('Your Google account has a security notice. Please log in on your web browser, resolve the notice, and try again.')
  145. return False
  146. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  147. self._downloader.report_warning('unable to log in: bad username or password')
  148. return False
  149. return True
  150. def _confirm_age(self):
  151. age_form = {
  152. 'next_url': '/',
  153. 'action_confirm': 'Confirm',
  154. }
  155. req = compat_urllib_request.Request(self._AGE_URL,
  156. compat_urllib_parse.urlencode(age_form).encode('ascii'))
  157. self._download_webpage(
  158. req, None,
  159. note='Confirming age', errnote='Unable to confirm age')
  160. return True
  161. def _real_initialize(self):
  162. if self._downloader is None:
  163. return
  164. if not self._set_language():
  165. return
  166. if not self._login():
  167. return
  168. self._confirm_age()
  169. class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
  170. IE_DESC = 'YouTube.com'
  171. _VALID_URL = r"""(?x)^
  172. (
  173. (?:https?://|//) # http(s):// or protocol-independent URL
  174. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  175. (?:www\.)?deturl\.com/www\.youtube\.com/|
  176. (?:www\.)?pwnyoutube\.com/|
  177. (?:www\.)?yourepeat\.com/|
  178. tube\.majestyc\.net/|
  179. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  180. (?:.*?\#/)? # handle anchor (#/) redirect urls
  181. (?: # the various things that can precede the ID:
  182. (?:(?:v|embed|e)/(?!videoseries)) # v/ or embed/ or e/
  183. |(?: # or the v= param in all its forms
  184. (?:(?:watch|movie)(?:_popup)?(?:\.php)?/?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  185. (?:\?|\#!?) # the params delimiter ? or # or #!
  186. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  187. v=
  188. )
  189. ))
  190. |youtu\.be/ # just youtu.be/xxxx
  191. |(?:www\.)?cleanvideosearch\.com/media/action/yt/watch\?videoId=
  192. )
  193. )? # all until now is optional -> you can pass the naked ID
  194. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  195. (?!.*?&list=) # combined list/video URLs are handled by the playlist IE
  196. (?(1).+)? # if we found the ID, everything can follow
  197. $"""
  198. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  199. _formats = {
  200. '5': {'ext': 'flv', 'width': 400, 'height': 240},
  201. '6': {'ext': 'flv', 'width': 450, 'height': 270},
  202. '13': {'ext': '3gp'},
  203. '17': {'ext': '3gp', 'width': 176, 'height': 144},
  204. '18': {'ext': 'mp4', 'width': 640, 'height': 360},
  205. '22': {'ext': 'mp4', 'width': 1280, 'height': 720},
  206. '34': {'ext': 'flv', 'width': 640, 'height': 360},
  207. '35': {'ext': 'flv', 'width': 854, 'height': 480},
  208. '36': {'ext': '3gp', 'width': 320, 'height': 240},
  209. '37': {'ext': 'mp4', 'width': 1920, 'height': 1080},
  210. '38': {'ext': 'mp4', 'width': 4096, 'height': 3072},
  211. '43': {'ext': 'webm', 'width': 640, 'height': 360},
  212. '44': {'ext': 'webm', 'width': 854, 'height': 480},
  213. '45': {'ext': 'webm', 'width': 1280, 'height': 720},
  214. '46': {'ext': 'webm', 'width': 1920, 'height': 1080},
  215. # 3d videos
  216. '82': {'ext': 'mp4', 'height': 360, 'format_note': '3D', 'preference': -20},
  217. '83': {'ext': 'mp4', 'height': 480, 'format_note': '3D', 'preference': -20},
  218. '84': {'ext': 'mp4', 'height': 720, 'format_note': '3D', 'preference': -20},
  219. '85': {'ext': 'mp4', 'height': 1080, 'format_note': '3D', 'preference': -20},
  220. '100': {'ext': 'webm', 'height': 360, 'format_note': '3D', 'preference': -20},
  221. '101': {'ext': 'webm', 'height': 480, 'format_note': '3D', 'preference': -20},
  222. '102': {'ext': 'webm', 'height': 720, 'format_note': '3D', 'preference': -20},
  223. # Apple HTTP Live Streaming
  224. '92': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  225. '93': {'ext': 'mp4', 'height': 360, 'format_note': 'HLS', 'preference': -10},
  226. '94': {'ext': 'mp4', 'height': 480, 'format_note': 'HLS', 'preference': -10},
  227. '95': {'ext': 'mp4', 'height': 720, 'format_note': 'HLS', 'preference': -10},
  228. '96': {'ext': 'mp4', 'height': 1080, 'format_note': 'HLS', 'preference': -10},
  229. '132': {'ext': 'mp4', 'height': 240, 'format_note': 'HLS', 'preference': -10},
  230. '151': {'ext': 'mp4', 'height': 72, 'format_note': 'HLS', 'preference': -10},
  231. # DASH mp4 video
  232. '133': {'ext': 'mp4', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  233. '134': {'ext': 'mp4', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  234. '135': {'ext': 'mp4', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  235. '136': {'ext': 'mp4', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  236. '137': {'ext': 'mp4', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  237. '138': {'ext': 'mp4', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  238. '160': {'ext': 'mp4', 'height': 144, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  239. '264': {'ext': 'mp4', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  240. # Dash mp4 audio
  241. '139': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 48, 'preference': -50},
  242. '140': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 128, 'preference': -50},
  243. '141': {'ext': 'm4a', 'format_note': 'DASH audio', 'vcodec': 'none', 'abr': 256, 'preference': -50},
  244. # Dash webm
  245. '167': {'ext': 'webm', 'height': 360, 'width': 640, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  246. '168': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  247. '169': {'ext': 'webm', 'height': 720, 'width': 1280, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  248. '170': {'ext': 'webm', 'height': 1080, 'width': 1920, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  249. '218': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  250. '219': {'ext': 'webm', 'height': 480, 'width': 854, 'format_note': 'DASH video', 'acodec': 'none', 'container': 'webm', 'vcodec': 'VP8', 'preference': -40},
  251. '242': {'ext': 'webm', 'height': 240, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  252. '243': {'ext': 'webm', 'height': 360, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  253. '244': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  254. '245': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  255. '246': {'ext': 'webm', 'height': 480, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  256. '247': {'ext': 'webm', 'height': 720, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  257. '248': {'ext': 'webm', 'height': 1080, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  258. '271': {'ext': 'webm', 'height': 1440, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  259. '272': {'ext': 'webm', 'height': 2160, 'format_note': 'DASH video', 'acodec': 'none', 'preference': -40},
  260. # Dash webm audio
  261. '171': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 128, 'preference': -50},
  262. '172': {'ext': 'webm', 'vcodec': 'none', 'format_note': 'DASH audio', 'abr': 256, 'preference': -50},
  263. # RTMP (unnamed)
  264. '_rtmp': {'protocol': 'rtmp'},
  265. }
  266. IE_NAME = 'youtube'
  267. _TESTS = [
  268. {
  269. 'url': 'http://www.youtube.com/watch?v=BaW_jenozKc',
  270. 'info_dict': {
  271. 'id': 'BaW_jenozKc',
  272. 'ext': 'mp4',
  273. 'title': 'youtube-dl test video "\'/\\ä↭𝕐',
  274. 'uploader': 'Philipp Hagemeister',
  275. 'uploader_id': 'phihag',
  276. 'upload_date': '20121002',
  277. '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 .',
  278. 'categories': ['Science & Technology'],
  279. 'like_count': int,
  280. 'dislike_count': int,
  281. }
  282. },
  283. {
  284. 'url': 'http://www.youtube.com/watch?v=UxxajLWwzqY',
  285. 'note': 'Test generic use_cipher_signature video (#897)',
  286. 'info_dict': {
  287. 'id': 'UxxajLWwzqY',
  288. 'ext': 'mp4',
  289. 'upload_date': '20120506',
  290. 'title': 'Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]',
  291. 'description': 'md5:fea86fda2d5a5784273df5c7cc994d9f',
  292. 'uploader': 'Icona Pop',
  293. 'uploader_id': 'IconaPop',
  294. }
  295. },
  296. {
  297. 'url': 'https://www.youtube.com/watch?v=07FYdnEawAQ',
  298. 'note': 'Test VEVO video with age protection (#956)',
  299. 'info_dict': {
  300. 'id': '07FYdnEawAQ',
  301. 'ext': 'mp4',
  302. 'upload_date': '20130703',
  303. 'title': 'Justin Timberlake - Tunnel Vision (Explicit)',
  304. 'description': 'md5:64249768eec3bc4276236606ea996373',
  305. 'uploader': 'justintimberlakeVEVO',
  306. 'uploader_id': 'justintimberlakeVEVO',
  307. }
  308. },
  309. {
  310. 'url': '//www.YouTube.com/watch?v=yZIXLfi8CZQ',
  311. 'note': 'Embed-only video (#1746)',
  312. 'info_dict': {
  313. 'id': 'yZIXLfi8CZQ',
  314. 'ext': 'mp4',
  315. 'upload_date': '20120608',
  316. 'title': 'Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012',
  317. 'description': 'md5:09b78bd971f1e3e289601dfba15ca4f7',
  318. 'uploader': 'SET India',
  319. 'uploader_id': 'setindia'
  320. }
  321. },
  322. {
  323. 'url': 'http://www.youtube.com/watch?v=a9LDPn-MO4I',
  324. 'note': '256k DASH audio (format 141) via DASH manifest',
  325. 'info_dict': {
  326. 'id': 'a9LDPn-MO4I',
  327. 'ext': 'm4a',
  328. 'upload_date': '20121002',
  329. 'uploader_id': '8KVIDEO',
  330. 'description': '',
  331. 'uploader': '8KVIDEO',
  332. 'title': 'UHDTV TEST 8K VIDEO.mp4'
  333. },
  334. 'params': {
  335. 'youtube_include_dash_manifest': True,
  336. 'format': '141',
  337. },
  338. },
  339. # DASH manifest with encrypted signature
  340. {
  341. 'url': 'https://www.youtube.com/watch?v=IB3lcPjvWLA',
  342. 'info_dict': {
  343. 'id': 'IB3lcPjvWLA',
  344. 'ext': 'm4a',
  345. 'title': 'Afrojack - The Spark ft. Spree Wilson',
  346. 'description': 'md5:9717375db5a9a3992be4668bbf3bc0a8',
  347. 'uploader': 'AfrojackVEVO',
  348. 'uploader_id': 'AfrojackVEVO',
  349. 'upload_date': '20131011',
  350. },
  351. 'params': {
  352. 'youtube_include_dash_manifest': True,
  353. 'format': '141',
  354. },
  355. },
  356. ]
  357. def __init__(self, *args, **kwargs):
  358. super(YoutubeIE, self).__init__(*args, **kwargs)
  359. self._player_cache = {}
  360. def report_video_info_webpage_download(self, video_id):
  361. """Report attempt to download video info webpage."""
  362. self.to_screen('%s: Downloading video info webpage' % video_id)
  363. def report_information_extraction(self, video_id):
  364. """Report attempt to extract video information."""
  365. self.to_screen('%s: Extracting video information' % video_id)
  366. def report_unavailable_format(self, video_id, format):
  367. """Report extracted video URL."""
  368. self.to_screen('%s: Format %s not available' % (video_id, format))
  369. def report_rtmp_download(self):
  370. """Indicate the download will use the RTMP protocol."""
  371. self.to_screen('RTMP download detected')
  372. def _signature_cache_id(self, example_sig):
  373. """ Return a string representation of a signature """
  374. return '.'.join(compat_str(len(part)) for part in example_sig.split('.'))
  375. def _extract_signature_function(self, video_id, player_url, example_sig):
  376. id_m = re.match(
  377. r'.*-(?P<id>[a-zA-Z0-9_-]+)(?:/watch_as3|/html5player)?\.(?P<ext>[a-z]+)$',
  378. player_url)
  379. if not id_m:
  380. raise ExtractorError('Cannot identify player %r' % player_url)
  381. player_type = id_m.group('ext')
  382. player_id = id_m.group('id')
  383. # Read from filesystem cache
  384. func_id = '%s_%s_%s' % (
  385. player_type, player_id, self._signature_cache_id(example_sig))
  386. assert os.path.basename(func_id) == func_id
  387. cache_spec = self._downloader.cache.load('youtube-sigfuncs', func_id)
  388. if cache_spec is not None:
  389. return lambda s: ''.join(s[i] for i in cache_spec)
  390. if player_type == 'js':
  391. code = self._download_webpage(
  392. player_url, video_id,
  393. note='Downloading %s player %s' % (player_type, player_id),
  394. errnote='Download of %s failed' % player_url)
  395. res = self._parse_sig_js(code)
  396. elif player_type == 'swf':
  397. urlh = self._request_webpage(
  398. player_url, video_id,
  399. note='Downloading %s player %s' % (player_type, player_id),
  400. errnote='Download of %s failed' % player_url)
  401. code = urlh.read()
  402. res = self._parse_sig_swf(code)
  403. else:
  404. assert False, 'Invalid player type %r' % player_type
  405. if cache_spec is None:
  406. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  407. cache_res = res(test_string)
  408. cache_spec = [ord(c) for c in cache_res]
  409. self._downloader.cache.store('youtube-sigfuncs', func_id, cache_spec)
  410. return res
  411. def _print_sig_code(self, func, example_sig):
  412. def gen_sig_code(idxs):
  413. def _genslice(start, end, step):
  414. starts = '' if start == 0 else str(start)
  415. ends = (':%d' % (end+step)) if end + step >= 0 else ':'
  416. steps = '' if step == 1 else (':%d' % step)
  417. return 's[%s%s%s]' % (starts, ends, steps)
  418. step = None
  419. start = '(Never used)' # Quelch pyflakes warnings - start will be
  420. # set as soon as step is set
  421. for i, prev in zip(idxs[1:], idxs[:-1]):
  422. if step is not None:
  423. if i - prev == step:
  424. continue
  425. yield _genslice(start, prev, step)
  426. step = None
  427. continue
  428. if i - prev in [-1, 1]:
  429. step = i - prev
  430. start = prev
  431. continue
  432. else:
  433. yield 's[%d]' % prev
  434. if step is None:
  435. yield 's[%d]' % i
  436. else:
  437. yield _genslice(start, i, step)
  438. test_string = ''.join(map(compat_chr, range(len(example_sig))))
  439. cache_res = func(test_string)
  440. cache_spec = [ord(c) for c in cache_res]
  441. expr_code = ' + '.join(gen_sig_code(cache_spec))
  442. signature_id_tuple = '(%s)' % (
  443. ', '.join(compat_str(len(p)) for p in example_sig.split('.')))
  444. code = ('if tuple(len(p) for p in s.split(\'.\')) == %s:\n'
  445. ' return %s\n') % (signature_id_tuple, expr_code)
  446. self.to_screen('Extracted signature function:\n' + code)
  447. def _parse_sig_js(self, jscode):
  448. funcname = self._search_regex(
  449. r'signature=([$a-zA-Z]+)', jscode,
  450. 'Initial JS player signature function name')
  451. jsi = JSInterpreter(jscode)
  452. initial_function = jsi.extract_function(funcname)
  453. return lambda s: initial_function([s])
  454. def _parse_sig_swf(self, file_contents):
  455. swfi = SWFInterpreter(file_contents)
  456. TARGET_CLASSNAME = 'SignatureDecipher'
  457. searched_class = swfi.extract_class(TARGET_CLASSNAME)
  458. initial_function = swfi.extract_function(searched_class, 'decipher')
  459. return lambda s: initial_function([s])
  460. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  461. """Turn the encrypted s field into a working signature"""
  462. if player_url is None:
  463. raise ExtractorError('Cannot decrypt signature without player_url')
  464. if player_url.startswith('//'):
  465. player_url = 'https:' + player_url
  466. try:
  467. player_id = (player_url, self._signature_cache_id(s))
  468. if player_id not in self._player_cache:
  469. func = self._extract_signature_function(
  470. video_id, player_url, s
  471. )
  472. self._player_cache[player_id] = func
  473. func = self._player_cache[player_id]
  474. if self._downloader.params.get('youtube_print_sig_code'):
  475. self._print_sig_code(func, s)
  476. return func(s)
  477. except Exception as e:
  478. tb = traceback.format_exc()
  479. raise ExtractorError(
  480. 'Signature extraction failed: ' + tb, cause=e)
  481. def _get_available_subtitles(self, video_id, webpage):
  482. try:
  483. sub_list = self._download_webpage(
  484. 'https://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  485. video_id, note=False)
  486. except ExtractorError as err:
  487. self._downloader.report_warning('unable to download video subtitles: %s' % compat_str(err))
  488. return {}
  489. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  490. sub_lang_list = {}
  491. for l in lang_list:
  492. lang = l[1]
  493. if lang in sub_lang_list:
  494. continue
  495. params = compat_urllib_parse.urlencode({
  496. 'lang': lang,
  497. 'v': video_id,
  498. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  499. 'name': unescapeHTML(l[0]).encode('utf-8'),
  500. })
  501. url = 'https://www.youtube.com/api/timedtext?' + params
  502. sub_lang_list[lang] = url
  503. if not sub_lang_list:
  504. self._downloader.report_warning('video doesn\'t have subtitles')
  505. return {}
  506. return sub_lang_list
  507. def _get_available_automatic_caption(self, video_id, webpage):
  508. """We need the webpage for getting the captions url, pass it as an
  509. argument to speed up the process."""
  510. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  511. self.to_screen('%s: Looking for automatic captions' % video_id)
  512. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  513. err_msg = 'Couldn\'t find automatic captions for %s' % video_id
  514. if mobj is None:
  515. self._downloader.report_warning(err_msg)
  516. return {}
  517. player_config = json.loads(mobj.group(1))
  518. try:
  519. args = player_config[u'args']
  520. caption_url = args[u'ttsurl']
  521. timestamp = args[u'timestamp']
  522. # We get the available subtitles
  523. list_params = compat_urllib_parse.urlencode({
  524. 'type': 'list',
  525. 'tlangs': 1,
  526. 'asrs': 1,
  527. })
  528. list_url = caption_url + '&' + list_params
  529. caption_list = self._download_xml(list_url, video_id)
  530. original_lang_node = caption_list.find('track')
  531. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  532. self._downloader.report_warning('Video doesn\'t have automatic captions')
  533. return {}
  534. original_lang = original_lang_node.attrib['lang_code']
  535. sub_lang_list = {}
  536. for lang_node in caption_list.findall('target'):
  537. sub_lang = lang_node.attrib['lang_code']
  538. params = compat_urllib_parse.urlencode({
  539. 'lang': original_lang,
  540. 'tlang': sub_lang,
  541. 'fmt': sub_format,
  542. 'ts': timestamp,
  543. 'kind': 'asr',
  544. })
  545. sub_lang_list[sub_lang] = caption_url + '&' + params
  546. return sub_lang_list
  547. # An extractor error can be raise by the download process if there are
  548. # no automatic captions but there are subtitles
  549. except (KeyError, ExtractorError):
  550. self._downloader.report_warning(err_msg)
  551. return {}
  552. @classmethod
  553. def extract_id(cls, url):
  554. mobj = re.match(cls._VALID_URL, url, re.VERBOSE)
  555. if mobj is None:
  556. raise ExtractorError('Invalid URL: %s' % url)
  557. video_id = mobj.group(2)
  558. return video_id
  559. def _extract_from_m3u8(self, manifest_url, video_id):
  560. url_map = {}
  561. def _get_urls(_manifest):
  562. lines = _manifest.split('\n')
  563. urls = filter(lambda l: l and not l.startswith('#'),
  564. lines)
  565. return urls
  566. manifest = self._download_webpage(manifest_url, video_id, 'Downloading formats manifest')
  567. formats_urls = _get_urls(manifest)
  568. for format_url in formats_urls:
  569. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  570. url_map[itag] = format_url
  571. return url_map
  572. def _extract_annotations(self, video_id):
  573. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  574. return self._download_webpage(url, video_id, note='Searching for annotations.', errnote='Unable to download video annotations.')
  575. def _real_extract(self, url):
  576. proto = (
  577. 'http' if self._downloader.params.get('prefer_insecure', False)
  578. else 'https')
  579. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  580. mobj = re.search(self._NEXT_URL_RE, url)
  581. if mobj:
  582. url = proto + '://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  583. video_id = self.extract_id(url)
  584. # Get video webpage
  585. url = proto + '://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  586. video_webpage = self._download_webpage(url, video_id)
  587. # Attempt to extract SWF player URL
  588. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  589. if mobj is not None:
  590. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  591. else:
  592. player_url = None
  593. # Get video info
  594. self.report_video_info_webpage_download(video_id)
  595. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  596. self.report_age_confirmation()
  597. age_gate = True
  598. # We simulate the access to the video from www.youtube.com/v/{video_id}
  599. # this can be viewed without login into Youtube
  600. data = compat_urllib_parse.urlencode({
  601. 'video_id': video_id,
  602. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  603. 'sts': self._search_regex(
  604. r'"sts"\s*:\s*(\d+)', video_webpage, 'sts'),
  605. })
  606. video_info_url = proto + '://www.youtube.com/get_video_info?' + data
  607. video_info_webpage = self._download_webpage(video_info_url, video_id,
  608. note=False,
  609. errnote='unable to download video info webpage')
  610. video_info = compat_parse_qs(video_info_webpage)
  611. else:
  612. age_gate = False
  613. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  614. video_info_url = (proto + '://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  615. % (video_id, el_type))
  616. video_info_webpage = self._download_webpage(video_info_url, video_id,
  617. note=False,
  618. errnote='unable to download video info webpage')
  619. video_info = compat_parse_qs(video_info_webpage)
  620. if 'token' in video_info:
  621. break
  622. if 'token' not in video_info:
  623. if 'reason' in video_info:
  624. raise ExtractorError(
  625. 'YouTube said: %s' % video_info['reason'][0],
  626. expected=True, video_id=video_id)
  627. else:
  628. raise ExtractorError(
  629. '"token" parameter not in video info for unknown reason',
  630. video_id=video_id)
  631. if 'view_count' in video_info:
  632. view_count = int(video_info['view_count'][0])
  633. else:
  634. view_count = None
  635. # Check for "rental" videos
  636. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  637. raise ExtractorError('"rental" videos not supported')
  638. # Start extracting information
  639. self.report_information_extraction(video_id)
  640. # uploader
  641. if 'author' not in video_info:
  642. raise ExtractorError('Unable to extract uploader name')
  643. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  644. # uploader_id
  645. video_uploader_id = None
  646. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  647. if mobj is not None:
  648. video_uploader_id = mobj.group(1)
  649. else:
  650. self._downloader.report_warning('unable to extract uploader nickname')
  651. # title
  652. if 'title' in video_info:
  653. video_title = video_info['title'][0]
  654. else:
  655. self._downloader.report_warning('Unable to extract video title')
  656. video_title = '_'
  657. # thumbnail image
  658. # We try first to get a high quality image:
  659. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  660. video_webpage, re.DOTALL)
  661. if m_thumb is not None:
  662. video_thumbnail = m_thumb.group(1)
  663. elif 'thumbnail_url' not in video_info:
  664. self._downloader.report_warning('unable to extract video thumbnail')
  665. video_thumbnail = None
  666. else: # don't panic if we can't find it
  667. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  668. # upload date
  669. upload_date = None
  670. mobj = re.search(r'(?s)id="eow-date.*?>(.*?)</span>', video_webpage)
  671. if mobj is None:
  672. mobj = re.search(
  673. r'(?s)id="watch-uploader-info".*?>.*?(?:Published|Uploaded|Streamed live) on (.*?)</strong>',
  674. video_webpage)
  675. if mobj is not None:
  676. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  677. upload_date = unified_strdate(upload_date)
  678. m_cat_container = self._search_regex(
  679. r'(?s)<h4[^>]*>\s*Category\s*</h4>\s*<ul[^>]*>(.*?)</ul>',
  680. video_webpage, 'categories', fatal=False)
  681. if m_cat_container:
  682. category = self._html_search_regex(
  683. r'(?s)<a[^<]+>(.*?)</a>', m_cat_container, 'category',
  684. default=None)
  685. video_categories = None if category is None else [category]
  686. else:
  687. video_categories = None
  688. # description
  689. video_description = get_element_by_id("eow-description", video_webpage)
  690. if video_description:
  691. video_description = re.sub(r'''(?x)
  692. <a\s+
  693. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  694. title="([^"]+)"\s+
  695. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  696. class="yt-uix-redirect-link"\s*>
  697. [^<]+
  698. </a>
  699. ''', r'\1', video_description)
  700. video_description = clean_html(video_description)
  701. else:
  702. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  703. if fd_mobj:
  704. video_description = unescapeHTML(fd_mobj.group(1))
  705. else:
  706. video_description = ''
  707. def _extract_count(count_name):
  708. count = self._search_regex(
  709. r'id="watch-%s"[^>]*>.*?([\d,]+)\s*</span>' % re.escape(count_name),
  710. video_webpage, count_name, default=None)
  711. if count is not None:
  712. return int(count.replace(',', ''))
  713. return None
  714. like_count = _extract_count('like')
  715. dislike_count = _extract_count('dislike')
  716. # subtitles
  717. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  718. if self._downloader.params.get('listsubtitles', False):
  719. self._list_available_subtitles(video_id, video_webpage)
  720. return
  721. if 'length_seconds' not in video_info:
  722. self._downloader.report_warning('unable to extract video duration')
  723. video_duration = None
  724. else:
  725. video_duration = int(compat_urllib_parse.unquote_plus(video_info['length_seconds'][0]))
  726. # annotations
  727. video_annotations = None
  728. if self._downloader.params.get('writeannotations', False):
  729. video_annotations = self._extract_annotations(video_id)
  730. # Decide which formats to download
  731. try:
  732. mobj = re.search(r';ytplayer\.config\s*=\s*({.*?});', video_webpage)
  733. if not mobj:
  734. raise ValueError('Could not find vevo ID')
  735. json_code = uppercase_escape(mobj.group(1))
  736. ytplayer_config = json.loads(json_code)
  737. args = ytplayer_config['args']
  738. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  739. # this signatures are encrypted
  740. if 'url_encoded_fmt_stream_map' not in args:
  741. raise ValueError('No stream_map present') # caught below
  742. re_signature = re.compile(r'[&,]s=')
  743. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  744. if m_s is not None:
  745. self.to_screen('%s: Encrypted signatures detected.' % video_id)
  746. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  747. m_s = re_signature.search(args.get('adaptive_fmts', ''))
  748. if m_s is not None:
  749. if 'adaptive_fmts' in video_info:
  750. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  751. else:
  752. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  753. except ValueError:
  754. pass
  755. def _map_to_format_list(urlmap):
  756. formats = []
  757. for itag, video_real_url in urlmap.items():
  758. dct = {
  759. 'format_id': itag,
  760. 'url': video_real_url,
  761. 'player_url': player_url,
  762. }
  763. if itag in self._formats:
  764. dct.update(self._formats[itag])
  765. formats.append(dct)
  766. return formats
  767. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  768. self.report_rtmp_download()
  769. formats = [{
  770. 'format_id': '_rtmp',
  771. 'protocol': 'rtmp',
  772. 'url': video_info['conn'][0],
  773. 'player_url': player_url,
  774. }]
  775. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  776. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  777. if 'rtmpe%3Dyes' in encoded_url_map:
  778. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  779. url_map = {}
  780. for url_data_str in encoded_url_map.split(','):
  781. url_data = compat_parse_qs(url_data_str)
  782. if 'itag' not in url_data or 'url' not in url_data:
  783. continue
  784. format_id = url_data['itag'][0]
  785. url = url_data['url'][0]
  786. if 'sig' in url_data:
  787. url += '&signature=' + url_data['sig'][0]
  788. elif 's' in url_data:
  789. encrypted_sig = url_data['s'][0]
  790. if not age_gate:
  791. jsplayer_url_json = self._search_regex(
  792. r'"assets":.+?"js":\s*("[^"]+")',
  793. video_webpage, 'JS player URL')
  794. player_url = json.loads(jsplayer_url_json)
  795. if player_url is None:
  796. player_url_json = self._search_regex(
  797. r'ytplayer\.config.*?"url"\s*:\s*("[^"]+")',
  798. video_webpage, 'age gate player URL')
  799. player_url = json.loads(player_url_json)
  800. if self._downloader.params.get('verbose'):
  801. if player_url is None:
  802. player_version = 'unknown'
  803. player_desc = 'unknown'
  804. else:
  805. if player_url.endswith('swf'):
  806. player_version = self._search_regex(
  807. r'-(.+?)(?:/watch_as3)?\.swf$', player_url,
  808. 'flash player', fatal=False)
  809. player_desc = 'flash player %s' % player_version
  810. else:
  811. player_version = self._search_regex(
  812. r'html5player-([^/]+?)(?:/html5player)?\.js',
  813. player_url,
  814. 'html5 player', fatal=False)
  815. player_desc = 'html5 player %s' % player_version
  816. parts_sizes = self._signature_cache_id(encrypted_sig)
  817. self.to_screen('{%s} signature length %s, %s' %
  818. (format_id, parts_sizes, player_desc))
  819. signature = self._decrypt_signature(
  820. encrypted_sig, video_id, player_url, age_gate)
  821. url += '&signature=' + signature
  822. if 'ratebypass' not in url:
  823. url += '&ratebypass=yes'
  824. url_map[format_id] = url
  825. formats = _map_to_format_list(url_map)
  826. elif video_info.get('hlsvp'):
  827. manifest_url = video_info['hlsvp'][0]
  828. url_map = self._extract_from_m3u8(manifest_url, video_id)
  829. formats = _map_to_format_list(url_map)
  830. else:
  831. raise ExtractorError('no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  832. # Look for the DASH manifest
  833. if (self._downloader.params.get('youtube_include_dash_manifest', False)):
  834. try:
  835. # The DASH manifest used needs to be the one from the original video_webpage.
  836. # The one found in get_video_info seems to be using different signatures.
  837. # However, in the case of an age restriction there won't be any embedded dashmpd in the video_webpage.
  838. # Luckily, it seems, this case uses some kind of default signature (len == 86), so the
  839. # combination of get_video_info and the _static_decrypt_signature() decryption fallback will work here.
  840. if age_gate:
  841. dash_manifest_url = video_info.get('dashmpd')[0]
  842. else:
  843. dash_manifest_url = ytplayer_config['args']['dashmpd']
  844. def decrypt_sig(mobj):
  845. s = mobj.group(1)
  846. dec_s = self._decrypt_signature(s, video_id, player_url, age_gate)
  847. return '/signature/%s' % dec_s
  848. dash_manifest_url = re.sub(r'/s/([\w\.]+)', decrypt_sig, dash_manifest_url)
  849. dash_doc = self._download_xml(
  850. dash_manifest_url, video_id,
  851. note='Downloading DASH manifest',
  852. errnote='Could not download DASH manifest')
  853. for r in dash_doc.findall('.//{urn:mpeg:DASH:schema:MPD:2011}Representation'):
  854. url_el = r.find('{urn:mpeg:DASH:schema:MPD:2011}BaseURL')
  855. if url_el is None:
  856. continue
  857. format_id = r.attrib['id']
  858. video_url = url_el.text
  859. filesize = int_or_none(url_el.attrib.get('{http://youtube.com/yt/2012/10/10}contentLength'))
  860. f = {
  861. 'format_id': format_id,
  862. 'url': video_url,
  863. 'width': int_or_none(r.attrib.get('width')),
  864. 'tbr': int_or_none(r.attrib.get('bandwidth'), 1000),
  865. 'asr': int_or_none(r.attrib.get('audioSamplingRate')),
  866. 'filesize': filesize,
  867. }
  868. try:
  869. existing_format = next(
  870. fo for fo in formats
  871. if fo['format_id'] == format_id)
  872. except StopIteration:
  873. f.update(self._formats.get(format_id, {}))
  874. formats.append(f)
  875. else:
  876. existing_format.update(f)
  877. except (ExtractorError, KeyError) as e:
  878. self.report_warning('Skipping DASH manifest: %s' % e, video_id)
  879. self._sort_formats(formats)
  880. return {
  881. 'id': video_id,
  882. 'uploader': video_uploader,
  883. 'uploader_id': video_uploader_id,
  884. 'upload_date': upload_date,
  885. 'title': video_title,
  886. 'thumbnail': video_thumbnail,
  887. 'description': video_description,
  888. 'categories': video_categories,
  889. 'subtitles': video_subtitles,
  890. 'duration': video_duration,
  891. 'age_limit': 18 if age_gate else 0,
  892. 'annotations': video_annotations,
  893. 'webpage_url': proto + '://www.youtube.com/watch?v=%s' % video_id,
  894. 'view_count': view_count,
  895. 'like_count': like_count,
  896. 'dislike_count': dislike_count,
  897. 'formats': formats,
  898. }
  899. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  900. IE_DESC = 'YouTube.com playlists'
  901. _VALID_URL = r"""(?x)(?:
  902. (?:https?://)?
  903. (?:\w+\.)?
  904. youtube\.com/
  905. (?:
  906. (?:course|view_play_list|my_playlists|artist|playlist|watch|embed/videoseries)
  907. \? (?:.*?&)*? (?:p|a|list)=
  908. | p/
  909. )
  910. (
  911. (?:PL|LL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,}
  912. # Top tracks, they can also include dots
  913. |(?:MC)[\w\.]*
  914. )
  915. .*
  916. |
  917. ((?:PL|LL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
  918. )"""
  919. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s'
  920. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  921. _VIDEO_RE = r'href="\s*/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  922. IE_NAME = 'youtube:playlist'
  923. _TESTS = [{
  924. 'url': 'https://www.youtube.com/playlist?list=PLwiyx1dc3P2JR9N8gQaQN_BCvlSlap7re',
  925. 'info_dict': {
  926. 'title': 'ytdl test PL',
  927. },
  928. 'playlist_count': 3,
  929. }, {
  930. 'url': 'https://www.youtube.com/playlist?list=PLtPgu7CB4gbZDA7i_euNxn75ISqxwZPYx',
  931. 'info_dict': {
  932. 'title': 'YDL_Empty_List',
  933. },
  934. 'playlist_count': 0,
  935. }, {
  936. 'note': 'Playlist with deleted videos (#651). As a bonus, the video #51 is also twice in this list.',
  937. 'url': 'https://www.youtube.com/playlist?list=PLwP_SiAcdui0KVebT0mU9Apz359a4ubsC',
  938. 'info_dict': {
  939. 'title': '29C3: Not my department',
  940. },
  941. 'playlist_count': 95,
  942. }, {
  943. 'note': 'issue #673',
  944. 'url': 'PLBB231211A4F62143',
  945. 'info_dict': {
  946. 'title': 'Team Fortress 2 (Class-based LP)',
  947. },
  948. 'playlist_mincount': 26,
  949. }, {
  950. 'note': 'Large playlist',
  951. 'url': 'https://www.youtube.com/playlist?list=UUBABnxM4Ar9ten8Mdjj1j0Q',
  952. 'info_dict': {
  953. 'title': 'Uploads from Cauchemar',
  954. },
  955. 'playlist_mincount': 799,
  956. }, {
  957. 'url': 'PLtPgu7CB4gbY9oDN3drwC3cMbJggS7dKl',
  958. 'info_dict': {
  959. 'title': 'YDL_safe_search',
  960. },
  961. 'playlist_count': 2,
  962. }, {
  963. 'note': 'embedded',
  964. 'url': 'http://www.youtube.com/embed/videoseries?list=PL6IaIsEjSbf96XFRuNccS_RuEXwNdsoEu',
  965. 'playlist_count': 4,
  966. 'info_dict': {
  967. 'title': 'JODA15',
  968. }
  969. }, {
  970. 'note': 'Embedded SWF player',
  971. 'url': 'http://www.youtube.com/p/YN5VISEtHet5D4NEvfTd0zcgFk84NqFZ?hl=en_US&fs=1&rel=0',
  972. 'playlist_count': 4,
  973. 'info_dict': {
  974. 'title': 'JODA7',
  975. }
  976. }]
  977. def _real_initialize(self):
  978. self._login()
  979. def _ids_to_results(self, ids):
  980. return [
  981. self.url_result(vid_id, 'Youtube', video_id=vid_id)
  982. for vid_id in ids]
  983. def _extract_mix(self, playlist_id):
  984. # The mixes are generated from a a single video
  985. # the id of the playlist is just 'RD' + video_id
  986. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  987. webpage = self._download_webpage(
  988. url, playlist_id, 'Downloading Youtube mix')
  989. search_title = lambda class_name: get_element_by_attribute('class', class_name, webpage)
  990. title_span = (
  991. search_title('playlist-title') or
  992. search_title('title long-title') or
  993. search_title('title'))
  994. title = clean_html(title_span)
  995. ids = orderedSet(re.findall(
  996. r'''(?xs)data-video-username=".*?".*?
  997. href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s''' % re.escape(playlist_id),
  998. webpage))
  999. url_results = self._ids_to_results(ids)
  1000. return self.playlist_result(url_results, playlist_id, title)
  1001. def _real_extract(self, url):
  1002. # Extract playlist id
  1003. mobj = re.match(self._VALID_URL, url)
  1004. if mobj is None:
  1005. raise ExtractorError('Invalid URL: %s' % url)
  1006. playlist_id = mobj.group(1) or mobj.group(2)
  1007. # Check if it's a video-specific URL
  1008. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1009. if 'v' in query_dict:
  1010. video_id = query_dict['v'][0]
  1011. if self._downloader.params.get('noplaylist'):
  1012. self.to_screen('Downloading just video %s because of --no-playlist' % video_id)
  1013. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1014. else:
  1015. self.to_screen('Downloading playlist %s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1016. if playlist_id.startswith('RD'):
  1017. # Mixes require a custom extraction process
  1018. return self._extract_mix(playlist_id)
  1019. if playlist_id.startswith('TL'):
  1020. raise ExtractorError('For downloading YouTube.com top lists, use '
  1021. 'the "yttoplist" keyword, for example "youtube-dl \'yttoplist:music:Top Tracks\'"', expected=True)
  1022. url = self._TEMPLATE_URL % playlist_id
  1023. page = self._download_webpage(url, playlist_id)
  1024. more_widget_html = content_html = page
  1025. # Check if the playlist exists or is private
  1026. if re.search(r'<div class="yt-alert-message">[^<]*?(The|This) playlist (does not exist|is private)[^<]*?</div>', page) is not None:
  1027. raise ExtractorError(
  1028. 'The playlist doesn\'t exist or is private, use --username or '
  1029. '--netrc to access it.',
  1030. expected=True)
  1031. # Extract the video ids from the playlist pages
  1032. ids = []
  1033. for page_num in itertools.count(1):
  1034. matches = re.finditer(self._VIDEO_RE, content_html)
  1035. # We remove the duplicates and the link with index 0
  1036. # (it's not the first video of the playlist)
  1037. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  1038. ids.extend(new_ids)
  1039. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1040. if not mobj:
  1041. break
  1042. more = self._download_json(
  1043. 'https://youtube.com/%s' % mobj.group('more'), playlist_id,
  1044. 'Downloading page #%s' % page_num,
  1045. transform_source=uppercase_escape)
  1046. content_html = more['content_html']
  1047. more_widget_html = more['load_more_widget_html']
  1048. playlist_title = self._html_search_regex(
  1049. r'(?s)<h1 class="pl-header-title[^"]*">\s*(.*?)\s*</h1>',
  1050. page, 'title')
  1051. url_results = self._ids_to_results(ids)
  1052. return self.playlist_result(url_results, playlist_id, playlist_title)
  1053. class YoutubeTopListIE(YoutubePlaylistIE):
  1054. IE_NAME = 'youtube:toplist'
  1055. IE_DESC = ('YouTube.com top lists, "yttoplist:{channel}:{list title}"'
  1056. ' (Example: "yttoplist:music:Top Tracks")')
  1057. _VALID_URL = r'yttoplist:(?P<chann>.*?):(?P<title>.*?)$'
  1058. _TESTS = [{
  1059. 'url': 'yttoplist:music:Trending',
  1060. 'playlist_mincount': 5,
  1061. 'skip': 'Only works for logged-in users',
  1062. }]
  1063. def _real_extract(self, url):
  1064. mobj = re.match(self._VALID_URL, url)
  1065. channel = mobj.group('chann')
  1066. title = mobj.group('title')
  1067. query = compat_urllib_parse.urlencode({'title': title})
  1068. channel_page = self._download_webpage(
  1069. 'https://www.youtube.com/%s' % channel, title)
  1070. link = self._html_search_regex(
  1071. r'''(?x)
  1072. <a\s+href="([^"]+)".*?>\s*
  1073. <span\s+class="branded-page-module-title-text">\s*
  1074. <span[^>]*>.*?%s.*?</span>''' % re.escape(query),
  1075. channel_page, 'list')
  1076. url = compat_urlparse.urljoin('https://www.youtube.com/', link)
  1077. video_re = r'data-index="\d+".*?data-video-id="([0-9A-Za-z_-]{11})"'
  1078. ids = []
  1079. # sometimes the webpage doesn't contain the videos
  1080. # retry until we get them
  1081. for i in itertools.count(0):
  1082. msg = 'Downloading Youtube mix'
  1083. if i > 0:
  1084. msg += ', retry #%d' % i
  1085. webpage = self._download_webpage(url, title, msg)
  1086. ids = orderedSet(re.findall(video_re, webpage))
  1087. if ids:
  1088. break
  1089. url_results = self._ids_to_results(ids)
  1090. return self.playlist_result(url_results, playlist_title=title)
  1091. class YoutubeChannelIE(InfoExtractor):
  1092. IE_DESC = 'YouTube.com channels'
  1093. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1094. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1095. _MORE_PAGES_URL = 'https://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
  1096. IE_NAME = 'youtube:channel'
  1097. _TESTS = [{
  1098. 'note': 'paginated channel',
  1099. 'url': 'https://www.youtube.com/channel/UCKfVa3S1e4PHvxWcwyMMg8w',
  1100. 'playlist_mincount': 91,
  1101. }]
  1102. def extract_videos_from_page(self, page):
  1103. ids_in_page = []
  1104. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1105. if mobj.group(1) not in ids_in_page:
  1106. ids_in_page.append(mobj.group(1))
  1107. return ids_in_page
  1108. def _real_extract(self, url):
  1109. # Extract channel id
  1110. mobj = re.match(self._VALID_URL, url)
  1111. if mobj is None:
  1112. raise ExtractorError('Invalid URL: %s' % url)
  1113. # Download channel page
  1114. channel_id = mobj.group(1)
  1115. video_ids = []
  1116. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  1117. channel_page = self._download_webpage(url, channel_id)
  1118. autogenerated = re.search(r'''(?x)
  1119. class="[^"]*?(?:
  1120. channel-header-autogenerated-label|
  1121. yt-channel-title-autogenerated
  1122. )[^"]*"''', channel_page) is not None
  1123. if autogenerated:
  1124. # The videos are contained in a single page
  1125. # the ajax pages can't be used, they are empty
  1126. video_ids = self.extract_videos_from_page(channel_page)
  1127. else:
  1128. # Download all channel pages using the json-based channel_ajax query
  1129. for pagenum in itertools.count(1):
  1130. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1131. page = self._download_json(
  1132. url, channel_id, note='Downloading page #%s' % pagenum,
  1133. transform_source=uppercase_escape)
  1134. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1135. video_ids.extend(ids_in_page)
  1136. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1137. break
  1138. self._downloader.to_screen('[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1139. url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1140. for video_id in video_ids]
  1141. return self.playlist_result(url_entries, channel_id)
  1142. class YoutubeUserIE(InfoExtractor):
  1143. IE_DESC = 'YouTube.com user videos (URL or "ytuser" keyword)'
  1144. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch|results)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1145. _TEMPLATE_URL = 'https://gdata.youtube.com/feeds/api/users/%s'
  1146. _GDATA_PAGE_SIZE = 50
  1147. _GDATA_URL = 'https://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1148. IE_NAME = 'youtube:user'
  1149. _TESTS = [{
  1150. 'url': 'https://www.youtube.com/user/TheLinuxFoundation',
  1151. 'playlist_mincount': 320,
  1152. 'info_dict': {
  1153. 'title': 'TheLinuxFoundation',
  1154. }
  1155. }, {
  1156. 'url': 'ytuser:phihag',
  1157. 'only_matching': True,
  1158. }]
  1159. @classmethod
  1160. def suitable(cls, url):
  1161. # Don't return True if the url can be extracted with other youtube
  1162. # extractor, the regex would is too permissive and it would match.
  1163. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1164. if any(ie.suitable(url) for ie in other_ies): return False
  1165. else: return super(YoutubeUserIE, cls).suitable(url)
  1166. def _real_extract(self, url):
  1167. # Extract username
  1168. mobj = re.match(self._VALID_URL, url)
  1169. if mobj is None:
  1170. raise ExtractorError('Invalid URL: %s' % url)
  1171. username = mobj.group(1)
  1172. # Download video ids using YouTube Data API. Result size per
  1173. # query is limited (currently to 50 videos) so we need to query
  1174. # page by page until there are no video ids - it means we got
  1175. # all of them.
  1176. def download_page(pagenum):
  1177. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1178. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1179. page = self._download_webpage(
  1180. gdata_url, username,
  1181. 'Downloading video ids from %d to %d' % (
  1182. start_index, start_index + self._GDATA_PAGE_SIZE))
  1183. try:
  1184. response = json.loads(page)
  1185. except ValueError as err:
  1186. raise ExtractorError('Invalid JSON in API response: ' + compat_str(err))
  1187. if 'entry' not in response['feed']:
  1188. return
  1189. # Extract video identifiers
  1190. entries = response['feed']['entry']
  1191. for entry in entries:
  1192. title = entry['title']['$t']
  1193. video_id = entry['id']['$t'].split('/')[-1]
  1194. yield {
  1195. '_type': 'url',
  1196. 'url': video_id,
  1197. 'ie_key': 'Youtube',
  1198. 'id': video_id,
  1199. 'title': title,
  1200. }
  1201. url_results = OnDemandPagedList(download_page, self._GDATA_PAGE_SIZE)
  1202. return self.playlist_result(url_results, playlist_title=username)
  1203. class YoutubeSearchIE(SearchInfoExtractor):
  1204. IE_DESC = 'YouTube.com searches'
  1205. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1206. _MAX_RESULTS = 1000
  1207. IE_NAME = 'youtube:search'
  1208. _SEARCH_KEY = 'ytsearch'
  1209. def _get_n_results(self, query, n):
  1210. """Get a specified number of results for a query"""
  1211. video_ids = []
  1212. pagenum = 0
  1213. limit = n
  1214. PAGE_SIZE = 50
  1215. while (PAGE_SIZE * pagenum) < limit:
  1216. result_url = self._API_URL % (
  1217. compat_urllib_parse.quote_plus(query.encode('utf-8')),
  1218. (PAGE_SIZE * pagenum) + 1)
  1219. data_json = self._download_webpage(
  1220. result_url, video_id='query "%s"' % query,
  1221. note='Downloading page %s' % (pagenum + 1),
  1222. errnote='Unable to download API page')
  1223. data = json.loads(data_json)
  1224. api_response = data['data']
  1225. if 'items' not in api_response:
  1226. raise ExtractorError(
  1227. '[youtube] No video results', expected=True)
  1228. new_ids = list(video['id'] for video in api_response['items'])
  1229. video_ids += new_ids
  1230. limit = min(n, api_response['totalItems'])
  1231. pagenum += 1
  1232. if len(video_ids) > n:
  1233. video_ids = video_ids[:n]
  1234. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1235. for video_id in video_ids]
  1236. return self.playlist_result(videos, query)
  1237. class YoutubeSearchDateIE(YoutubeSearchIE):
  1238. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1239. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1240. _SEARCH_KEY = 'ytsearchdate'
  1241. IE_DESC = 'YouTube.com searches, newest videos first'
  1242. class YoutubeSearchURLIE(InfoExtractor):
  1243. IE_DESC = 'YouTube.com search URLs'
  1244. IE_NAME = 'youtube:search_url'
  1245. _VALID_URL = r'https?://(?:www\.)?youtube\.com/results\?(.*?&)?search_query=(?P<query>[^&]+)(?:[&]|$)'
  1246. _TESTS = [{
  1247. 'url': 'https://www.youtube.com/results?baz=bar&search_query=youtube-dl+test+video&filters=video&lclk=video',
  1248. 'playlist_mincount': 5,
  1249. 'info_dict': {
  1250. 'title': 'youtube-dl test video',
  1251. }
  1252. }]
  1253. def _real_extract(self, url):
  1254. mobj = re.match(self._VALID_URL, url)
  1255. query = compat_urllib_parse.unquote_plus(mobj.group('query'))
  1256. webpage = self._download_webpage(url, query)
  1257. result_code = self._search_regex(
  1258. r'(?s)<ol class="item-section"(.*?)</ol>', webpage, 'result HTML')
  1259. part_codes = re.findall(
  1260. r'(?s)<h3 class="yt-lockup-title">(.*?)</h3>', result_code)
  1261. entries = []
  1262. for part_code in part_codes:
  1263. part_title = self._html_search_regex(
  1264. [r'(?s)title="([^"]+)"', r'>([^<]+)</a>'], part_code, 'item title', fatal=False)
  1265. part_url_snippet = self._html_search_regex(
  1266. r'(?s)href="([^"]+)"', part_code, 'item URL')
  1267. part_url = compat_urlparse.urljoin(
  1268. 'https://www.youtube.com/', part_url_snippet)
  1269. entries.append({
  1270. '_type': 'url',
  1271. 'url': part_url,
  1272. 'title': part_title,
  1273. })
  1274. return {
  1275. '_type': 'playlist',
  1276. 'entries': entries,
  1277. 'title': query,
  1278. }
  1279. class YoutubeShowIE(InfoExtractor):
  1280. IE_DESC = 'YouTube.com (multi-season) shows'
  1281. _VALID_URL = r'https?://www\.youtube\.com/show/(?P<id>[^?#]*)'
  1282. IE_NAME = 'youtube:show'
  1283. _TESTS = [{
  1284. 'url': 'http://www.youtube.com/show/airdisasters',
  1285. 'playlist_mincount': 3,
  1286. 'info_dict': {
  1287. 'id': 'airdisasters',
  1288. 'title': 'Air Disasters',
  1289. }
  1290. }]
  1291. def _real_extract(self, url):
  1292. mobj = re.match(self._VALID_URL, url)
  1293. playlist_id = mobj.group('id')
  1294. webpage = self._download_webpage(
  1295. url, playlist_id, 'Downloading show webpage')
  1296. # There's one playlist for each season of the show
  1297. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1298. self.to_screen('%s: Found %s seasons' % (playlist_id, len(m_seasons)))
  1299. entries = [
  1300. self.url_result(
  1301. 'https://www.youtube.com' + season.group(1), 'YoutubePlaylist')
  1302. for season in m_seasons
  1303. ]
  1304. title = self._og_search_title(webpage, fatal=False)
  1305. return {
  1306. '_type': 'playlist',
  1307. 'id': playlist_id,
  1308. 'title': title,
  1309. 'entries': entries,
  1310. }
  1311. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1312. """
  1313. Base class for extractors that fetch info from
  1314. http://www.youtube.com/feed_ajax
  1315. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1316. """
  1317. _LOGIN_REQUIRED = True
  1318. # use action_load_personal_feed instead of action_load_system_feed
  1319. _PERSONAL_FEED = False
  1320. @property
  1321. def _FEED_TEMPLATE(self):
  1322. action = 'action_load_system_feed'
  1323. if self._PERSONAL_FEED:
  1324. action = 'action_load_personal_feed'
  1325. return 'https://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1326. @property
  1327. def IE_NAME(self):
  1328. return 'youtube:%s' % self._FEED_NAME
  1329. def _real_initialize(self):
  1330. self._login()
  1331. def _real_extract(self, url):
  1332. feed_entries = []
  1333. paging = 0
  1334. for i in itertools.count(1):
  1335. info = self._download_json(self._FEED_TEMPLATE % paging,
  1336. '%s feed' % self._FEED_NAME,
  1337. 'Downloading page %s' % i)
  1338. feed_html = info.get('feed_html') or info.get('content_html')
  1339. load_more_widget_html = info.get('load_more_widget_html') or feed_html
  1340. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1341. ids = orderedSet(m.group(1) for m in m_ids)
  1342. feed_entries.extend(
  1343. self.url_result(video_id, 'Youtube', video_id=video_id)
  1344. for video_id in ids)
  1345. mobj = re.search(
  1346. r'data-uix-load-more-href="/?[^"]+paging=(?P<paging>\d+)',
  1347. load_more_widget_html)
  1348. if mobj is None:
  1349. break
  1350. paging = mobj.group('paging')
  1351. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1352. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1353. IE_DESC = 'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1354. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1355. _FEED_NAME = 'recommended'
  1356. _PLAYLIST_TITLE = 'Youtube Recommended videos'
  1357. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1358. IE_DESC = 'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1359. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1360. _FEED_NAME = 'watch_later'
  1361. _PLAYLIST_TITLE = 'Youtube Watch Later'
  1362. _PERSONAL_FEED = True
  1363. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1364. IE_DESC = 'Youtube watch history, "ythistory" keyword (requires authentication)'
  1365. _VALID_URL = 'https?://www\.youtube\.com/feed/history|:ythistory'
  1366. _FEED_NAME = 'history'
  1367. _PERSONAL_FEED = True
  1368. _PLAYLIST_TITLE = 'Youtube Watch History'
  1369. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1370. IE_NAME = 'youtube:favorites'
  1371. IE_DESC = 'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1372. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1373. _LOGIN_REQUIRED = True
  1374. def _real_extract(self, url):
  1375. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1376. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, 'favourites playlist id')
  1377. return self.url_result(playlist_id, 'YoutubePlaylist')
  1378. class YoutubeSubscriptionsIE(YoutubePlaylistIE):
  1379. IE_NAME = 'youtube:subscriptions'
  1380. IE_DESC = 'YouTube.com subscriptions feed, "ytsubs" keyword (requires authentication)'
  1381. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1382. _TESTS = []
  1383. def _real_extract(self, url):
  1384. title = 'Youtube Subscriptions'
  1385. page = self._download_webpage('https://www.youtube.com/feed/subscriptions', title)
  1386. # The extraction process is the same as for playlists, but the regex
  1387. # for the video ids doesn't contain an index
  1388. ids = []
  1389. more_widget_html = content_html = page
  1390. for page_num in itertools.count(1):
  1391. matches = re.findall(r'href="\s*/watch\?v=([0-9A-Za-z_-]{11})', content_html)
  1392. new_ids = orderedSet(matches)
  1393. ids.extend(new_ids)
  1394. mobj = re.search(r'data-uix-load-more-href="/?(?P<more>[^"]+)"', more_widget_html)
  1395. if not mobj:
  1396. break
  1397. more = self._download_json(
  1398. 'https://youtube.com/%s' % mobj.group('more'), title,
  1399. 'Downloading page #%s' % page_num,
  1400. transform_source=uppercase_escape)
  1401. content_html = more['content_html']
  1402. more_widget_html = more['load_more_widget_html']
  1403. return {
  1404. '_type': 'playlist',
  1405. 'title': title,
  1406. 'entries': self._ids_to_results(ids),
  1407. }
  1408. class YoutubeTruncatedURLIE(InfoExtractor):
  1409. IE_NAME = 'youtube:truncated_url'
  1410. IE_DESC = False # Do not list
  1411. _VALID_URL = r'''(?x)
  1412. (?:https?://)?[^/]+/watch\?(?:
  1413. feature=[a-z_]+|
  1414. annotation_id=annotation_[^&]+
  1415. )?$|
  1416. (?:https?://)?(?:www\.)?youtube\.com/attribution_link\?a=[^&]+$
  1417. '''
  1418. _TESTS = [{
  1419. 'url': 'http://www.youtube.com/watch?annotation_id=annotation_3951667041',
  1420. 'only_matching': True,
  1421. }, {
  1422. 'url': 'http://www.youtube.com/watch?',
  1423. 'only_matching': True,
  1424. }]
  1425. def _real_extract(self, url):
  1426. raise ExtractorError(
  1427. 'Did you forget to quote the URL? Remember that & is a meta '
  1428. 'character in most shells, so you want to put the URL in quotes, '
  1429. 'like youtube-dl '
  1430. '"http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc" '
  1431. ' or simply youtube-dl BaW_jenozKc .',
  1432. expected=True)