jsinterp.py 33 KB

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