2
0

youtube.py 74 KB

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