youtube.py 76 KB

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