youtube.py 77 KB

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