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.

181 lines
6.1 KiB

  1. from __future__ import unicode_literals
  2. import json
  3. import re
  4. from .utils import (
  5. ExtractorError,
  6. )
  7. class JSInterpreter(object):
  8. def __init__(self, code):
  9. self.code = code
  10. self._functions = {}
  11. self._objects = {}
  12. def interpret_statement(self, stmt, local_vars, allow_recursion=20):
  13. if allow_recursion < 0:
  14. raise ExtractorError('Recursion limit reached')
  15. if stmt.startswith('var '):
  16. stmt = stmt[len('var '):]
  17. ass_m = re.match(r'^(?P<out>[a-z]+)(?:\[(?P<index>[^\]]+)\])?' +
  18. r'=(?P<expr>.*)$', stmt)
  19. if ass_m:
  20. if ass_m.groupdict().get('index'):
  21. def assign(val):
  22. lvar = local_vars[ass_m.group('out')]
  23. idx = self.interpret_expression(
  24. ass_m.group('index'), local_vars, allow_recursion)
  25. assert isinstance(idx, int)
  26. lvar[idx] = val
  27. return val
  28. expr = ass_m.group('expr')
  29. else:
  30. def assign(val):
  31. local_vars[ass_m.group('out')] = val
  32. return val
  33. expr = ass_m.group('expr')
  34. elif stmt.startswith('return '):
  35. assign = lambda v: v
  36. expr = stmt[len('return '):]
  37. else:
  38. # Try interpreting it as an expression
  39. expr = stmt
  40. assign = lambda v: v
  41. v = self.interpret_expression(expr, local_vars, allow_recursion)
  42. return assign(v)
  43. def interpret_expression(self, expr, local_vars, allow_recursion):
  44. if expr.isdigit():
  45. return int(expr)
  46. if expr.isalpha():
  47. return local_vars[expr]
  48. try:
  49. return json.loads(expr)
  50. except ValueError:
  51. pass
  52. m = re.match(
  53. r'^(?P<var>[$a-zA-Z0-9_]+)\.(?P<member>[^(]+)(?:\(+(?P<args>[^()]*)\))?$',
  54. expr)
  55. if m:
  56. variable = m.group('var')
  57. member = m.group('member')
  58. arg_str = m.group('args')
  59. if variable in local_vars:
  60. obj = local_vars[variable]
  61. else:
  62. if variable not in self._objects:
  63. self._objects[variable] = self.extract_object(variable)
  64. obj = self._objects[variable]
  65. if arg_str is None:
  66. # Member access
  67. if member == 'length':
  68. return len(obj)
  69. return obj[member]
  70. assert expr.endswith(')')
  71. # Function call
  72. if arg_str == '':
  73. argvals = tuple()
  74. else:
  75. argvals = tuple([
  76. self.interpret_expression(v, local_vars, allow_recursion)
  77. for v in arg_str.split(',')])
  78. if member == 'split':
  79. assert argvals == ('',)
  80. return list(obj)
  81. if member == 'join':
  82. assert len(argvals) == 1
  83. return argvals[0].join(obj)
  84. if member == 'reverse':
  85. assert len(argvals) == 0
  86. obj.reverse()
  87. return obj
  88. if member == 'slice':
  89. assert len(argvals) == 1
  90. return obj[argvals[0]:]
  91. if member == 'splice':
  92. assert isinstance(obj, list)
  93. index, howMany = argvals
  94. res = []
  95. for i in range(index, min(index + howMany, len(obj))):
  96. res.append(obj.pop(index))
  97. return res
  98. return obj[member](argvals)
  99. m = re.match(
  100. r'^(?P<in>[a-z]+)\[(?P<idx>.+)\]$', expr)
  101. if m:
  102. val = local_vars[m.group('in')]
  103. idx = self.interpret_expression(
  104. m.group('idx'), local_vars, allow_recursion - 1)
  105. return val[idx]
  106. m = re.match(r'^(?P<a>.+?)(?P<op>[%])(?P<b>.+?)$', expr)
  107. if m:
  108. a = self.interpret_expression(
  109. m.group('a'), local_vars, allow_recursion)
  110. b = self.interpret_expression(
  111. m.group('b'), local_vars, allow_recursion)
  112. return a % b
  113. m = re.match(
  114. r'^(?P<func>[a-zA-Z$]+)\((?P<args>[a-z0-9,]+)\)$', expr)
  115. if m:
  116. fname = m.group('func')
  117. argvals = tuple([
  118. int(v) if v.isdigit() else local_vars[v]
  119. for v in m.group('args').split(',')])
  120. if fname not in self._functions:
  121. self._functions[fname] = self.extract_function(fname)
  122. return self._functions[fname](argvals)
  123. raise ExtractorError('Unsupported JS expression %r' % expr)
  124. def extract_object(self, objname):
  125. obj = {}
  126. obj_m = re.search(
  127. (r'(?:var\s+)?%s\s*=\s*\{' % re.escape(objname)) +
  128. r'\s*(?P<fields>([a-zA-Z$0-9]+\s*:\s*function\(.*?\)\s*\{.*?\})*)' +
  129. r'\}\s*;',
  130. self.code)
  131. fields = obj_m.group('fields')
  132. # Currently, it only supports function definitions
  133. fields_m = re.finditer(
  134. r'(?P<key>[a-zA-Z$0-9]+)\s*:\s*function'
  135. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  136. fields)
  137. for f in fields_m:
  138. argnames = f.group('args').split(',')
  139. obj[f.group('key')] = self.build_function(argnames, f.group('code'))
  140. return obj
  141. def extract_function(self, funcname):
  142. func_m = re.search(
  143. (r'(?:function %s|[{;]%s\s*=\s*function)' % (
  144. re.escape(funcname), re.escape(funcname))) +
  145. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  146. self.code)
  147. if func_m is None:
  148. raise ExtractorError('Could not find JS function %r' % funcname)
  149. argnames = func_m.group('args').split(',')
  150. return self.build_function(argnames, func_m.group('code'))
  151. def build_function(self, argnames, code):
  152. def resf(args):
  153. local_vars = dict(zip(argnames, args))
  154. for stmt in code.split(';'):
  155. res = self.interpret_statement(stmt, local_vars)
  156. return res
  157. return resf