jsinterp.py 34 KB

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