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.

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