Ejemplo n.º 1
0
 def stream(self):
     '''returns a dictionary with available streams'''
     streams = {}  #not sure this is needed for the finally to work
     try:
         streams = livestreamer.Livestreamer().streams(
             self.URL_TEMPLATE.format(
                 id=int(self.session['uid']) + 100_000_000,
                 srv=int(self.session['camserv']) - 500))
     finally:
         return streams.get('best')
Ejemplo n.º 2
0
 def get_stream_location(self):
     if self.video_loc:
         return self.video_loc
     while True:
         try:
             streamer = livestreamer.Livestreamer()
             plugin = streamer.resolve_url('http://twitch.tv/twitchplayspokemon')
             streams = plugin.get_streams()
             return streams['source'].url
         except KeyError:
             print 'unable to connect to stream, sleeping 30 seconds...'
             time.sleep(30)
Ejemplo n.º 3
0
 def run(self):
     global recording, hilos
     isOnline = self.isOnline()
     if isOnline == False:
         self.online = False
     else:
         self.online = True
         self.file = os.path.join(
             setting['save_directory'], self.modelo,
             f'{datetime.datetime.fromtimestamp(time.time()).strftime("%Y.%m.%d_%H.%M.%S")}_{self.modelo}.mp4'
         )
         try:
             session = livestreamer.Livestreamer()
             streams = session.streams(f'hlsvariant://{isOnline}')
             stream = streams['best']
             fd = stream.open()
             if not isModelInListofObjects(self.modelo, recording):
                 os.makedirs(os.path.join(setting['save_directory'],
                                          self.modelo),
                             exist_ok=True)
                 with open(self.file, 'wb') as f:
                     self.lock.acquire()
                     recording.append(self)
                     for index, hilo in enumerate(hilos):
                         if hilo.modelo == self.modelo:
                             del hilos[index]
                             break
                     self.lock.release()
                     while not (self._stopevent.isSet()
                                or os.fstat(f.fileno()).st_nlink == 0):
                         try:
                             data = fd.read(1024)
                             f.write(data)
                         except:
                             fd.close()
                             break
                 if setting['postProcessingCommand']:
                     processingQueue.put({
                         'model': self.modelo,
                         'path': self.file
                     })
         except Exception as e:
             with open('log.log', 'a+') as f:
                 f.write(
                     f'\n{datetime.datetime.now().strftime("%d/%m/%Y %H:%M:%S")} EXCEPTION: {e}\n'
                 )
             self.stop()
         finally:
             self.exceptionHandler()
Ejemplo n.º 4
0
def livestreamer_cb(word, word_eol, userdata):
    word = [(word[i] if len(word) > i else "") for i in range(3)]

    channel = word[1]

    url = "http://www.twitch.tv/{}".format(channel)

    data = get_twitch_info(channel)

    if not 'streams' in data:
        format(channel + " is not live on twitch.tv/" + channel, onoff=False)
        return hexchat.EAT_ALL

    streams = livestreamer.Livestreamer()

    streams.set_option("http-query-params", "client_id=" + client_id)

    streams = streams.streams(url)

    if not 'best' in streams:
        format(channel + " is not live on twitch.tv/" + channel, onoff=False)
        return hexchat.EAT_ALL

    data = data['streams'][0]

    uploader = data["channel"]["display_name"]
    game = data["channel"]["game"]
    title = data["channel"]["status"]
    viewers = str(data["viewers"])

    stream = streams['best']
    format(uploader + " is streaming " + game + " for " + viewers +
           " viewers on " + url,
           onoff=True)

    subprocess.Popen([
        vlc_path, '--file-caching', '10000', stream.url,
        ":meta-title={}".format(title)
    ],
                     shell=False,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.PIPE,
                     stdin=subprocess.PIPE)
Ejemplo n.º 5
0
def play_stream():

    url = first_or_none(plugin.request.args.get('url'))
    if not url:
        plugin.notify("No URL to stream provided")
        return []

    plugin.log.info("Trying to find a stream to play on {0}".format(url))
    session = livestreamer.Livestreamer()

    streams = session.streams(url)

    qual = plugin.request.args.get('q', 'best')
    label = plugin.request.args.get('label', 'stream')
    stream = streams.get(qual)

    if stream is None:
        qlist = ','.join(streams.keys())
        plugin.log.error("Failed to find stream with the requested quality "
                         "({0}) with URL: {1} "
                         "(qualities available: {2})".format(qual, url, qlist or "N/A"))
        plugin.notify("No streams available for this URL, Geo-Locked?")
    else:
        if isinstance(stream, (HTTPStream, )):
            plugin.set_resolved_url(stream.url)
        elif isinstance(stream, (RTMPStream,)):
            rtmp = stream.params.pop('rtmp')
            args = ["{0}={1}".format(k, v) for k, v in stream.params.items()]
            item = {
                'label': label,
                'path': '{0} {1}'.format(rtmp, " ".join(args))
            }
            plugin.play_video(item)
        else:
            cache_id, cache = get_proxy_cache(stream=stream)

            plugin.set_resolved_url(generate_proxy_url(cache_id))
Ejemplo n.º 6
0
                        pack = stream.encode(frame)
                    else:
                        pack = stream.encode(frame)
                    if pack:
                        buffer.mux(pack)


def output_stream_write():
    #time.sleep(5)
    while True:
        container = av.open(tmp)
        print(container)
        output.mux(frame)


session = livestreamer.Livestreamer()
session.set_option("http-headers", "Client-ID=ewvlchtxgqq88ru9gmfp1gmyt6h2b93")
streams = session.streams("http://www.twitch.tv/kalashz0r")
print(streams)
stream = streams['1080p60']

input = av.open(stream.url, options={'buffer_size': '1000000'})

tmp = BytesIO()

buffer = av.open(tmp, 'w', 'mp4')

output = av.open('rtmp://live.restream.io/live/re_882197_78625223222fd0769d68',
                 mode='w',
                 format='flv')
Ejemplo n.º 7
0
Archivo: ocr.py Proyecto: pmrowla/pokr
    screen = raw[screen_y:screen_y+432, screen_x:screen_x+480]
    screen = cv2.resize(screen, (160, 144))
    return screen

def test_corpus():
    import os
    for fn in os.listdir('corpus'):
        print '#' * 20 + ' ' + fn
        print
        print identifier.screen_to_text(extract_screen(cv2.cvtColor(cv2.imread('corpus/' + fn), cv2.COLOR_BGR2GRAY)))

#test_corpus()

if '--direct' in sys.argv:
    import livestreamer
    livestreamer = livestreamer.Livestreamer()
    plugin = livestreamer.resolve_url('http://twitch.tv/twitchplayspokemon')
    streams = plugin.get_streams()
    cv = cv2.VideoCapture(streams['source'].url)
else:
    cv = cv2.VideoCapture('/dev/stdin')

frame_queue = Queue.Queue(120)

def grab_frames():
    while True:
        cv.grab()
        success, frame = cv.retrieve()
        if success:
            try:
                frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
Ejemplo n.º 8
0
def download(user_id, code, sessKey):
    if user_id in recording:
        return
    recording.append(user_id)
    wsurl = 'ws://chat2.neolive.kr/socket.io/?EIO=3&transport=websocket'
    hello = '42["Init",{"site":"winktv","deviceType":"webPc","deviceVersion":"1.0.0","userAgent":"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.87 Safari/537.36","sessKey":"' + sessKey + '","ReturnParam":true}]'
    #message = '42["Login",{"sessKey":"2f87bc6e722892ef9a985c71f7ccea122ea5c6f48bd11ffd3d9aebc024885054","id":"ao3jpr","ReturnParam":true}]'
    room = '42["WatchInfo",{"roomid":"' + code + '","action":"watch","ReturnParam":true}]'
    ws = create_connection(wsurl,
                           http_proxy_host="34.92.3.74",
                           http_proxy_port=3654)
    #ws.send(hello)
    while 1:
        res = ws.recv()
        #print(res)
        if res == '40':
            sys.stdout.write(f'{user_id}发送hello')
            ws.send(hello)
        elif 'Init' in res:
            ws.send(room)
        elif 'WatchInfo' in res:
            nres = re.findall(r'\[.*\]', res)[0]
            data = json.loads(nres)
            result = data[-1]
            isget = result['result']
            if not isget:
                if 'errorData' in result:
                    ecode = result['errorData']['code']
                    if 'needUnlimitItem' in ecode:
                        sys.stdout.write(f'\r\033[K{user_id}满,重试')
                        ws.close()
                        time.sleep(1)
                        ws = create_connection(wsurl,
                                               http_proxy_host="34.92.3.74",
                                               http_proxy_port=3654)
                        continue
                    else:
                        print(ecode)
                        ws.close()
            break
        elif 'error' in res:
            ws.close()
            break
    #if 'WatchInfo' in res:
    if isget:
        #nres = re.findall(r'\[.*\]',res)[0]
        #data = json.loads(nres)
        #result = data[-1]
        #isget = result['result']

        media = result['media']
        playlist = result['PlayList']
        user_nick = media['userNick']
        user_id = media['userId']
        title = media['title']
        hls = playlist['hls']
        streamurl = hls[0]['url']
        #session = streamlink.Streamlink()
        session = livestreamer.Livestreamer()
        if threads:
            session.set_option('hls-segment-threads', int(threads))
        if trytimes:
            session.set_option('hls-segment-attempts', int(trytimes))
        session.set_option('hls-live-edge', 9999)
        try:
            streams = session.streams('hlsvariant://' + streamurl)
            stream = streams['best']
        except:
            print(user_id, streams)
            if user_id in recording:
                recording.remove(user_id)
            return
        filename = f"{user_id}-{time.strftime('%y%m%d_%H%M%S')}-{user_nick}-{title}.ts"
        opath = "/root/b/d/kr"
        path = f"/root/b/d/kr/{user_id}"
        try:
            fd = stream.open()
            if not os.path.exists(path):
                os.makedirs(path)
            else:
                files = os.listdir(path)
                for file in files:
                    fp = os.path.join(path, file)
                    shutil.move(fp, opath)
            filepath = os.path.join(path, filename)
            try:
                f = open(filepath, 'wb')
            except:
                title = '_'
                filename = f"{user_id}-{time.strftime('%y%m%d_%H%M%S')}-{user_nick}-{title}.ts"
                filepath = os.path.join(path, filename)
                f = open(filepath, 'wb')
            readsize = 1024 * 8
            limitsize = 1024 * 1024 * 1024
            fs = 0
            print(f"\r\033[K{user_id} {user_nick} start recording")
            while 1:
                data = fd.read(readsize)
                if data:
                    fs += f.write(data)
                    if fs >= limitsize:
                        f.close()
                        shutil.move(filepath, opath)
                        filename = f"{user_id}-{time.strftime('%y%m%d_%H%M%S')}-{user_nick}-{title}.ts"
                        filepath = os.path.join(path, filename)
                        f = open(filepath, 'wb')
                        fs = 0
                else:
                    break
        except Exception as e:
            print(f"\r\033[K{e}")
        finally:
            print(f"\r\033[K{user_id} {user_nick} recording end")
            if 'f' in locals():
                f.close()
            if 'fd' in locals():
                fd.close()
            if user_id in recording:
                recording.remove(user_id)
            files = os.listdir(path)
            if not files:
                os.rmdir(path)
    else:
        try:
            print(f"\r\033[K{user_id} {user_nick} recording end")
            files = os.listdir(path)
            if not files:
                os.rmdir(path)
        except:
            pass
        if user_id in recording:
            recording.remove(user_id)
Ejemplo n.º 9
0
 def get_stream_location(self):
     streamer = livestreamer.Livestreamer()
     plugin = streamer.resolve_url('http://twitch.tv/twitchplayspokemon')
     streams = plugin.get_streams()
     return streams['source'].url