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.

258 lines
8.7 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. if variable not in self._objects:
  116. self._objects[variable] = self.extract_object(variable)
  117. obj = self._objects[variable]
  118. if arg_str is None:
  119. # Member access
  120. if member == 'length':
  121. return len(obj)
  122. return obj[member]
  123. assert expr.endswith(')')
  124. # Function call
  125. if arg_str == '':
  126. argvals = tuple()
  127. else:
  128. argvals = tuple([
  129. self.interpret_expression(v, local_vars, allow_recursion)
  130. for v in arg_str.split(',')])
  131. if member == 'split':
  132. assert argvals == ('',)
  133. return list(obj)
  134. if member == 'join':
  135. assert len(argvals) == 1
  136. return argvals[0].join(obj)
  137. if member == 'reverse':
  138. assert len(argvals) == 0
  139. obj.reverse()
  140. return obj
  141. if member == 'slice':
  142. assert len(argvals) == 1
  143. return obj[argvals[0]:]
  144. if member == 'splice':
  145. assert isinstance(obj, list)
  146. index, howMany = argvals
  147. res = []
  148. for i in range(index, min(index + howMany, len(obj))):
  149. res.append(obj.pop(index))
  150. return res
  151. return obj[member](argvals)
  152. m = re.match(
  153. r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr)
  154. if m:
  155. val = local_vars[m.group('in')]
  156. idx = self.interpret_expression(
  157. m.group('idx'), local_vars, allow_recursion - 1)
  158. return val[idx]
  159. for op, opfunc in _OPERATORS:
  160. m = re.match(r'(?P<x>.+?)%s(?P<y>.+)' % re.escape(op), expr)
  161. if not m:
  162. continue
  163. x, abort = self.interpret_statement(
  164. m.group('x'), local_vars, allow_recursion - 1)
  165. if abort:
  166. raise ExtractorError(
  167. 'Premature left-side return of %s in %r' % (op, expr))
  168. y, abort = self.interpret_statement(
  169. m.group('y'), local_vars, allow_recursion - 1)
  170. if abort:
  171. raise ExtractorError(
  172. 'Premature right-side return of %s in %r' % (op, expr))
  173. return opfunc(x, y)
  174. m = re.match(
  175. r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr)
  176. if m:
  177. fname = m.group('func')
  178. argvals = tuple([
  179. int(v) if v.isdigit() else local_vars[v]
  180. for v in m.group('args').split(',')]) if len(m.group('args')) > 0 else tuple()
  181. if fname not in self._functions:
  182. self._functions[fname] = self.extract_function(fname)
  183. return self._functions[fname](argvals)
  184. raise ExtractorError('Unsupported JS expression %r' % expr)
  185. def extract_object(self, objname):
  186. obj = {}
  187. obj_m = re.search(
  188. (r'(?<!this\.)%s\s*=\s*\{' % re.escape(objname)) +
  189. r'\s*(?P<fields>([a-zA-Z$0-9]+\s*:\s*function\(.*?\)\s*\{.*?\}(?:,\s*)?)*)' +
  190. r'\}\s*;',
  191. self.code)
  192. fields = obj_m.group('fields')
  193. # Currently, it only supports function definitions
  194. fields_m = re.finditer(
  195. r'(?P<key>[a-zA-Z$0-9]+)\s*:\s*function'
  196. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  197. fields)
  198. for f in fields_m:
  199. argnames = f.group('args').split(',')
  200. obj[f.group('key')] = self.build_function(argnames, f.group('code'))
  201. return obj
  202. def extract_function(self, funcname):
  203. func_m = re.search(
  204. r'''(?x)
  205. (?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s*
  206. \((?P<args>[^)]*)\)\s*
  207. \{(?P<code>[^}]+)\}''' % (
  208. re.escape(funcname), re.escape(funcname), re.escape(funcname)),
  209. self.code)
  210. if func_m is None:
  211. raise ExtractorError('Could not find JS function %r' % funcname)
  212. argnames = func_m.group('args').split(',')
  213. return self.build_function(argnames, func_m.group('code'))
  214. def call_function(self, funcname, *args):
  215. f = self.extract_function(funcname)
  216. return f(args)
  217. def build_function(self, argnames, code):
  218. def resf(args):
  219. local_vars = dict(zip(argnames, args))
  220. for stmt in code.split(';'):
  221. res, abort = self.interpret_statement(stmt, local_vars)
  222. if abort:
  223. break
  224. return res
  225. return resf