Compare commits

...

8 Commits

Author SHA1 Message Date
jastrab
0481d66f8b
Merge efad43c197 into c5098961b0 2024-08-21 22:32:54 -04:00
dirkf
c5098961b0 [Youtube] Rework n function extraction pattern
Now also succeeds with player b12cc44b
2024-08-06 20:59:09 +01:00
dirkf
dbc08fba83 [jsinterp] Improve slice implementation for player b12cc44b
Partly taken from yt-dlp/yt-dlp#10664, thx seproDev
        Fixes #32896
2024-08-06 20:51:38 +01:00
Aiur Adept
71223bff39
[Youtube] Fix nsig extraction for player 20dfca59 (#32891)
* dirkf's patch for nsig extraction
* add generic search per  yt-dlp/yt-dlp/pull/10611 - thx bashonly

---------

Co-authored-by: dirkf <fieldhouse@gmx.net>
2024-08-01 19:18:34 +01:00
Jastrab
efad43c197 [joj] Fixed extractor 2022-01-16 11:15:15 +01:00
Jastrab
e9cb2c9f71 [joj] Fixed extractor 2022-01-15 21:30:46 +01:00
Jastrab
4cf557e765 [markiza] Fixed extractor 2022-01-15 21:27:57 +01:00
Jastrab
63af7465cc [rtvs] Fixed extractor for Slovak television and radio 2022-01-15 21:08:06 +01:00
7 changed files with 238 additions and 60 deletions

View File

@ -425,6 +425,34 @@ class TestJSInterpreter(unittest.TestCase):
self._test(jsi, [''], args=['', '-']) self._test(jsi, [''], args=['', '-'])
self._test(jsi, [], args=['', '']) self._test(jsi, [], args=['', ''])
def test_slice(self):
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice()}', [0, 1, 2, 3, 4, 5, 6, 7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(0)}', [0, 1, 2, 3, 4, 5, 6, 7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(5)}', [5, 6, 7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(99)}', [])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-2)}', [7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-99)}', [0, 1, 2, 3, 4, 5, 6, 7, 8])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(0, 0)}', [])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(1, 0)}', [])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(0, 1)}', [0])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(3, 6)}', [3, 4, 5])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(1, -1)}', [1, 2, 3, 4, 5, 6, 7])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-1, 1)}', [])
self._test('function f(){return [0, 1, 2, 3, 4, 5, 6, 7, 8].slice(-3, -1)}', [6, 7])
self._test('function f(){return "012345678".slice()}', '012345678')
self._test('function f(){return "012345678".slice(0)}', '012345678')
self._test('function f(){return "012345678".slice(5)}', '5678')
self._test('function f(){return "012345678".slice(99)}', '')
self._test('function f(){return "012345678".slice(-2)}', '78')
self._test('function f(){return "012345678".slice(-99)}', '012345678')
self._test('function f(){return "012345678".slice(0, 0)}', '')
self._test('function f(){return "012345678".slice(1, 0)}', '')
self._test('function f(){return "012345678".slice(0, 1)}', '0')
self._test('function f(){return "012345678".slice(3, 6)}', '345')
self._test('function f(){return "012345678".slice(1, -1)}', '1234567')
self._test('function f(){return "012345678".slice(-1, 1)}', '')
self._test('function f(){return "012345678".slice(-3, -1)}', '67')
if __name__ == '__main__': if __name__ == '__main__':
unittest.main() unittest.main()

View File

@ -174,6 +174,14 @@ _NSIG_TESTS = [
'https://www.youtube.com/s/player/5604538d/player_ias.vflset/en_US/base.js', 'https://www.youtube.com/s/player/5604538d/player_ias.vflset/en_US/base.js',
'7X-he4jjvMx7BCX', 'sViSydX8IHtdWA', '7X-he4jjvMx7BCX', 'sViSydX8IHtdWA',
), ),
(
'https://www.youtube.com/s/player/20dfca59/player_ias.vflset/en_US/base.js',
'-fLCxedkAk4LUTK2', 'O8kfRq1y1eyHGw',
),
(
'https://www.youtube.com/s/player/b12cc44b/player_ias.vflset/en_US/base.js',
'keLa5R2U00sR9SQK', 'N1OGyujjEwMnLw',
),
] ]

View File

@ -2,6 +2,7 @@
from __future__ import unicode_literals from __future__ import unicode_literals
import re import re
import json
from .common import InfoExtractor from .common import InfoExtractor
from ..compat import compat_str from ..compat import compat_str
@ -21,7 +22,8 @@ class JojIE(InfoExtractor):
(?P<id>[^/?#^]+) (?P<id>[^/?#^]+)
''' '''
_TESTS = [{ _TESTS = [{
'url': 'https://media.joj.sk/embed/a388ec4c-6019-4a4a-9312-b1bee194e932', 'url':
'https://media.joj.sk/embed/a388ec4c-6019-4a4a-9312-b1bee194e932',
'info_dict': { 'info_dict': {
'id': 'a388ec4c-6019-4a4a-9312-b1bee194e932', 'id': 'a388ec4c-6019-4a4a-9312-b1bee194e932',
'ext': 'mp4', 'ext': 'mp4',
@ -64,16 +66,20 @@ class JojIE(InfoExtractor):
r'(?s)(?:src|bitrates)\s*=\s*({.+?});', webpage, 'bitrates', r'(?s)(?:src|bitrates)\s*=\s*({.+?});', webpage, 'bitrates',
default='{}'), default='{}'),
video_id, transform_source=js_to_json, fatal=False) video_id, transform_source=js_to_json, fatal=False)
quality = self._search_regex(
r'var qualityLabels = ({.*?});', webpage, 'quality', default=None)
quality = json.loads(quality)
formats = [] formats = []
for format_url in try_get(bitrates, lambda x: x['mp4'], list) or []: for format_url in try_get(bitrates, lambda x: x['mp4'], list) or []:
if isinstance(format_url, compat_str): if isinstance(format_url, compat_str):
height = self._search_regex( height = self._search_regex(
r'(\d+)[pP]\.', format_url, 'height', default=None) r'-(\d+)p?\.', format_url, 'height', default=None)
formats.append({ formats.append({
'url': format_url, 'url': format_url,
'format_id': '%sp' % height if height else None, 'format_id': '%sp' % height if height else None,
'height': int(height), 'height': int(height),
'resolution': quality.get(compat_str(height)+'p')
}) })
if not formats: if not formats:
playlist = self._download_xml( playlist = self._download_xml(
@ -104,5 +110,5 @@ class JojIE(InfoExtractor):
'title': title, 'title': title,
'thumbnail': thumbnail, 'thumbnail': thumbnail,
'duration': duration, 'duration': duration,
'formats': formats, 'formats': formats
} }

View File

@ -1,21 +1,23 @@
# coding: utf-8 # coding: utf-8
from __future__ import unicode_literals from __future__ import unicode_literals
# update 15.01.2022 jastrab
import re import re
import json
from .common import InfoExtractor from .common import InfoExtractor
from ..compat import compat_str
from ..utils import ( from ..utils import (
orderedSet, orderedSet,
parse_duration, url_or_none,
try_get, determine_ext
) )
class MarkizaIE(InfoExtractor): class MarkizaIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?videoarchiv\.markiza\.sk/(?:video/(?:[^/]+/)*|embed/)(?P<id>\d+)(?:[_/]|$)' _VALID_URL = r'https:\/\/(?:www\.)?videoarchiv\.markiza\.sk\/(?:video\/(?:[^\/]+\/)*|embed\/)epizoda\/(?P<id>\d+)(?:[\_\/\-]|$)'
_TESTS = [{ _TESTS = [{
'url': 'http://videoarchiv.markiza.sk/video/oteckovia/84723_oteckovia-109', 'url': 'http://videoarchiv.markiza.sk/video/oteckovia/\
84723_oteckovia-109',
'md5': 'ada4e9fad038abeed971843aa028c7b0', 'md5': 'ada4e9fad038abeed971843aa028c7b0',
'info_dict': { 'info_dict': {
'id': '139078', 'id': '139078',
@ -26,54 +28,89 @@ class MarkizaIE(InfoExtractor):
'duration': 2760, 'duration': 2760,
}, },
}, { }, {
'url': 'http://videoarchiv.markiza.sk/video/televizne-noviny/televizne-noviny/85430_televizne-noviny', 'url': ' https://videoarchiv.markiza.sk/video/laska-na-prenajom/epizoda/58779-seria-1-epizoda-14',
'info_dict': { 'info_dict': {
'id': '85430', 'id': '85430',
'title': 'Televízne noviny', 'title': 'Televízne noviny',
}, },
'playlist_count': 23, 'playlist_count': 23,
}, { }, {
'url': 'http://videoarchiv.markiza.sk/video/oteckovia/84723', 'url': 'https://videoarchiv.markiza.sk/video/oteckovia/84723',
'only_matching': True, 'only_matching': True,
}, { }, {
'url': 'http://videoarchiv.markiza.sk/video/84723', 'url': 'https://videoarchiv.markiza.sk/video/84723',
'only_matching': True, 'only_matching': True,
}, { }, {
'url': 'http://videoarchiv.markiza.sk/video/filmy/85190_kamenak', 'url': 'https://videoarchiv.markiza.sk/video/filmy/85190_kamenak',
'only_matching': True, 'only_matching': True,
}, { }, {
'url': 'http://videoarchiv.markiza.sk/video/reflex/zo-zakulisia/84651_pribeh-alzbetky', 'url': 'https://videoarchiv.markiza.sk/video/reflex/zo-zakulisia/84651_pribeh-alzbetky',
'only_matching': True, 'only_matching': True,
}, { }, {
'url': 'http://videoarchiv.markiza.sk/embed/85295', 'url': 'https://videoarchiv.markiza.sk/embed/85295',
'only_matching': True, 'only_matching': True,
}] }]
def _real_extract(self, url): def _real_extract(self, url):
video_id = self._match_id(url) video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id)
embed = self._search_regex(
r'<iframe src="(https:\/\/media.*?)" style="',
webpage, 'embed', fatal=False)
webpage = self._download_webpage(embed, video_id)
data = self._search_regex(
r'processAdTagModifier\((\{.*)\), {"video":',
webpage, 'embed', fatal=False)
data2 = self._search_regex(
r'processAdTagModifier\(\{.*\), ({"video":.*)\);',
webpage, 'embed', fatal=False)
data = re.sub('\\\\/', '/', data)
data2 = re.sub('\\\\/', '/', data2)
info = json.loads(data)
info2 = json.loads(data2)
data = self._download_json( formats = []
'http://videoarchiv.markiza.sk/json/video_jwplayer7.json', for format_id, format_list in info['tracks'].items():
video_id, query={'id': video_id}) if not isinstance(format_list, list):
format_list = [format_list]
info = self._parse_jwplayer_data(data, m3u8_id='hls', mpd_id='dash') for format_dict in format_list:
if not isinstance(format_dict, dict):
if info.get('_type') == 'playlist': continue
info.update({ format_url = url_or_none(format_dict.get('src'))
'id': video_id, format_type = format_dict.get('type')
'title': try_get( ext = determine_ext(format_url)
data, lambda x: x['details']['name'], compat_str), if (format_type == 'application/x-mpegURL'
}) or format_id == 'HLS' or ext == 'm3u8'):
else: formats.extend(self._extract_m3u8_formats(
info['duration'] = parse_duration( format_url, video_id, 'mp4',
try_get(data, lambda x: x['details']['duration'], compat_str)) entry_protocol='m3u8_native', m3u8_id='hls',
return info fatal=False))
elif (format_type == 'application/dash+xml'
or format_id == 'DASH' or ext == 'mpd'):
formats.extend(self._extract_mpd_formats(
format_url, video_id, mpd_id='dash', fatal=False))
else:
formats.append({
'url': format_url,
})
thumbnail = info.get('plugins').get('thumbnails').get('url')
thumbnail = re.sub('$Num$', '001', thumbnail)
duration = info.get('duration')
title2 = info2.get('video').get('title')
title = info2.get('video').get('custom').get('show_title')
return {
'id': video_id,
'title': title + ' - ' + title2,
'thumbnail': thumbnail,
'duration': duration,
'formats': formats
}
class MarkizaPageIE(InfoExtractor): class MarkizaPageIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?(?:(?:[^/]+\.)?markiza|tvnoviny)\.sk/(?:[^/]+/)*(?P<id>\d+)_' _VALID_URL = r'https?://(?:www\.)?(?:(?:[^/]+\.)?markiza|tvnoviny)\.sk/(?:[^/]+/)*(?P<id>\d+)_'
_TESTS = [{ _TESTS = [{
'url': 'http://www.markiza.sk/soubiz/zahranicny/1923705_oteckovia-maju-svoj-den-ti-slavni-nie-su-o-nic-menej-rozkosni', 'url': 'https://www.markiza.sk/soubiz/zahranicny/1923705_oteckovia-maju-svoj-den-ti-slavni-nie-su-o-nic-menej-rozkosni',
'md5': 'ada4e9fad038abeed971843aa028c7b0', 'md5': 'ada4e9fad038abeed971843aa028c7b0',
'info_dict': { 'info_dict': {
'id': '139355', 'id': '139355',
@ -87,29 +124,30 @@ class MarkizaPageIE(InfoExtractor):
'skip_download': True, 'skip_download': True,
}, },
}, { }, {
'url': 'http://dajto.markiza.sk/filmy-a-serialy/1774695_frajeri-vo-vegas', 'url': 'https://dajto.markiza.sk/filmy-a-serialy/1774695_frajeri-vo-vegas',
'only_matching': True, 'only_matching': True,
}, { }, {
'url': 'http://superstar.markiza.sk/aktualne/1923870_to-je-ale-telo-spevacka-ukazala-sexy-postavicku-v-bikinach', 'url': 'https://superstar.markiza.sk/aktualne/\
1923870_to-je-ale-telo-spevacka-ukazala-sexy-postavicku-v-bikinach',
'only_matching': True, 'only_matching': True,
}, { }, {
'url': 'http://hybsa.markiza.sk/aktualne/1923790_uzasna-atmosfera-na-hybsa-v-poprade-superstaristi-si-prve-koncerty-pred-davom-ludi-poriadne-uzili', 'url': 'https://hybsa.markiza.sk/aktualne/1923790_uzasna-atmosfera-na-hybsa-v-poprade-superstaristi-si-prve-koncerty-pred-davom-ludi-poriadne-uzili',
'only_matching': True, 'only_matching': True,
}, { }, {
'url': 'http://doma.markiza.sk/filmy/1885250_moja-vysnivana-svadba', 'url': 'https://doma.markiza.sk/filmy/1885250_moja-vysnivana-svadba',
'only_matching': True, 'only_matching': True,
}, { }, {
'url': 'http://www.tvnoviny.sk/domace/1923887_po-smrti-manzela-ju-cakalo-poriadne-prekvapenie', 'url': 'https://www.tvnoviny.sk/domace/1923887_po-smrti-manzela-ju-cakalo-poriadne-prekvapenie',
'only_matching': True, 'only_matching': True,
}] }]
@classmethod @classmethod
def suitable(cls, url): def suitable(cls, url):
return False if MarkizaIE.suitable(url) else super(MarkizaPageIE, cls).suitable(url) return False if MarkizaIE.suitable(url) else \
super(MarkizaPageIE, cls).suitable(url)
def _real_extract(self, url): def _real_extract(self, url):
playlist_id = self._match_id(url) playlist_id = self._match_id(url)
webpage = self._download_webpage( webpage = self._download_webpage(
# Downloading for some hosts (e.g. dajto, doma) fails with 500 # Downloading for some hosts (e.g. dajto, doma) fails with 500
# although everything seems to be OK, so considering 500 # although everything seems to be OK, so considering 500
@ -117,7 +155,8 @@ class MarkizaPageIE(InfoExtractor):
url, playlist_id, expected_status=500) url, playlist_id, expected_status=500)
entries = [ entries = [
self.url_result('http://videoarchiv.markiza.sk/video/%s' % video_id) self.url_result(
'http://videoarchiv.markiza.sk/video/%s' % video_id)
for video_id in orderedSet(re.findall( for video_id in orderedSet(re.findall(
r'(?:initPlayer_|data-entity=["\']|id=["\']player_)(\d+)', r'(?:initPlayer_|data-entity=["\']|id=["\']player_)(\d+)',
webpage))] webpage))]

View File

@ -1,7 +1,13 @@
# coding: utf-8 # coding: utf-8
from __future__ import unicode_literals from __future__ import unicode_literals
import re
from .common import InfoExtractor from .common import InfoExtractor
from ..utils import (
url_or_none,
determine_ext
)
class RTVSIE(InfoExtractor): class RTVSIE(InfoExtractor):
@ -26,7 +32,8 @@ class RTVSIE(InfoExtractor):
'id': '63118', 'id': '63118',
'ext': 'mp4', 'ext': 'mp4',
'title': 'Amaro Džives - Náš deň', 'title': 'Amaro Džives - Náš deň',
'description': 'Galavečer pri príležitosti Medzinárodného dňa Rómov.' 'description':
'Galavečer pri príležitosti Medzinárodného dňa Rómov.'
}, },
'params': { 'params': {
'skip_download': True, 'skip_download': True,
@ -36,12 +43,66 @@ class RTVSIE(InfoExtractor):
def _real_extract(self, url): def _real_extract(self, url):
video_id = self._match_id(url) video_id = self._match_id(url)
webpage = self._download_webpage(url, video_id) if url.find('/radio/') != -1:
a2 = url.split('/')[-1]
a1 = url.split('/')[-2]
embed = self._download_webpage(
"https://www.rtvs.sk/embed/radio/archive/%s/%s" % (a1, a2),
video_id)
audio_id = re.search('audio5f.json?id=(?P<id>[^\"]+)', embed)
audio_id = audio_id.group('id')
info = self._download_json(
"https://www.rtvs.sk/json/audio5f.json?id=%s" % audio_id,
audio_id)
playlist_url = self._search_regex( formats = []
r'playlist["\']?\s*:\s*(["\'])(?P<url>(?:(?!\1).)+)\1', webpage, formats.append({
'playlist url', group='url') 'url': info['playlist'][0]['sources'][0]['src'],
'format_id': None,
'height': 0
})
info = info['playlist'][0]
return {
'id': audio_id,
'title': info.get('title'),
'thumbnail': info.get('image'),
'formats': formats
}
else:
info = self._download_json(
"https://www.rtvs.sk/json/archive5f.json?id=%s" % video_id,
video_id)
info = info.get('clip')
data = self._download_json( formats = []
playlist_url, video_id, 'Downloading playlist')[0] for format_id, format_list in info.items():
return self._parse_jwplayer_data(data, video_id=video_id) if not isinstance(format_list, list):
format_list = [format_list]
for format_dict in format_list:
if not isinstance(format_dict, dict):
continue
format_url = url_or_none(format_dict.get('src'))
format_type = format_dict.get('type')
ext = determine_ext(format_url)
if (format_type == 'application/x-mpegURL'
or format_id == 'HLS' or ext == 'm3u8'):
formats.extend(self._extract_m3u8_formats(
format_url, video_id, 'mp4',
entry_protocol='m3u8_native', m3u8_id='hls',
fatal=False))
elif (format_type == 'application/dash+xml'
or format_id == 'DASH' or ext == 'mpd'):
pass
else:
formats.append({
'url': format_url,
})
formats = sorted(formats, key=lambda i: i['tbr'])
dt = info.get('datetime_create')
return {
'id': video_id,
'title': info.get('title') + '-' + dt[:10],
'thumbnail': info.get('image'),
'description': info.get('description'),
'formats': formats
}

View File

@ -1659,17 +1659,46 @@ class YoutubeIE(YoutubeBaseInfoExtractor):
def _extract_n_function_name(self, jscode): def _extract_n_function_name(self, jscode):
func_name, idx = self._search_regex( func_name, idx = self._search_regex(
# new: (b=String.fromCharCode(110),c=a.get(b))&&c=nfunc[idx](c) # new: (b=String.fromCharCode(110),c=a.get(b))&&c=nfunc[idx](c)
# or: (b="nn"[+a.D],c=a.get(b))&&(c=nfunc[idx](c)s # or: (b="nn"[+a.D],c=a.get(b))&&(c=nfunc[idx](c)
# old: .get("n"))&&(b=nfunc[idx](b) # or: (PL(a),b=a.j.n||null)&&(b=nfunc[idx](b)
# older: .get("n"))&&(b=nfunc(b) # or: (b="nn"[+a.D],vL(a),c=a.j[b]||null)&&(c=narray[idx](c),a.set(b,c),narray.length||nfunc("")
# old: (b=a.get("n"))&&(b=nfunc[idx](b)(?P<c>[a-z])\s*=\s*[a-z]\s*
# older: (b=a.get("n"))&&(b=nfunc(b)
r'''(?x) r'''(?x)
(?:\(\s*(?P<b>[a-z])\s*=\s*(?: \((?:[\w$()\s]+,)*?\s* # (
String\s*\.\s*fromCharCode\s*\(\s*110\s*\)| (?P<b>[a-z])\s*=\s* # b=
"n+"\[\s*\+?s*[\w$.]+\s*] (?:
)\s*,(?P<c>[a-z])\s*=\s*[a-z]\s*)? (?: # expect ,c=a.get(b) (etc)
\.\s*get\s*\(\s*(?(b)(?P=b)|"n{1,2}")(?:\s*\)){2}\s*&&\s*\(\s*(?(c)(?P=c)|b)\s*=\s* String\s*\.\s*fromCharCode\s*\(\s*110\s*\)|
(?P<nfunc>[a-zA-Z_$][\w$]*)(?:\s*\[(?P<idx>\d+)\])?\s*\(\s*[\w$]+\s*\) "n+"\[\s*\+?s*[\w$.]+\s*]
''', jscode, 'Initial JS player n function name', group=('nfunc', 'idx')) )\s*(?:,[\w$()\s]+(?=,))*|
(?P<old>[\w$]+) # a (old[er])
)\s*
(?(old)
# b.get("n")
(?:\.\s*[\w$]+\s*|\[\s*[\w$]+\s*]\s*)*?
(?:\.\s*n|\[\s*"n"\s*]|\.\s*get\s*\(\s*"n"\s*\))
| # ,c=a.get(b)
,\s*(?P<c>[a-z])\s*=\s*[a-z]\s*
(?:\.\s*[\w$]+\s*|\[\s*[\w$]+\s*]\s*)*?
(?:\[\s*(?P=b)\s*]|\.\s*get\s*\(\s*(?P=b)\s*\))
)
# interstitial junk
\s*(?:\|\|\s*null\s*)?(?:\)\s*)?&&\s*(?:\(\s*)?
(?(c)(?P=c)|(?P=b))\s*=\s* # [c|b]=
# nfunc|nfunc[idx]
(?P<nfunc>[a-zA-Z_$][\w$]*)(?:\s*\[(?P<idx>\d+)\])?\s*\(\s*[\w$]+\s*\)
''', jscode, 'Initial JS player n function name', group=('nfunc', 'idx'),
default=(None, None))
# thx bashonly: yt-dlp/yt-dlp/pull/10611
if not func_name:
self.report_warning('Falling back to generic n function search')
return self._search_regex(
r'''(?xs)
(?:(?<=[^\w$])|^) # instead of \b, which ignores $
(?P<name>(?!\d)[a-zA-Z\d_$]+)\s*=\s*function\((?!\d)[a-zA-Z\d_$]+\)
\s*\{(?:(?!};).)+?["']enhanced_except_
''', jscode, 'Initial JS player n function name', group='name')
if not idx: if not idx:
return func_name return func_name

View File

@ -925,9 +925,16 @@ class JSInterpreter(object):
obj.reverse() obj.reverse()
return obj return obj
elif member == 'slice': elif member == 'slice':
assertion(isinstance(obj, list), 'must be applied on a list') assertion(isinstance(obj, (list, compat_str)), 'must be applied on a list or string')
assertion(len(argvals) == 1, 'takes exactly one argument') # From [1]:
return obj[argvals[0]:] # .slice() - like [:]
# .slice(n) - like [n:] (not [slice(n)]
# .slice(m, n) - like [m:n] or [slice(m, n)]
# [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
assertion(len(argvals) <= 2, 'takes between 0 and 2 arguments')
if len(argvals) < 2:
argvals += (None,)
return obj[slice(*argvals)]
elif member == 'splice': elif member == 'splice':
assertion(isinstance(obj, list), 'must be applied on a list') assertion(isinstance(obj, list), 'must be applied on a list')
assertion(argvals, 'takes one or more arguments') assertion(argvals, 'takes one or more arguments')