Beispiel #1
0
	def __init__(self, conf, dbfile, mode):
#--------------------------------------------------------------------------args
		self.conf = conf
		self.mode = mode
		self.dbfile = dbfile
#-----------------------------------------------------------------configuration
		self.dbpath = conf['DIRECTORY']['database_dir']
		#self.twitch_username = conf['TWITCH']['username']

		cmd_list = []
		for cmd in conf['COMMANDS']:
			cmd_list.append(conf['COMMANDS'][cmd])
		self.cmd_list = list(map(shlex.split, cmd_list))
		self.cmd_index = 0
		self.cmd = self.cmd_list[self.cmd_index]
#-----------------------------------------------------------------------objects
		#self.twitch = services.Twitch()
		self.streamlink = streamlink.Streamlink()
		self.q = player.ProcessList(player.StreamPlayer().play)
#-------------------------------------------------------------establish history
		self.currentpad = 'main'
		self.prevpad = self.currentpad
		self.prevdb = self.dbfile
#------------------------------------------------------------------static texts
		#res = os.path.abspath(os.path.join(os.path.dirname(__file__), 'resources'))
		res = os.path.abspath(os.path.dirname(__file__))
		with open(os.path.join(res, 'help.txt'), 'r') as handle:
			self.helpmenu = handle.readlines()

		with open(os.path.join(res, 'firstrun.txt'), 'r') as handle:
			self.firstrun = handle.readlines()
Beispiel #2
0
def download_twitch_vod(url, stream_name, output_filename,
                        buffer_size=8192, output_progress=True):
    """download a video object to the given output file.
    """
    oauth_token = _get_oauth_token()
    session = streamlink.Streamlink()
    session.set_plugin_option("twitch", "oauth-token", oauth_token)

    streams = session.streams(url)

    if streams and stream_name in streams:
        stream = streams[stream_name]
    else:
        raise StreamException("Could not find stream {1} at url {2}".format(
            stream_name, url))

    total_downloaded = 0
    with stream.open() as stream_file, open(output_filename, "wb") as output_file:
        if output_progress:
            progress_bar = _download_progress_bar()

        chunk = stream_file.read(buffer_size)

        while chunk:
            total_downloaded += len(chunk)

            if output_progress:
                progress_bar.update(total_downloaded)

            output_file.write(chunk)
            chunk = stream_file.read(buffer_size)
Beispiel #3
0
def main(args):
    s = streamlink.Streamlink()
    streams = s.streams(args.url)

    if not streams:
        sys.exit(1)

    available_quality = list(streams.keys())
    quality_to_request = "best" if args.prefsize not in available_quality else args.prefsize

    # start qjoypad if available_quality
    start_qjoypad_with_profile("mpv")

    # start mpv
    mpv_script_to_use = "/opt/qbigscreen/start-mpv.sh"
    if not os.path.exists(mpv_script_to_use):
        mpv_script_to_use = os.path.expanduser(
            "~/.config/qbigscreen/scripts/start-mpv.sh")

    p = subprocess.Popen("streamlink --player {} {} {}".format(
        mpv_script_to_use, args.url, quality_to_request).split(" "))
    create_lockfile("mpv")
    returncode = p.wait()

    start_qjoypad_with_profile("none")
    delete_lockfile()

    sys.exit(100 + returncode)
Beispiel #4
0
 def get_stream(self, key):
     '''
     获取直播流
     :param key: 房间显示id
     :return: stream
     '''
     if not self.judge_in(key):
         return None
     live_info = self.live_infos.copy()[key]
     logger.info('%s[RoomID:%s]获取直播流' % (live_info['uname'], key))
     session = streamlink.Streamlink()
     session.set_option("http-cookies", self.cookies)
     session.set_option("http-headers", headers)
     streams = None
     retry = 0
     while streams is None:
         try:
             if retry < 3:
                 streams = session.streams('https://live.bilibili.com/%s' %
                                           key)
             else:
                 logger.warning('%s[RoomID:%s]获取直播流失败,重试次数已达上限' %
                                (live_info['uname'], key))
                 return None
         except:
             logger.warning('%s[RoomID:%s]获取直播流失败,正在重试' %
                            (live_info['uname'], key))
             retry += 1
             time.sleep(1)
     if streams == {}:
         logger.error('%s[RoomID:%s]未获取到直播流,可能是下播或者网络问题' %
                      (live_info['uname'], key))
         return None
     if 'best' in streams:
         logger.info('%s[RoomID:%s]获取到best直播流' % (live_info['uname'], key))
         return streams['best']
     elif 'source' in streams:
         logger.info('%s[RoomID:%s]获取到source直播流' %
                     (live_info['uname'], key))
         return streams['source']
     elif 'worst' in streams:
         logger.info('%s[RoomID:%s]获取到worst直播流' % (live_info['uname'], key))
         return streams['worst']
     else:
         logger.info('%s[RoomID:%s]未获取到直播流' % (live_info['uname'], key))
         return None
Beispiel #5
0
 def get_stream(self, key):
     '''
     获取直播流
     :param key: 房间显示id
     :return: stream
     '''
     if not self.judge_in(key):
         return None
     live_info = self.live_infos.copy()[key]
     logger.info('%s[RoomID:%s]获取直播流' % (live_info['uname'], key))
     session = streamlink.Streamlink()
     session.set_option("http-cookies", self.cookies)
     session.set_option("http-headers", headers)
     log_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), 'log', 'stream.log')
     session.set_loglevel("debug")
     session.set_logoutput(open(log_path, 'a',encoding='utf-8'))
     streams = None
     while streams is None:
         try:
             streams = session.streams('https://live.bilibili.com/%s' % key)
         except:
             logger.warning('%s[RoomID:%s]获取直播流失败,正在重试' % (live_info['uname'], key))
             time.sleep(1)
     if streams == {}:
         logger.error('%s[RoomID:%s]未获取到直播流,可能是下播或者网络问题' % (live_info['uname'], key))
         return None
     if 'best' in streams:
         logger.info('%s[RoomID:%s]获取到best直播流' % (live_info['uname'], key))
         return streams['best']
     elif 'source' in streams:
         logger.info('%s[RoomID:%s]获取到source直播流' % (live_info['uname'], key))
         return streams['source']
     elif 'worst' in streams:
         logger.info('%s[RoomID:%s]获取到worst直播流' % (live_info['uname'], key))
         return streams['worst']
     else:
         logger.info('%s[RoomID:%s]未获取到直播流' % (live_info['uname'], key))
         return None
Beispiel #6
0
import io
import os
import uuid
import streamlink
import asyncio
import tensorflow as tf

from sanic import Sanic
from sanic.response import json
from PIL import Image

app = Sanic()
app.config.KEEP_ALIVE = False

streamlink_session = streamlink.Streamlink()


def load_graph(graph_file):
    """
    Load a frozen TensorFlow graph
    """
    import tensorflow as tf
    with tf.gfile.GFile(graph_file, "rb") as f:
        graph_def = tf.GraphDef()
        graph_def.ParseFromString(f.read())

    with tf.Graph().as_default() as graph:
        tf.import_graph_def(graph_def)

    return graph
Beispiel #7
0
 def __init__(self, grid):
     self.streamlink_session = streamlink.Streamlink()
     self.grid = grid
     self.stream_history = set()
     self.load_stream_history()
Beispiel #8
0
tba = tbapi.TBAParser(api_key=getAPIKey.Key.tba, cache=False)

debug = True
if debug:
    eventkey = '2018vapor'
else:
    eventkey = input("Please enter the event key as it appears in TBA: ")
try:
    eventtba = tba.get_event(event_key=eventkey)
except tbapi.InvalidKeyError:
    raise ValueError('That event does not exist!')
webcast = eventtba.webcasts[0]
if debug:
    print(webcast.channel)

stream = streamlink.Streamlink()


def logstart():
    with db.Session() as session:
        starting = streamdb(eventkey=eventkey,
                            starttime=datetime.datetime.now().timestamp())
        session.add(starting)


def checkiflive():
    streams = stream.streams(url)
    try:
        streams['best']
        return True
    except KeyError:
def zfg(bot, trigger):
    session = streamlink.Streamlink()
    session.set_plugin_option("twitch", "disable_hosting", True)
    st = session.streams("https://twitch.tv/zfg1")
    if not st:
        return bot.say("zfg isn't streaming :(")
    s = st['best']
    fd = s.open()
    data = fd.read(int(5e6))
    fd.close()
    fname = '/home/desu/test/s.bin'
    open(fname, 'wb').write(data)
    capture = cv2.VideoCapture(fname)
    imgdata = capture.read()[1]
    i = imgdata[..., ::-1]
    fc = cv2.cvtColor(i, cv2.COLOR_RGB2BGR)
    cv2.imwrite('/home/desu/htdocs/desu/zfg/captured_frame.png', fc)
    psplit_crop = fc[310:330, 270:330]
    cv2.imwrite('/home/desu/htdocs/desu/zfg/psplit_crop.png', psplit_crop)
    psplit_prep = cv2.cvtColor(psplit_crop, cv2.COLOR_BGR2GRAY)
    psplit_prep = cv2.threshold(psplit_prep, 0, 255,
                                cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
    rows, cols = psplit_prep.shape
    psplit_r = cv2.resize(psplit_prep, (int(cols * 4), int(rows * 4)))
    psplit_string = pytesseract.image_to_string(
        psplit_r,
        config='-psm 7 -c tessedit_char_whitelist=.+-:0123456789').replace(
            " ", "")
    if (psplit_string[0] != '-') and (psplit_string[0] != '+'):
        psplit_string = "\x0F-\x0F"
    timer_crop = fc[427:465, 179:331]
    cv2.imwrite('/home/desu/htdocs/desu/zfg/timer_crop.png', timer_crop)
    rows, cols, _ = timer_crop.shape
    tc_r = cv2.resize(timer_crop, (int(cols * 4), int(rows * 4)))
    timer_string = pytesseract.image_to_string(
        tc_r,
        config='-psm 7 -c tessedit_char_whitelist=.+-:0123456789').replace(
            " ", "")
    if psplit_string != "\x0F-\x0F":
        try:
            psplit_td, psplitsign = parse_timer(psplit_string)
            timer_td, timersign = parse_timer(timer_string)
        except ValueError as err:
            now = datetime.datetime.now().isoformat()
            cv2.imwrite(
                '/home/desu/htdocs/desu/zfg/errors/captured_frame_{}.png'.
                format(now), fc)
            cv2.imwrite(
                '/home/desu/htdocs/desu/zfg/errors/psplit_crop_{}.png'.format(
                    now), psplit_crop)
            cv2.imwrite(
                '/home/desu/htdocs/desu/zfg/errors/psplit_r_{}.png'.format(
                    now), psplit_r)
            cv2.imwrite(
                '/home/desu/htdocs/desu/zfg/errors/timer_crop_{}.png'.format(
                    now), timer_crop)
            cv2.imwrite(
                '/home/desu/htdocs/desu/zfg/errors/tc_r_{}.png'.format(now),
                tc_r)
            return bot.say(
                "Timer parsing error, error:{} ... try again in a bit. https://dasu.moe/desu/zfg/"
                .format(err))
        dampe = datetime.timedelta(hours=1, minutes=45, seconds=0)
        ttd_s = (timer_td.total_seconds() -
                 (dampe.total_seconds() -
                  psplit_td.total_seconds())) if not psplitsign else (
                      timer_td.total_seconds() -
                      (dampe.total_seconds() + psplit_td.total_seconds()))
        ttd = secondstotimer(ttd_s)
        if not ttd.startswith('-'):
            ttd = "Already passed"
    else:
        ttd = "-1:45:00"  #just show this for the first 12~ minutes of a run
    bot.say(
        "Time: {} ({} PB) | Est. time to Dampe: {} | Images: https://dasu.moe/desu/zfg/ | https://twitch.tv/zfg1 "
        .format(
            timer_string, "\x0303" + psplit_string.replace(' ', '') +
            "\x0F" if psplit_string.startswith('-') else "\x0304" +
            psplit_string.replace(' ', '') + "\x0F", ttd))
Beispiel #10
0
    def __init__(self,
                 filename,
                 config,
                 list_streams=False,
                 init_stream_list=None):
        """ Init and try to load a stream list, nothing about curses yet """

        global TITLE_STRING

        self.db_was_read = False

        # Open the storage (create it if necessary)
        try:
            db_dir = os.path.dirname(filename)
            if not os.path.exists(db_dir):
                os.makedirs(db_dir)
            f = shelve.open(filename, 'c')
        except Exception:
            raise ShelveError(
                'Database could not be opened, another livestreamer-curses instance might be already running. '
                'Please note that a database created with Python 2.x cannot be used with Python 3.x and vice versa.'
            )

        self.max_id = 0
        if init_stream_list:
            f['streams'] = init_stream_list
            for i, s in enumerate(f['streams']):
                s['id'] = s.get('id') or i
                s['seen'] = s.get('seen') or 0
                s['last_seen'] = s.get('last_seen') or 0
            self.max_id = i
            f.sync()

        # Sort streams by view count
        try:
            self.streams = sorted(f['streams'],
                                  key=lambda s: s['seen'],
                                  reverse=True)
            for s in self.streams:
                # Max id, needed when adding a new stream
                self.max_id = max(self.max_id, s['id'])
                s['online'] = 2
            if list_streams:
                print(json.dumps(self.streams))
                f.close()
                sys.exit(0)
        except:
            self.streams = []
        self.db_was_read = True
        self.filtered_streams = list(self.streams)
        self.filter = ''
        self.all_streams_offline = None
        self.show_offline_streams = False
        self.config = config

        TITLE_STRING = TITLE_STRING.format(self.config.VERSION)

        self.cmd_list = list(map(shlex.split, self.config.STREAMLINK_COMMANDS))
        self.cmd_index = 0
        self.cmd = self.cmd_list[self.cmd_index]

        self.last_autocheck = 0

        self.default_res = self.config.DEFAULT_RESOLUTION

        self.store = f
        self.store.sync()

        self.no_streams = self.streams == []
        self.no_stream_shown = self.no_streams
        self.q = ProcessList(StreamPlayer().play)

        self.streamlink = streamlink.Streamlink()
Beispiel #11
0
    def do_GET(self):

        p = urlparse.urlparse(self.path)

        try:
            params = dict(urlparse.parse_qsl(p.query))
        except:
            params = {}

        xbmc.log(repr(params))

        if params == {}:

            xbmc.log("stream not found")
            self.send_error(404, "Invalid stream")
            return

        else:

            session = streamlink.Streamlink()
            #session.set_loglevel("debug")
            #session.set_logoutput(sys.stdout)

            try:
                session.load_plugins(custom_plugins)
            except:
                pass

            url = params.get('url')
            quality = params.get('q', None)
            if not quality:
                quality = 'best'

            streams = session.streams(url)
            stream = streams.get(quality)

            # ZATTOO:
            if url.startswith(('https://zattoo.com', 'https://tvonline.ewe.de',
                               'https://nettv.netcologne.de')):
                plugin_email = setting('zattoo_email')
                plugin_password = setting('zattoo_password')

                if plugin_email and plugin_password:
                    xbmc.log('Found Zattoo login')
                    session.set_plugin_option('zattoo', 'email', plugin_email)
                    session.set_plugin_option('zattoo', 'password',
                                              plugin_password)
                else:
                    xbmc.log('Missing Zattoo login')

            if not stream:

                xbmc.log("No stream resolved")
                self.send_error(404, "Stream not found")
                return

            elif isinstance(stream, HLSStream):

                res = session.http.get(stream.url)

                self.send_response(res.status_code, res.reason)
                self.send_header("content-type",
                                 res.headers.get('content-type', 'text'))
                self.end_headers()

                for line in res.text.splitlines(False):
                    if line and not line.startswith('#'):
                        self.wfile.write(
                            urlparse.urljoin(stream.url, line) + '\n')
                    else:
                        self.wfile.write(line + '\n')
                return

            elif isinstance(stream, HTTPStream):
                res = session.http.get(stream.url, headers=self.headers)

                self.send_response(res.status_code, res.reason)
                for name, value in res.headers.items():
                    self.send_header(name, value)
                self.end_headers()
            else:
                self.send_response(200, "OK")
                self.end_headers()

            # return the stream
            fh = None
            try:
                fh = stream.open()
                shutil.copyfileobj(fh, self.wfile)
            finally:
                if fh:
                    fh.close()
Beispiel #12
0
# -*- coding: UTF-8 -*-

# import cv2

import streamlink
from pystream import StreamThread

# import m3u8


movie = 'http://q.1y666.com:2100/20190405/qQmSQhlE/index.m3u8'


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

print('[INFO]获取了视屏流地址.....')

for k, v in streams.items():
    print(k, v)

source = None

lists = ['best', 'high', 'source', 'mobile', 'medium',  'low', 'worst']
Beispiel #13
0
        os.kill(self.proc.pid, signal.SIGINT)
    def is_running(self):
        return self.proc.is_alive()
    def wait(self, timeout: Optional[float] = None):
        self.proc.join(timeout)
    def kill(self):
        self.proc.kill()
    def finished(self):
        return self.proc.exitcode == 0


_streamlink = streamlink.Streamlink({
    'hds-timeout': 20.0,
    'hls-timeout': 20.0,
    'http-timeout': 20.0,
    'http-stream-timeout': 20.0,
    'stream-timeout': 20.0,
    'rtmp-timeout': 20.0,
    'http-ssl-verify': False,
})

class StreamlinkDownloader:
    def __init__(
        self,
        url: str,
        dirpath: str,
        filename: Optional[str] = None,
        bufsize: int = 8192,
        stream_timeout: int = 300,
        resolv_retry_interval: int = 5,
        resolv_retry_count: int = 4,
Beispiel #14
0
 def __init__(self):
     self.session = streamlink.Streamlink()