jsinterp.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  1. from __future__ import unicode_literals
  2. import itertools
  3. import json
  4. import math
  5. import operator
  6. import re
  7. from .utils import (
  8. error_to_compat_str,
  9. ExtractorError,
  10. js_to_json,
  11. remove_quotes,
  12. unified_timestamp,
  13. )
  14. from .compat import (
  15. compat_collections_chain_map as ChainMap,
  16. compat_itertools_zip_longest as zip_longest,
  17. compat_str,
  18. )
  19. def _js_bit_op(op):
  20. def wrapped(a, b):
  21. def zeroise(x):
  22. return 0 if x in (None, JS_Undefined) else x
  23. return op(zeroise(a), zeroise(b))
  24. return wrapped
  25. def _js_arith_op(op):
  26. def wrapped(a, b):
  27. if JS_Undefined in (a, b):
  28. return float('nan')
  29. return op(a or 0, b or 0)
  30. return wrapped
  31. def _js_div(a, b):
  32. if JS_Undefined in (a, b) or not (a and b):
  33. return float('nan')
  34. return float('inf') if not b else operator.truediv(a or 0, b)
  35. def _js_mod(a, b):
  36. if JS_Undefined in (a, b) or not b:
  37. return float('nan')
  38. return (a or 0) % b
  39. def _js_exp(a, b):
  40. if not b:
  41. return 1 # even 0 ** 0 !!
  42. elif JS_Undefined in (a, b):
  43. return float('nan')
  44. return (a or 0) ** b
  45. def _js_eq_op(op):
  46. def wrapped(a, b):
  47. if set((a, b)) <= set((None, JS_Undefined)):
  48. return op(a, a)
  49. return op(a, b)
  50. return wrapped
  51. def _js_comp_op(op):
  52. def wrapped(a, b):
  53. if JS_Undefined in (a, b):
  54. return False
  55. return op(a or 0, b or 0)
  56. return wrapped
  57. def _js_ternary(cndn, if_true=True, if_false=False):
  58. """Simulate JS's ternary operator (cndn?if_true:if_false)"""
  59. if cndn in (False, None, 0, '', JS_Undefined):
  60. return if_false
  61. try:
  62. if math.isnan(cndn): # NB: NaN cannot be checked by membership
  63. return if_false
  64. except TypeError:
  65. pass
  66. return if_true
  67. # (op, definition) in order of binding priority, tightest first
  68. # avoid dict to maintain order
  69. # definition None => Defined in JSInterpreter._operator
  70. _OPERATORS = (
  71. ('>>', _js_bit_op(operator.rshift)),
  72. ('<<', _js_bit_op(operator.lshift)),
  73. ('+', _js_arith_op(operator.add)),
  74. ('-', _js_arith_op(operator.sub)),
  75. ('*', _js_arith_op(operator.mul)),
  76. ('/', _js_div),
  77. ('%', _js_mod),
  78. ('**', _js_exp),
  79. )
  80. _COMP_OPERATORS = (
  81. ('===', operator.is_),
  82. ('==', _js_eq_op(operator.eq)),
  83. ('!==', operator.is_not),
  84. ('!=', _js_eq_op(operator.ne)),
  85. ('<=', _js_comp_op(operator.le)),
  86. ('>=', _js_comp_op(operator.ge)),
  87. ('<', _js_comp_op(operator.lt)),
  88. ('>', _js_comp_op(operator.gt)),
  89. )
  90. _LOG_OPERATORS = (
  91. ('|', _js_bit_op(operator.or_)),
  92. ('^', _js_bit_op(operator.xor)),
  93. ('&', _js_bit_op(operator.and_)),
  94. )
  95. _SC_OPERATORS = (
  96. ('?', None),
  97. ('??', None),
  98. ('||', None),
  99. ('&&', None),
  100. )
  101. _OPERATOR_RE = '|'.join(map(lambda x: re.escape(x[0]), _OPERATORS + _LOG_OPERATORS))
  102. _NAME_RE = r'[a-zA-Z_$][\w$]*'
  103. _MATCHING_PARENS = dict(zip(*zip('()', '{}', '[]')))
  104. _QUOTES = '\'"/'
  105. class JS_Undefined(object):
  106. pass
  107. class JS_Break(ExtractorError):
  108. def __init__(self):
  109. ExtractorError.__init__(self, 'Invalid break')
  110. class JS_Continue(ExtractorError):
  111. def __init__(self):
  112. ExtractorError.__init__(self, 'Invalid continue')
  113. class JS_Throw(ExtractorError):
  114. def __init__(self, e):
  115. self.error = e
  116. ExtractorError.__init__(self, 'Uncaught exception ' + error_to_compat_str(e))
  117. class LocalNameSpace(ChainMap):
  118. def __getitem__(self, key):
  119. try:
  120. return super(LocalNameSpace, self).__getitem__(key)
  121. except KeyError:
  122. return JS_Undefined
  123. def __setitem__(self, key, value):
  124. for scope in self.maps:
  125. if key in scope:
  126. scope[key] = value
  127. return
  128. self.maps[0][key] = value
  129. def __delitem__(self, key):
  130. raise NotImplementedError('Deleting is not supported')
  131. def __repr__(self):
  132. return 'LocalNameSpace%s' % (self.maps, )
  133. class JSInterpreter(object):
  134. __named_object_counter = 0
  135. _RE_FLAGS = {
  136. # special knowledge: Python's re flags are bitmask values, current max 128
  137. # invent new bitmask values well above that for literal parsing
  138. # TODO: new pattern class to execute matches with these flags
  139. 'd': 1024, # Generate indices for substring matches
  140. 'g': 2048, # Global search
  141. 'i': re.I, # Case-insensitive search
  142. 'm': re.M, # Multi-line search
  143. 's': re.S, # Allows . to match newline characters
  144. 'u': re.U, # Treat a pattern as a sequence of unicode code points
  145. 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
  146. }
  147. _EXC_NAME = '__youtube_dl_exception__'
  148. _OBJ_NAME = '__youtube_dl_jsinterp_obj'
  149. OP_CHARS = None
  150. def __init__(self, code, objects=None):
  151. self.code, self._functions = code, {}
  152. self._objects = {} if objects is None else objects
  153. if type(self).OP_CHARS is None:
  154. type(self).OP_CHARS = self.OP_CHARS = self.__op_chars()
  155. class Exception(ExtractorError):
  156. def __init__(self, msg, *args, **kwargs):
  157. expr = kwargs.pop('expr', None)
  158. if expr is not None:
  159. msg = '{0} in: {1!r}'.format(msg.rstrip(), expr[:100])
  160. super(JSInterpreter.Exception, self).__init__(msg, *args, **kwargs)
  161. @classmethod
  162. def __op_chars(cls):
  163. op_chars = set(';,')
  164. for op in cls._all_operators():
  165. for c in op[0]:
  166. op_chars.add(c)
  167. return op_chars
  168. def _named_object(self, namespace, obj):
  169. self.__named_object_counter += 1
  170. name = '%s%d' % (self._OBJ_NAME, self.__named_object_counter)
  171. namespace[name] = obj
  172. return name
  173. @classmethod
  174. def _regex_flags(cls, expr):
  175. flags = 0
  176. if not expr:
  177. return flags, expr
  178. for idx, ch in enumerate(expr):
  179. if ch not in cls._RE_FLAGS:
  180. break
  181. flags |= cls._RE_FLAGS[ch]
  182. return flags, expr[idx + 1:]
  183. @classmethod
  184. def _separate(cls, expr, delim=',', max_split=None, skip_delims=None):
  185. if not expr:
  186. return
  187. counters = {k: 0 for k in _MATCHING_PARENS.values()}
  188. start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1
  189. in_quote, escaping, skipping = None, False, 0
  190. after_op, in_regex_char_group, skip_re = True, False, 0
  191. for idx, char in enumerate(expr):
  192. if skip_re > 0:
  193. skip_re -= 1
  194. continue
  195. if not in_quote:
  196. if char in _MATCHING_PARENS:
  197. counters[_MATCHING_PARENS[char]] += 1
  198. elif char in counters:
  199. counters[char] -= 1
  200. if not escaping and char in _QUOTES and in_quote in (char, None):
  201. if in_quote or after_op or char != '/':
  202. in_quote = None if in_quote and not in_regex_char_group else char
  203. elif in_quote == '/' and char in '[]':
  204. in_regex_char_group = char == '['
  205. escaping = not escaping and in_quote and char == '\\'
  206. after_op = not in_quote and char in cls.OP_CHARS or (char == ' ' and after_op)
  207. if char != delim[pos] or any(counters.values()) or in_quote:
  208. pos = skipping = 0
  209. continue
  210. elif skipping > 0:
  211. skipping -= 1
  212. continue
  213. elif pos == 0 and skip_delims:
  214. here = expr[idx:]
  215. for s in skip_delims if isinstance(skip_delims, (list, tuple)) else [skip_delims]:
  216. if here.startswith(s) and s:
  217. skipping = len(s) - 1
  218. break
  219. if skipping > 0:
  220. continue
  221. if pos < delim_len:
  222. pos += 1
  223. continue
  224. yield expr[start: idx - delim_len]
  225. start, pos = idx + 1, 0
  226. splits += 1
  227. if max_split and splits >= max_split:
  228. break
  229. yield expr[start:]
  230. @classmethod
  231. def _separate_at_paren(cls, expr, delim):
  232. separated = list(cls._separate(expr, delim, 1))
  233. if len(separated) < 2:
  234. raise cls.Exception('No terminating paren {delim} in {expr}'.format(**locals()))
  235. return separated[0][1:].strip(), separated[1].strip()
  236. @staticmethod
  237. def _all_operators():
  238. return itertools.chain(
  239. # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  240. _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS)
  241. def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
  242. if op in ('||', '&&'):
  243. if (op == '&&') ^ _js_ternary(left_val):
  244. return left_val # short circuiting
  245. elif op == '??':
  246. if left_val not in (None, JS_Undefined):
  247. return left_val
  248. elif op == '?':
  249. right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
  250. right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
  251. opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
  252. if not opfunc:
  253. return right_val
  254. try:
  255. return opfunc(left_val, right_val)
  256. except Exception as e:
  257. raise self.Exception('Failed to evaluate {left_val!r} {op} {right_val!r}'.format(**locals()), expr, cause=e)
  258. def _index(self, obj, idx, allow_undefined=False):
  259. if idx == 'length':
  260. return len(obj)
  261. try:
  262. return obj[int(idx)] if isinstance(obj, list) else obj[idx]
  263. except Exception as e:
  264. if allow_undefined:
  265. return JS_Undefined
  266. raise self.Exception('Cannot get index {idx}'.format(**locals()), expr=repr(obj), cause=e)
  267. def _dump(self, obj, namespace):
  268. try:
  269. return json.dumps(obj)
  270. except TypeError:
  271. return self._named_object(namespace, obj)
  272. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  273. if allow_recursion < 0:
  274. raise self.Exception('Recursion limit reached')
  275. allow_recursion -= 1
  276. should_return = False
  277. sub_statements = list(self._separate(stmt, ';')) or ['']
  278. expr = stmt = sub_statements.pop().strip()
  279. for sub_stmt in sub_statements:
  280. ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
  281. if should_return:
  282. return ret, should_return
  283. m = re.match(r'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$)|(?P<throw>throw\s+)', stmt)
  284. if m:
  285. expr = stmt[len(m.group(0)):].strip()
  286. if m.group('throw'):
  287. raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
  288. should_return = not m.group('var')
  289. if not expr:
  290. return None, should_return
  291. if expr[0] in _QUOTES:
  292. inner, outer = self._separate(expr, expr[0], 1)
  293. if expr[0] == '/':
  294. flags, outer = self._regex_flags(outer)
  295. inner = re.compile(inner[1:], flags=flags) # , strict=True))
  296. else:
  297. inner = json.loads(js_to_json(inner + expr[0])) # , strict=True))
  298. if not outer:
  299. return inner, should_return
  300. expr = self._named_object(local_vars, inner) + outer
  301. if expr.startswith('new '):
  302. obj = expr[4:]
  303. if obj.startswith('Date('):
  304. left, right = self._separate_at_paren(obj[4:], ')')
  305. expr = unified_timestamp(
  306. self.interpret_expression(left, local_vars, allow_recursion), False)
  307. if not expr:
  308. raise self.Exception('Failed to parse date {left!r}'.format(**locals()), expr=expr)
  309. expr = self._dump(int(expr * 1000), local_vars) + right
  310. else:
  311. raise self.Exception('Unsupported object {obj}'.format(**locals()), expr=expr)
  312. if expr.startswith('void '):
  313. left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
  314. return None, should_return
  315. if expr.startswith('{'):
  316. inner, outer = self._separate_at_paren(expr, '}')
  317. # try for object expression (Map)
  318. sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
  319. if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
  320. return dict(
  321. (key_expr if re.match(_NAME_RE, key_expr) else key_expr,
  322. self.interpret_expression(val_expr, local_vars, allow_recursion))
  323. for key_expr, val_expr in sub_expressions), should_return
  324. # or statement list
  325. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  326. if not outer or should_abort:
  327. return inner, should_abort or should_return
  328. else:
  329. expr = self._dump(inner, local_vars) + outer
  330. if expr.startswith('('):
  331. inner, outer = self._separate_at_paren(expr, ')')
  332. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  333. if not outer or should_abort:
  334. return inner, should_abort or should_return
  335. else:
  336. expr = self._dump(inner, local_vars) + outer
  337. if expr.startswith('['):
  338. inner, outer = self._separate_at_paren(expr, ']')
  339. name = self._named_object(local_vars, [
  340. self.interpret_expression(item, local_vars, allow_recursion)
  341. for item in self._separate(inner)])
  342. expr = name + outer
  343. m = re.match(r'''(?x)
  344. (?P<try>try|finally)\s*|
  345. (?P<catch>catch\s*(?P<err>\(\s*{_NAME_RE}\s*\)))|
  346. (?P<switch>switch)\s*\(|
  347. (?P<for>for)\s*\(|
  348. '''.format(**globals()), expr)
  349. md = m.groupdict() if m else {}
  350. if md.get('try'):
  351. if expr[m.end()] == '{':
  352. try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
  353. else:
  354. try_expr, expr = expr[m.end() - 1:], ''
  355. try:
  356. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  357. if should_abort:
  358. return ret, True
  359. except JS_Throw as e:
  360. local_vars[self._EXC_NAME] = e.error
  361. except Exception as e:
  362. # XXX: This works for now, but makes debugging future issues very hard
  363. local_vars[self._EXC_NAME] = e
  364. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  365. return ret, should_abort or should_return
  366. elif md.get('catch'):
  367. catch_expr, expr = self._separate_at_paren(expr[m.end():], '}')
  368. if self._EXC_NAME in local_vars:
  369. catch_vars = local_vars.new_child({m.group('err'): local_vars.pop(self._EXC_NAME)})
  370. ret, should_abort = self.interpret_statement(catch_expr, catch_vars, allow_recursion)
  371. if should_abort:
  372. return ret, True
  373. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  374. return ret, should_abort or should_return
  375. elif md.get('for'):
  376. constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
  377. if remaining.startswith('{'):
  378. body, expr = self._separate_at_paren(remaining, '}')
  379. else:
  380. switch_m = re.match(r'switch\s*\(', remaining) # FIXME
  381. if switch_m:
  382. switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
  383. body, expr = self._separate_at_paren(remaining, '}')
  384. body = 'switch(%s){%s}' % (switch_val, body)
  385. else:
  386. body, expr = remaining, ''
  387. start, cndn, increment = self._separate(constructor, ';')
  388. self.interpret_expression(start, local_vars, allow_recursion)
  389. while True:
  390. if not _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  391. break
  392. try:
  393. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  394. if should_abort:
  395. return ret, True
  396. except JS_Break:
  397. break
  398. except JS_Continue:
  399. pass
  400. self.interpret_expression(increment, local_vars, allow_recursion)
  401. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  402. return ret, should_abort or should_return
  403. elif md.get('switch'):
  404. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
  405. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  406. body, expr = self._separate_at_paren(remaining, '}')
  407. items = body.replace('default:', 'case default:').split('case ')[1:]
  408. for default in (False, True):
  409. matched = False
  410. for item in items:
  411. case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  412. if default:
  413. matched = matched or case == 'default'
  414. elif not matched:
  415. matched = (case != 'default'
  416. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  417. if not matched:
  418. continue
  419. try:
  420. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  421. if should_abort:
  422. return ret
  423. except JS_Break:
  424. break
  425. if matched:
  426. break
  427. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  428. return ret, should_abort or should_return
  429. # Comma separated statements
  430. sub_expressions = list(self._separate(expr))
  431. if len(sub_expressions) > 1:
  432. for sub_expr in sub_expressions:
  433. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  434. if should_abort:
  435. return ret, True
  436. return ret, False
  437. for m in re.finditer(r'''(?x)
  438. (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  439. (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  440. var = m.group('var1') or m.group('var2')
  441. start, end = m.span()
  442. sign = m.group('pre_sign') or m.group('post_sign')
  443. ret = local_vars[var]
  444. local_vars[var] += 1 if sign[0] == '+' else -1
  445. if m.group('pre_sign'):
  446. ret = local_vars[var]
  447. expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  448. if not expr:
  449. return None, should_return
  450. m = re.match(r'''(?x)
  451. (?P<assign>
  452. (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
  453. (?P<op>{_OPERATOR_RE})?
  454. =(?!=)(?P<expr>.*)$
  455. )|(?P<return>
  456. (?!if|return|true|false|null|undefined)(?P<name>{_NAME_RE})$
  457. )|(?P<indexing>
  458. (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
  459. )|(?P<attribute>
  460. (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
  461. )|(?P<function>
  462. (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  463. )'''.format(**globals()), expr)
  464. md = m.groupdict() if m else {}
  465. if md.get('assign'):
  466. left_val = local_vars.get(m.group('out'))
  467. if not m.group('index'):
  468. local_vars[m.group('out')] = self._operator(
  469. m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  470. return local_vars[m.group('out')], should_return
  471. elif left_val in (None, JS_Undefined):
  472. raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  473. idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
  474. if not isinstance(idx, (int, float)):
  475. raise self.Exception('List index %s must be integer' % (idx, ), expr=expr)
  476. idx = int(idx)
  477. left_val[idx] = self._operator(
  478. m.group('op'), self._index(left_val, idx), m.group('expr'), expr, local_vars, allow_recursion)
  479. return left_val[idx], should_return
  480. elif expr.isdigit():
  481. return int(expr), should_return
  482. elif expr == 'break':
  483. raise JS_Break()
  484. elif expr == 'continue':
  485. raise JS_Continue()
  486. elif expr == 'undefined':
  487. return JS_Undefined, should_return
  488. elif md.get('return'):
  489. return local_vars[m.group('name')], should_return
  490. try:
  491. ret = json.loads(js_to_json(expr)) # strict=True)
  492. if not md.get('attribute'):
  493. return ret, should_return
  494. except ValueError:
  495. pass
  496. if md.get('indexing'):
  497. val = local_vars[m.group('in')]
  498. idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
  499. return self._index(val, idx), should_return
  500. for op, _ in self._all_operators():
  501. # hackety: </> have higher priority than <</>>, but don't confuse them
  502. skip_delim = (op + op) if op in '<>*?' else None
  503. if op == '?':
  504. skip_delim = (skip_delim, '?.')
  505. separated = list(self._separate(expr, op, skip_delims=skip_delim))
  506. if len(separated) < 2:
  507. continue
  508. right_expr = separated.pop()
  509. while op == '-' and len(separated) > 1 and not separated[-1].strip():
  510. right_expr = '-' + right_expr
  511. separated.pop()
  512. left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
  513. return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
  514. if md.get('attribute'):
  515. variable, member, nullish = m.group('var', 'member', 'nullish')
  516. if not member:
  517. member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  518. arg_str = expr[m.end():]
  519. if arg_str.startswith('('):
  520. arg_str, remaining = self._separate_at_paren(arg_str, ')')
  521. else:
  522. arg_str, remaining = None, arg_str
  523. def assertion(cndn, msg):
  524. """ assert, but without risk of getting optimized out """
  525. if not cndn:
  526. raise ExtractorError('{member} {msg}'.format(**locals()), expr=expr)
  527. def eval_method():
  528. if (variable, member) == ('console', 'debug'):
  529. return
  530. types = {
  531. 'String': compat_str,
  532. 'Math': float,
  533. }
  534. obj = local_vars.get(variable)
  535. if obj in (JS_Undefined, None):
  536. obj = types.get(variable, JS_Undefined)
  537. if obj is JS_Undefined:
  538. try:
  539. if variable not in self._objects:
  540. self._objects[variable] = self.extract_object(variable)
  541. obj = self._objects[variable]
  542. except self.Exception:
  543. if not nullish:
  544. raise
  545. if nullish and obj is JS_Undefined:
  546. return JS_Undefined
  547. # Member access
  548. if arg_str is None:
  549. return self._index(obj, member, nullish)
  550. # Function call
  551. argvals = [
  552. self.interpret_expression(v, local_vars, allow_recursion)
  553. for v in self._separate(arg_str)]
  554. if obj == compat_str:
  555. if member == 'fromCharCode':
  556. assertion(argvals, 'takes one or more arguments')
  557. return ''.join(map(chr, argvals))
  558. raise self.Exception('Unsupported string method ' + member, expr=expr)
  559. elif obj == float:
  560. if member == 'pow':
  561. assertion(len(argvals) == 2, 'takes two arguments')
  562. return argvals[0] ** argvals[1]
  563. raise self.Exception('Unsupported Math method ' + member, expr=expr)
  564. if member == 'split':
  565. assertion(argvals, 'takes one or more arguments')
  566. assertion(len(argvals) == 1, 'with limit argument is not implemented')
  567. return obj.split(argvals[0]) if argvals[0] else list(obj)
  568. elif member == 'join':
  569. assertion(isinstance(obj, list), 'must be applied on a list')
  570. assertion(len(argvals) == 1, 'takes exactly one argument')
  571. return argvals[0].join(obj)
  572. elif member == 'reverse':
  573. assertion(not argvals, 'does not take any arguments')
  574. obj.reverse()
  575. return obj
  576. elif member == 'slice':
  577. assertion(isinstance(obj, list), 'must be applied on a list')
  578. assertion(len(argvals) == 1, 'takes exactly one argument')
  579. return obj[argvals[0]:]
  580. elif member == 'splice':
  581. assertion(isinstance(obj, list), 'must be applied on a list')
  582. assertion(argvals, 'takes one or more arguments')
  583. index, howMany = map(int, (argvals + [len(obj)])[:2])
  584. if index < 0:
  585. index += len(obj)
  586. add_items = argvals[2:]
  587. res = []
  588. for i in range(index, min(index + howMany, len(obj))):
  589. res.append(obj.pop(index))
  590. for i, item in enumerate(add_items):
  591. obj.insert(index + i, item)
  592. return res
  593. elif member == 'unshift':
  594. assertion(isinstance(obj, list), 'must be applied on a list')
  595. assertion(argvals, 'takes one or more arguments')
  596. for item in reversed(argvals):
  597. obj.insert(0, item)
  598. return obj
  599. elif member == 'pop':
  600. assertion(isinstance(obj, list), 'must be applied on a list')
  601. assertion(not argvals, 'does not take any arguments')
  602. if not obj:
  603. return
  604. return obj.pop()
  605. elif member == 'push':
  606. assertion(argvals, 'takes one or more arguments')
  607. obj.extend(argvals)
  608. return obj
  609. elif member == 'forEach':
  610. assertion(argvals, 'takes one or more arguments')
  611. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  612. f, this = (argvals + [''])[:2]
  613. return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  614. elif member == 'indexOf':
  615. assertion(argvals, 'takes one or more arguments')
  616. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  617. idx, start = (argvals + [0])[:2]
  618. try:
  619. return obj.index(idx, start)
  620. except ValueError:
  621. return -1
  622. idx = int(member) if isinstance(obj, list) else member
  623. return obj[idx](argvals, allow_recursion=allow_recursion)
  624. if remaining:
  625. ret, should_abort = self.interpret_statement(
  626. self._named_object(local_vars, eval_method()) + remaining,
  627. local_vars, allow_recursion)
  628. return ret, should_return or should_abort
  629. else:
  630. return eval_method(), should_return
  631. elif md.get('function'):
  632. fname = m.group('fname')
  633. argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  634. for v in self._separate(m.group('args'))]
  635. if fname in local_vars:
  636. return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  637. elif fname not in self._functions:
  638. self._functions[fname] = self.extract_function(fname)
  639. return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  640. raise self.Exception(
  641. 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  642. def interpret_expression(self, expr, local_vars, allow_recursion):
  643. ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  644. if should_return:
  645. raise self.Exception('Cannot return from an expression', expr)
  646. return ret
  647. def extract_object(self, objname):
  648. _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  649. obj = {}
  650. obj_m = re.search(
  651. r'''(?x)
  652. (?<!this\.)%s\s*=\s*{\s*
  653. (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
  654. }\s*;
  655. ''' % (re.escape(objname), _FUNC_NAME_RE),
  656. self.code)
  657. if not obj_m:
  658. raise self.Exception('Could not find object ' + objname)
  659. fields = obj_m.group('fields')
  660. # Currently, it only supports function definitions
  661. fields_m = re.finditer(
  662. r'''(?x)
  663. (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  664. ''' % (_FUNC_NAME_RE, _NAME_RE),
  665. fields)
  666. for f in fields_m:
  667. argnames = self.build_arglist(f.group('args'))
  668. obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
  669. return obj
  670. def extract_function_code(self, funcname):
  671. """ @returns argnames, code """
  672. func_m = re.search(
  673. r'''(?xs)
  674. (?:
  675. function\s+%(name)s|
  676. [{;,]\s*%(name)s\s*=\s*function|
  677. (?:var|const|let)\s+%(name)s\s*=\s*function
  678. )\s*
  679. \((?P<args>[^)]*)\)\s*
  680. (?P<code>{.+})''' % {'name': re.escape(funcname)},
  681. self.code)
  682. code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match
  683. if func_m is None:
  684. raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  685. return self.build_arglist(func_m.group('args')), code
  686. def extract_function(self, funcname):
  687. return self.extract_function_from_code(*self.extract_function_code(funcname))
  688. def extract_function_from_code(self, argnames, code, *global_stack):
  689. local_vars = {}
  690. while True:
  691. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
  692. if mobj is None:
  693. break
  694. start, body_start = mobj.span()
  695. body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
  696. name = self._named_object(
  697. local_vars,
  698. self.extract_function_from_code(
  699. self.build_arglist(mobj.group('args')),
  700. body, local_vars, *global_stack))
  701. code = code[:start] + name + remaining
  702. return self.build_function(argnames, code, local_vars, *global_stack)
  703. def call_function(self, funcname, *args):
  704. return self.extract_function(funcname)(args)
  705. @classmethod
  706. def build_arglist(cls, arg_text):
  707. if not arg_text:
  708. return []
  709. def valid_arg(y):
  710. y = y.strip()
  711. if not y:
  712. raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
  713. return y
  714. return [valid_arg(x) for x in cls._separate(arg_text)]
  715. def build_function(self, argnames, code, *global_stack):
  716. global_stack = list(global_stack) or [{}]
  717. argnames = tuple(argnames)
  718. def resf(args, kwargs={}, allow_recursion=100):
  719. global_stack[0].update(
  720. zip_longest(argnames, args, fillvalue=None))
  721. global_stack[0].update(kwargs)
  722. var_stack = LocalNameSpace(*global_stack)
  723. ret, should_abort = self.interpret_statement(code.replace('\n', ''), var_stack, allow_recursion - 1)
  724. if should_abort:
  725. return ret
  726. return resf