youtube.py 88 KB

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