Beispiel #1
0
    def reload_session(self):
        """ Replace the current stream with a new stream,
            the new stream will be generated from _get_streams()
            after the given reload time.
        """
        self.logger.debug("Reloading session for playlist")
        cache = Cache(filename="streamdata.json",
                      key_prefix="cache:{0}".format(self.stream.url))
        cache_stream_name = cache.get("cache_stream_name", "best")
        cache_url = cache.get("cache_url")
        self.logger.debug("Current stream_name: {0}".format(cache_stream_name))
        if not cache_url:
            # corrupt cache data
            # if more than one instance of streamlink
            # with the same stream_url and hls-session-reload is running
            self.logger.warning(
                "Missing cache data, hls-session-reload is now deactivated")
            self.session_time = int(time() + time())
            return

        streams = self.session.streams(cache_url)
        if not streams:
            self.logger.debug(
                "No stream found for reload_session, stream might be offline.")
            return

        self.stream = streams[cache_stream_name]
        new_cache = Cache(filename="streamdata.json",
                          key_prefix="cache:{0}".format(self.stream.url))
        new_cache.set("cache_stream_name", cache_stream_name,
                      (self.session_reload + 60))
        new_cache.set("cache_url", cache_url, (self.session_reload + 60))
        self.session_time = int(time())
Beispiel #2
0
def check_version(force=False):
    console.logger.debug("run ... check_version")
    cache = Cache(filename="cli.json")
    latest_version = cache.get("latest_version")

    if force or not latest_version:
        res = requests.get("https://pypi.python.org/pypi/livecli/json")
        data = res.json()
        latest_version = data.get("info").get("version")
        cache.set("latest_version", latest_version, (60 * 60 * 24))

    version_info_printed = cache.get("version_info_printed")
    if not force and version_info_printed:
        return

    installed_version = StrictVersion(livecli.version)
    latest_version = StrictVersion(latest_version)

    if latest_version > installed_version:
        console.logger.info("A new version of Livecli ({0}) is "
                            "available!".format(latest_version))
        cache.set("version_info_printed", True, (60 * 60 * 6))
    elif force:
        console.logger.info("Your Livecli version ({0}) is up to date!",
                            installed_version)

    if force:
        sys.exit()
Beispiel #3
0
 def _update_cache(self, hls_url):
     cache = Cache(filename="streamdata.json",
                   key_prefix="cache:{0}".format(hls_url))
     cache.set("cache_stream_name", "live",
               (self.session.get_option("hls-session-reload") + 60))
     cache.set("cache_url", self.url,
               (self.session.get_option("hls-session-reload") + 60))
Beispiel #4
0
    def reload_session(self):
        """ Replace the current stream with a new stream,
            after the given reload time.
        """
        self.logger.debug("Reloading session for playlist")
        cache = Cache(filename="streamdata.json",
                      key_prefix="cache:{0}".format(self.stream.url))
        cache_stream_name = cache.get("cache_stream_name", "best")
        cache_url = cache.get("cache_url")
        self.logger.debug("Current stream_url: {0}".format(cache_url))
        self.logger.debug("Current stream_name: {0}".format(cache_stream_name))
        if not cache_url:
            # corrupt cache data, if more than one instance of streamlink
            # with the same stream_url (m3u8) and hls-session-reload is running
            # this is very rare and shouldn't be a problem
            self.logger.warning(
                "Missing cache data, hls-session-reload is now deactivated, a stream restart might help."
            )
            self.session_reload_time = int(time() + time())
            return

        try:
            streams = self.session.streams(cache_url)
        except Exception as e:
            streams = ""
            self.logger.error(str(e))
            self.logger.warning(
                "something went wrong, hls-session-reload is now deactivated, a stream restart might help."
            )
            self.session_reload_time = int(time() + time())
            return

        if not streams:
            self.logger.debug(
                "No stream found for hls-session-reload, stream might be offline."
            )
            return

        self.stream = streams[cache_stream_name]
        new_cache = Cache(filename="streamdata.json",
                          key_prefix="cache:{0}".format(self.stream.url))
        new_cache.set("cache_stream_name", cache_stream_name,
                      (self.session_reload + 60))
        new_cache.set("cache_url", cache_url, (self.session_reload + 60))
        self.session_reload_time = int(time())
Beispiel #5
0
def cache_stream_data(cache_stream_name, cache_stream_url):
    """Caches data for hls-session-reload
    :param cache_stream_name: stream quality name
    :param cache_stream_url: stream url
    """
    cache = Cache(filename="streamdata.json",
                  key_prefix="cache:{0}".format(cache_stream_url))
    cache.set("cache_stream_name", cache_stream_name,
              (args.hls_session_reload + 60))
    cache.set("cache_url", args.url, (args.hls_session_reload + 60))
Beispiel #6
0
    def reload_session(self):
        """ Replace the current stream with a new stream,
            the new stream will be generated from _get_streams()
            after the given reload time.
        """
        self.logger.debug("Reloading session for playlist")
        cache = Cache(filename="streamdata.json",
                      key_prefix="cache:{0}".format(self.stream.url))
        cache_stream_name = cache.get("cache_stream_name", "best")
        cache_url = cache.get("cache_url")
        if not cache_url:
            # corrupt cache data
            # if more than one instance of streamlink
            # with the same stream_url and hls-session-reload is running
            self.logger.warning(
                "Missing cache data, hls-session-reload is now deactivated")
            self.session_time = int(time() + time())
            return

        channel = self.session.resolve_url(cache_url)
        streams = channel._get_streams()
        try:
            # HLSStream with parse_variant_playlist
            self.stream = streams[cache_stream_name]
        except KeyError:
            # if stream_name is '1080p source' but the cache is '1080p'
            for source_stream_name in streams.keys():
                if cache_stream_name in source_stream_name:
                    self.stream = streams[source_stream_name]
        except TypeError:
            # HLSStream without parse_variant_playlist
            for name, hls_stream in streams:
                self.stream = hls_stream

        new_cache = Cache(filename="streamdata.json",
                          key_prefix="cache:{0}".format(self.stream.url))
        new_cache.set("cache_stream_name", cache_stream_name,
                      (self.session_reload + 60))
        new_cache.set("cache_url", cache_url, (self.session_reload + 60))
        self.session_time = int(time())
Beispiel #7
0
 def __init__(self, url):
     """Inits Resolve with default settings"""
     super(Resolve, self).__init__(url)
     self._session_attributes = Cache(filename="plugin-cache.json", key_prefix="resolve:attributes")
     self._cache_url = self._session_attributes.get("cache_url")
     if self._cache_url:
         self.referer = self._cache_url
     else:
         self.referer = self.url.replace("resolve://", "")
     self.headers = {
         "User-Agent": useragents.FIREFOX,
         "Referer": self.referer
     }
Beispiel #8
0
    def __init__(self, url):
        super(Zattoo, self).__init__(url)
        self._session_attributes = Cache(filename='plugin-cache.json', key_prefix='zattoo:attributes')
        self._authed = self._session_attributes.get('beaker.session.id') and self._session_attributes.get('pzuid') and self._session_attributes.get('power_guide_hash')
        self._uuid = self._session_attributes.get('uuid')
        self._expires = self._session_attributes.get('expires', 946684800)

        self.base_url = 'https://{0}'.format(Zattoo._url_re.match(url).group('base_url'))
        self.headers = {
            'User-Agent': useragents.CHROME,
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            'X-Requested-With': 'XMLHttpRequest',
            'Referer': self.base_url
        }
Beispiel #9
0
 def __init__(self, url):
     super(FC2, self).__init__(url)
     self._session_attributes = Cache(filename='plugin-cache.json',
                                      key_prefix='fc2:attributes')
     self._authed = (self._session_attributes.get('fcu')
                     and self._session_attributes.get('fgcv')
                     and self._session_attributes.get('FCSID')
                     and self._session_attributes.get('login_status')
                     and self._session_attributes.get('glgd_val')
                     and self._session_attributes.get('PHPSESSID')
                     and self._session_attributes.get('secure_check_fc2'))
     self._expires = self._session_attributes.get(
         'expires',
         time.time() + self.expires_time)
Beispiel #10
0
def _play_stream(HTTPBase, redirect=False):
    """Creates a livecli session and plays the stream."""
    session = Livecli()
    session.set_logprefix("[ID-{0}]".format(str(int(time()))[4:]))
    logger = session.logger.new_module("livecli-server")
    session.set_loglevel("info")

    logger.info("User-Agent: {0}".format(
        HTTPBase.headers.get("User-Agent", "???")))
    logger.info("Client: {0}".format(HTTPBase.client_address))
    logger.info("Address: {0}".format(HTTPBase.address_string()))

    # Load custom user plugins
    if os.path.isdir(PLUGINS_DIR):
        session.load_plugins(PLUGINS_DIR)

    old_data = parse_qsl(urlparse(HTTPBase.path).query)
    data = []
    for k, v in old_data:
        data += [(unquote_plus(k), unquote_plus(v))]

    data_other, session = command_session(session, data)

    url = data_other.get("url")
    if not url:
        HTTPBase._headers(404, "text/html")
        logger.error("No URL provided.")
        return
    quality = (data_other.get("q") or data_other.get("quality")
               or data_other.get("stream") or data_other.get("default-stream")
               or "best")
    try:
        cache = data_other.get("cache") or 4096
    except TypeError:
        cache = 4096

    loglevel = data_other.get("l") or data_other.get("loglevel") or "debug"
    session.set_loglevel(loglevel)
    try:
        if redirect is True:
            streams = session.streams(url, stream_types=["hls", "http"])
        else:
            streams = session.streams(url)
    except Exception as e:
        HTTPBase._headers(404, "text/html")
        logger.error("No Stream Found!")
        return

    if not streams:
        HTTPBase._headers(404, "text/html")
        return

    # XXX: only one quality will work currently
    try:
        stream = streams[quality]
    except KeyError:
        stream = streams["best"]
        quality = "best"

    if isinstance(stream, HTTPStream) is False and isinstance(
            stream, HDSStream) is False:
        # allow only http based streams: HDS HLS HTTP
        # RTMP is not supported
        HTTPBase._headers(404, "text/html")
        return

    if redirect is True:
        logger.info("301 - URL: {0}".format(stream.url))
        HTTPBase.send_response(301)
        HTTPBase.send_header("Location", stream.url)
        HTTPBase.end_headers()
        logger.info("301 - done")
        return

    hls_session_reload = data_other.get("hls-session-reload")
    if hls_session_reload:
        livecli_cache = Cache(filename="streamdata.json",
                              key_prefix="cache:{0}".format(stream.url))
        livecli_cache.set("cache_stream_name", quality,
                          (int(hls_session_reload) + 60))
        livecli_cache.set("cache_url", url, (int(hls_session_reload) + 60))
        session.set_option("hls-session-reload", int(hls_session_reload))

    try:
        fd = stream.open()
    except StreamError as err:
        HTTPBase._headers(404, "text/html")
        logger.error("Could not open stream: {0}".format(err))
        return

    HTTPBase._headers(200, "video/unknown")
    try:
        logger.debug("Pre-buffering {0} bytes".format(cache))
        while True:
            buff = fd.read(cache)
            if not buff:
                logger.error("No Data!")
                break
            HTTPBase.wfile.write(buff)
        HTTPBase.wfile.close()
    except socket.error as e:
        if isinstance(e.args, tuple):
            if e.errno == errno.EPIPE:
                # remote peer disconnected
                logger.info("Detected remote disconnect")
                pass
            else:
                logger.error(str(e))
        else:
            logger.error(str(e))

    fd.close()
    logger.info("Stream ended")
    fd = None
Beispiel #11
0
 def __init__(self, url):
     super(ABweb, self).__init__(url)
     self._session_attributes = Cache(filename='plugin-cache.json', key_prefix='abweb:attributes')
     self._authed = self._session_attributes.get('ASP.NET_SessionId') and self._session_attributes.get('.abportail1')
     self._expires = self._session_attributes.get('expires', time.time() + self.expires_time)
Beispiel #12
0
 def __init__(self, url):
     super(WWENetwork, self).__init__(url)
     http.headers.update({"User-Agent": useragents.CHROME})
     self._session_attributes = Cache(filename="plugin-cache.json", key_prefix="wwenetwork:attributes")
     self._session_key = self.cache.get("session_key")
     self._authed = self._session_attributes.get("ipid") and self._session_attributes.get("fprt")