jsinterp.py 33 KB

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