Ejemplo n.º 1
0
 def setUp(self, load_plugins=True):
     self.mocker = requests_mock.Mocker()
     self.mocker.register_uri(requests_mock.ANY, requests_mock.ANY, text="")
     self.mocker.start()
     self.session = Streamlink()
     if load_plugins:
         self.session.load_plugins(self.PluginPath)
Ejemplo n.º 2
0
    def _test_args(self, args, commandline, mock_argv, mock_popen, mock_call, mock_sleep, mock_setup_streamlink,
                   passthrough=False, exit_code=0):
        mock_argv.__getitem__.side_effect = lambda x: args[x]

        def side_effect(results):
            def fn(*args):
                result = results.pop(0)
                return result

            return fn

        mock_popen.return_value = Mock(poll=Mock(side_effect=side_effect([None, 0])))

        session = Streamlink()
        session.load_plugins(os.path.join(os.path.dirname(__file__), "plugin"))

        actual_exit_code = 0
        with patch('streamlink_cli.main.streamlink', session):
            try:
                streamlink_cli.main.main()
            except SystemExit as exc:
                actual_exit_code = exc.code

        self.assertEqual(exit_code, actual_exit_code)
        mock_setup_streamlink.assert_called_with()
        if not passthrough:
            mock_popen.assert_called_with(commandline, stderr=ANY, stdout=ANY, bufsize=ANY, stdin=ANY)
        else:
            mock_call.assert_called_with(commandline, stderr=ANY, stdout=ANY)
 def __init__(self,
              board,
              target_url,
              drmbypass=False,
              reset=False,
              verbosity=False):
     self.exit = False
     self.slink_exit = False
     self.target_url = target_url
     self.stream = None
     self.stream_fd = None
     self.stream_url = None
     self.width = None
     self.height = None
     self.frame_size = None
     self.stream_opened = False
     self.slk = Streamlink()
     self.slk.set_option('ringbuffer-size', 131072)
     self.slink_running = False
     self.fapp_xclbin = None
     self.fapp_drmbypass = drmbypass
     self.dec_process = None
     self.enc_process = None
     self.board = board
     self.board_reset = reset
     self.verb = verbosity
     if board == 'aws':
         self.fapp_xclbin = FPGA_BITSTREAM_AWS
     elif board == 'u200':
         self.fapp_xclbin = FPGA_BITSTREAM_U200
     else:
         raise UnknownFPGAboard(f'FPGA Board {board} not supported')
     self.thread_slk = Thread(target=self.slink_read)
 def init_streamlink(self):
     self.session = Streamlink()
     self.session.set_option("http-headers", "User-Agent=Mozilla/5.0 (Windows NT 10.0 Win64 x64 rv:72.0) Gecko/20100101 Firefox/72.0")
     self.streams = self.session.streams(self.webcam)
     if self.streams is None:
         raise ValueError("cannot open the stream link %s" % self.webcam)
     try:
         qlist = list(self.streams.keys())
         print(qlist)
         quality = max([q for q in qlist if q[-1].lower() == 'p'])
         print('The stream quality is {}'.format(quality))
         self.stream = self.streams['%s' % quality]
         self.stream_url = self.stream.url
         self.video_cap = cv2.VideoCapture(self.stream_url)
     except Exception as e:
         print(e)
         # raise ValueError("cannot open the stream link %s" % self.webcam)
         try:
             quality = 'best'
             print('The stream quality is {}'.format(quality))
             self.stream = self.streams['%s' % quality]
             self.stream_url = self.stream.url
             self.video_cap = cv2.VideoCapture(self.stream_url)
         except:
             try:
                 quality = list(self.streams.keys())[0]
                 print('---can not find the best stream quality, use the first one---')
                 print('The stream quality is {}'.format(quality))
                 self.stream = self.streams['%s' % quality]
                 self.stream_url = self.stream.url
                 self.video_cap = cv2.VideoCapture(self.stream_url)
             except Exception as e:
                 print(e)
             finally:
                 raise ValueError("cannot open the stream link %s" % self.webcam)
Ejemplo n.º 5
0
    def test_https_proxy_set_only(self):
        session = Streamlink()
        session.set_option("https-proxy", "https://testhttpsproxy.com")

        self.assertFalse("http" in session.http.proxies)
        self.assertEqual("https://testhttpsproxy.com",
                         session.http.proxies['https'])
Ejemplo n.º 6
0
def setup_plugin_options(session: Streamlink, plugin: Type[Plugin]):
    """Sets Streamlink plugin options."""
    pname = plugin.module
    required = OrderedDict({})

    for parg in plugin.arguments:
        if parg.options.get("help") == argparse.SUPPRESS:
            continue

        value = getattr(
            args, parg.dest if parg.is_global else parg.namespace_dest(pname))
        session.set_plugin_option(pname, parg.dest, value)

        if not parg.is_global:
            if parg.required:
                required[parg.name] = parg
            # if the value is set, check to see if any of the required arguments are not set
            if parg.required or value:
                try:
                    for rparg in plugin.arguments.requires(parg.name):
                        required[rparg.name] = rparg
                except RuntimeError:
                    log.error(
                        f"{pname} plugin has a configuration error and the arguments cannot be parsed"
                    )
                    break

    if required:
        for req in required.values():
            if not session.get_plugin_option(pname, req.dest):
                prompt = f"{req.prompt or f'Enter {pname} {req.name}'}: "
                session.set_plugin_option(
                    pname, req.dest,
                    console.askpass(prompt)
                    if req.sensitive else console.ask(prompt))
Ejemplo n.º 7
0
            def test(self, mock_http):
                self.session = Streamlink()
                self.session.load_plugins('plugins')

                mock_http.get = api.HTTPSession().get
                mock_http.json = api.HTTPSession().json

                Resolve.bind(self.session, "test.resolve")

                default_iframe = "http://mocked/default/iframe"
                file_url = _stream_data["url"]
                self_url = "http://mocked/live"

                with requests_mock.Mocker() as mock:
                    mock.get(default_iframe,
                             text=text_with_playlist % file_url)
                    mock.get(file_url, text=_stream_data["text"])
                    mock.get(self_url, text=_website_text)

                    self.session.set_plugin_option("resolve",
                                                   "whitelist_netloc",
                                                   ["mocked"])

                    plugin = Resolve(self_url)
                    streams = plugin._get_streams()
                    self.assertIn(_stream_data["name"], streams)
Ejemplo n.º 8
0
    def get_video(self):
        session = Streamlink()  #创建一个会话

        try:
            streams = session.streams(self.movie)  #在会话里输入url会返回直播的flv缓存地址
        except:
            try:
                streams = streamlink.streams(self.movie)
            except:
                print('[INFO]该网站不存在plug接口')
                exit(0)

        print('[INFO]获取了视屏流地址.....')
        list = ['source', 'medium', 'best', 'worse']
        for l in list:
            if streams[l].url:
                print('[INFO]获得视频%s' % l)
                source = streams[l].url
                if 'm3u8' in str(source):
                    print('[ERROR]%s存在m3u8,暂不支持下载,' % l)
                    continue
                else:
                    socket.setdefaulttimeout(10)
                    while streams[l].url:
                        try:
                            name = time.strftime('%m%d_%H%M%S',
                                                 time.localtime()) + '.flv'
                            print(name + '正在缓存')
                            path = './video/' + name
                            request.urlretrieve(
                                source, os.path.join(path))  # 'video/1.flv'
                            print('[INFO]您缓存的直播已下播......')
                            break
                        except socket.timeout:
                            continue
Ejemplo n.º 9
0
 def __init__(self, stream_data):
     # streamlink (low overhead for consecutive retreivals)
     self.__session = Streamlink()
     self.__url = stream_data['url']
     self.__tag = stream_data['tag']
     self.__frame = None
     # for saving frames locally
     self.__image_path = f'../images/{stream_data["image_path"]}.png'
Ejemplo n.º 10
0
    def test_set_via_session(self):
        with self._mock_console_input() as console_input:
            session = Streamlink({"user-input-requester": console_input})
            session.load_plugins(os.path.join(os.path.dirname(__file__), "plugins"))

            p = session.resolve_url("http://test.se/channel")
            self.assertEqual("username", p.input_ask("username"))
            self.assertEqual("password", p.input_ask_password("password"))
Ejemplo n.º 11
0
 def __init__(self, status_func=None):
     PlayerBase.__init__(self, status_func)
     self.qualities_cache = Cache(_cache_size)
     self.streamlink = Streamlink()
     #check if this works for multiple streams
     self._output = self._create_output()
     self.lock = threading.Lock()
     self.alive_threads = []
Ejemplo n.º 12
0
 def search_resolutions(self, go):
     streamlink = Streamlink()
     streams = streamlink.streams(f"https://www.twitch.tv/{go}")
     list_resolution = [i for i in streams]
     if "worst" in list_resolution:
         list_resolution.remove("worst")
     if "best" in list_resolution:
         list_resolution.remove("best")
     self.dialog_select_resolution(list_r=list_resolution)
Ejemplo n.º 13
0
 def openStream(self):
     self.safeClose(self.stream)
     session = Streamlink()
     if self.accessToken != "":
         session.set_plugin_option('twitch', 'oauth-token',
                                   self.accessToken)
     streams = streamlink.streams("http://twitch.tv/{0}".format(
         self.username))
     stream = streams['best']
     self.stream = stream.open()
Ejemplo n.º 14
0
def get_stream_url(streamer):
    s = Streamlink()
    url = "https://twitch.tv/" + streamer
    streams = s.streams(url)
    if streams == {}:
        return ""
    stream = streams["best"]
    fd = stream.open()
    stream_url = fd.writer.stream.url
    fd.close()
    return stream_url
Ejemplo n.º 15
0
    def test_arguments(self):
        from streamlink_cli.main import setup_plugin_args
        session = Streamlink()
        parser = MagicMock()
        group = parser.add_argument_group("Plugin Options").add_argument_group("UStreamTV")

        session.plugins = {
            'ustreamtv': UStreamTV
        }

        setup_plugin_args(session, parser)

        group.add_argument.assert_called_with('--ustream-password', metavar="PASSWORD", help=ANY)
Ejemplo n.º 16
0
    def test_arguments(self):
        from streamlink_cli.main import setup_plugin_args
        session = Streamlink()
        parser = MagicMock()
        plugin_parser = MagicMock()
        parser.add_argument_group = MagicMock(return_value=plugin_parser)

        session.plugins = {
            'ustreamtv': UStreamTV
        }

        setup_plugin_args(session, parser)

        plugin_parser.add_argument.assert_called_with('--ustream-password', metavar="PASSWORD", help=ANY)
Ejemplo n.º 17
0
def api(url: str):
    streamlink = Streamlink()

    try:
        plugin = streamlink.resolve_url(url)
        streams = plugin.streams()
    except NoPluginError as e:
        raise HTTPException(
            status_code=500,
            detail="Streamlink is unable to handle the URL '{0}'".format(url))
    except PluginError as e:
        if e.__str__().startswith('Unable to find channel'):
            raise HTTPException(status_code=404, detail="Stream not found")
        raise HTTPException(status_code=500,
                            detail="Error while fetching stream - " + str(e))
    except Exception:
        raise HTTPException(status_code=500,
                            detail="Error while fetching stream")

    out = {}
    for quality, stream in streams.items():
        out[quality] = stream.url

    live = False
    if len(streams.items()) > 0:
        live = True

    try:
        id = plugin.channel_id
    except:
        id = plugin.video_id

    try:
        channel = plugin.channel
    except:
        channel = None

    return {
        'streams': out,
        'url': url,
        'channel': {
            'live': live,
            'id': id,
            'plugin': plugin.module,
            'author': plugin.author,
            'channel': channel,
            'url': plugin.url,
            'title': plugin.title
        }
    }
Ejemplo n.º 18
0
    def subject(self, **params):
        with requests_mock.Mocker() as mock:
            mock.get("https://api.twitch.tv/kraken/users?login=foo",
                     json={"users": [{
                         "_id": 1234
                     }]})
            mock.get(
                "https://api.twitch.tv/kraken/streams/1234",
                json={"stream": None} if params.pop("offline", False) else {
                    "stream": {
                        "stream_type":
                        params.pop("stream_type", "live"),
                        "broadcast_platform":
                        params.pop("broadcast_platform", "live"),
                        "channel": {
                            "broadcaster_software":
                            params.pop("broadcaster_software", "")
                        }
                    }
                })

            session = Streamlink()
            Twitch.bind(session, "tests.plugins.test_twitch")
            plugin = Twitch("https://www.twitch.tv/foo")
            plugin.options.set("disable-reruns", params.pop("disable", True))

            return plugin._check_for_rerun()
Ejemplo n.º 19
0
    def start(self, *mocked, **params):
        with requests_mock.Mocker() as mock:
            mocked_users = mock.get(
                "https://api.twitch.tv/kraken/users.json?login=foo",
                json={"users": [{
                    "_id": 1234
                }]})
            mocked_stream = mock.get(
                "https://api.twitch.tv/kraken/streams/1234.json",
                json={"stream": None} if params.pop("offline", False) else {
                    "stream": {
                        "stream_type":
                        params.pop("stream_type", "live"),
                        "broadcast_platform":
                        params.pop("broadcast_platform", "live"),
                        "channel": {
                            "broadcaster_software":
                            params.pop("broadcaster_software", "")
                        }
                    }
                })

            session = Streamlink()
            Twitch.bind(session, "tests.plugins.test_twitch")
            plugin = Twitch("https://www.twitch.tv/foo")
            plugin.options.set("disable-reruns", params.pop("disable", True))
            try:
                streams = plugin.streams()
            except TestTwitchReruns.StopError:
                streams = True
                pass

            return streams, mocked_users, mocked_stream, mocked[0]
Ejemplo n.º 20
0
    def subject(channel, hosts=None, disable=False):
        with requests_mock.Mocker() as mock:
            mock.register_uri(requests_mock.ANY,
                              requests_mock.ANY,
                              exc=requests_mock.exceptions.InvalidRequest)
            if hosts is None:
                mock.post("https://gql.twitch.tv/gql", json={})
            else:
                mock.post("https://gql.twitch.tv/gql",
                          response_list=[{
                              "json": {
                                  "data": {
                                      "user": {
                                          "id": host[0],
                                          "hosting":
                                          None if not host[1:3] else {
                                              "login": host[1],
                                              "displayName": host[2]
                                          }
                                      }
                                  }
                              }
                          } for host in hosts])

            session = Streamlink()
            Twitch.bind(session, "tests.plugins.test_twitch")
            plugin = Twitch("https://twitch.tv/{0}".format(channel))
            plugin.options.set("disable-hosting", disable)

            res = plugin._switch_to_hosted_channel()
            return res, plugin.channel, plugin.author
Ejemplo n.º 21
0
 def setUp(self):
     self.session = Streamlink()
     self.session.http = MagicMock(HTTPSession)
     self.session.http.headers = {}
     Generic.bind(self.session, "test.generic")
     self.res_plugin = Generic("generic://https://example.com")
     self.res_plugin.html_text = ''
Ejemplo n.º 22
0
def startRecording(model):
    # 处理队列
    #global processingQueue
    #    try:
    result = requests.get(
        'https://chaturbate.com/api/chatvideocontext/{}/'.format(
            model)).json()

    session = Streamlink()
    session.set_option('http-headers',
                       "referer=https://www.chaturbate.com/{}".format(model))
    ts = "hlsvariant://{}".format(result['hls_source'].rsplit('?')[0])
    print(ts)
    streams = session.streams(ts)
    stream = streams["best"]
    fd = stream.open()
Ejemplo n.º 23
0
    def subject(self, channel, hosts=None, disable=False):
        with requests_mock.Mocker() as mock:
            mock.get("https://api.twitch.tv/kraken/users?login=foo",
                     json={"users": [{
                         "_id": 1
                     }]})
            if hosts is None:
                mock.get("https://tmi.twitch.tv/hosts", json={})
            else:
                mock.get("https://tmi.twitch.tv/hosts", [{
                    "json": {
                        "hosts": [
                            dict(host_id=host_id,
                                 target_id=target_id,
                                 target_login=target_login,
                                 target_display_name=target_display_name)
                        ]
                    }
                } for host_id, target_id, target_login, target_display_name in
                                                         hosts])

            session = Streamlink()
            Twitch.bind(session, "tests.plugins.test_twitch")
            plugin = Twitch("https://twitch.tv/{0}".format(channel))
            plugin.options.set("disable-hosting", disable)

            res = plugin._switch_to_hosted_channel()
            return res, plugin.channel, plugin._channel_id, plugin.author
Ejemplo n.º 24
0
    def __new__(mcs, name, bases, dict):
        plugin_path = os.path.dirname(streamlink.plugins.__file__)
        plugins = []
        for loader, pname, ispkg in pkgutil.iter_modules([plugin_path]):
            module = load_module(pname, plugin_path)
            if hasattr(module, "__plugin__"):
                plugins.append((pname))

        session = Streamlink()

        def gentest(pname):
            def load_plugin_test(self):
                # Reset file variable to ensure it is still open when doing
                # load_plugin else python might open the plugin source .py
                # using ascii encoding instead of utf-8.
                # See also open() call here: imp._HackedGetData.get_data
                file, pathname, desc = imp.find_module(pname, [plugin_path])
                session.load_plugin(pname, file, pathname, desc)
                # validate that can_handle_url does not fail
                session.plugins[pname].can_handle_url("http://test.com")

            return load_plugin_test

        for pname in plugins:
            dict['test_{0}_load'.format(pname)] = gentest(pname)

        return type.__new__(mcs, name, bases, dict)
Ejemplo n.º 25
0
    def setUpClass(cls):
        cls.session = Streamlink()
        docs_dir = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "../docs"))
        plugins_dir = streamlinkplugins.__path__[0]

        with open(os.path.join(docs_dir, "plugin_matrix.rst")) as plfh:
            parts = re.split(r"\n[= ]+\n", plfh.read())
            cls.plugins_in_docs = list(
                re.findall(r"^([\w_]+)\s", parts[3], re.MULTILINE))

        with open(os.path.join(plugins_dir, ".removed")) as rmfh:
            cls.plugins_removed = [
                pname for pname in rmfh.read().split("\n")
                if pname and not pname.startswith("#")
            ]

        tests_plugins_dir = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "plugins"))
        tests_plugin_files = glob(os.path.join(tests_plugins_dir, "test_*.py"))

        cls.plugins = cls.session.plugins.keys()
        cls.plugin_tests = [
            re.sub(r"^test_(.+)\.py$", r"\1", os.path.basename(file))
            for file in tests_plugin_files
        ]
        cls.plugins_no_protocols = [
            pname for pname in cls.plugins if pname not in cls.protocol_tests
        ]
        cls.plugin_tests_no_protocols = [
            pname for pname in cls.plugin_tests
            if pname not in cls.protocol_tests
        ]
Ejemplo n.º 26
0
    def setUp(self):
        self.session = Streamlink()
        docs_dir = os.path.abspath(
            os.path.join(os.path.dirname(__file__), "../docs"))

        with open(os.path.join(docs_dir, "plugin_matrix.rst")) as plfh:
            parts = self.title_re.split(plfh.read())
            self.plugins_in_docs = list(self.plugin_re.findall(parts[3]))
Ejemplo n.º 27
0
    def test_arguments(self):
        from streamlink_cli.main import setup_plugin_args
        session = Streamlink()
        parser = MagicMock()
        plugin_parser = MagicMock()
        parser.add_argument_group = MagicMock(return_value=plugin_parser)

        session.plugins = {
            'tvplayer': TVPlayer
        }

        setup_plugin_args(session, parser)

        self.assertSequenceEqual(plugin_parser.add_argument.mock_calls,
                                 [call('--tvplayer-email', metavar="EMAIL", help=ANY),
                                  call('--tvplayer-password', metavar="PASSWORD", help=ANY)],
                                 )
Ejemplo n.º 28
0
def session():
    session = Streamlink()
    session.set_option("http-cookies",
                       {"sessioncookiekey": "sessioncookieval"})
    session.set_option("http-headers",
                       {"sessionheaderkey": "sessionheaderval"})
    session.set_option("http-query-params",
                       {"sessionqueryparamkey": "sessionqueryparamval"})

    return session
Ejemplo n.º 29
0
class viewThread(threading.Thread):
    streamlink = Streamlink()
    fd = None
    run_v = False
    fileHandle = None

    def __init__(self, channel, quality):
        threading.Thread.__init__(self)
        self.channel = channel
        self.quality = quality

        # Create the Streamlink session
        url = "http://twitch.tv/"
        url += channel[1:]
        #  print "url"+url

        try:
            self.streamlink.set_option("http-proxy", http_proxy)
            #  self.streamlink.set_option("https-proxy", http_proxy)
            self.streamlink.set_option("rtmp-proxy", http_proxy)
            streams = self.streamlink.streams(url)
        except NoPluginError:
            exit("Streamlink is unable to handle the URL '{0}'".format(url))
        except PluginError as err:
            exit("Plugin error: {0}".format(err))

            # Look for specified stream
        if quality not in streams:
            exit("Unable to find '{0}' stream on URL '{1}'".format(
                quality, url))

            # We found the stream
        stream = streams[quality]
        self.fd = stream.open()
        #
        #open fil
        self.fileHandle = open('videodump.flv', 'w')

    def run(self):
        print "Starting recording"
        self.run_v = True
        # Get lock to synchronize threads
        while self.run_v:
            try:
                if self.fd:
                    data = self.fd.read(1024)
                    self.fileHandle.write(data)

            except KeyboardInterrupt:
                print "Ctrl-c pressed ..."
                self.run_v = False

    def stop(self):
        self.run_v = False
        if self.fd:
            self.fd.close()
        if self.fileHandle:
            self.fileHandle.close()
Ejemplo n.º 30
0
def extract_stream(stream_url):
    """extracts the stream url from the encrypted url"""
    url = stream_url[0]

    print "Attempting to extract {0}".format(url)
    # Create the Streamlink session
    streamlink = Streamlink()

    #stream quality
    quality = "best"
    # Enable logging
    streamlink.set_loglevel("info")
    streamlink.set_logoutput(sys.stdout)

    # Attempt to fetch streams
    try:
        streams = streamlink.streams(url)
    except NoPluginError:
        exit("Streamlink is unable to handle the URL '{0}'".format(url))
    except PluginError as err:
        exit("Plugin error: {0}".format(err))

    if not streams:
        exit("No streams found on URL '{0}'".format(url))

    # Look for specified stream
    if quality not in streams:
        exit("Unable to find '{0}' stream on URL '{1}'".format(quality, url))

    # We found the stream
    stream = streams[quality]

    return stream.url
Ejemplo n.º 31
0
    def test_arguments(self):
        from streamlink_cli.main import setup_plugin_args
        session = Streamlink()
        parser = MagicMock()
        plugin_parser = MagicMock()
        parser.add_argument_group = MagicMock(return_value=plugin_parser)

        session.plugins = {
            'funimationnow': FunimationNow
        }

        setup_plugin_args(session, parser)

        self.assertSequenceEqual(plugin_parser.add_argument.mock_calls,
                                 [call('--funimation-language',
                                       choices=["en", "ja", "english", "japanese"],
                                       default="english", help=ANY),
                                  call('--funimation-mux-subtitles', action="store_true", help=ANY)])
Ejemplo n.º 32
0
    def test_arguments(self):
        from streamlink_cli.main import setup_plugin_args
        session = Streamlink()
        parser = MagicMock()
        plugin_parser = MagicMock()
        parser.add_argument_group = MagicMock(return_value=plugin_parser)

        session.plugins = {'funimationnow': FunimationNow}

        setup_plugin_args(session, parser)

        self.assertSequenceEqual(plugin_parser.add_argument.mock_calls, [
            call('--funimation-language',
                 choices=["en", "ja", "english", "japanese"],
                 default="english",
                 help=ANY),
            call('--funimation-mux-subtitles', action="store_true", help=ANY)
        ])
Ejemplo n.º 33
0
    def test_arguments(self):
        from streamlink_cli.main import setup_plugin_args
        session = Streamlink()
        parser = MagicMock()
        plugin_parser = MagicMock()
        parser.add_argument_group = MagicMock(return_value=plugin_parser)

        session.plugins = {'tvplayer': TVPlayer}

        setup_plugin_args(session, parser)

        self.assertSequenceEqual(
            plugin_parser.add_argument.mock_calls,
            [
                call('--tvplayer-email', metavar="EMAIL", help=ANY),
                call('--tvplayer-password', metavar="PASSWORD", help=ANY)
            ],
        )
Ejemplo n.º 34
0
class TestPluginStream(unittest.TestCase):
    def setUp(self):
        self.session = Streamlink()

    def assertDictHas(self, a, b):
        for key, value in a.items():
            self.assertEqual(b[key], value)

    def _test_akamaihd(self, surl, url):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, AkamaiHDStream))
        self.assertEqual(stream.url, url)

    @patch('streamlink.stream.HLSStream.parse_variant_playlist')
    def _test_hls(self, surl, url, mock_parse):
        mock_parse.return_value = {}

        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)
        mock_parse.assert_called_with(self.session, url)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, HLSStream))
        self.assertEqual(stream.url, url)

    @patch('streamlink.stream.HLSStream.parse_variant_playlist')
    def _test_hlsvariant(self, surl, url, mock_parse):
        mock_parse.return_value = {"best": HLSStream(self.session, url)}

        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        mock_parse.assert_called_with(self.session, url)

        self.assertFalse("live" in streams)
        self.assertTrue("best" in streams)

        stream = streams["best"]
        self.assertTrue(isinstance(stream, HLSStream))
        self.assertEqual(stream.url, url)

    def _test_rtmp(self, surl, url, params):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, RTMPStream))
        self.assertEqual(stream.params["rtmp"], url)
        self.assertDictHas(params, stream.params)

    def _test_http(self, surl, url, params):
        channel = self.session.resolve_url(surl)
        streams = channel.get_streams()

        self.assertTrue("live" in streams)

        stream = streams["live"]
        self.assertTrue(isinstance(stream, HTTPStream))
        self.assertEqual(stream.url, url)
        self.assertDictHas(params, stream.args)

    def test_plugin_rtmp(self):
        self._test_rtmp("rtmp://hostname.se/stream",
                        "rtmp://hostname.se/stream", dict())

        self._test_rtmp("rtmp://hostname.se/stream live=1 qarg='a \\'string' noq=test",
                        "rtmp://hostname.se/stream", dict(live=True, qarg='a \'string', noq="test"))

        self._test_rtmp("rtmp://hostname.se/stream live=1 num=47",
                        "rtmp://hostname.se/stream", dict(live=True, num=47))

        self._test_rtmp("rtmp://hostname.se/stream conn=['B:1','S:authMe','O:1','NN:code:1.23','NS:flag:ok','O:0']",
                        "rtmp://hostname.se/stream",
                        dict(conn=['B:1', 'S:authMe', 'O:1', 'NN:code:1.23', 'NS:flag:ok', 'O:0']))

    def test_plugin_hls(self):
        self._test_hls("hls://https://hostname.se/playlist.m3u8",
                       "https://hostname.se/playlist.m3u8")

        self._test_hls("hls://hostname.se/playlist.m3u8",
                       "http://hostname.se/playlist.m3u8")

        self._test_hlsvariant("hls://hostname.se/playlist.m3u8",
                              "http://hostname.se/playlist.m3u8")

        self._test_hlsvariant("hls://https://hostname.se/playlist.m3u8",
                              "https://hostname.se/playlist.m3u8")

    def test_plugin_akamaihd(self):
        self._test_akamaihd("akamaihd://http://hostname.se/stream",
                            "http://hostname.se/stream")

        self._test_akamaihd("akamaihd://hostname.se/stream",
                            "http://hostname.se/stream")

    def test_plugin_http(self):
        self._test_http("httpstream://http://hostname.se/auth.php auth=('test','test2')",
                        "http://hostname.se/auth.php", dict(auth=("test", "test2")))

        self._test_http("httpstream://hostname.se/auth.php auth=('test','test2')",
                        "http://hostname.se/auth.php", dict(auth=("test", "test2")))

        self._test_http("httpstream://https://hostname.se/auth.php verify=False params={'key': 'a value'}",
                        "https://hostname.se/auth.php?key=a+value", dict(verify=False, params=dict(key='a value')))

    def test_parse_params(self):
        self.assertEqual(
            dict(verify=False, params=dict(key="a value")),
            parse_params("""verify=False params={'key': 'a value'}""")
        )
        self.assertEqual(
            dict(verify=False),
            parse_params("""verify=False""")
        )
        self.assertEqual(
            dict(conn=['B:1', 'S:authMe', 'O:1', 'NN:code:1.23', 'NS:flag:ok', 'O:0']),
            parse_params(""""conn=['B:1', 'S:authMe', 'O:1', 'NN:code:1.23', 'NS:flag:ok', 'O:0']""")
        )

    def test_stream_weight(self):
        self.assertEqual(
            (720, "pixels"),
            stream_weight("720p"))
        self.assertEqual(
            (721, "pixels"),
            stream_weight("720p+"))
        self.assertEqual(
            (780, "pixels"),
            stream_weight("720p60"))

        self.assertTrue(
            stream_weight("720p+") > stream_weight("720p"))
        self.assertTrue(
            stream_weight("720p") == stream_weight("720p"))
        self.assertTrue(
            stream_weight("720p_3000k") > stream_weight("720p_2500k"))
        self.assertTrue(
            stream_weight("720p60_3000k") > stream_weight("720p_3000k"))
        self.assertTrue(
            stream_weight("720p_3000k") < stream_weight("720p+_3000k"))

        self.assertTrue(
            stream_weight("3000k") > stream_weight("2500k"))
Ejemplo n.º 35
0
 def setUp(self):
     self.session = Streamlink()
     self.session.load_plugins(self.PluginPath)
Ejemplo n.º 36
0
 def setUp(self):
     self.session = Streamlink()
Ejemplo n.º 37
0
def get_session():
    s = Streamlink()
    s.load_plugins(PluginPath)
    return s
Ejemplo n.º 38
0
class TestSession(unittest.TestCase):
    PluginPath = os.path.join(os.path.dirname(__file__), "plugins")

    def setUp(self):
        self.session = Streamlink()
        self.session.load_plugins(self.PluginPath)

    def test_exceptions(self):
        try:
            self.session.resolve_url("invalid url")
            self.assertTrue(False)
        except NoPluginError:
            self.assertTrue(True)

    def test_load_plugins(self):
        plugins = self.session.get_plugins()
        self.assertTrue(plugins["testplugin"])

    def test_builtin_plugins(self):
        plugins = self.session.get_plugins()
        self.assertTrue("twitch" in plugins)

    def test_resolve_url(self):
        plugins = self.session.get_plugins()
        channel = self.session.resolve_url("http://test.se/channel")
        self.assertTrue(isinstance(channel, Plugin))
        self.assertTrue(isinstance(channel, plugins["testplugin"]))

    def test_resolve_url_priority(self):
        from tests.plugins.testplugin import TestPlugin

        class HighPriority(TestPlugin):
            @classmethod
            def priority(cls, url):
                return HIGH_PRIORITY

        class LowPriority(TestPlugin):
            @classmethod
            def priority(cls, url):
                return LOW_PRIORITY

        self.session.plugins = {
            "test_plugin": TestPlugin,
            "test_plugin_low": LowPriority,
            "test_plugin_high": HighPriority,
        }
        channel = self.session.resolve_url_no_redirect("http://test.se/channel")
        plugins = self.session.get_plugins()

        self.assertTrue(isinstance(channel, plugins["test_plugin_high"]))
        self.assertEqual(HIGH_PRIORITY, channel.priority(channel.url))

    def test_resolve_url_no_redirect(self):
        plugins = self.session.get_plugins()
        channel = self.session.resolve_url_no_redirect("http://test.se/channel")
        self.assertTrue(isinstance(channel, Plugin))
        self.assertTrue(isinstance(channel, plugins["testplugin"]))

    def test_options(self):
        self.session.set_option("test_option", "option")
        self.assertEqual(self.session.get_option("test_option"), "option")
        self.assertEqual(self.session.get_option("non_existing"), None)

        self.assertEqual(self.session.get_plugin_option("testplugin", "a_option"), "default")
        self.session.set_plugin_option("testplugin", "another_option", "test")
        self.assertEqual(self.session.get_plugin_option("testplugin", "another_option"), "test")
        self.assertEqual(self.session.get_plugin_option("non_existing", "non_existing"), None)
        self.assertEqual(self.session.get_plugin_option("testplugin", "non_existing"), None)

    def test_plugin(self):
        channel = self.session.resolve_url("http://test.se/channel")
        streams = channel.get_streams()

        self.assertTrue("best" in streams)
        self.assertTrue("worst" in streams)
        self.assertTrue(streams["best"] is streams["1080p"])
        self.assertTrue(streams["worst"] is streams["350k"])
        self.assertTrue(isinstance(streams["rtmp"], RTMPStream))
        self.assertTrue(isinstance(streams["http"], HTTPStream))
        self.assertTrue(isinstance(streams["hls"], HLSStream))
        self.assertTrue(isinstance(streams["akamaihd"], AkamaiHDStream))

    def test_plugin_stream_types(self):
        channel = self.session.resolve_url("http://test.se/channel")
        streams = channel.get_streams(stream_types=["http", "rtmp"])

        self.assertTrue(isinstance(streams["480p"], HTTPStream))
        self.assertTrue(isinstance(streams["480p_rtmp"], RTMPStream))

        streams = channel.get_streams(stream_types=["rtmp", "http"])

        self.assertTrue(isinstance(streams["480p"], RTMPStream))
        self.assertTrue(isinstance(streams["480p_http"], HTTPStream))

    def test_plugin_stream_sorted_excludes(self):
        channel = self.session.resolve_url("http://test.se/channel")
        streams = channel.get_streams(sorting_excludes=["1080p", "3000k"])

        self.assertTrue("best" in streams)
        self.assertTrue("worst" in streams)
        self.assertTrue(streams["best"] is streams["1500k"])

        streams = channel.get_streams(sorting_excludes=[">=1080p", ">1500k"])
        self.assertTrue(streams["best"] is streams["1500k"])

        streams = channel.get_streams(sorting_excludes=lambda q: not q.endswith("p"))
        self.assertTrue(streams["best"] is streams["3000k"])

    def test_plugin_support(self):
        channel = self.session.resolve_url("http://test.se/channel")
        streams = channel.get_streams()

        self.assertTrue("support" in streams)
        self.assertTrue(isinstance(streams["support"], HTTPStream))