Python module (submodule repositary), which provides content (video streams) from various online stream sources to corresponding Enigma2, Kodi, Plex plugins

jsinterp.py 8.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. # This code comes from youtube-dl: https://github.com/rg3/youtube-dl/blob/master/youtube_dl/jsinterp.py
  2. from __future__ import unicode_literals
  3. import json
  4. import operator
  5. import re
  6. _OPERATORS = [
  7. ('|', operator.or_),
  8. ('^', operator.xor),
  9. ('&', operator.and_),
  10. ('>>', operator.rshift),
  11. ('<<', operator.lshift),
  12. ('-', operator.sub),
  13. ('+', operator.add),
  14. ('%', operator.mod),
  15. ('/', operator.truediv),
  16. ('*', operator.mul),
  17. ]
  18. _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]
  19. _ASSIGN_OPERATORS.append(('=', lambda cur, right: right))
  20. _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'
  21. class JSInterpreter(object):
  22. def __init__(self, code, objects=None):
  23. if objects is None:
  24. objects = {}
  25. self.code = code
  26. self._functions = {}
  27. self._objects = objects
  28. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  29. if allow_recursion < 0:
  30. print '[JSInterpreter] Recursion limit reached'
  31. return None
  32. should_abort = False
  33. stmt = stmt.lstrip()
  34. stmt_m = re.match(r'var\s', stmt)
  35. if stmt_m:
  36. expr = stmt[len(stmt_m.group(0)):]
  37. else:
  38. return_m = re.match(r'return(?:\s+|$)', stmt)
  39. if return_m:
  40. expr = stmt[len(return_m.group(0)):]
  41. should_abort = True
  42. else:
  43. # Try interpreting it as an expression
  44. expr = stmt
  45. v = self.interpret_expression(expr, local_vars, allow_recursion)
  46. return v, should_abort
  47. def interpret_expression(self, expr, local_vars, allow_recursion):
  48. expr = expr.strip()
  49. if expr == '': # Empty expression
  50. return None
  51. if expr.startswith('('):
  52. parens_count = 0
  53. for m in re.finditer(r'[()]', expr):
  54. if m.group(0) == '(':
  55. parens_count += 1
  56. else:
  57. parens_count -= 1
  58. if parens_count == 0:
  59. sub_expr = expr[1:m.start()]
  60. sub_result = self.interpret_expression(
  61. sub_expr, local_vars, allow_recursion)
  62. remaining_expr = expr[m.end():].strip()
  63. if not remaining_expr:
  64. return sub_result
  65. else:
  66. expr = json.dumps(sub_result) + remaining_expr
  67. break
  68. else:
  69. print '[JSInterpreter] Premature end of parens in %r' % expr
  70. return None
  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. print '[JSInterpreter] Premature left-side return of %s in %r' % (op, expr)
  167. return None
  168. y, abort = self.interpret_statement(
  169. m.group('y'), local_vars, allow_recursion - 1)
  170. if abort:
  171. print '[JSInterpreter] Premature right-side return of %s in %r' % (op, expr)
  172. return None
  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(',')])
  181. if fname not in self._functions:
  182. self._functions[fname] = self.extract_function(fname)
  183. return self._functions[fname](argvals)
  184. print '[JSInterpreter] Unsupported JS expression %r' % expr
  185. return None
  186. def extract_object(self, objname):
  187. obj = {}
  188. obj_m = re.search(
  189. (r'(?:var\s+)?%s\s*=\s*\{' % re.escape(objname)) +
  190. r'\s*(?P<fields>([a-zA-Z$0-9]+\s*:\s*function\(.*?\)\s*\{.*?\}(?:,\s*)?)*)' +
  191. r'\}\s*;',
  192. self.code)
  193. fields = obj_m.group('fields')
  194. # Currently, it only supports function definitions
  195. fields_m = re.finditer(
  196. r'(?P<key>[a-zA-Z$0-9]+)\s*:\s*function'
  197. r'\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}',
  198. fields)
  199. for f in fields_m:
  200. argnames = f.group('args').split(',')
  201. obj[f.group('key')] = self.build_function(argnames, f.group('code'))
  202. return obj
  203. def extract_function(self, funcname):
  204. func_m = re.search(
  205. r'''(?x)
  206. (?:function\s+%s|[{;,]%s\s*=\s*function|var\s+%s\s*=\s*function)\s*
  207. \((?P<args>[^)]*)\)\s*
  208. \{(?P<code>[^}]+)\}''' % (
  209. re.escape(funcname), re.escape(funcname), re.escape(funcname)),
  210. self.code)
  211. if func_m is None:
  212. print '[JSInterpreter] Could not find JS function %r' % funcname
  213. return None
  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