You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

256 lines
8.6 KiB

  1. from __future__ import unicode_literals
  2. import json
  3. import operator
  4. import re
  5. from .utils import (
  6. ExtractorError,
  7. )
  8. _OPERATORS = [
  9. ('|', operator.or_),
  10. ('^', operator.xor),
  11. ('&', operator.and_),
  12. ('>>', operator.rshift),
  13. ('<<', operator.lshift),
  14. ('-', operator.sub),
  15. ('+', operator.add),
  16. ('%', operator.mod),
  17. ('/', operator.truediv),
  18. ('*', operator.mul),
  19. ]
  20. _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]
  21. _ASSIGN_OPERATORS.append(('=', lambda cur, right: right))
  22. _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'
  23. class JSInterpreter(object):
  24. def __init__(self, code, objects=None):
  25. if objects is None:
  26. objects = {}
  27. self.code = code
  28. self._functions = {}
  29. self._objects = objects
  30. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  31. if allow_recursion < 0:
  32. raise ExtractorError('Recursion limit reached')
  33. should_abort = False
  34. stmt = stmt.lstrip()
  35. stmt_m = re.match(r'var\s', stmt)
  36. if stmt_m:
  37. expr = stmt[len(stmt_m.group(0)):]
  38. else:
  39. return_m = re.match(r'return(?:\s+|$)', stmt)
  40. if return_m:
  41. expr = stmt[len(return_m.group(0)):]
  42. should_abort = True
  43. else:
  44. # Try interpreting it as an expression
  45. expr = stmt
  46. v = self.interpret_expression(expr, local_vars, allow_recursion)
  47. return v, should_abort
  48. def interpret_expression(self, expr, local_vars, allow_recursion):
  49. expr = expr.strip()
  50. if expr == '': # Empty expression
  51. return None
  52. if expr.startswith('('):
  53. parens_count = 0
  54. for m in re.finditer(r'[()]', expr):
  55. if m.group(0) == '(':
  56. parens_count += 1
  57. else:
  58. parens_count -= 1
  59. if parens_count == 0:
  60. sub_expr = expr[1:m.start()]
  61. sub_result = self.interpret_expression(
  62. sub_expr, local_vars, allow_recursion)
  63. remaining_expr = expr[m.end():].strip()
  64. if not remaining_expr:
  65. return sub_result
  66. else:
  67. expr = json.dumps(sub_result) + remaining_expr
  68. break
  69. else:
  70. raise ExtractorError('Premature end of parens in %r' % expr)
  71. for op, opfunc in _ASSIGN_OPERATORS:
  72. m = re.match(r'''(?x)
  73. (?P<out>%s)(?:\[(?P<index>[^\]]+?)\])?
  74. \s*%s
  75. (?P<expr>.*)$''' % (_NAME_RE, re.escape(op)), expr)
  76. if not m:
  77. continue
  78. right_val = self.interpret_expression(
  79. m.group('expr'), local_vars, allow_recursion - 1)
  80. if m.groupdict().get('index'):
  81. lvar = local_vars[m.group('out')]
  82. idx = self.interpret_expression(
  83. m.group('index'), local_vars, allow_recursion)
  84. assert isinstance(idx, int)
  85. cur = lvar[idx]
  86. val = opfunc(cur, right_val)
  87. lvar[idx] = val
  88. return val
  89. else:
  90. cur = local_vars.get(m.group('out'))
  91. val = opfunc(cur, right_val)
  92. local_vars[m.group('out')] = val
  93. return val
  94. if expr.isdigit():
  95. return int(expr)
  96. var_m = re.match(
  97. r'(?!if|return|true|false)(?P<name>%s)$' % _NAME_RE,
  98. expr)
  99. if var_m:
  100. return local_vars[var_m.group('name')]
  101. try:
  102. return json.loads(expr)
  103. except ValueError:
  104. pass
  105. m = re.match(
  106. r'(?P<var>%s)\.(?P<member>[^(]+)(?:\(+(?P<args>[^()]*)\))?$' % _NAME_RE,
  107. expr)
  108. if m:
  109. variable = m.group('var')
  110. member = m.group('member')
  111. arg_str = m.group('args')
  112. if variable in local_vars:
  113. obj = local_vars[variable]
  114. else:
  115. obj = self._objects.setdefault(
  116. variable, self.extract_object(variable))
  117. if arg_str is None:
  118. # Member access
  119. if member == 'length':
  120. return len(obj)
  121. return obj[member]
  122. assert expr.endswith(')')
  123. # Function call
  124. if arg_str == '':
  125. argvals = tuple()
  126. else:
  127. argvals = tuple([
  128. self.interpret_expression(v, local_vars, allow_recursion)
  129. for v in arg_str.split(',')])
  130. if member == 'split':
  131. assert argvals == ('',)
  132. return list(obj)
  133. if member == 'join':
  134. assert len(argvals) == 1
  135. return argvals[0].join(obj)
  136. if member == 'reverse':
  137. assert len(argvals) == 0
  138. obj.reverse()
  139. return obj
  140. if member == 'slice':
  141. assert len(argvals) == 1
  142. return obj[argvals[0]:]
  143. if member == 'splice':
  144. assert isinstance(obj, list)
  145. index, howMany = argvals
  146. res = []
  147. for i in range(index, min(index + howMany, len(obj))):
  148. res.append(obj.pop(index))
  149. return res
  150. return obj[member](argvals)
  151. m = re.match(
  152. r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr)
  153. if m:
  154. val = local_vars[m.group('in')]
  155. idx = self.interpret_expression(
  156. m.group('idx'), local_vars, allow_recursion - 1)
  157. return val[idx]
  158. for op, opfunc in _OPERATORS:
  159. m = re.match(r'(?P<x>.+?)%s(?P<y>.+)' % re.escape(op), expr)
  160. if not m:
  161. continue
  162. x, abort = self.interpret_statement(
  163. m.group('x'), local_vars, allow_recursion - 1)
  164. if abort:
  165. raise ExtractorError(
  166. 'Premature left-side return of %s in %r' % (op, expr))
  167. y, abort = self.interpret_statement(
  168. m.group('y'), local_vars, allow_recursion - 1)
  169. if abort:
  170. raise ExtractorError(
  171. 'Premature right-side return of %s in %r' % (op, expr))
  172. return opfunc(x, y)
  173. m = re.match(
  174. r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]+)\)$' % _NAME_RE, expr)
  175. if m:
  176. fname = m.group('func')
  177. argvals = tuple([
  178. int(v) if v.isdigit() else local_vars[v]
  179. for v in m.group('args').split(',')])
  180. self._functions.setdefault(fname, self.extract_function(fname))
  181. return self._functions[fname](argvals)
  182. raise ExtractorError('Unsupported JS expression %r' % expr)
  183. def extract_object(self, objname):
  184. obj = {}
  185. obj_m = re.search(
  186. (r'(?:var\s+)?%s\s*=\s*\{' % re.escape(objname)) +
  187. r'\s*(?P<fields>([a-zA-Z$0-9]+\s*:\s*function\(.*?\)\s*\{.*?\}(?:,\s*)?)*)' +
  188. r'\}\s*;',
  189. self.code)
  190. fields = obj_m.group('fields')
  191. # Currently, it only supports function definitions
  192. fields_m = re.finditer(
  193. r'(?P<key>[a-zA-Z$0-9]+)\s*:\s*function'
  194. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  195. fields)
  196. for f in fields_m:
  197. argnames = f.group('args').split(',')
  198. obj[f.group('key')] = self.build_function(argnames, f.group('code'))
  199. return obj
  200. def extract_function(self, funcname):
  201. func_m = re.search(
  202. r'''(?x)
  203. (?:function\s+%s|[{;,]%s\s*=\s*function|var\s+%s\s*=\s*function)\s*
  204. \((?P<args>[^)]*)\)\s*
  205. \{(?P<code>[^}]+)\}''' % (
  206. re.escape(funcname), re.escape(funcname), re.escape(funcname)),
  207. self.code)
  208. if func_m is None:
  209. raise ExtractorError('Could not find JS function %r' % funcname)
  210. argnames = func_m.group('args').split(',')
  211. return self.build_function(argnames, func_m.group('code'))
  212. def call_function(self, funcname, *args):
  213. f = self.extract_function(funcname)
  214. return f(args)
  215. def build_function(self, argnames, code):
  216. def resf(args):
  217. local_vars = dict(zip(argnames, args))
  218. for stmt in code.split(';'):
  219. res, abort = self.interpret_statement(stmt, local_vars)
  220. if abort:
  221. break
  222. return res
  223. return resf