jsinterp.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. from __future__ import unicode_literals
  2. import json
  3. import operator
  4. import re
  5. from .utils import (
  6. ExtractorError,
  7. remove_quotes,
  8. )
  9. from .compat import (
  10. compat_collections_abc,
  11. compat_str,
  12. )
  13. MutableMapping = compat_collections_abc.MutableMapping
  14. class Nonlocal:
  15. pass
  16. _OPERATORS = [
  17. ('|', operator.or_),
  18. ('^', operator.xor),
  19. ('&', operator.and_),
  20. ('>>', operator.rshift),
  21. ('<<', operator.lshift),
  22. ('-', operator.sub),
  23. ('+', operator.add),
  24. ('%', operator.mod),
  25. ('/', operator.truediv),
  26. ('*', operator.mul),
  27. ]
  28. _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]
  29. _ASSIGN_OPERATORS.append(('=', (lambda cur, right: right)))
  30. _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'
  31. class JS_Break(ExtractorError):
  32. def __init__(self):
  33. ExtractorError.__init__(self, 'Invalid break')
  34. class JS_Continue(ExtractorError):
  35. def __init__(self):
  36. ExtractorError.__init__(self, 'Invalid continue')
  37. class LocalNameSpace(MutableMapping):
  38. def __init__(self, *stack):
  39. self.stack = tuple(stack)
  40. def __getitem__(self, key):
  41. for scope in self.stack:
  42. if key in scope:
  43. return scope[key]
  44. raise KeyError(key)
  45. def __setitem__(self, key, value):
  46. for scope in self.stack:
  47. if key in scope:
  48. scope[key] = value
  49. break
  50. else:
  51. self.stack[0][key] = value
  52. return value
  53. def __delitem__(self, key):
  54. raise NotImplementedError('Deleting is not supported')
  55. def __iter__(self):
  56. for scope in self.stack:
  57. for scope_item in iter(scope):
  58. yield scope_item
  59. def __len__(self, key):
  60. return len(iter(self))
  61. def __repr__(self):
  62. return 'LocalNameSpace%s' % (self.stack, )
  63. class JSInterpreter(object):
  64. def __init__(self, code, objects=None):
  65. if objects is None:
  66. objects = {}
  67. self.code = code
  68. self._functions = {}
  69. self._objects = objects
  70. self.__named_object_counter = 0
  71. def _named_object(self, namespace, obj):
  72. self.__named_object_counter += 1
  73. name = '__youtube_dl_jsinterp_obj%s' % (self.__named_object_counter, )
  74. namespace[name] = obj
  75. return name
  76. @staticmethod
  77. def _separate(expr, delim=',', max_split=None):
  78. if not expr:
  79. return
  80. parens = {'(': 0, '{': 0, '[': 0, ']': 0, '}': 0, ')': 0}
  81. start, splits, pos, max_pos = 0, 0, 0, len(delim) - 1
  82. for idx, char in enumerate(expr):
  83. if char in parens:
  84. parens[char] += 1
  85. is_in_parens = (parens['['] - parens[']']
  86. or parens['('] - parens[')']
  87. or parens['{'] - parens['}'])
  88. if char == delim[pos] and not is_in_parens:
  89. if pos == max_pos:
  90. pos = 0
  91. yield expr[start: idx - max_pos]
  92. start = idx + 1
  93. splits += 1
  94. if max_split and splits >= max_split:
  95. break
  96. else:
  97. pos += 1
  98. else:
  99. pos = 0
  100. yield expr[start:]
  101. @staticmethod
  102. def _separate_at_paren(expr, delim):
  103. separated = list(JSInterpreter._separate(expr, delim, 1))
  104. if len(separated) < 2:
  105. raise ExtractorError('No terminating paren {0} in {1}'.format(delim, expr))
  106. return separated[0][1:].strip(), separated[1].strip()
  107. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  108. if allow_recursion < 0:
  109. raise ExtractorError('Recursion limit reached')
  110. sub_statements = list(self._separate(stmt, ';'))
  111. stmt = (sub_statements or ['']).pop()
  112. for sub_stmt in sub_statements:
  113. ret, should_abort = self.interpret_statement(sub_stmt, local_vars, allow_recursion - 1)
  114. if should_abort:
  115. return ret
  116. should_abort = False
  117. stmt = stmt.lstrip()
  118. stmt_m = re.match(r'var\s', stmt)
  119. if stmt_m:
  120. expr = stmt[len(stmt_m.group(0)):]
  121. else:
  122. return_m = re.match(r'return(?:\s+|$)', stmt)
  123. if return_m:
  124. expr = stmt[len(return_m.group(0)):]
  125. should_abort = True
  126. else:
  127. # Try interpreting it as an expression
  128. expr = stmt
  129. v = self.interpret_expression(expr, local_vars, allow_recursion)
  130. return v, should_abort
  131. def interpret_expression(self, expr, local_vars, allow_recursion):
  132. expr = expr.strip()
  133. if expr == '': # Empty expression
  134. return None
  135. if expr.startswith('{'):
  136. inner, outer = self._separate_at_paren(expr, '}')
  137. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion - 1)
  138. if not outer or should_abort:
  139. return inner
  140. else:
  141. expr = json.dumps(inner) + outer
  142. if expr.startswith('('):
  143. inner, outer = self._separate_at_paren(expr, ')')
  144. inner = self.interpret_expression(inner, local_vars, allow_recursion)
  145. if not outer:
  146. return inner
  147. else:
  148. expr = json.dumps(inner) + outer
  149. if expr.startswith('['):
  150. inner, outer = self._separate_at_paren(expr, ']')
  151. name = self._named_object(local_vars, [
  152. self.interpret_expression(item, local_vars, allow_recursion)
  153. for item in self._separate(inner)])
  154. expr = name + outer
  155. m = re.match(r'try\s*', expr)
  156. if m:
  157. if expr[m.end()] == '{':
  158. try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
  159. else:
  160. try_expr, expr = expr[m.end() - 1:], ''
  161. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion - 1)
  162. if should_abort:
  163. return ret
  164. return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
  165. m = re.match(r'(?:(?P<catch>catch)|(?P<for>for)|(?P<switch>switch))\s*\(', expr)
  166. md = m.groupdict() if m else {}
  167. if md.get('catch'):
  168. # We ignore the catch block
  169. _, expr = self._separate_at_paren(expr, '}')
  170. return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
  171. elif md.get('for'):
  172. def raise_constructor_error(c):
  173. raise ExtractorError(
  174. 'Premature return in the initialization of a for loop in {0!r}'.format(c))
  175. constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
  176. if remaining.startswith('{'):
  177. body, expr = self._separate_at_paren(remaining, '}')
  178. else:
  179. m = re.match(r'switch\s*\(', remaining) # FIXME
  180. if m:
  181. switch_val, remaining = self._separate_at_paren(remaining[m.end() - 1:], ')')
  182. body, expr = self._separate_at_paren(remaining, '}')
  183. body = 'switch(%s){%s}' % (switch_val, body)
  184. else:
  185. body, expr = remaining, ''
  186. start, cndn, increment = self._separate(constructor, ';')
  187. if self.interpret_statement(start, local_vars, allow_recursion - 1)[1]:
  188. raise_constructor_error(constructor)
  189. while True:
  190. if not self.interpret_expression(cndn, local_vars, allow_recursion):
  191. break
  192. try:
  193. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion - 1)
  194. if should_abort:
  195. return ret
  196. except JS_Break:
  197. break
  198. except JS_Continue:
  199. pass
  200. if self.interpret_statement(increment, local_vars, allow_recursion - 1)[1]:
  201. raise_constructor_error(constructor)
  202. return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
  203. elif md.get('switch'):
  204. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
  205. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  206. body, expr = self._separate_at_paren(remaining, '}')
  207. items = body.replace('default:', 'case default:').split('case ')[1:]
  208. for default in (False, True):
  209. matched = False
  210. for item in items:
  211. case, stmt = [i.strip() for i in self._separate(item, ':', 1)]
  212. if default:
  213. matched = matched or case == 'default'
  214. elif not matched:
  215. matched = (case != 'default'
  216. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  217. if not matched:
  218. continue
  219. try:
  220. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion - 1)
  221. if should_abort:
  222. return ret
  223. except JS_Break:
  224. break
  225. if matched:
  226. break
  227. return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
  228. # Comma separated statements
  229. sub_expressions = list(self._separate(expr))
  230. expr = sub_expressions.pop().strip() if sub_expressions else ''
  231. for sub_expr in sub_expressions:
  232. self.interpret_expression(sub_expr, local_vars, allow_recursion)
  233. for m in re.finditer(r'''(?x)
  234. (?P<pre_sign>\+\+|--)(?P<var1>%(_NAME_RE)s)|
  235. (?P<var2>%(_NAME_RE)s)(?P<post_sign>\+\+|--)''' % globals(), expr):
  236. var = m.group('var1') or m.group('var2')
  237. start, end = m.span()
  238. sign = m.group('pre_sign') or m.group('post_sign')
  239. ret = local_vars[var]
  240. local_vars[var] += 1 if sign[0] == '+' else -1
  241. if m.group('pre_sign'):
  242. ret = local_vars[var]
  243. expr = expr[:start] + json.dumps(ret) + expr[end:]
  244. for op, opfunc in _ASSIGN_OPERATORS:
  245. m = re.match(r'''(?x)
  246. (?P<out>%s)(?:\[(?P<index>[^\]]+?)\])?
  247. \s*%s
  248. (?P<expr>.*)$''' % (_NAME_RE, re.escape(op)), expr)
  249. if not m:
  250. continue
  251. right_val = self.interpret_expression(m.group('expr'), local_vars, allow_recursion)
  252. if m.groupdict().get('index'):
  253. lvar = local_vars[m.group('out')]
  254. idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
  255. if not isinstance(idx, int):
  256. raise ExtractorError('List indices must be integers: %s' % (idx, ))
  257. cur = lvar[idx]
  258. val = opfunc(cur, right_val)
  259. lvar[idx] = val
  260. return val
  261. else:
  262. cur = local_vars.get(m.group('out'))
  263. val = opfunc(cur, right_val)
  264. local_vars[m.group('out')] = val
  265. return val
  266. if expr.isdigit():
  267. return int(expr)
  268. if expr == 'break':
  269. raise JS_Break()
  270. elif expr == 'continue':
  271. raise JS_Continue()
  272. var_m = re.match(
  273. r'(?!if|return|true|false|null)(?P<name>%s)$' % _NAME_RE,
  274. expr)
  275. if var_m:
  276. return local_vars[var_m.group('name')]
  277. try:
  278. return json.loads(expr)
  279. except ValueError:
  280. pass
  281. m = re.match(
  282. r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr)
  283. if m:
  284. val = local_vars[m.group('in')]
  285. idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
  286. return val[idx]
  287. def raise_expr_error(where, op, exp):
  288. raise ExtractorError('Premature {0} return of {1} in {2!r}'.format(where, op, exp))
  289. for op, opfunc in _OPERATORS:
  290. separated = list(self._separate(expr, op))
  291. if len(separated) < 2:
  292. continue
  293. right_val = separated.pop()
  294. left_val = op.join(separated)
  295. left_val, should_abort = self.interpret_statement(
  296. left_val, local_vars, allow_recursion - 1)
  297. if should_abort:
  298. raise_expr_error('left-side', op, expr)
  299. right_val, should_abort = self.interpret_statement(
  300. right_val, local_vars, allow_recursion - 1)
  301. if should_abort:
  302. raise_expr_error('right-side', op, expr)
  303. return opfunc(left_val or 0, right_val)
  304. m = re.match(
  305. r'(?P<var>%s)(?:\.(?P<member>[^(]+)|\[(?P<member2>[^]]+)\])\s*' % _NAME_RE,
  306. expr)
  307. if m:
  308. variable = m.group('var')
  309. nl = Nonlocal()
  310. nl.member = remove_quotes(m.group('member') or m.group('member2'))
  311. arg_str = expr[m.end():]
  312. if arg_str.startswith('('):
  313. arg_str, remaining = self._separate_at_paren(arg_str, ')')
  314. else:
  315. arg_str, remaining = None, arg_str
  316. def assertion(cndn, msg):
  317. """ assert, but without risk of getting optimized out """
  318. if not cndn:
  319. raise ExtractorError('{0} {1}: {2}'.format(nl.member, msg, expr))
  320. def eval_method():
  321. # nonlocal member
  322. member = nl.member
  323. if variable == 'String':
  324. obj = compat_str
  325. elif variable in local_vars:
  326. obj = local_vars[variable]
  327. else:
  328. if variable not in self._objects:
  329. self._objects[variable] = self.extract_object(variable)
  330. obj = self._objects[variable]
  331. if arg_str is None:
  332. # Member access
  333. if member == 'length':
  334. return len(obj)
  335. return obj[member]
  336. # Function call
  337. argvals = [
  338. self.interpret_expression(v, local_vars, allow_recursion)
  339. for v in self._separate(arg_str)]
  340. if obj == compat_str:
  341. if member == 'fromCharCode':
  342. assertion(argvals, 'takes one or more arguments')
  343. return ''.join(map(chr, argvals))
  344. raise ExtractorError('Unsupported string method %s' % (member, ))
  345. if member == 'split':
  346. assertion(argvals, 'takes one or more arguments')
  347. assertion(argvals == [''], 'with arguments is not implemented')
  348. return list(obj)
  349. elif member == 'join':
  350. assertion(isinstance(obj, list), 'must be applied on a list')
  351. assertion(len(argvals) == 1, 'takes exactly one argument')
  352. return argvals[0].join(obj)
  353. elif member == 'reverse':
  354. assertion(not argvals, 'does not take any arguments')
  355. obj.reverse()
  356. return obj
  357. elif member == 'slice':
  358. assertion(isinstance(obj, list), 'must be applied on a list')
  359. assertion(len(argvals) == 1, 'takes exactly one argument')
  360. return obj[argvals[0]:]
  361. elif member == 'splice':
  362. assertion(isinstance(obj, list), 'must be applied on a list')
  363. assertion(argvals, 'takes one or more arguments')
  364. index, howMany = map(int, (argvals + [len(obj)])[:2])
  365. if index < 0:
  366. index += len(obj)
  367. add_items = argvals[2:]
  368. res = []
  369. for i in range(index, min(index + howMany, len(obj))):
  370. res.append(obj.pop(index))
  371. for i, item in enumerate(add_items):
  372. obj.insert(index + i, item)
  373. return res
  374. elif member == 'unshift':
  375. assertion(isinstance(obj, list), 'must be applied on a list')
  376. assertion(argvals, 'takes one or more arguments')
  377. for item in reversed(argvals):
  378. obj.insert(0, item)
  379. return obj
  380. elif member == 'pop':
  381. assertion(isinstance(obj, list), 'must be applied on a list')
  382. assertion(not argvals, 'does not take any arguments')
  383. if not obj:
  384. return
  385. return obj.pop()
  386. elif member == 'push':
  387. assertion(argvals, 'takes one or more arguments')
  388. obj.extend(argvals)
  389. return obj
  390. elif member == 'forEach':
  391. assertion(argvals, 'takes one or more arguments')
  392. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  393. f, this = (argvals + [''])[:2]
  394. return [f((item, idx, obj), this=this) for idx, item in enumerate(obj)]
  395. elif member == 'indexOf':
  396. assertion(argvals, 'takes one or more arguments')
  397. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  398. idx, start = (argvals + [0])[:2]
  399. try:
  400. return obj.index(idx, start)
  401. except ValueError:
  402. return -1
  403. if isinstance(obj, list):
  404. member = int(member)
  405. nl.member = member
  406. return obj[member](argvals)
  407. if remaining:
  408. return self.interpret_expression(
  409. self._named_object(local_vars, eval_method()) + remaining,
  410. local_vars, allow_recursion)
  411. else:
  412. return eval_method()
  413. m = re.match(r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr)
  414. if m:
  415. fname = m.group('func')
  416. argvals = tuple([
  417. int(v) if v.isdigit() else local_vars[v]
  418. for v in self._separate(m.group('args'))])
  419. if fname in local_vars:
  420. return local_vars[fname](argvals)
  421. elif fname not in self._functions:
  422. self._functions[fname] = self.extract_function(fname)
  423. return self._functions[fname](argvals)
  424. if expr:
  425. raise ExtractorError('Unsupported JS expression %r' % expr)
  426. def extract_object(self, objname):
  427. _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  428. obj = {}
  429. obj_m = re.search(
  430. r'''(?x)
  431. (?<!this\.)%s\s*=\s*{\s*
  432. (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
  433. }\s*;
  434. ''' % (re.escape(objname), _FUNC_NAME_RE),
  435. self.code)
  436. fields = obj_m.group('fields')
  437. # Currently, it only supports function definitions
  438. fields_m = re.finditer(
  439. r'''(?x)
  440. (?P<key>%s)\s*:\s*function\s*\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}
  441. ''' % _FUNC_NAME_RE,
  442. fields)
  443. for f in fields_m:
  444. argnames = f.group('args').split(',')
  445. obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
  446. return obj
  447. def extract_function_code(self, funcname):
  448. """ @returns argnames, code """
  449. func_m = re.search(
  450. r'''(?x)
  451. (?:function\s+%(f_n)s|[{;,]\s*%(f_n)s\s*=\s*function|var\s+%(f_n)s\s*=\s*function)\s*
  452. \((?P<args>[^)]*)\)\s*
  453. (?P<code>\{(?:(?!};)[^"]|"([^"]|\\")*")+\})''' % {'f_n': re.escape(funcname), },
  454. self.code)
  455. code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match
  456. if func_m is None:
  457. raise ExtractorError('Could not find JS function %r' % funcname)
  458. return func_m.group('args').split(','), code
  459. def extract_function(self, funcname):
  460. return self.extract_function_from_code(*self.extract_function_code(funcname))
  461. def extract_function_from_code(self, argnames, code, *global_stack):
  462. local_vars = {}
  463. while True:
  464. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
  465. if mobj is None:
  466. break
  467. start, body_start = mobj.span()
  468. body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
  469. name = self._named_object(
  470. local_vars,
  471. self.extract_function_from_code(
  472. [x.strip() for x in mobj.group('args').split(',')],
  473. body, local_vars, *global_stack))
  474. code = code[:start] + name + remaining
  475. return self.build_function(argnames, code, local_vars, *global_stack)
  476. def call_function(self, funcname, *args):
  477. return self.extract_function(funcname)(args)
  478. def build_function(self, argnames, code, *global_stack):
  479. global_stack = list(global_stack) or [{}]
  480. local_vars = global_stack.pop(0)
  481. def resf(args, **kwargs):
  482. local_vars.update(dict(zip(argnames, args)))
  483. local_vars.update(kwargs)
  484. var_stack = LocalNameSpace(local_vars, *global_stack)
  485. for stmt in self._separate(code.replace('\n', ''), ';'):
  486. ret, should_abort = self.interpret_statement(stmt, var_stack)
  487. if should_abort:
  488. break
  489. return ret
  490. return resf