youtube.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  1. # coding: utf-8
  2. import collections
  3. import errno
  4. import io
  5. import itertools
  6. import json
  7. import os.path
  8. import re
  9. import string
  10. import struct
  11. import traceback
  12. import zlib
  13. from .common import InfoExtractor, SearchInfoExtractor
  14. from .subtitles import SubtitlesInfoExtractor
  15. from ..utils import (
  16. compat_chr,
  17. compat_parse_qs,
  18. compat_urllib_parse,
  19. compat_urllib_request,
  20. compat_urlparse,
  21. compat_str,
  22. clean_html,
  23. get_cachedir,
  24. get_element_by_id,
  25. get_element_by_attribute,
  26. ExtractorError,
  27. unescapeHTML,
  28. unified_strdate,
  29. orderedSet,
  30. write_json_file,
  31. )
  32. class YoutubeBaseInfoExtractor(InfoExtractor):
  33. """Provide base functions for Youtube extractors"""
  34. _LOGIN_URL = 'https://accounts.google.com/ServiceLogin'
  35. _LANG_URL = r'https://www.youtube.com/?hl=en&persist_hl=1&gl=US&persist_gl=1&opt_out_ackd=1'
  36. _AGE_URL = 'http://www.youtube.com/verify_age?next_url=/&gl=US&hl=en'
  37. _NETRC_MACHINE = 'youtube'
  38. # If True it will raise an error if no login info is provided
  39. _LOGIN_REQUIRED = False
  40. def report_lang(self):
  41. """Report attempt to set language."""
  42. self.to_screen(u'Setting language')
  43. def _set_language(self):
  44. request = compat_urllib_request.Request(self._LANG_URL)
  45. try:
  46. self.report_lang()
  47. self._download_webpage(self._LANG_URL, None, False)
  48. except ExtractorError as err:
  49. self._downloader.report_warning(u'unable to set language: %s' % compat_str(err.cause))
  50. return False
  51. return True
  52. def _login(self):
  53. (username, password) = self._get_login_info()
  54. # No authentication to be performed
  55. if username is None:
  56. if self._LOGIN_REQUIRED:
  57. raise ExtractorError(u'No login info available, needed for using %s.' % self.IE_NAME, expected=True)
  58. return False
  59. login_page = self._download_webpage(self._LOGIN_URL, None, False,
  60. u'Unable to fetch login page')
  61. galx = self._search_regex(r'(?s)<input.+?name="GALX".+?value="(.+?)"',
  62. login_page, u'Login GALX parameter')
  63. # Log in
  64. login_form_strs = {
  65. u'continue': u'https://www.youtube.com/signin?action_handle_signin=true&feature=sign_in_button&hl=en_US&nomobiletemp=1',
  66. u'Email': username,
  67. u'GALX': galx,
  68. u'Passwd': password,
  69. u'PersistentCookie': u'yes',
  70. u'_utf8': u'霱',
  71. u'bgresponse': u'js_disabled',
  72. u'checkConnection': u'',
  73. u'checkedDomains': u'youtube',
  74. u'dnConn': u'',
  75. u'pstMsg': u'0',
  76. u'rmShown': u'1',
  77. u'secTok': u'',
  78. u'signIn': u'Sign in',
  79. u'timeStmp': u'',
  80. u'service': u'youtube',
  81. u'uilel': u'3',
  82. u'hl': u'en_US',
  83. }
  84. # Convert to UTF-8 *before* urlencode because Python 2.x's urlencode
  85. # chokes on unicode
  86. login_form = dict((k.encode('utf-8'), v.encode('utf-8')) for k,v in login_form_strs.items())
  87. login_data = compat_urllib_parse.urlencode(login_form).encode('ascii')
  88. request = compat_urllib_request.Request(self._LOGIN_URL, login_data)
  89. try:
  90. self.report_login()
  91. login_results = self._download_webpage(request, None, False)
  92. if re.search(r'(?i)<form[^>]* id="gaia_loginform"', login_results) is not None:
  93. self._downloader.report_warning(u'unable to log in: bad username or password')
  94. return False
  95. except ExtractorError as err:
  96. self._downloader.report_warning(u'unable to log in: %s' % compat_str(err.cause))
  97. return False
  98. return True
  99. def _confirm_age(self):
  100. age_form = {
  101. 'next_url': '/',
  102. 'action_confirm': 'Confirm',
  103. }
  104. request = compat_urllib_request.Request(self._AGE_URL, compat_urllib_parse.urlencode(age_form))
  105. self.report_age_confirmation()
  106. self._download_webpage(request, None, False, u'Unable to confirm age')
  107. return True
  108. def _real_initialize(self):
  109. if self._downloader is None:
  110. return
  111. if not self._set_language():
  112. return
  113. if not self._login():
  114. return
  115. self._confirm_age()
  116. class YoutubeIE(YoutubeBaseInfoExtractor, SubtitlesInfoExtractor):
  117. IE_DESC = u'YouTube.com'
  118. _VALID_URL = r"""(?x)^
  119. (
  120. (?:https?://|//)? # http(s):// or protocol-independent URL (optional)
  121. (?:(?:(?:(?:\w+\.)?[yY][oO][uU][tT][uU][bB][eE](?:-nocookie)?\.com/|
  122. tube\.majestyc\.net/|
  123. youtube\.googleapis\.com/) # the various hostnames, with wildcard subdomains
  124. (?:.*?\#/)? # handle anchor (#/) redirect urls
  125. (?: # the various things that can precede the ID:
  126. (?:(?:v|embed|e)/) # v/ or embed/ or e/
  127. |(?: # or the v= param in all its forms
  128. (?:(?:watch|movie)(?:_popup)?(?:\.php)?)? # preceding watch(_popup|.php) or nothing (like /?v=xxxx)
  129. (?:\?|\#!?) # the params delimiter ? or # or #!
  130. (?:.*?&)? # any other preceding param (like /?s=tuff&v=xxxx)
  131. v=
  132. )
  133. ))
  134. |youtu\.be/ # just youtu.be/xxxx
  135. )
  136. )? # all until now is optional -> you can pass the naked ID
  137. ([0-9A-Za-z_-]{11}) # here is it! the YouTube video ID
  138. (?(1).+)? # if we found the ID, everything can follow
  139. $"""
  140. _NEXT_URL_RE = r'[\?&]next_url=([^&]+)'
  141. # Listed in order of quality
  142. _available_formats = ['38', '37', '46', '22', '45', '35', '44', '34', '18', '43', '6', '5', '36', '17', '13',
  143. # Apple HTTP Live Streaming
  144. '96', '95', '94', '93', '92', '132', '151',
  145. # 3D
  146. '85', '84', '102', '83', '101', '82', '100',
  147. # Dash video
  148. '138', '137', '248', '136', '247', '135', '246',
  149. '245', '244', '134', '243', '133', '242', '160',
  150. # Dash audio
  151. '141', '172', '140', '171', '139',
  152. ]
  153. _available_formats_prefer_free = ['38', '46', '37', '45', '22', '44', '35', '43', '34', '18', '6', '5', '36', '17', '13',
  154. # Apple HTTP Live Streaming
  155. '96', '95', '94', '93', '92', '132', '151',
  156. # 3D
  157. '85', '102', '84', '101', '83', '100', '82',
  158. # Dash video
  159. '138', '248', '137', '247', '136', '246', '245',
  160. '244', '135', '243', '134', '242', '133', '160',
  161. # Dash audio
  162. '172', '141', '171', '140', '139',
  163. ]
  164. _video_formats_map = {
  165. 'flv': ['35', '34', '6', '5'],
  166. '3gp': ['36', '17', '13'],
  167. 'mp4': ['38', '37', '22', '18'],
  168. 'webm': ['46', '45', '44', '43'],
  169. }
  170. _video_extensions = {
  171. '13': '3gp',
  172. '17': '3gp',
  173. '18': 'mp4',
  174. '22': 'mp4',
  175. '36': '3gp',
  176. '37': 'mp4',
  177. '38': 'mp4',
  178. '43': 'webm',
  179. '44': 'webm',
  180. '45': 'webm',
  181. '46': 'webm',
  182. # 3d videos
  183. '82': 'mp4',
  184. '83': 'mp4',
  185. '84': 'mp4',
  186. '85': 'mp4',
  187. '100': 'webm',
  188. '101': 'webm',
  189. '102': 'webm',
  190. # Apple HTTP Live Streaming
  191. '92': 'mp4',
  192. '93': 'mp4',
  193. '94': 'mp4',
  194. '95': 'mp4',
  195. '96': 'mp4',
  196. '132': 'mp4',
  197. '151': 'mp4',
  198. # Dash mp4
  199. '133': 'mp4',
  200. '134': 'mp4',
  201. '135': 'mp4',
  202. '136': 'mp4',
  203. '137': 'mp4',
  204. '138': 'mp4',
  205. '160': 'mp4',
  206. # Dash mp4 audio
  207. '139': 'm4a',
  208. '140': 'm4a',
  209. '141': 'm4a',
  210. # Dash webm
  211. '171': 'webm',
  212. '172': 'webm',
  213. '242': 'webm',
  214. '243': 'webm',
  215. '244': 'webm',
  216. '245': 'webm',
  217. '246': 'webm',
  218. '247': 'webm',
  219. '248': 'webm',
  220. }
  221. _video_dimensions = {
  222. '5': '400x240',
  223. '6': '???',
  224. '13': '???',
  225. '17': '176x144',
  226. '18': '640x360',
  227. '22': '1280x720',
  228. '34': '640x360',
  229. '35': '854x480',
  230. '36': '320x240',
  231. '37': '1920x1080',
  232. '38': '4096x3072',
  233. '43': '640x360',
  234. '44': '854x480',
  235. '45': '1280x720',
  236. '46': '1920x1080',
  237. '82': '360p',
  238. '83': '480p',
  239. '84': '720p',
  240. '85': '1080p',
  241. '92': '240p',
  242. '93': '360p',
  243. '94': '480p',
  244. '95': '720p',
  245. '96': '1080p',
  246. '100': '360p',
  247. '101': '480p',
  248. '102': '720p',
  249. '132': '240p',
  250. '151': '72p',
  251. '133': '240p',
  252. '134': '360p',
  253. '135': '480p',
  254. '136': '720p',
  255. '137': '1080p',
  256. '138': '>1080p',
  257. '139': '48k',
  258. '140': '128k',
  259. '141': '256k',
  260. '160': '192p',
  261. '171': '128k',
  262. '172': '256k',
  263. '242': '240p',
  264. '243': '360p',
  265. '244': '480p',
  266. '245': '480p',
  267. '246': '480p',
  268. '247': '720p',
  269. '248': '1080p',
  270. }
  271. _special_itags = {
  272. '82': '3D',
  273. '83': '3D',
  274. '84': '3D',
  275. '85': '3D',
  276. '100': '3D',
  277. '101': '3D',
  278. '102': '3D',
  279. '133': 'DASH Video',
  280. '134': 'DASH Video',
  281. '135': 'DASH Video',
  282. '136': 'DASH Video',
  283. '137': 'DASH Video',
  284. '138': 'DASH Video',
  285. '139': 'DASH Audio',
  286. '140': 'DASH Audio',
  287. '141': 'DASH Audio',
  288. '160': 'DASH Video',
  289. '171': 'DASH Audio',
  290. '172': 'DASH Audio',
  291. '242': 'DASH Video',
  292. '243': 'DASH Video',
  293. '244': 'DASH Video',
  294. '245': 'DASH Video',
  295. '246': 'DASH Video',
  296. '247': 'DASH Video',
  297. '248': 'DASH Video',
  298. }
  299. IE_NAME = u'youtube'
  300. _TESTS = [
  301. {
  302. u"url": u"http://www.youtube.com/watch?v=BaW_jenozKc",
  303. u"file": u"BaW_jenozKc.mp4",
  304. u"info_dict": {
  305. u"title": u"youtube-dl test video \"'/\\ä↭𝕐",
  306. u"uploader": u"Philipp Hagemeister",
  307. u"uploader_id": u"phihag",
  308. u"upload_date": u"20121002",
  309. u"description": u"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 ."
  310. }
  311. },
  312. {
  313. u"url": u"http://www.youtube.com/watch?v=UxxajLWwzqY",
  314. u"file": u"UxxajLWwzqY.mp4",
  315. u"note": u"Test generic use_cipher_signature video (#897)",
  316. u"info_dict": {
  317. u"upload_date": u"20120506",
  318. u"title": u"Icona Pop - I Love It (feat. Charli XCX) [OFFICIAL VIDEO]",
  319. u"description": u"md5:5b292926389560516e384ac437c0ec07",
  320. u"uploader": u"Icona Pop",
  321. u"uploader_id": u"IconaPop"
  322. }
  323. },
  324. {
  325. u"url": u"https://www.youtube.com/watch?v=07FYdnEawAQ",
  326. u"file": u"07FYdnEawAQ.mp4",
  327. u"note": u"Test VEVO video with age protection (#956)",
  328. u"info_dict": {
  329. u"upload_date": u"20130703",
  330. u"title": u"Justin Timberlake - Tunnel Vision (Explicit)",
  331. u"description": u"md5:64249768eec3bc4276236606ea996373",
  332. u"uploader": u"justintimberlakeVEVO",
  333. u"uploader_id": u"justintimberlakeVEVO"
  334. }
  335. },
  336. {
  337. u"url": u"//www.YouTube.com/watch?v=yZIXLfi8CZQ",
  338. u"file": u"yZIXLfi8CZQ.mp4",
  339. u"note": u"Embed-only video (#1746)",
  340. u"info_dict": {
  341. u"upload_date": u"20120608",
  342. u"title": u"Principal Sexually Assaults A Teacher - Episode 117 - 8th June 2012",
  343. u"description": u"md5:09b78bd971f1e3e289601dfba15ca4f7",
  344. u"uploader": u"SET India",
  345. u"uploader_id": u"setindia"
  346. }
  347. },
  348. ]
  349. @classmethod
  350. def suitable(cls, url):
  351. """Receives a URL and returns True if suitable for this IE."""
  352. if YoutubePlaylistIE.suitable(url): return False
  353. return re.match(cls._VALID_URL, url) is not None
  354. def __init__(self, *args, **kwargs):
  355. super(YoutubeIE, self).__init__(*args, **kwargs)
  356. self._player_cache = {}
  357. def report_video_info_webpage_download(self, video_id):
  358. """Report attempt to download video info webpage."""
  359. self.to_screen(u'%s: Downloading video info webpage' % video_id)
  360. def report_information_extraction(self, video_id):
  361. """Report attempt to extract video information."""
  362. self.to_screen(u'%s: Extracting video information' % video_id)
  363. def report_unavailable_format(self, video_id, format):
  364. """Report extracted video URL."""
  365. self.to_screen(u'%s: Format %s not available' % (video_id, format))
  366. def report_rtmp_download(self):
  367. """Indicate the download will use the RTMP protocol."""
  368. self.to_screen(u'RTMP download detected')
  369. def _extract_signature_function(self, video_id, player_url, slen):
  370. id_m = re.match(r'.*-(?P<id>[a-zA-Z0-9_-]+)\.(?P<ext>[a-z]+)$',
  371. player_url)
  372. player_type = id_m.group('ext')
  373. player_id = id_m.group('id')
  374. # Read from filesystem cache
  375. func_id = '%s_%s_%d' % (player_type, player_id, slen)
  376. assert os.path.basename(func_id) == func_id
  377. cache_dir = get_cachedir(self._downloader.params)
  378. cache_enabled = cache_dir is not None
  379. if cache_enabled:
  380. cache_fn = os.path.join(os.path.expanduser(cache_dir),
  381. u'youtube-sigfuncs',
  382. func_id + '.json')
  383. try:
  384. with io.open(cache_fn, 'r', encoding='utf-8') as cachef:
  385. cache_spec = json.load(cachef)
  386. return lambda s: u''.join(s[i] for i in cache_spec)
  387. except IOError:
  388. pass # No cache available
  389. if player_type == 'js':
  390. code = self._download_webpage(
  391. player_url, video_id,
  392. note=u'Downloading %s player %s' % (player_type, player_id),
  393. errnote=u'Download of %s failed' % player_url)
  394. res = self._parse_sig_js(code)
  395. elif player_type == 'swf':
  396. urlh = self._request_webpage(
  397. player_url, video_id,
  398. note=u'Downloading %s player %s' % (player_type, player_id),
  399. errnote=u'Download of %s failed' % player_url)
  400. code = urlh.read()
  401. res = self._parse_sig_swf(code)
  402. else:
  403. assert False, 'Invalid player type %r' % player_type
  404. if cache_enabled:
  405. try:
  406. test_string = u''.join(map(compat_chr, range(slen)))
  407. cache_res = res(test_string)
  408. cache_spec = [ord(c) for c in cache_res]
  409. try:
  410. os.makedirs(os.path.dirname(cache_fn))
  411. except OSError as ose:
  412. if ose.errno != errno.EEXIST:
  413. raise
  414. write_json_file(cache_spec, cache_fn)
  415. except Exception:
  416. tb = traceback.format_exc()
  417. self._downloader.report_warning(
  418. u'Writing cache to %r failed: %s' % (cache_fn, tb))
  419. return res
  420. def _print_sig_code(self, func, slen):
  421. def gen_sig_code(idxs):
  422. def _genslice(start, end, step):
  423. starts = u'' if start == 0 else str(start)
  424. ends = (u':%d' % (end+step)) if end + step >= 0 else u':'
  425. steps = u'' if step == 1 else (u':%d' % step)
  426. return u's[%s%s%s]' % (starts, ends, steps)
  427. step = None
  428. start = '(Never used)' # Quelch pyflakes warnings - start will be
  429. # set as soon as step is set
  430. for i, prev in zip(idxs[1:], idxs[:-1]):
  431. if step is not None:
  432. if i - prev == step:
  433. continue
  434. yield _genslice(start, prev, step)
  435. step = None
  436. continue
  437. if i - prev in [-1, 1]:
  438. step = i - prev
  439. start = prev
  440. continue
  441. else:
  442. yield u's[%d]' % prev
  443. if step is None:
  444. yield u's[%d]' % i
  445. else:
  446. yield _genslice(start, i, step)
  447. test_string = u''.join(map(compat_chr, range(slen)))
  448. cache_res = func(test_string)
  449. cache_spec = [ord(c) for c in cache_res]
  450. expr_code = u' + '.join(gen_sig_code(cache_spec))
  451. code = u'if len(s) == %d:\n return %s\n' % (slen, expr_code)
  452. self.to_screen(u'Extracted signature function:\n' + code)
  453. def _parse_sig_js(self, jscode):
  454. funcname = self._search_regex(
  455. r'signature=([a-zA-Z]+)', jscode,
  456. u'Initial JS player signature function name')
  457. functions = {}
  458. def argidx(varname):
  459. return string.lowercase.index(varname)
  460. def interpret_statement(stmt, local_vars, allow_recursion=20):
  461. if allow_recursion < 0:
  462. raise ExtractorError(u'Recursion limit reached')
  463. if stmt.startswith(u'var '):
  464. stmt = stmt[len(u'var '):]
  465. ass_m = re.match(r'^(?P<out>[a-z]+)(?:\[(?P<index>[^\]]+)\])?' +
  466. r'=(?P<expr>.*)$', stmt)
  467. if ass_m:
  468. if ass_m.groupdict().get('index'):
  469. def assign(val):
  470. lvar = local_vars[ass_m.group('out')]
  471. idx = interpret_expression(ass_m.group('index'),
  472. local_vars, allow_recursion)
  473. assert isinstance(idx, int)
  474. lvar[idx] = val
  475. return val
  476. expr = ass_m.group('expr')
  477. else:
  478. def assign(val):
  479. local_vars[ass_m.group('out')] = val
  480. return val
  481. expr = ass_m.group('expr')
  482. elif stmt.startswith(u'return '):
  483. assign = lambda v: v
  484. expr = stmt[len(u'return '):]
  485. else:
  486. raise ExtractorError(
  487. u'Cannot determine left side of statement in %r' % stmt)
  488. v = interpret_expression(expr, local_vars, allow_recursion)
  489. return assign(v)
  490. def interpret_expression(expr, local_vars, allow_recursion):
  491. if expr.isdigit():
  492. return int(expr)
  493. if expr.isalpha():
  494. return local_vars[expr]
  495. m = re.match(r'^(?P<in>[a-z]+)\.(?P<member>.*)$', expr)
  496. if m:
  497. member = m.group('member')
  498. val = local_vars[m.group('in')]
  499. if member == 'split("")':
  500. return list(val)
  501. if member == 'join("")':
  502. return u''.join(val)
  503. if member == 'length':
  504. return len(val)
  505. if member == 'reverse()':
  506. return val[::-1]
  507. slice_m = re.match(r'slice\((?P<idx>.*)\)', member)
  508. if slice_m:
  509. idx = interpret_expression(
  510. slice_m.group('idx'), local_vars, allow_recursion-1)
  511. return val[idx:]
  512. m = re.match(
  513. r'^(?P<in>[a-z]+)\[(?P<idx>.+)\]$', expr)
  514. if m:
  515. val = local_vars[m.group('in')]
  516. idx = interpret_expression(m.group('idx'), local_vars,
  517. allow_recursion-1)
  518. return val[idx]
  519. m = re.match(r'^(?P<a>.+?)(?P<op>[%])(?P<b>.+?)$', expr)
  520. if m:
  521. a = interpret_expression(m.group('a'),
  522. local_vars, allow_recursion)
  523. b = interpret_expression(m.group('b'),
  524. local_vars, allow_recursion)
  525. return a % b
  526. m = re.match(
  527. r'^(?P<func>[a-zA-Z]+)\((?P<args>[a-z0-9,]+)\)$', expr)
  528. if m:
  529. fname = m.group('func')
  530. if fname not in functions:
  531. functions[fname] = extract_function(fname)
  532. argvals = [int(v) if v.isdigit() else local_vars[v]
  533. for v in m.group('args').split(',')]
  534. return functions[fname](argvals)
  535. raise ExtractorError(u'Unsupported JS expression %r' % expr)
  536. def extract_function(funcname):
  537. func_m = re.search(
  538. r'function ' + re.escape(funcname) +
  539. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  540. jscode)
  541. argnames = func_m.group('args').split(',')
  542. def resf(args):
  543. local_vars = dict(zip(argnames, args))
  544. for stmt in func_m.group('code').split(';'):
  545. res = interpret_statement(stmt, local_vars)
  546. return res
  547. return resf
  548. initial_function = extract_function(funcname)
  549. return lambda s: initial_function([s])
  550. def _parse_sig_swf(self, file_contents):
  551. if file_contents[1:3] != b'WS':
  552. raise ExtractorError(
  553. u'Not an SWF file; header is %r' % file_contents[:3])
  554. if file_contents[:1] == b'C':
  555. content = zlib.decompress(file_contents[8:])
  556. else:
  557. raise NotImplementedError(u'Unsupported compression format %r' %
  558. file_contents[:1])
  559. def extract_tags(content):
  560. pos = 0
  561. while pos < len(content):
  562. header16 = struct.unpack('<H', content[pos:pos+2])[0]
  563. pos += 2
  564. tag_code = header16 >> 6
  565. tag_len = header16 & 0x3f
  566. if tag_len == 0x3f:
  567. tag_len = struct.unpack('<I', content[pos:pos+4])[0]
  568. pos += 4
  569. assert pos+tag_len <= len(content)
  570. yield (tag_code, content[pos:pos+tag_len])
  571. pos += tag_len
  572. code_tag = next(tag
  573. for tag_code, tag in extract_tags(content)
  574. if tag_code == 82)
  575. p = code_tag.index(b'\0', 4) + 1
  576. code_reader = io.BytesIO(code_tag[p:])
  577. # Parse ABC (AVM2 ByteCode)
  578. def read_int(reader=None):
  579. if reader is None:
  580. reader = code_reader
  581. res = 0
  582. shift = 0
  583. for _ in range(5):
  584. buf = reader.read(1)
  585. assert len(buf) == 1
  586. b = struct.unpack('<B', buf)[0]
  587. res = res | ((b & 0x7f) << shift)
  588. if b & 0x80 == 0:
  589. break
  590. shift += 7
  591. return res
  592. def u30(reader=None):
  593. res = read_int(reader)
  594. assert res & 0xf0000000 == 0
  595. return res
  596. u32 = read_int
  597. def s32(reader=None):
  598. v = read_int(reader)
  599. if v & 0x80000000 != 0:
  600. v = - ((v ^ 0xffffffff) + 1)
  601. return v
  602. def read_string(reader=None):
  603. if reader is None:
  604. reader = code_reader
  605. slen = u30(reader)
  606. resb = reader.read(slen)
  607. assert len(resb) == slen
  608. return resb.decode('utf-8')
  609. def read_bytes(count, reader=None):
  610. if reader is None:
  611. reader = code_reader
  612. resb = reader.read(count)
  613. assert len(resb) == count
  614. return resb
  615. def read_byte(reader=None):
  616. resb = read_bytes(1, reader=reader)
  617. res = struct.unpack('<B', resb)[0]
  618. return res
  619. # minor_version + major_version
  620. read_bytes(2 + 2)
  621. # Constant pool
  622. int_count = u30()
  623. for _c in range(1, int_count):
  624. s32()
  625. uint_count = u30()
  626. for _c in range(1, uint_count):
  627. u32()
  628. double_count = u30()
  629. read_bytes((double_count-1) * 8)
  630. string_count = u30()
  631. constant_strings = [u'']
  632. for _c in range(1, string_count):
  633. s = read_string()
  634. constant_strings.append(s)
  635. namespace_count = u30()
  636. for _c in range(1, namespace_count):
  637. read_bytes(1) # kind
  638. u30() # name
  639. ns_set_count = u30()
  640. for _c in range(1, ns_set_count):
  641. count = u30()
  642. for _c2 in range(count):
  643. u30()
  644. multiname_count = u30()
  645. MULTINAME_SIZES = {
  646. 0x07: 2, # QName
  647. 0x0d: 2, # QNameA
  648. 0x0f: 1, # RTQName
  649. 0x10: 1, # RTQNameA
  650. 0x11: 0, # RTQNameL
  651. 0x12: 0, # RTQNameLA
  652. 0x09: 2, # Multiname
  653. 0x0e: 2, # MultinameA
  654. 0x1b: 1, # MultinameL
  655. 0x1c: 1, # MultinameLA
  656. }
  657. multinames = [u'']
  658. for _c in range(1, multiname_count):
  659. kind = u30()
  660. assert kind in MULTINAME_SIZES, u'Invalid multiname kind %r' % kind
  661. if kind == 0x07:
  662. u30() # namespace_idx
  663. name_idx = u30()
  664. multinames.append(constant_strings[name_idx])
  665. else:
  666. multinames.append('[MULTINAME kind: %d]' % kind)
  667. for _c2 in range(MULTINAME_SIZES[kind]):
  668. u30()
  669. # Methods
  670. method_count = u30()
  671. MethodInfo = collections.namedtuple(
  672. 'MethodInfo',
  673. ['NEED_ARGUMENTS', 'NEED_REST'])
  674. method_infos = []
  675. for method_id in range(method_count):
  676. param_count = u30()
  677. u30() # return type
  678. for _ in range(param_count):
  679. u30() # param type
  680. u30() # name index (always 0 for youtube)
  681. flags = read_byte()
  682. if flags & 0x08 != 0:
  683. # Options present
  684. option_count = u30()
  685. for c in range(option_count):
  686. u30() # val
  687. read_bytes(1) # kind
  688. if flags & 0x80 != 0:
  689. # Param names present
  690. for _ in range(param_count):
  691. u30() # param name
  692. mi = MethodInfo(flags & 0x01 != 0, flags & 0x04 != 0)
  693. method_infos.append(mi)
  694. # Metadata
  695. metadata_count = u30()
  696. for _c in range(metadata_count):
  697. u30() # name
  698. item_count = u30()
  699. for _c2 in range(item_count):
  700. u30() # key
  701. u30() # value
  702. def parse_traits_info():
  703. trait_name_idx = u30()
  704. kind_full = read_byte()
  705. kind = kind_full & 0x0f
  706. attrs = kind_full >> 4
  707. methods = {}
  708. if kind in [0x00, 0x06]: # Slot or Const
  709. u30() # Slot id
  710. u30() # type_name_idx
  711. vindex = u30()
  712. if vindex != 0:
  713. read_byte() # vkind
  714. elif kind in [0x01, 0x02, 0x03]: # Method / Getter / Setter
  715. u30() # disp_id
  716. method_idx = u30()
  717. methods[multinames[trait_name_idx]] = method_idx
  718. elif kind == 0x04: # Class
  719. u30() # slot_id
  720. u30() # classi
  721. elif kind == 0x05: # Function
  722. u30() # slot_id
  723. function_idx = u30()
  724. methods[function_idx] = multinames[trait_name_idx]
  725. else:
  726. raise ExtractorError(u'Unsupported trait kind %d' % kind)
  727. if attrs & 0x4 != 0: # Metadata present
  728. metadata_count = u30()
  729. for _c3 in range(metadata_count):
  730. u30() # metadata index
  731. return methods
  732. # Classes
  733. TARGET_CLASSNAME = u'SignatureDecipher'
  734. searched_idx = multinames.index(TARGET_CLASSNAME)
  735. searched_class_id = None
  736. class_count = u30()
  737. for class_id in range(class_count):
  738. name_idx = u30()
  739. if name_idx == searched_idx:
  740. # We found the class we're looking for!
  741. searched_class_id = class_id
  742. u30() # super_name idx
  743. flags = read_byte()
  744. if flags & 0x08 != 0: # Protected namespace is present
  745. u30() # protected_ns_idx
  746. intrf_count = u30()
  747. for _c2 in range(intrf_count):
  748. u30()
  749. u30() # iinit
  750. trait_count = u30()
  751. for _c2 in range(trait_count):
  752. parse_traits_info()
  753. if searched_class_id is None:
  754. raise ExtractorError(u'Target class %r not found' %
  755. TARGET_CLASSNAME)
  756. method_names = {}
  757. method_idxs = {}
  758. for class_id in range(class_count):
  759. u30() # cinit
  760. trait_count = u30()
  761. for _c2 in range(trait_count):
  762. trait_methods = parse_traits_info()
  763. if class_id == searched_class_id:
  764. method_names.update(trait_methods.items())
  765. method_idxs.update(dict(
  766. (idx, name)
  767. for name, idx in trait_methods.items()))
  768. # Scripts
  769. script_count = u30()
  770. for _c in range(script_count):
  771. u30() # init
  772. trait_count = u30()
  773. for _c2 in range(trait_count):
  774. parse_traits_info()
  775. # Method bodies
  776. method_body_count = u30()
  777. Method = collections.namedtuple('Method', ['code', 'local_count'])
  778. methods = {}
  779. for _c in range(method_body_count):
  780. method_idx = u30()
  781. u30() # max_stack
  782. local_count = u30()
  783. u30() # init_scope_depth
  784. u30() # max_scope_depth
  785. code_length = u30()
  786. code = read_bytes(code_length)
  787. if method_idx in method_idxs:
  788. m = Method(code, local_count)
  789. methods[method_idxs[method_idx]] = m
  790. exception_count = u30()
  791. for _c2 in range(exception_count):
  792. u30() # from
  793. u30() # to
  794. u30() # target
  795. u30() # exc_type
  796. u30() # var_name
  797. trait_count = u30()
  798. for _c2 in range(trait_count):
  799. parse_traits_info()
  800. assert p + code_reader.tell() == len(code_tag)
  801. assert len(methods) == len(method_idxs)
  802. method_pyfunctions = {}
  803. def extract_function(func_name):
  804. if func_name in method_pyfunctions:
  805. return method_pyfunctions[func_name]
  806. if func_name not in methods:
  807. raise ExtractorError(u'Cannot find function %r' % func_name)
  808. m = methods[func_name]
  809. def resfunc(args):
  810. registers = ['(this)'] + list(args) + [None] * m.local_count
  811. stack = []
  812. coder = io.BytesIO(m.code)
  813. while True:
  814. opcode = struct.unpack('!B', coder.read(1))[0]
  815. if opcode == 36: # pushbyte
  816. v = struct.unpack('!B', coder.read(1))[0]
  817. stack.append(v)
  818. elif opcode == 44: # pushstring
  819. idx = u30(coder)
  820. stack.append(constant_strings[idx])
  821. elif opcode == 48: # pushscope
  822. # We don't implement the scope register, so we'll just
  823. # ignore the popped value
  824. stack.pop()
  825. elif opcode == 70: # callproperty
  826. index = u30(coder)
  827. mname = multinames[index]
  828. arg_count = u30(coder)
  829. args = list(reversed(
  830. [stack.pop() for _ in range(arg_count)]))
  831. obj = stack.pop()
  832. if mname == u'split':
  833. assert len(args) == 1
  834. assert isinstance(args[0], compat_str)
  835. assert isinstance(obj, compat_str)
  836. if args[0] == u'':
  837. res = list(obj)
  838. else:
  839. res = obj.split(args[0])
  840. stack.append(res)
  841. elif mname == u'slice':
  842. assert len(args) == 1
  843. assert isinstance(args[0], int)
  844. assert isinstance(obj, list)
  845. res = obj[args[0]:]
  846. stack.append(res)
  847. elif mname == u'join':
  848. assert len(args) == 1
  849. assert isinstance(args[0], compat_str)
  850. assert isinstance(obj, list)
  851. res = args[0].join(obj)
  852. stack.append(res)
  853. elif mname in method_pyfunctions:
  854. stack.append(method_pyfunctions[mname](args))
  855. else:
  856. raise NotImplementedError(
  857. u'Unsupported property %r on %r'
  858. % (mname, obj))
  859. elif opcode == 72: # returnvalue
  860. res = stack.pop()
  861. return res
  862. elif opcode == 79: # callpropvoid
  863. index = u30(coder)
  864. mname = multinames[index]
  865. arg_count = u30(coder)
  866. args = list(reversed(
  867. [stack.pop() for _ in range(arg_count)]))
  868. obj = stack.pop()
  869. if mname == u'reverse':
  870. assert isinstance(obj, list)
  871. obj.reverse()
  872. else:
  873. raise NotImplementedError(
  874. u'Unsupported (void) property %r on %r'
  875. % (mname, obj))
  876. elif opcode == 93: # findpropstrict
  877. index = u30(coder)
  878. mname = multinames[index]
  879. res = extract_function(mname)
  880. stack.append(res)
  881. elif opcode == 97: # setproperty
  882. index = u30(coder)
  883. value = stack.pop()
  884. idx = stack.pop()
  885. obj = stack.pop()
  886. assert isinstance(obj, list)
  887. assert isinstance(idx, int)
  888. obj[idx] = value
  889. elif opcode == 98: # getlocal
  890. index = u30(coder)
  891. stack.append(registers[index])
  892. elif opcode == 99: # setlocal
  893. index = u30(coder)
  894. value = stack.pop()
  895. registers[index] = value
  896. elif opcode == 102: # getproperty
  897. index = u30(coder)
  898. pname = multinames[index]
  899. if pname == u'length':
  900. obj = stack.pop()
  901. assert isinstance(obj, list)
  902. stack.append(len(obj))
  903. else: # Assume attribute access
  904. idx = stack.pop()
  905. assert isinstance(idx, int)
  906. obj = stack.pop()
  907. assert isinstance(obj, list)
  908. stack.append(obj[idx])
  909. elif opcode == 128: # coerce
  910. u30(coder)
  911. elif opcode == 133: # coerce_s
  912. assert isinstance(stack[-1], (type(None), compat_str))
  913. elif opcode == 164: # modulo
  914. value2 = stack.pop()
  915. value1 = stack.pop()
  916. res = value1 % value2
  917. stack.append(res)
  918. elif opcode == 208: # getlocal_0
  919. stack.append(registers[0])
  920. elif opcode == 209: # getlocal_1
  921. stack.append(registers[1])
  922. elif opcode == 210: # getlocal_2
  923. stack.append(registers[2])
  924. elif opcode == 211: # getlocal_3
  925. stack.append(registers[3])
  926. elif opcode == 214: # setlocal_2
  927. registers[2] = stack.pop()
  928. elif opcode == 215: # setlocal_3
  929. registers[3] = stack.pop()
  930. else:
  931. raise NotImplementedError(
  932. u'Unsupported opcode %d' % opcode)
  933. method_pyfunctions[func_name] = resfunc
  934. return resfunc
  935. initial_function = extract_function(u'decipher')
  936. return lambda s: initial_function([s])
  937. def _decrypt_signature(self, s, video_id, player_url, age_gate=False):
  938. """Turn the encrypted s field into a working signature"""
  939. if player_url is not None:
  940. if player_url.startswith(u'//'):
  941. player_url = u'https:' + player_url
  942. try:
  943. player_id = (player_url, len(s))
  944. if player_id not in self._player_cache:
  945. func = self._extract_signature_function(
  946. video_id, player_url, len(s)
  947. )
  948. self._player_cache[player_id] = func
  949. func = self._player_cache[player_id]
  950. if self._downloader.params.get('youtube_print_sig_code'):
  951. self._print_sig_code(func, len(s))
  952. return func(s)
  953. except Exception:
  954. tb = traceback.format_exc()
  955. self._downloader.report_warning(
  956. u'Automatic signature extraction failed: ' + tb)
  957. self._downloader.report_warning(
  958. u'Warning: Falling back to static signature algorithm')
  959. return self._static_decrypt_signature(
  960. s, video_id, player_url, age_gate)
  961. def _static_decrypt_signature(self, s, video_id, player_url, age_gate):
  962. if age_gate:
  963. # The videos with age protection use another player, so the
  964. # algorithms can be different.
  965. if len(s) == 86:
  966. return s[2:63] + s[82] + s[64:82] + s[63]
  967. if len(s) == 93:
  968. return s[86:29:-1] + s[88] + s[28:5:-1]
  969. elif len(s) == 92:
  970. return s[25] + s[3:25] + s[0] + s[26:42] + s[79] + s[43:79] + s[91] + s[80:83]
  971. elif len(s) == 91:
  972. return s[84:27:-1] + s[86] + s[26:5:-1]
  973. elif len(s) == 90:
  974. return s[25] + s[3:25] + s[2] + s[26:40] + s[77] + s[41:77] + s[89] + s[78:81]
  975. elif len(s) == 89:
  976. return s[84:78:-1] + s[87] + s[77:60:-1] + s[0] + s[59:3:-1]
  977. elif len(s) == 88:
  978. return s[7:28] + s[87] + s[29:45] + s[55] + s[46:55] + s[2] + s[56:87] + s[28]
  979. elif len(s) == 87:
  980. return s[6:27] + s[4] + s[28:39] + s[27] + s[40:59] + s[2] + s[60:]
  981. elif len(s) == 86:
  982. return s[80:72:-1] + s[16] + s[71:39:-1] + s[72] + s[38:16:-1] + s[82] + s[15::-1]
  983. elif len(s) == 85:
  984. return s[3:11] + s[0] + s[12:55] + s[84] + s[56:84]
  985. elif len(s) == 84:
  986. return s[78:70:-1] + s[14] + s[69:37:-1] + s[70] + s[36:14:-1] + s[80] + s[:14][::-1]
  987. elif len(s) == 83:
  988. return s[80:63:-1] + s[0] + s[62:0:-1] + s[63]
  989. elif len(s) == 82:
  990. return s[80:37:-1] + s[7] + s[36:7:-1] + s[0] + s[6:0:-1] + s[37]
  991. elif len(s) == 81:
  992. return s[56] + s[79:56:-1] + s[41] + s[55:41:-1] + s[80] + s[40:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  993. elif len(s) == 80:
  994. return s[1:19] + s[0] + s[20:68] + s[19] + s[69:80]
  995. elif len(s) == 79:
  996. return s[54] + s[77:54:-1] + s[39] + s[53:39:-1] + s[78] + s[38:34:-1] + s[0] + s[33:29:-1] + s[34] + s[28:9:-1] + s[29] + s[8:0:-1] + s[9]
  997. else:
  998. raise ExtractorError(u'Unable to decrypt signature, key length %d not supported; retrying might work' % (len(s)))
  999. def _get_available_subtitles(self, video_id, webpage):
  1000. try:
  1001. sub_list = self._download_webpage(
  1002. 'http://video.google.com/timedtext?hl=en&type=list&v=%s' % video_id,
  1003. video_id, note=False)
  1004. except ExtractorError as err:
  1005. self._downloader.report_warning(u'unable to download video subtitles: %s' % compat_str(err))
  1006. return {}
  1007. lang_list = re.findall(r'name="([^"]*)"[^>]+lang_code="([\w\-]+)"', sub_list)
  1008. sub_lang_list = {}
  1009. for l in lang_list:
  1010. lang = l[1]
  1011. params = compat_urllib_parse.urlencode({
  1012. 'lang': lang,
  1013. 'v': video_id,
  1014. 'fmt': self._downloader.params.get('subtitlesformat', 'srt'),
  1015. 'name': l[0].encode('utf-8'),
  1016. })
  1017. url = u'http://www.youtube.com/api/timedtext?' + params
  1018. sub_lang_list[lang] = url
  1019. if not sub_lang_list:
  1020. self._downloader.report_warning(u'video doesn\'t have subtitles')
  1021. return {}
  1022. return sub_lang_list
  1023. def _get_available_automatic_caption(self, video_id, webpage):
  1024. """We need the webpage for getting the captions url, pass it as an
  1025. argument to speed up the process."""
  1026. sub_format = self._downloader.params.get('subtitlesformat', 'srt')
  1027. self.to_screen(u'%s: Looking for automatic captions' % video_id)
  1028. mobj = re.search(r';ytplayer.config = ({.*?});', webpage)
  1029. err_msg = u'Couldn\'t find automatic captions for %s' % video_id
  1030. if mobj is None:
  1031. self._downloader.report_warning(err_msg)
  1032. return {}
  1033. player_config = json.loads(mobj.group(1))
  1034. try:
  1035. args = player_config[u'args']
  1036. caption_url = args[u'ttsurl']
  1037. timestamp = args[u'timestamp']
  1038. # We get the available subtitles
  1039. list_params = compat_urllib_parse.urlencode({
  1040. 'type': 'list',
  1041. 'tlangs': 1,
  1042. 'asrs': 1,
  1043. })
  1044. list_url = caption_url + '&' + list_params
  1045. caption_list = self._download_xml(list_url, video_id)
  1046. original_lang_node = caption_list.find('track')
  1047. if original_lang_node is None or original_lang_node.attrib.get('kind') != 'asr' :
  1048. self._downloader.report_warning(u'Video doesn\'t have automatic captions')
  1049. return {}
  1050. original_lang = original_lang_node.attrib['lang_code']
  1051. sub_lang_list = {}
  1052. for lang_node in caption_list.findall('target'):
  1053. sub_lang = lang_node.attrib['lang_code']
  1054. params = compat_urllib_parse.urlencode({
  1055. 'lang': original_lang,
  1056. 'tlang': sub_lang,
  1057. 'fmt': sub_format,
  1058. 'ts': timestamp,
  1059. 'kind': 'asr',
  1060. })
  1061. sub_lang_list[sub_lang] = caption_url + '&' + params
  1062. return sub_lang_list
  1063. # An extractor error can be raise by the download process if there are
  1064. # no automatic captions but there are subtitles
  1065. except (KeyError, ExtractorError):
  1066. self._downloader.report_warning(err_msg)
  1067. return {}
  1068. def _print_formats(self, formats):
  1069. print('Available formats:')
  1070. for x in formats:
  1071. print('%s\t:\t%s\t[%s]%s' %(x, self._video_extensions.get(x, 'flv'),
  1072. self._video_dimensions.get(x, '???'),
  1073. ' ('+self._special_itags[x]+')' if x in self._special_itags else ''))
  1074. def _extract_id(self, url):
  1075. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1076. if mobj is None:
  1077. raise ExtractorError(u'Invalid URL: %s' % url)
  1078. video_id = mobj.group(2)
  1079. return video_id
  1080. def _get_video_url_list(self, url_map):
  1081. """
  1082. Transform a dictionary in the format {itag:url} to a list of (itag, url)
  1083. with the requested formats.
  1084. """
  1085. req_format = self._downloader.params.get('format', None)
  1086. format_limit = self._downloader.params.get('format_limit', None)
  1087. available_formats = self._available_formats_prefer_free if self._downloader.params.get('prefer_free_formats', False) else self._available_formats
  1088. if format_limit is not None and format_limit in available_formats:
  1089. format_list = available_formats[available_formats.index(format_limit):]
  1090. else:
  1091. format_list = available_formats
  1092. existing_formats = [x for x in format_list if x in url_map]
  1093. if len(existing_formats) == 0:
  1094. raise ExtractorError(u'no known formats available for video')
  1095. if self._downloader.params.get('listformats', None):
  1096. self._print_formats(existing_formats)
  1097. return
  1098. if req_format is None or req_format == 'best':
  1099. video_url_list = [(existing_formats[0], url_map[existing_formats[0]])] # Best quality
  1100. elif req_format == 'worst':
  1101. video_url_list = [(existing_formats[-1], url_map[existing_formats[-1]])] # worst quality
  1102. elif req_format in ('-1', 'all'):
  1103. video_url_list = [(f, url_map[f]) for f in existing_formats] # All formats
  1104. else:
  1105. # Specific formats. We pick the first in a slash-delimeted sequence.
  1106. # Format can be specified as itag or 'mp4' or 'flv' etc. We pick the highest quality
  1107. # available in the specified format. For example,
  1108. # if '1/2/3/4' is requested and '2' and '4' are available, we pick '2'.
  1109. # if '1/mp4/3/4' is requested and '1' and '5' (is a mp4) are available, we pick '1'.
  1110. # if '1/mp4/3/4' is requested and '4' and '5' (is a mp4) are available, we pick '5'.
  1111. req_formats = req_format.split('/')
  1112. video_url_list = None
  1113. for rf in req_formats:
  1114. if rf in url_map:
  1115. video_url_list = [(rf, url_map[rf])]
  1116. break
  1117. if rf in self._video_formats_map:
  1118. for srf in self._video_formats_map[rf]:
  1119. if srf in url_map:
  1120. video_url_list = [(srf, url_map[srf])]
  1121. break
  1122. else:
  1123. continue
  1124. break
  1125. if video_url_list is None:
  1126. raise ExtractorError(u'requested format not available')
  1127. return video_url_list
  1128. def _extract_from_m3u8(self, manifest_url, video_id):
  1129. url_map = {}
  1130. def _get_urls(_manifest):
  1131. lines = _manifest.split('\n')
  1132. urls = filter(lambda l: l and not l.startswith('#'),
  1133. lines)
  1134. return urls
  1135. manifest = self._download_webpage(manifest_url, video_id, u'Downloading formats manifest')
  1136. formats_urls = _get_urls(manifest)
  1137. for format_url in formats_urls:
  1138. itag = self._search_regex(r'itag/(\d+?)/', format_url, 'itag')
  1139. url_map[itag] = format_url
  1140. return url_map
  1141. def _extract_annotations(self, video_id):
  1142. url = 'https://www.youtube.com/annotations_invideo?features=1&legacy=1&video_id=%s' % video_id
  1143. return self._download_webpage(url, video_id, note=u'Searching for annotations.', errnote=u'Unable to download video annotations.')
  1144. def _real_extract(self, url):
  1145. # Extract original video URL from URL with redirection, like age verification, using next_url parameter
  1146. mobj = re.search(self._NEXT_URL_RE, url)
  1147. if mobj:
  1148. url = 'https://www.youtube.com/' + compat_urllib_parse.unquote(mobj.group(1)).lstrip('/')
  1149. video_id = self._extract_id(url)
  1150. # Get video webpage
  1151. url = 'https://www.youtube.com/watch?v=%s&gl=US&hl=en&has_verified=1' % video_id
  1152. video_webpage = self._download_webpage(url, video_id)
  1153. # Attempt to extract SWF player URL
  1154. mobj = re.search(r'swfConfig.*?"(https?:\\/\\/.*?watch.*?-.*?\.swf)"', video_webpage)
  1155. if mobj is not None:
  1156. player_url = re.sub(r'\\(.)', r'\1', mobj.group(1))
  1157. else:
  1158. player_url = None
  1159. # Get video info
  1160. self.report_video_info_webpage_download(video_id)
  1161. if re.search(r'player-age-gate-content">', video_webpage) is not None:
  1162. self.report_age_confirmation()
  1163. age_gate = True
  1164. # We simulate the access to the video from www.youtube.com/v/{video_id}
  1165. # this can be viewed without login into Youtube
  1166. data = compat_urllib_parse.urlencode({'video_id': video_id,
  1167. 'el': 'player_embedded',
  1168. 'gl': 'US',
  1169. 'hl': 'en',
  1170. 'eurl': 'https://youtube.googleapis.com/v/' + video_id,
  1171. 'asv': 3,
  1172. 'sts':'1588',
  1173. })
  1174. video_info_url = 'https://www.youtube.com/get_video_info?' + data
  1175. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1176. note=False,
  1177. errnote='unable to download video info webpage')
  1178. video_info = compat_parse_qs(video_info_webpage)
  1179. else:
  1180. age_gate = False
  1181. for el_type in ['&el=embedded', '&el=detailpage', '&el=vevo', '']:
  1182. video_info_url = ('https://www.youtube.com/get_video_info?&video_id=%s%s&ps=default&eurl=&gl=US&hl=en'
  1183. % (video_id, el_type))
  1184. video_info_webpage = self._download_webpage(video_info_url, video_id,
  1185. note=False,
  1186. errnote='unable to download video info webpage')
  1187. video_info = compat_parse_qs(video_info_webpage)
  1188. if 'token' in video_info:
  1189. break
  1190. if 'token' not in video_info:
  1191. if 'reason' in video_info:
  1192. raise ExtractorError(u'YouTube said: %s' % video_info['reason'][0], expected=True)
  1193. else:
  1194. raise ExtractorError(u'"token" parameter not in video info for unknown reason')
  1195. if 'view_count' in video_info:
  1196. view_count = int(video_info['view_count'][0])
  1197. else:
  1198. view_count = None
  1199. # Check for "rental" videos
  1200. if 'ypc_video_rental_bar_text' in video_info and 'author' not in video_info:
  1201. raise ExtractorError(u'"rental" videos not supported')
  1202. # Start extracting information
  1203. self.report_information_extraction(video_id)
  1204. # uploader
  1205. if 'author' not in video_info:
  1206. raise ExtractorError(u'Unable to extract uploader name')
  1207. video_uploader = compat_urllib_parse.unquote_plus(video_info['author'][0])
  1208. # uploader_id
  1209. video_uploader_id = None
  1210. mobj = re.search(r'<link itemprop="url" href="http://www.youtube.com/(?:user|channel)/([^"]+)">', video_webpage)
  1211. if mobj is not None:
  1212. video_uploader_id = mobj.group(1)
  1213. else:
  1214. self._downloader.report_warning(u'unable to extract uploader nickname')
  1215. # title
  1216. if 'title' in video_info:
  1217. video_title = compat_urllib_parse.unquote_plus(video_info['title'][0])
  1218. else:
  1219. self._downloader.report_warning(u'Unable to extract video title')
  1220. video_title = u'_'
  1221. # thumbnail image
  1222. # We try first to get a high quality image:
  1223. m_thumb = re.search(r'<span itemprop="thumbnail".*?href="(.*?)">',
  1224. video_webpage, re.DOTALL)
  1225. if m_thumb is not None:
  1226. video_thumbnail = m_thumb.group(1)
  1227. elif 'thumbnail_url' not in video_info:
  1228. self._downloader.report_warning(u'unable to extract video thumbnail')
  1229. video_thumbnail = None
  1230. else: # don't panic if we can't find it
  1231. video_thumbnail = compat_urllib_parse.unquote_plus(video_info['thumbnail_url'][0])
  1232. # upload date
  1233. upload_date = None
  1234. mobj = re.search(r'id="eow-date.*?>(.*?)</span>', video_webpage, re.DOTALL)
  1235. if mobj is not None:
  1236. upload_date = ' '.join(re.sub(r'[/,-]', r' ', mobj.group(1)).split())
  1237. upload_date = unified_strdate(upload_date)
  1238. # description
  1239. video_description = get_element_by_id("eow-description", video_webpage)
  1240. if video_description:
  1241. video_description = re.sub(r'''(?x)
  1242. <a\s+
  1243. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1244. title="([^"]+)"\s+
  1245. (?:[a-zA-Z-]+="[^"]+"\s+)*?
  1246. class="yt-uix-redirect-link"\s*>
  1247. [^<]+
  1248. </a>
  1249. ''', r'\1', video_description)
  1250. video_description = clean_html(video_description)
  1251. else:
  1252. fd_mobj = re.search(r'<meta name="description" content="([^"]+)"', video_webpage)
  1253. if fd_mobj:
  1254. video_description = unescapeHTML(fd_mobj.group(1))
  1255. else:
  1256. video_description = u''
  1257. def _extract_count(klass):
  1258. count = self._search_regex(r'class="%s">([\d,]+)</span>' % re.escape(klass), video_webpage, klass, fatal=False)
  1259. if count is not None:
  1260. return int(count.replace(',', ''))
  1261. return None
  1262. like_count = _extract_count(u'likes-count')
  1263. dislike_count = _extract_count(u'dislikes-count')
  1264. # subtitles
  1265. video_subtitles = self.extract_subtitles(video_id, video_webpage)
  1266. if self._downloader.params.get('listsubtitles', False):
  1267. self._list_available_subtitles(video_id, video_webpage)
  1268. return
  1269. if 'length_seconds' not in video_info:
  1270. self._downloader.report_warning(u'unable to extract video duration')
  1271. video_duration = ''
  1272. else:
  1273. video_duration = compat_urllib_parse.unquote_plus(video_info['length_seconds'][0])
  1274. # annotations
  1275. video_annotations = None
  1276. if self._downloader.params.get('writeannotations', False):
  1277. video_annotations = self._extract_annotations(video_id)
  1278. # Decide which formats to download
  1279. try:
  1280. mobj = re.search(r';ytplayer.config = ({.*?});', video_webpage)
  1281. if not mobj:
  1282. raise ValueError('Could not find vevo ID')
  1283. info = json.loads(mobj.group(1))
  1284. args = info['args']
  1285. # Easy way to know if the 's' value is in url_encoded_fmt_stream_map
  1286. # this signatures are encrypted
  1287. if 'url_encoded_fmt_stream_map' not in args:
  1288. raise ValueError(u'No stream_map present') # caught below
  1289. re_signature = re.compile(r'[&,]s=')
  1290. m_s = re_signature.search(args['url_encoded_fmt_stream_map'])
  1291. if m_s is not None:
  1292. self.to_screen(u'%s: Encrypted signatures detected.' % video_id)
  1293. video_info['url_encoded_fmt_stream_map'] = [args['url_encoded_fmt_stream_map']]
  1294. m_s = re_signature.search(args.get('adaptive_fmts', u''))
  1295. if m_s is not None:
  1296. if 'adaptive_fmts' in video_info:
  1297. video_info['adaptive_fmts'][0] += ',' + args['adaptive_fmts']
  1298. else:
  1299. video_info['adaptive_fmts'] = [args['adaptive_fmts']]
  1300. except ValueError:
  1301. pass
  1302. if 'conn' in video_info and video_info['conn'][0].startswith('rtmp'):
  1303. self.report_rtmp_download()
  1304. video_url_list = [(None, video_info['conn'][0])]
  1305. elif len(video_info.get('url_encoded_fmt_stream_map', [])) >= 1 or len(video_info.get('adaptive_fmts', [])) >= 1:
  1306. encoded_url_map = video_info.get('url_encoded_fmt_stream_map', [''])[0] + ',' + video_info.get('adaptive_fmts',[''])[0]
  1307. if 'rtmpe%3Dyes' in encoded_url_map:
  1308. raise ExtractorError('rtmpe downloads are not supported, see https://github.com/rg3/youtube-dl/issues/343 for more information.', expected=True)
  1309. url_map = {}
  1310. for url_data_str in encoded_url_map.split(','):
  1311. url_data = compat_parse_qs(url_data_str)
  1312. if 'itag' in url_data and 'url' in url_data:
  1313. url = url_data['url'][0]
  1314. if 'sig' in url_data:
  1315. url += '&signature=' + url_data['sig'][0]
  1316. elif 's' in url_data:
  1317. encrypted_sig = url_data['s'][0]
  1318. if self._downloader.params.get('verbose'):
  1319. if age_gate:
  1320. if player_url is None:
  1321. player_version = 'unknown'
  1322. else:
  1323. player_version = self._search_regex(
  1324. r'-(.+)\.swf$', player_url,
  1325. u'flash player', fatal=False)
  1326. player_desc = 'flash player %s' % player_version
  1327. else:
  1328. player_version = self._search_regex(
  1329. r'html5player-(.+?)\.js', video_webpage,
  1330. 'html5 player', fatal=False)
  1331. player_desc = u'html5 player %s' % player_version
  1332. parts_sizes = u'.'.join(compat_str(len(part)) for part in encrypted_sig.split('.'))
  1333. self.to_screen(u'encrypted signature length %d (%s), itag %s, %s' %
  1334. (len(encrypted_sig), parts_sizes, url_data['itag'][0], player_desc))
  1335. if not age_gate:
  1336. jsplayer_url_json = self._search_regex(
  1337. r'"assets":.+?"js":\s*("[^"]+")',
  1338. video_webpage, u'JS player URL')
  1339. player_url = json.loads(jsplayer_url_json)
  1340. signature = self._decrypt_signature(
  1341. encrypted_sig, video_id, player_url, age_gate)
  1342. url += '&signature=' + signature
  1343. if 'ratebypass' not in url:
  1344. url += '&ratebypass=yes'
  1345. url_map[url_data['itag'][0]] = url
  1346. video_url_list = self._get_video_url_list(url_map)
  1347. if not video_url_list:
  1348. return
  1349. elif video_info.get('hlsvp'):
  1350. manifest_url = video_info['hlsvp'][0]
  1351. url_map = self._extract_from_m3u8(manifest_url, video_id)
  1352. video_url_list = self._get_video_url_list(url_map)
  1353. if not video_url_list:
  1354. return
  1355. else:
  1356. raise ExtractorError(u'no conn, hlsvp or url_encoded_fmt_stream_map information found in video info')
  1357. results = []
  1358. for itag, video_real_url in video_url_list:
  1359. # Extension
  1360. video_extension = self._video_extensions.get(itag, 'flv')
  1361. video_format = '{0} - {1}{2}'.format(itag if itag else video_extension,
  1362. self._video_dimensions.get(itag, '???'),
  1363. ' ('+self._special_itags[itag]+')' if itag in self._special_itags else '')
  1364. results.append({
  1365. 'id': video_id,
  1366. 'url': video_real_url,
  1367. 'uploader': video_uploader,
  1368. 'uploader_id': video_uploader_id,
  1369. 'upload_date': upload_date,
  1370. 'title': video_title,
  1371. 'ext': video_extension,
  1372. 'format': video_format,
  1373. 'format_id': itag,
  1374. 'thumbnail': video_thumbnail,
  1375. 'description': video_description,
  1376. 'player_url': player_url,
  1377. 'subtitles': video_subtitles,
  1378. 'duration': video_duration,
  1379. 'age_limit': 18 if age_gate else 0,
  1380. 'annotations': video_annotations,
  1381. 'webpage_url': 'https://www.youtube.com/watch?v=%s' % video_id,
  1382. 'view_count': view_count,
  1383. 'like_count': like_count,
  1384. 'dislike_count': dislike_count,
  1385. })
  1386. return results
  1387. class YoutubePlaylistIE(YoutubeBaseInfoExtractor):
  1388. IE_DESC = u'YouTube.com playlists'
  1389. _VALID_URL = r"""(?:
  1390. (?:https?://)?
  1391. (?:\w+\.)?
  1392. youtube\.com/
  1393. (?:
  1394. (?:course|view_play_list|my_playlists|artist|playlist|watch)
  1395. \? (?:.*?&)*? (?:p|a|list)=
  1396. | p/
  1397. )
  1398. ((?:PL|EC|UU|FL|RD)?[0-9A-Za-z-_]{10,})
  1399. .*
  1400. |
  1401. ((?:PL|EC|UU|FL|RD)[0-9A-Za-z-_]{10,})
  1402. )"""
  1403. _TEMPLATE_URL = 'https://www.youtube.com/playlist?list=%s&page=%s'
  1404. _MORE_PAGES_INDICATOR = r'data-link-type="next"'
  1405. _VIDEO_RE = r'href="/watch\?v=(?P<id>[0-9A-Za-z_-]{11})&amp;[^"]*?index=(?P<index>\d+)'
  1406. IE_NAME = u'youtube:playlist'
  1407. @classmethod
  1408. def suitable(cls, url):
  1409. """Receives a URL and returns True if suitable for this IE."""
  1410. return re.match(cls._VALID_URL, url, re.VERBOSE) is not None
  1411. def _real_initialize(self):
  1412. self._login()
  1413. def _ids_to_results(self, ids):
  1414. return [self.url_result(vid_id, 'Youtube', video_id=vid_id)
  1415. for vid_id in ids]
  1416. def _extract_mix(self, playlist_id):
  1417. # The mixes are generated from a a single video
  1418. # the id of the playlist is just 'RD' + video_id
  1419. url = 'https://youtube.com/watch?v=%s&list=%s' % (playlist_id[-11:], playlist_id)
  1420. webpage = self._download_webpage(url, playlist_id, u'Downloading Youtube mix')
  1421. title_span = (get_element_by_attribute('class', 'title long-title', webpage) or
  1422. get_element_by_attribute('class', 'title ', webpage))
  1423. title = clean_html(title_span)
  1424. video_re = r'data-index="\d+".*?href="/watch\?v=([0-9A-Za-z_-]{11})&amp;[^"]*?list=%s' % re.escape(playlist_id)
  1425. ids = orderedSet(re.findall(video_re, webpage))
  1426. url_results = self._ids_to_results(ids)
  1427. return self.playlist_result(url_results, playlist_id, title)
  1428. def _real_extract(self, url):
  1429. # Extract playlist id
  1430. mobj = re.match(self._VALID_URL, url, re.VERBOSE)
  1431. if mobj is None:
  1432. raise ExtractorError(u'Invalid URL: %s' % url)
  1433. playlist_id = mobj.group(1) or mobj.group(2)
  1434. # Check if it's a video-specific URL
  1435. query_dict = compat_urlparse.parse_qs(compat_urlparse.urlparse(url).query)
  1436. if 'v' in query_dict:
  1437. video_id = query_dict['v'][0]
  1438. if self._downloader.params.get('noplaylist'):
  1439. self.to_screen(u'Downloading just video %s because of --no-playlist' % video_id)
  1440. return self.url_result(video_id, 'Youtube', video_id=video_id)
  1441. else:
  1442. self.to_screen(u'Downloading playlist PL%s - add --no-playlist to just download video %s' % (playlist_id, video_id))
  1443. if playlist_id.startswith('RD'):
  1444. # Mixes require a custom extraction process
  1445. return self._extract_mix(playlist_id)
  1446. # Extract the video ids from the playlist pages
  1447. ids = []
  1448. for page_num in itertools.count(1):
  1449. url = self._TEMPLATE_URL % (playlist_id, page_num)
  1450. page = self._download_webpage(url, playlist_id, u'Downloading page #%s' % page_num)
  1451. matches = re.finditer(self._VIDEO_RE, page)
  1452. # We remove the duplicates and the link with index 0
  1453. # (it's not the first video of the playlist)
  1454. new_ids = orderedSet(m.group('id') for m in matches if m.group('index') != '0')
  1455. ids.extend(new_ids)
  1456. if re.search(self._MORE_PAGES_INDICATOR, page) is None:
  1457. break
  1458. playlist_title = self._og_search_title(page)
  1459. url_results = self._ids_to_results(ids)
  1460. return self.playlist_result(url_results, playlist_id, playlist_title)
  1461. class YoutubeChannelIE(InfoExtractor):
  1462. IE_DESC = u'YouTube.com channels'
  1463. _VALID_URL = r"^(?:https?://)?(?:youtu\.be|(?:\w+\.)?youtube(?:-nocookie)?\.com)/channel/([0-9A-Za-z_-]+)"
  1464. _MORE_PAGES_INDICATOR = 'yt-uix-load-more'
  1465. _MORE_PAGES_URL = 'http://www.youtube.com/c4_browse_ajax?action_load_more_videos=1&flow=list&paging=%s&view=0&sort=da&channel_id=%s'
  1466. IE_NAME = u'youtube:channel'
  1467. def extract_videos_from_page(self, page):
  1468. ids_in_page = []
  1469. for mobj in re.finditer(r'href="/watch\?v=([0-9A-Za-z_-]+)&?', page):
  1470. if mobj.group(1) not in ids_in_page:
  1471. ids_in_page.append(mobj.group(1))
  1472. return ids_in_page
  1473. def _real_extract(self, url):
  1474. # Extract channel id
  1475. mobj = re.match(self._VALID_URL, url)
  1476. if mobj is None:
  1477. raise ExtractorError(u'Invalid URL: %s' % url)
  1478. # Download channel page
  1479. channel_id = mobj.group(1)
  1480. video_ids = []
  1481. url = 'https://www.youtube.com/channel/%s/videos' % channel_id
  1482. channel_page = self._download_webpage(url, channel_id)
  1483. autogenerated = re.search(r'''(?x)
  1484. class="[^"]*?(?:
  1485. channel-header-autogenerated-label|
  1486. yt-channel-title-autogenerated
  1487. )[^"]*"''', channel_page) is not None
  1488. if autogenerated:
  1489. # The videos are contained in a single page
  1490. # the ajax pages can't be used, they are empty
  1491. video_ids = self.extract_videos_from_page(channel_page)
  1492. else:
  1493. # Download all channel pages using the json-based channel_ajax query
  1494. for pagenum in itertools.count(1):
  1495. url = self._MORE_PAGES_URL % (pagenum, channel_id)
  1496. page = self._download_webpage(url, channel_id,
  1497. u'Downloading page #%s' % pagenum)
  1498. page = json.loads(page)
  1499. ids_in_page = self.extract_videos_from_page(page['content_html'])
  1500. video_ids.extend(ids_in_page)
  1501. if self._MORE_PAGES_INDICATOR not in page['load_more_widget_html']:
  1502. break
  1503. self._downloader.to_screen(u'[youtube] Channel %s: Found %i videos' % (channel_id, len(video_ids)))
  1504. url_entries = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1505. for video_id in video_ids]
  1506. return self.playlist_result(url_entries, channel_id)
  1507. class YoutubeUserIE(InfoExtractor):
  1508. IE_DESC = u'YouTube.com user videos (URL or "ytuser" keyword)'
  1509. _VALID_URL = r'(?:(?:(?:https?://)?(?:\w+\.)?youtube\.com/(?:user/)?(?!(?:attribution_link|watch)(?:$|[^a-z_A-Z0-9-])))|ytuser:)(?!feed/)([A-Za-z0-9_-]+)'
  1510. _TEMPLATE_URL = 'http://gdata.youtube.com/feeds/api/users/%s'
  1511. _GDATA_PAGE_SIZE = 50
  1512. _GDATA_URL = 'http://gdata.youtube.com/feeds/api/users/%s/uploads?max-results=%d&start-index=%d&alt=json'
  1513. IE_NAME = u'youtube:user'
  1514. @classmethod
  1515. def suitable(cls, url):
  1516. # Don't return True if the url can be extracted with other youtube
  1517. # extractor, the regex would is too permissive and it would match.
  1518. other_ies = iter(klass for (name, klass) in globals().items() if name.endswith('IE') and klass is not cls)
  1519. if any(ie.suitable(url) for ie in other_ies): return False
  1520. else: return super(YoutubeUserIE, cls).suitable(url)
  1521. def _real_extract(self, url):
  1522. # Extract username
  1523. mobj = re.match(self._VALID_URL, url)
  1524. if mobj is None:
  1525. raise ExtractorError(u'Invalid URL: %s' % url)
  1526. username = mobj.group(1)
  1527. # Download video ids using YouTube Data API. Result size per
  1528. # query is limited (currently to 50 videos) so we need to query
  1529. # page by page until there are no video ids - it means we got
  1530. # all of them.
  1531. video_ids = []
  1532. for pagenum in itertools.count(0):
  1533. start_index = pagenum * self._GDATA_PAGE_SIZE + 1
  1534. gdata_url = self._GDATA_URL % (username, self._GDATA_PAGE_SIZE, start_index)
  1535. page = self._download_webpage(gdata_url, username,
  1536. u'Downloading video ids from %d to %d' % (start_index, start_index + self._GDATA_PAGE_SIZE))
  1537. try:
  1538. response = json.loads(page)
  1539. except ValueError as err:
  1540. raise ExtractorError(u'Invalid JSON in API response: ' + compat_str(err))
  1541. if 'entry' not in response['feed']:
  1542. # Number of videos is a multiple of self._MAX_RESULTS
  1543. break
  1544. # Extract video identifiers
  1545. ids_in_page = []
  1546. for entry in response['feed']['entry']:
  1547. ids_in_page.append(entry['id']['$t'].split('/')[-1])
  1548. video_ids.extend(ids_in_page)
  1549. # A little optimization - if current page is not
  1550. # "full", ie. does not contain PAGE_SIZE video ids then
  1551. # we can assume that this page is the last one - there
  1552. # are no more ids on further pages - no need to query
  1553. # again.
  1554. if len(ids_in_page) < self._GDATA_PAGE_SIZE:
  1555. break
  1556. url_results = [
  1557. self.url_result(video_id, 'Youtube', video_id=video_id)
  1558. for video_id in video_ids]
  1559. return self.playlist_result(url_results, playlist_title=username)
  1560. class YoutubeSearchIE(SearchInfoExtractor):
  1561. IE_DESC = u'YouTube.com searches'
  1562. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc'
  1563. _MAX_RESULTS = 1000
  1564. IE_NAME = u'youtube:search'
  1565. _SEARCH_KEY = 'ytsearch'
  1566. def _get_n_results(self, query, n):
  1567. """Get a specified number of results for a query"""
  1568. video_ids = []
  1569. pagenum = 0
  1570. limit = n
  1571. while (50 * pagenum) < limit:
  1572. result_url = self._API_URL % (compat_urllib_parse.quote_plus(query), (50*pagenum)+1)
  1573. data = self._download_webpage(result_url, u'query "%s"' % query,
  1574. u'Downloading page %s' % pagenum, u'Unable to download API page')
  1575. api_response = json.loads(data)['data']
  1576. if not 'items' in api_response:
  1577. raise ExtractorError(u'[youtube] No video results')
  1578. new_ids = list(video['id'] for video in api_response['items'])
  1579. video_ids += new_ids
  1580. limit = min(n, api_response['totalItems'])
  1581. pagenum += 1
  1582. if len(video_ids) > n:
  1583. video_ids = video_ids[:n]
  1584. videos = [self.url_result(video_id, 'Youtube', video_id=video_id)
  1585. for video_id in video_ids]
  1586. return self.playlist_result(videos, query)
  1587. class YoutubeSearchDateIE(YoutubeSearchIE):
  1588. IE_NAME = YoutubeSearchIE.IE_NAME + ':date'
  1589. _API_URL = 'https://gdata.youtube.com/feeds/api/videos?q=%s&start-index=%i&max-results=50&v=2&alt=jsonc&orderby=published'
  1590. _SEARCH_KEY = 'ytsearchdate'
  1591. IE_DESC = u'YouTube.com searches, newest videos first'
  1592. class YoutubeShowIE(InfoExtractor):
  1593. IE_DESC = u'YouTube.com (multi-season) shows'
  1594. _VALID_URL = r'https?://www\.youtube\.com/show/(.*)'
  1595. IE_NAME = u'youtube:show'
  1596. def _real_extract(self, url):
  1597. mobj = re.match(self._VALID_URL, url)
  1598. show_name = mobj.group(1)
  1599. webpage = self._download_webpage(url, show_name, u'Downloading show webpage')
  1600. # There's one playlist for each season of the show
  1601. m_seasons = list(re.finditer(r'href="(/playlist\?list=.*?)"', webpage))
  1602. self.to_screen(u'%s: Found %s seasons' % (show_name, len(m_seasons)))
  1603. return [self.url_result('https://www.youtube.com' + season.group(1), 'YoutubePlaylist') for season in m_seasons]
  1604. class YoutubeFeedsInfoExtractor(YoutubeBaseInfoExtractor):
  1605. """
  1606. Base class for extractors that fetch info from
  1607. http://www.youtube.com/feed_ajax
  1608. Subclasses must define the _FEED_NAME and _PLAYLIST_TITLE properties.
  1609. """
  1610. _LOGIN_REQUIRED = True
  1611. # use action_load_personal_feed instead of action_load_system_feed
  1612. _PERSONAL_FEED = False
  1613. @property
  1614. def _FEED_TEMPLATE(self):
  1615. action = 'action_load_system_feed'
  1616. if self._PERSONAL_FEED:
  1617. action = 'action_load_personal_feed'
  1618. return 'http://www.youtube.com/feed_ajax?%s=1&feed_name=%s&paging=%%s' % (action, self._FEED_NAME)
  1619. @property
  1620. def IE_NAME(self):
  1621. return u'youtube:%s' % self._FEED_NAME
  1622. def _real_initialize(self):
  1623. self._login()
  1624. def _real_extract(self, url):
  1625. feed_entries = []
  1626. paging = 0
  1627. for i in itertools.count(1):
  1628. info = self._download_webpage(self._FEED_TEMPLATE % paging,
  1629. u'%s feed' % self._FEED_NAME,
  1630. u'Downloading page %s' % i)
  1631. info = json.loads(info)
  1632. feed_html = info['feed_html']
  1633. m_ids = re.finditer(r'"/watch\?v=(.*?)["&]', feed_html)
  1634. ids = orderedSet(m.group(1) for m in m_ids)
  1635. feed_entries.extend(
  1636. self.url_result(video_id, 'Youtube', video_id=video_id)
  1637. for video_id in ids)
  1638. if info['paging'] is None:
  1639. break
  1640. paging = info['paging']
  1641. return self.playlist_result(feed_entries, playlist_title=self._PLAYLIST_TITLE)
  1642. class YoutubeSubscriptionsIE(YoutubeFeedsInfoExtractor):
  1643. IE_DESC = u'YouTube.com subscriptions feed, "ytsubs" keyword(requires authentication)'
  1644. _VALID_URL = r'https?://www\.youtube\.com/feed/subscriptions|:ytsubs(?:criptions)?'
  1645. _FEED_NAME = 'subscriptions'
  1646. _PLAYLIST_TITLE = u'Youtube Subscriptions'
  1647. class YoutubeRecommendedIE(YoutubeFeedsInfoExtractor):
  1648. IE_DESC = u'YouTube.com recommended videos, "ytrec" keyword (requires authentication)'
  1649. _VALID_URL = r'https?://www\.youtube\.com/feed/recommended|:ytrec(?:ommended)?'
  1650. _FEED_NAME = 'recommended'
  1651. _PLAYLIST_TITLE = u'Youtube Recommended videos'
  1652. class YoutubeWatchLaterIE(YoutubeFeedsInfoExtractor):
  1653. IE_DESC = u'Youtube watch later list, "ytwatchlater" keyword (requires authentication)'
  1654. _VALID_URL = r'https?://www\.youtube\.com/feed/watch_later|:ytwatchlater'
  1655. _FEED_NAME = 'watch_later'
  1656. _PLAYLIST_TITLE = u'Youtube Watch Later'
  1657. _PERSONAL_FEED = True
  1658. class YoutubeHistoryIE(YoutubeFeedsInfoExtractor):
  1659. IE_DESC = u'Youtube watch history, "ythistory" keyword (requires authentication)'
  1660. _VALID_URL = u'https?://www\.youtube\.com/feed/history|:ythistory'
  1661. _FEED_NAME = 'history'
  1662. _PERSONAL_FEED = True
  1663. _PLAYLIST_TITLE = u'Youtube Watch History'
  1664. class YoutubeFavouritesIE(YoutubeBaseInfoExtractor):
  1665. IE_NAME = u'youtube:favorites'
  1666. IE_DESC = u'YouTube.com favourite videos, "ytfav" keyword (requires authentication)'
  1667. _VALID_URL = r'https?://www\.youtube\.com/my_favorites|:ytfav(?:ou?rites)?'
  1668. _LOGIN_REQUIRED = True
  1669. def _real_extract(self, url):
  1670. webpage = self._download_webpage('https://www.youtube.com/my_favorites', 'Youtube Favourites videos')
  1671. playlist_id = self._search_regex(r'list=(.+?)["&]', webpage, u'favourites playlist id')
  1672. return self.url_result(playlist_id, 'YoutubePlaylist')
  1673. class YoutubeTruncatedURLIE(InfoExtractor):
  1674. IE_NAME = 'youtube:truncated_url'
  1675. IE_DESC = False # Do not list
  1676. _VALID_URL = r'(?:https?://)?[^/]+/watch\?feature=[a-z_]+$'
  1677. def _real_extract(self, url):
  1678. raise ExtractorError(
  1679. u'Did you forget to quote the URL? Remember that & is a meta '
  1680. u'character in most shells, so you want to put the URL in quotes, '
  1681. u'like youtube-dl '
  1682. u'\'http://www.youtube.com/watch?feature=foo&v=BaW_jenozKc\''
  1683. u' (or simply youtube-dl BaW_jenozKc ).',
  1684. expected=True)