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