youtube.py 86 KB

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