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