Ejemplo n.º 1
0
    def open(self, url, quality):
        """Attempt to open stream from *url*.

        Exits with '-1' (using self.exit()) in case of error, including
        an error msg.
        """

        self.original_url = url
        try:
            self.livestreamer = Livestreamer()
            self._load_config()
            streams = self.livestreamer.streams(url)
        except NoPluginError:
            self.exit(
                "Livestreamer is unable to handle the URL '{}'".format(url))
        except PluginError as err:
            self.exit("Plugin error: {}".format(err))

        if quality not in streams:
            print("Unable to find '{}' stream on URL '{}'".format(
                quality, url),
                  file=sys.stderr)
            self.exit("List of available streams: {}".format(
                sorted(streams.keys())))

        self.stream = streams[quality]
        try:
            self.fd = self.stream.open()
        except StreamError as err:
            self.exit("Failed to open stream: {}".format(err))
Ejemplo n.º 2
0
def GetYoutubeFullLink(url):
	from livestreamer import Livestreamer
	livestr = Livestreamer()
	channel = livestr.resolve_url(url)
	streams = channel.get_streams()
	stream = streams["best"]
	return stream.url
Ejemplo n.º 3
0
    def __init__(self):
        self.gchoice = -1
        self.cchoice = -1
        self.exit_now = False
        self.state = 'none'
        self.keybingings = {
            ord('q'): self.quit,
            ord('f'): self.get_favorites,
            ord('s'): self.get_fav_games,
            ord('g'): self.get_games,
            ord('n'): self.get_next,
            ord('r'): self.refresh,
            ord('p'): self.get_previous
        }

        self.games = []
        self.favs = []
        self.channels = []
        self.twitch = Twitch(config.get('settings', 'twitchapiurl'),
                             config.get('settings', 'channel'),
                             config.get('settings', 'game'))
        self.livestreamer = Livestreamer()

        try:
            self.run()
        except Exception as e:
            print e.message
Ejemplo n.º 4
0
def stream(videoServerUrl, model):
    session = Livestreamer()
    session.set_option('http-headers',
                       'referer=https://bongacams.com/%s' % model)

    url = 'hlsvariant://https:%s/hls/stream_%s/playlist.m3u8' % (
        videoServerUrl, model)

    streams = session.streams(url)
    stream = streams['best']
    fd = stream.open()

    now = datetime.datetime.now()
    filePath = '%s/%s.mp4' % (model, model + now.strftime('%Y-%m-%d-%H-%M'))
    print(' - Start record stream')
    if not os.path.exists(model):
        os.makedirs(model)
    with open(filePath, 'wb') as f:
        while True:
            try:
                data = fd.read(1024)
                f.write(data)
            except:
                print(' - Error write record into file')
                f.close()
                return
Ejemplo n.º 5
0
def GetYoutubeFullLink(url):
    from livestreamer import Livestreamer
    livestr = Livestreamer()
    channel = livestr.resolve_url(url)
    streams = channel.get_streams()
    stream = streams["best"]
    return stream.url
Ejemplo n.º 6
0
def startRecording(model):
    try:
        session = Livestreamer()
        url = get.stream(model)
        if url == 'Offline':
            return
        recording.append(model.lower())
        streams = session.streams("hlsvariant://" + url)
        stream = streams["best"]
        fd = stream.open()
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime("%Y%m%d_%H%M%S")
        file_path = "{path}/{model}/{st}-{model}.mp4".format(
            path=settings['save_directory'], model=model, st=st)
        directory = file_path.rsplit('/', 1)[0] + '/'
        if not os.path.exists(directory):
            os.makedirs(directory)
        with open(file_path, 'wb') as f:
            while True:
                try:
                    data = fd.read(1024)
                    f.write(data)
                except:
                    break

    finally:
        os.system('rclone move "{}" milo:milo/b/MFC/"{}"'.format(
            file_Path, model))
        if model.lower() in recording:
            recording.remove(model.lower())
        if settings['post_processing_command']:
            processing_queue.put({'model': model, 'path': file_path})
Ejemplo n.º 7
0
def startRecording(model, link):
    session = Livestreamer()

    streams = session.streams("hls://http://transcode.k8s-do.naked.com/hls/" +
                              link + "/index.m3u8")
    stream = streams["best"]
    fd = stream.open()
    ts = time.time()
    st = datetime.datetime.fromtimestamp(ts).strftime("%Y.%m.%d_%H.%M.%S")
    if not os.path.exists("{path}/{model}".format(path=save_directory,
                                                  model=model)):
        os.makedirs("{path}/{model}".format(path=save_directory, model=model))
    with open(
            "{path}/{model}/{st}_{model}.mp4".format(path=save_directory,
                                                     model=model,
                                                     st=st), 'wb') as f:
        recording.append(model.lower())
        while True:
            try:
                data = fd.read(1024)
                f.write(data)
            except:
                recording.remove(model)
                f.close()
                return ()
Ejemplo n.º 8
0
class TestPluginStream(unittest.TestCase):
    def setUp(self):
        self.session = Livestreamer()

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

    def _test_akamaihd(self, surl, host, streamname):
        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.host, host)
        self.assertEqual(stream.streamname, streamname)

    def _test_hls(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, 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_plugin(self):
        self._test_rtmp("rtmp://hostname.se/stream",
                        "rtmp://hostname.se/stream", dict())

        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 live=1 qarg='a \'string' noq=test",
            "rtmp://hostname.se/stream",
            dict(live=True, qarg='a \'string', noq="test"))

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

        self._test_akamaihd("akamaihd://http://hostname.se/stream",
                            "http://hostname.se", "stream")
Ejemplo n.º 9
0
class TestPluginStream(unittest.TestCase):
    def setUp(self):
        self.session = Livestreamer()

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

    def _test_akamaihd(self, surl, host, streamname):
        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.host, host)
        self.assertEqual(stream.streamname, streamname)

    def _test_hls(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, 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_plugin(self):
        self._test_rtmp("rtmp://hostname.se/stream",
                         "rtmp://hostname.se/stream", dict())

        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 live=1 qarg='a \'string' noq=test",
                        "rtmp://hostname.se/stream", dict(live=True, qarg='a \'string', noq="test"))

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

        self._test_akamaihd("akamaihd://http://hostname.se/stream",
                            "http://hostname.se", "stream")
Ejemplo n.º 10
0
def _getLiveUrl(target):
    livestreamer = Livestreamer()
    streams = livestreamer.streams("http://www.twitch.tv/" + target)
    print(streams)
    if streams:
        # default
        # xx = streams.popitem()
        # return xx[1].url
        xx = streams.get('high')
        return xx.url
    return None
Ejemplo n.º 11
0
def _getLiveUrl(target):
    livestreamer = Livestreamer()
    streams = livestreamer.streams("http://www.twitch.tv/" + target)
    print(streams)
    if streams:
        # default
        # xx = streams.popitem()
        # return xx[1].url
        xx = streams.get('high')
        return xx.url
    return None
Ejemplo n.º 12
0
def test_start(model):
    model_link_api = 'https://chaturbate.com/api/chatvideocontext/' + model + '/'
    result = requests.get(model_link_api).json()
    session = Livestreamer()
    session.set_option('http-header',"referer=https://www.chaturbate.com/{}/".format(model))
    stream = session.streams("hlsvariant://{}".format(result['hls_source'].rsplit('?')[0]))
    stream = stream['best']
    fd = stream.open()
    
    with open(model + '.mp4', 'wb') as file:
        while True:
            data = fd.read(1024)
            file.write(data)
Ejemplo n.º 13
0
    def __init__(self, threadID, output_location, name, yt_stream, start_time):
        threading.Thread.__init__(self)

        self.threadID = threadID
        self.output = os.path.abspath(output_location)
        self.name = name
        self.start_time = start_time
        self.bufferSize = 1024
        self.maxSize = self.bufferSize * 1024 * 50  # 10 MB videos
        self.livestreamer = Livestreamer()
        self.numOfIndexes = 5
        self.outFiles = []

        self.yt_stream = yt_stream.strip('\'"')
Ejemplo n.º 14
0
def startRecording(modelData, num):
    try:
        recording.append(modelData['username'].lower())
        with urllib.request.urlopen(
                "https://www.camsoda.com/api/v1/video/vtoken/{model}?username=guest_{num}"
                .format(model=modelData['username'], num=num)) as videoapi:
            data2 = json.loads(videoapi.read().decode())
            if str(modelData['status']) != 'limited':
                if str(modelData['status']) == 'private':
                    server = data2['private_servers'][0]
                elif modelData['status'] == 'online':
                    server = data2['edge_servers'][0]
                else:
                    server = data2['mjpeg_server']
                link = "hlsvariant://https://{server}/{app}/mp4:{stream_name}_mjpeg/playlist.m3u8?token={token}".format(
                    server=server,
                    app=data2['app'],
                    stream_name=data2['stream_name'],
                    token=data2['token'])
            if not os.path.exists("{path}/{model}".format(
                    path=save_directory, model=modelData['username'])):
                os.makedirs("{path}/{model}".format(
                    path=save_directory, model=modelData['username']))
            session = Livestreamer()
            streams = session.streams(link)
            stream = streams["best"]
            fd = stream.open()
            ts = time.time()
            st = datetime.datetime.fromtimestamp(ts).strftime(
                "%Y.%m.%d_%H.%M.%S")
            with open(
                    "{path}/{model}/{st}_{model}.mp4".format(
                        path=save_directory,
                        model=modelData['username'],
                        st=st), 'wb') as f:
                while True:
                    try:
                        data = fd.read(1024)
                        f.write(data)
                    except:
                        recording.remove(modelData['username'].lower())
                        #print("{} stream has ended".format(modelData['username']))
                        f.close()
                        return ()
        recording.remove(modelData['username'].lower())
        #print("{} stream has ended".format(modelData['username']))

    except:
        recording.remove(modelData['username'].lower())
Ejemplo n.º 15
0
def face_detect(x, y, width, height, stream_url):
    x = x*426/651
    y = y*240/398
    width = width*426/651
    height = height*240/398
    cascade_fn = "haarcascade_frontalface_alt.xml"
    nested_fn = "haarcascade_eye.xml"

    cascade = cv2.CascadeClassifier(cascade_fn)
    nested = cv2.CascadeClassifier(nested_fn)

    FFMPEG_BIN = 'C:/ffmpeg/bin/ffmpeg.exe'

    livestreamer = Livestreamer()
    plugin = livestreamer.resolve_url(stream_url)
    streams = plugin.get_streams()
    stream = streams.get("best")
    VIDEO_URL = stream.url
    print VIDEO_URL
    pipe = sp.Popen([FFMPEG_BIN, "-i", VIDEO_URL,
                     "-loglevel", "quiet",  # no text output
                     "-an",  # disable audio
                     "-f", "image2pipe",
                     "-pix_fmt", "bgr24",
                     "-vcodec", "rawvideo", "-"],
                    stdin=sp.PIPE, stdout=sp.PIPE)
    interval = 0
    while True:
        raw_image = pipe.stdout.read(426 * 240 * 3)  # read 432*240*3 bytes (= 1 frame)
        img = np.fromstring(raw_image, dtype='uint8').reshape((240, 426, 3))
        img = img[y:(y + height), x:(x + width)]
        gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        gray = cv2.equalizeHist(gray)

        rects = detect(gray, cascade)
        vis = img.copy()
        if rects:
            interval += 1
        draw_rects(vis, rects, (0, 255, 0))
        for x1, y1, x2, y2 in rects:
            roi = gray[y1:y2, x1:x2]
            vis_roi = vis[y1:y2, x1:x2]
            subrects = detect(roi.copy(), nested)
            draw_rects(vis_roi, subrects, (255, 0, 0))

        cv2.imwrite('./media/face', vis)
        if cv2.waitKey(5) == 27:
            break
    cv2.destroyAllWindows()
Ejemplo n.º 16
0
def startRecording(model):
    global postProcessingCommand
    global processingQueue
    try:
        result = requests.get('https://chaturbate.com/api/chatvideocontext/{}/'.format(model)).text
        result = json.loads(result)
        session = Livestreamer()
        session.set_option('http-headers', "referer=https://www.chaturbate.com/{}".format(model))
        streams = session.streams("hlsvariant://{}".format(result['hls_source'].rsplit('?')[0]))
        stream = streams["best"]
        fd = stream.open()
        now = datetime.datetime.now()
        filePath = directory_structure.format(path=save_directory, model=model, gender=result['broadcaster_gender'],
                                              seconds=now.strftime("%S"),
                                              minutes=now.strftime("%M"), hour=now.strftime("%H"),
                                              day=now.strftime("%d"),
                                              month=now.strftime("%m"), year=now.strftime("%Y"))
        directory = filePath.rsplit('/', 1)[0]+'/'
        if not os.path.exists(directory):
            os.makedirs(directory)
        with open(filePath, 'wb') as f:
            recording.append(model)
            while True:
                try:
                    data = fd.read(1024)
                    f.write(data)
                except:
                    f.close()
                    recording.remove(model)
                    if postProcessingCommand != "":
                        processingQueue.put({'model':model, 'path':filePath, 'gender':gender})
                    elif completed_directory != "":
                        finishedDir = completed_directory.format(path=save_directory, model=model,
                                                                 gender=gender, seconds=now.strftime("%S"),
                                                                 minutes=now.strftime("%M"),
                                                                 hour=now.strftime("%H"), day=now.strftime("%d"),
                                                                 month=now.strftime("%m"), year=now.strftime("%Y"))

                        if not os.path.exists(finishedDir):
                            os.makedirs(finishedDir)
                        os.rename(filePath, finishedDir+'/'+filePath.rsplit['/',1][0])
                    return

        if model in recording:
            recording.remove(model)
    except:
        if model in recording:
            recording.remove(model)
Ejemplo n.º 17
0
    def __init__(self, model, save_directory):
        self.__model = model
        self.save_directory = save_directory

        options_url = 'https://it.chaturbate.com/api/chatvideocontext/{}'.format(
            model)
        self.options = json.loads(requests.get(options_url).content)

        self.session = Livestreamer()
        self.session.set_option('http-headers',
                                'referer={}'.format(options_url))

        self.streams = None
        self.__get_live_streams()

        self.__record_status = True
Ejemplo n.º 18
0
    def open(self, url, quality):
        """Attempt to open stream from *url*.

        Exits with '-1' (using self.exit()) in case of error, including
        an error msg.
        """

        self.original_url = url
        try:
            self.livestreamer = Livestreamer()
            self._load_config()
            streams = self.livestreamer.streams(url)
        except NoPluginError:
            self.exit("Livestreamer is unable to handle the URL '{}'".
                      format(url))
        except PluginError as err:
            self.exit("Plugin error: {}".format(err))

        if quality not in streams:
            print("Unable to find '{}' stream on URL '{}'"
                  .format(quality, url), file=sys.stderr)
            self.exit("List of available streams: {}".
                      format(sorted(streams.keys())))

        self.stream = streams[quality]
        try:
            self.fd = self.stream.open()
        except StreamError as err:
            self.exit("Failed to open stream: {}".format(err))
Ejemplo n.º 19
0
def stream_recording():
 
    print("STARTING TO RECORD STREAM")

    session = Livestreamer()
    stream = session.streams('http://www.twitch.tv/' + channel)

    print("CONNECTED TO STREAM")
    stream = stream['source']
    fd = stream.open()
    print("CONNECTED!")
    f = open("stream.dat", 'wb')

    while True:
        data = fd.read(1024)
        f.write(data)
 def __init__(self):    
     self.gchoice = -1
     self.cchoice = -1    
     self.exit_now = False
     self.state = 'none'
     self.keybingings = {
         ord('q'):       self.quit,
         ord('f'):       self.get_favorites,
         ord('s'):       self.get_fav_games,
         ord('g'):       self.get_games,
         ord('n'):       self.get_next,
         ord('r'):       self.refresh,
         ord('p'):       self.get_previous            
     }
     
     self.games = []
     self.favs = []
     self.channels = []        
     self.twitch = Twitch(config.get('settings', 'twitchapiurl'), config.get('settings', 'channel'), config.get('settings', 'game'))
     self.livestreamer = Livestreamer()
     
     try:
         self.run()
     except Exception as e:
         print e.message
Ejemplo n.º 21
0
def startRecording(model):
    try:
        model = model.lower()
        req = urllib.request.Request('https://www.cam4.com/' + model)
        req.add_header('UserAgent', UserAgent)
        resp = urllib.request.urlopen(req)
        resp = resp.read().decode().splitlines()
        videoPlayUrl = ""
        videoAppUrl = ""
        for line in resp:
            if "videoPlayUrl" in line:
                for part in line.split("&"):
                    if "videoPlayUrl" in part and videoPlayUrl == "":
                        videoPlayUrl = part[13:]
                    elif "videoAppUrl" in part and videoAppUrl == "":
                        videoAppUrl = part.split("//")[1]
        session = Livestreamer()
        session.set_option('http-headers',
                           "referer=https://www.cam4.com/{}".format(model))
        streams = session.streams(
            "hlsvariant://https://{}/amlst:{}_aac/playlist.m3u8?referer=www.cam4.com&timestamp={}"
            .format(videoAppUrl, videoPlayUrl, str(int(time.time() * 1000))))
        stream = streams["best"]
        fd = stream.open()
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime("%Y.%m.%d_%H.%M.%S")
        if not os.path.exists("{path}/{model}".format(path=save_directory,
                                                      model=model)):
            os.makedirs("{path}/{model}".format(path=save_directory,
                                                model=model))
        with open(
                "{path}/{model}/{st}_{model}.mp4".format(path=save_directory,
                                                         model=model,
                                                         st=st), 'wb') as f:
            recording.append(model)
            while True:
                try:
                    data = fd.read(1024)
                    f.write(data)
                except:
                    recording.remove(model)

        if model in recording:
            recording.remove(model)
    except:
        if model in recording:
            recording.remove(model)
Ejemplo n.º 22
0
def watch(url):
    session = Livestreamer()
    session.set_loglevel('info')
    session.set_logoutput(sys.stdout)
    session.set_option('http-headers',
                       'Client-ID=jzkbprff40iqj646a697cyrvl0zt2m6')

    streams = session.streams(url)
    stream = streams['audio_only']

    fd = stream.open()  # read to nowhere
    while True:
        fd.read(1024)
Ejemplo n.º 23
0
def main():
    session = Livestreamer()
    session.set_option("http-headers",
                       "Client-ID=jzkbprff40iqj646a697cyrvl0zt2m6")
    streams = session.streams("twitch.tv/tsm_myth")
    stream = streams['720p60']
    fname = "downloading.mpg"
    vid_file = open(fname, "wb")
    fd = stream.open()
    new_bytes = 0

    for i in range(0, 8 * 1024):
        new_bytes = fd.read(2048)
        vid_file.write(new_bytes)
    print "Done buffering."

    startReadingFrames(fname, vid_file, fd)
Ejemplo n.º 24
0
def startRecording(model):
    try:
        URL = "https://chaturbate.com/{}/".format(model)
        result = urllib.request.urlopen(URL)
        result = result.read().decode()
        for line in result.splitlines():
            if "m3u8" in line:
                stream = line.split("'")[1]
                break
        soup = BeautifulSoup(result, 'lxml')
        soup = soup.findAll('div', id="tabs_content_container")
        for line in str(soup).split():
            if 'Sex:' in line:
                gender = line.split("</dt><dd>")[1][:-5].lower()
        session = Livestreamer()
        session.set_option('http-headers',
                           "referer=https://www.cam4.com/{}".format(model))
        streams = session.streams("hlsvariant://{}".format(stream))
        stream = streams["best"]
        fd = stream.open()
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime("%d.%m.%Y_%H.%M.%S")
        if not os.path.exists("{path}/{model}_{gender}".format(
                path=save_directory, model=model, gender=gender)):
            os.makedirs("{path}/{model}_{gender}".format(path=save_directory,
                                                         model=model,
                                                         gender=gender))
        with open(
                "{path}/{model}_{gender}/{st}_{model}_{gender}.mp4".format(
                    path=save_directory, model=model, gender=gender, st=st),
                'wb') as f:
            recording.append(model)
            while True:
                try:
                    data = fd.read(1024)
                    f.write(data)
                except:
                    f.close()
                    recording.remove(model)
                    return

        if model in recording:
            recording.remove(model)
    except:
        if model in recording:
            recording.remove(model)
Ejemplo n.º 25
0
class recordingThread(threading.Thread):
    def __init__(self, threadID, output_location, name, yt_stream, start_time):
        threading.Thread.__init__(self)

        self.threadID = threadID
        self.output = os.path.abspath(output_location)
        self.name = name
        self.start_time = start_time
        self.bufferSize = 1024
        self.maxSize = self.bufferSize * 1024 * 50  # 10 MB videos
        self.livestreamer = Livestreamer()
        self.numOfIndexes = 5
        self.outFiles = []

        self.yt_stream = yt_stream.strip('\'"')

    def run(self):
        print "Starting %s Thread Recorder - %s" % (self.name, self.start_time)
        name_conv_dict = {
            'output_location': self.output,
            'name': self.name,
            'time': time.strftime("%H%M_%d%b%y")
        }
        output_location = NAME_FORMAT.format(**name_conv_dict)

        try:
            available_streams = self.livestreamer.streams(self.yt_stream)
            bestStream = available_streams['best']
            stream_obj = bestStream.open()
            for i in range(self.numOfIndexes):
                outFileName = output_location.replace(".mp4",
                                                      "_" + str(i) + ".mp4")
                self.outFiles.append(outFileName)
                outVid = open(outFileName, 'ab')
                currByteCount = 0
                while currByteCount < self.maxSize:
                    data = stream_obj.read(512 * 1024)
                    outVid.write(data)
                    currByteCount += 512 * 1024
                    outVid.flush()

            stream_obj.close()

        except LivestreamerError as err:
            print self.threadID + " Exception."
            print err

        except Exception, e:
            print self.threadID + " Exception."
            print e.message

        print self.name + " Done Recording."
        outVid.close()

        print self.name + " Re-encoding..."
        self.reencode()
        print self.name + " Re-encoding Done."
Ejemplo n.º 26
0
def start(portNum):
	global LIVESTREAMER
	LIVESTREAMER = Livestreamer()
	LIVESTREAMER.set_option('hls-segment-threads', '3')
	LIVESTREAMER.set_option('hds-segment-threads', '3')
	LIVESTREAMER.set_option('stream-segment-threads', '3')

	global httpd
	#httpd = ThreadedHTTPServer(('', portNum), StreamHandler)
	httpd = StoppableHTTPServer(('', portNum), StreamHandler)
	try:
		#thread.start_new_thread(httpd.serve, ())
		t1 = threading.Thread(target = httpd.serve, args = ())
		t1.daemon = True
		t1.start()
		print "Livestreamer: Server Starts - {0}:{1}".format("localhost", portNum)
	except Exception as ex:
		print ex
 def serveFile(self, fURL, sendData):
     from livestreamer import Livestreamer, StreamError, PluginError, NoPluginError
     session = Livestreamer()
     if '|' in fURL:
             sp = fURL.split('|')
             fURL = sp[0]
             headers = dict(urlparse.parse_qsl(sp[1]))
             session.set_option("http-headers", headers)
             session.set_option("http-ssl-verify",False)
     try:
         streams = session.streams(fURL)
     except:
         traceback.print_exc(file=sys.stdout)
         self.send_response(403)
     self.send_response(200)
     #print "XBMCLocalProxy: Sending headers..."
     self.end_headers()
     
     if (sendData):
         #print "XBMCLocalProxy: Sending data..."
         fileout = self.wfile
         try:
             stream = streams["best"]
             try:
                 response = stream.open()
                 buf = 'INIT'
                 while (buf != None and len(buf) > 0):
                     buf = response.read(300 * 1024)
                     fileout.write(buf)
                     fileout.flush()
                 response.close()
                 fileout.close()
                 #print time.asctime(), "Closing connection"
             except socket.error, e:
                 #print time.asctime(), "Client Closed the connection."
                 try:
                     response.close()
                     fileout.close()
                 except Exception, e:
                     return
             except Exception, e:
                 traceback.print_exc(file=sys.stdout)
                 response.close()
                 fileout.close()
Ejemplo n.º 28
0
def get_stream(stream_url):
    # change to a stream that is actually online
    livestreamer = Livestreamer()
    stream = None
    try:
        plugin = livestreamer.resolve_url("http://www.twitch.tv/" + stream_url)
        plugin.set_option('oauth_token', 'xtlhyl6uapy6znsvuhy4zfk0jbt086')
        streams = plugin.get_streams()
        # It seems best isn't necessarily the best, twitch doesn't seem to consider 60
        # streams, so we should search for those first.
        if '1080p60' in streams:
            stream = streams['1080p60']
        elif '720p60' in streams:
            stream = streams['720p60']
        else:
            stream = streams['best']
    except Exception:
        pass
    return stream
Ejemplo n.º 29
0
def start(portNum):
    global LIVESTREAMER
    LIVESTREAMER = Livestreamer()
    global httpd
    httpd = ThreadedHTTPServer(("localhost", portNum), StreamHandler)
    print "Livestreamer: Server Starts - {0}:{1}".format("localhost", portNum)
    try:
        httpd.serve_forever()
    except:
        pass
Ejemplo n.º 30
0
    def serveFile(self, fURL, sendData):
        from livestreamer import Livestreamer, StreamError, PluginError, NoPluginError
        session = Livestreamer()
        if '|' in fURL:
            sp = fURL.split('|')
            fURL = sp[0]
            headers = dict(urlparse.parse_qsl(sp[1]))
            session.set_option("http-headers", headers)
        try:
            streams = session.streams(fURL)
        except:
            traceback.print_exc(file=sys.stdout)
            self.send_response(403)
        self.send_response(200)
        #print "XBMCLocalProxy: Sending headers..."
        self.end_headers()

        if (sendData):
            #print "XBMCLocalProxy: Sending data..."
            fileout = self.wfile
            try:
                stream = streams["best"]
                try:
                    response = stream.open()
                    buf = 'INIT'
                    while (buf != None and len(buf) > 0):
                        buf = response.read(300 * 1024)
                        fileout.write(buf)
                        fileout.flush()
                    response.close()
                    fileout.close()
                    #print time.asctime(), "Closing connection"
                except socket.error, e:
                    #print time.asctime(), "Client Closed the connection."
                    try:
                        response.close()
                        fileout.close()
                    except Exception, e:
                        return
                except Exception, e:
                    traceback.print_exc(file=sys.stdout)
                    response.close()
                    fileout.close()
    def serveFile(self, fURL, sendData):
        if (sendData):
            fURL, quality = player.GetStreamUrl(unquote(fURL))
            session = Livestreamer()
            if '|' in fURL:
                sp = fURL.split('|')
                fURL = sp[0]
                headers = dict(urlparse.parse_qsl(sp[1]))
                session.set_option("http-headers", headers)
                session.set_option("http-ssl-verify", False)
                session.set_option("hls-segment-threads", 3)
                session.set_option("stream-segment-threads", 3)
            try:
                #streams = session.streams(fURL)
                channel = session.resolve_url(fURL)
                streams = channel.get_streams()
            except Exception as ex:
                traceback.print_exc(file=sys.stdout)
                self.send_response(403)
            self.send_response(200)
            #print "XBMCLocalProxy: Sending headers..."
            self.end_headers()

            #print "XBMCLocalProxy: Sending data..."
            fileout = self.wfile
            try:
                stream = streams[quality]
                try:
                    response = stream.open()
                    buf = 'INIT'
                    while (buf != None and len(buf) > 0):
                        buf = response.read(200 * 1024)
                        fileout.write(buf)
                        fileout.flush()
                    response.close()
                    fileout.close()
                    #print time.asctime(), "Closing connection"
                except socket.error, e:
                    #print time.asctime(), "Client Closed the connection."
                    try:
                        response.close()
                        fileout.close()
                    except Exception, e:
                        return
                except Exception, e:
                    traceback.print_exc(file=sys.stdout)
                    response.close()
                    fileout.close()
Ejemplo n.º 32
0
    def _init_stream(self, oauth, channel):
        session = Livestreamer()

        session.set_plugin_option(self.LIVESTREAMER_PLUGIN_TWITCH,
                                  self.OAUTH_TOKEN_KEY, oauth)
        session.set_option(self.RING_BUFFER_SIZE_KEY, self.buffer_size)

        streams = session.streams(self._generate_stream_url(channel))
        return streams.get(self.resolution)
Ejemplo n.º 33
0
def startRecording(model):
    try:
        recording[model['uid']] = model['nm']
        session = Livestreamer()
        streams = session.streams("hlsvariant://http://video{srv}.myfreecams.com:1935/NxServer/ngrp:mfc_{id}.f4v_mobile/playlist.m3u8"
          .format(id=(int(model['uid']) + 100000000),
            srv=(int(model['camserv']) - 500)))
        stream = streams["best"]
        fd = stream.open()
        now = datetime.datetime.now()
        filePath = directory_structure.format(path=save_directory, model=model['nm'], uid=model['uid'],
                                              seconds=now.strftime("%S"), day=now.strftime("%d"),
                                              minutes=now.strftime("%M"), hour=now.strftime("%H"),
                                              month=now.strftime("%m"), year=now.strftime("%Y"))
        directory = filePath.rsplit('/', 1)[0]+'/'
        if not os.path.exists(directory):
            os.makedirs(directory)
        with open(filePath, 'wb') as f:
            minViewers = filter['autoStopViewers'] if model['condition'] == 'viewers' else filter['stopViewers']
            while modelDict[model['uid']]['rc'] >= minViewers:
                try:
                    data = fd.read(1024)
                    f.write(data)
                except:
                    f.close()
                    recording.pop(model['uid'], None)

            recording.pop(model['uid'], None)
            if postProcessingCommand != "":
                processingQueue.put({'model':model['nm'], 'path': filePath, 'uid':model['uid']})
            elif completed_directory != "":
                finishedDir = completed_directory.format(path=save_directory, model=model, uid=model['uid'],
                                                         seconds=now.strftime("%S"), minutes=now.strftime("%M"),
                                                         hour=now.strftime("%H"), day=now.strftime("%d"),
                                                         month=now.strftime("%m"), year=now.strftime("%Y"))
                if not os.path.exists(finishedDir):
                    os.makedirs(finishedDir)
                os.rename(filePath, finishedDir+'/'+filePath.rsplit('/', 1)[1])
                return

    finally:
        recording.pop(model['uid'], None)
Ejemplo n.º 34
0
 def __init__(self, session, streamFile=None):
     self.session = session
     Screen.__init__(self, session)
     self['info'] = Label('...')
     self['actions'] = ActionMap(
         [
             'OkCancelActions', 'ShortcutActions', 'WizardActions',
             'ColorActions', 'SetupActions', 'NumberActions', 'MenuActions'
         ], {
             'ok': self.keyOK,
             'cancel': self.keyCancel,
             'up': self.keyUp,
             'down': self.keyDown,
             'left': self.keyLeft,
             'right': self.keyRight
         }, -1)
     self.streamBin = '/usr/bin/rtmpdump'
     self.streamPipe = '/tmp/greekstreamtv.avi'
     if not streamFile:
         self.streamFile = resolveFilename(
             SCOPE_PLUGINS, 'Extensions/GreekStreamTV/stream.xml')
     else:
         self.streamFile = streamFile
     self.lvstreamer = Livestreamer()
     self.streamList = []
     self.makeStreamList()
     self.streamMenuList = MenuList([],
                                    enableWrapAround=True,
                                    content=eListboxPythonMultiContent)
     self.streamMenuList.l.setFont(0, gFont('Regular', 22))
     self.streamMenuList.l.setFont(1, gFont('Regular', 18))
     self.streamMenuList.l.setItemHeight(37)
     self['streamlist'] = self.streamMenuList
     self.streamMenuList.setList(map(streamListEntry, self.streamList))
     self.onLayoutFinish.append(self.layoutFinished)
     self.beforeService = None
     self.currentService = None
     self.playerStoped = False
     self.keyLocked = False
     self.pd = None
     self.qsel = None
     return
Ejemplo n.º 35
0
def stream_recording():
    from livestreamer import Livestreamer
 
    print(": Starting to record stream")
 
    session = Livestreamer()
    stream = session.streams('http://www.twitch.tv/' + channel)
    print("Connecting to stream")
    stream = stream['source']
    fd = stream.open()
    print("Connected!")

    #lock = threading.Lock()
    f = open("stream.dat", 'wb')# with open("stream.dat", 'wb') as f:

    global front
    while True:
        data = fd.read(1024)
        f.write(data)
        front += len(data)
def startRecording(model):
    try:
        URL = "https://chaturbate.com/{}/".format(model)
        result = urllib.request.urlopen(URL)
        result = result.read().decode()
        for line in result.splitlines():
            if "m3u8" in line:
                stream = line.split("'")[1]
                break
        session = Livestreamer()
        session.set_option(
            'http-headers',
            "referer=https://www.chaturbate.com/{}".format(model))
        streams = session.streams("hlsvariant://{}".format(stream))
        stream = streams["best"]
        fd = stream.open()
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime("%Y.%m.%d_%H.%M.%S")
        if not os.path.exists("{path}/{model}".format(path=save_directory,
                                                      model=model)):
            os.makedirs("{path}/{model}".format(path=save_directory,
                                                model=model))
        with open(
                "{path}/{model}/{st}_{model}.mp4".format(path=save_directory,
                                                         model=model,
                                                         st=st), 'wb') as f:
            recording.append(model)
            while True:
                try:
                    data = fd.read(1024)
                    f.write(data)
                except:
                    f.close()
                    recording.remove(model)
                    return

        if model in recording:
            recording.remove(model)
    except:
        if model in recording:
            recording.remove(model)
Ejemplo n.º 37
0
    def __init__(self, session, streamFile=None):
        Screen.__init__(self, session)
        self.setTitle(_("GreekStreamTV list"))
        self["info"] = Label("...")
        self["key_red"] = StaticText(_("Cancel"))
        self["key_green"] = StaticText(_("Play"))

        self["actions"] = ActionMap(["OkCancelActions", "WizardActions", "ColorActions"],
        {
            "ok"    : self.keyOK,
            "green" : self.keyOK,
            "cancel": self.keyCancel,
            "red"   : self.keyCancel,
            "up"    : self.keyUp,
            "down"  : self.keyDown,
            "left"  : self.keyLeft,
            "right" : self.keyRight,
        }, -1)

        self.streamBin  = "/usr/bin/rtmpdump"
        self.streamPipe = "/tmp/greekstreamtv.avi"

        if not streamFile:
            self.streamFile = resolveFilename(SCOPE_PLUGINS, "Extensions/GreekStreamTV/stream.xml")
        else:
            self.streamFile = streamFile

        self.lvstreamer = Livestreamer()

        self.streamList = []
        self.makeStreamList()
        self["streamlist"] = StreamList(self.streamList)

        self.onLayoutFinish.append(self.layoutFinished)

        self.beforeService  = None
        self.currentService = None
        self.playerStoped   = False
        self.keyLocked = False
        self.pd = None
        self.qsel = None
Ejemplo n.º 38
0
def openStream(url, quality):
    """Open a livestreamer URL and return the stream"""

    livestreamer = Livestreamer()
    setOptions(livestreamer)

    try:
        streams = livestreamer.streams(url)
    except NoPluginError:
        print("Unable to Find Plugin")
        abort(404)

    except PluginError as err:
        print("Plugin error: {0}".format(err))
        abort(404)

    if quality not in streams:
        print("Quality {0} not available in {1}".format(quality, url))
        abort(404)

    return streams[quality]
Ejemplo n.º 39
0
def openStream(url, quality):
    """Open a livestreamer URL and return the stream"""

    livestreamer = Livestreamer()
    setOptions(livestreamer)

    try:
        streams = livestreamer.streams(url)
    except NoPluginError:
        print("Unable to Find Plugin")
        abort(404)

    except PluginError as err:
        print("Plugin error: {0}".format(err))
        abort(404)

    if quality not in streams:
        print("Quality {0} not available in {1}".format(quality, url))
        abort(404)

    return streams[quality]
Ejemplo n.º 40
0
class Application:
    def __init__(self, window, stream_list):
        self.window = window
        self.stream_list = stream_list
        self.livestreamer = Livestreamer()
    
    def refresh_key(self):
        self.stream_list.update_streamers()
        self.refresh_screen()

    def refresh_screen(self):
        self.window.screen.erase()
        self.window.draw_borders()
        self.window.draw_help()
        self.stream_list.draw_streamers()
        self.window.screen.refresh()

    def up_key(self, distance=1):
        self.stream_list.move_up(distance)
        self.refresh_screen()

    def down_key(self, distance=1):
        self.stream_list.move_down(distance)
        self.refresh_screen()

    def sort_key(self):
        self.stream_list.toggle_sort()
        self.refresh_screen()

    def sort_order_key(self):
        self.stream_list.toggle_sort_order()
        self.refresh_screen()

    def resize_event(self):
        self.window.resize_term()
        self.refresh_screen()

    def play_stream(self, livestreamer_config=None, quality="best"):
        url = self.stream_list.get_twitch_url()
        streams = self.livestreamer.streams(url)
        
        stream = streams[quality]

        call = []
        call.append('livestreamer')
        call.append('--quiet')
        if livestreamer_config is not None:
            call.append('--config')
            call.append(livestreamer_config)
        call.append(url)
        call.append(quality)

        subprocess.Popen(call)
Ejemplo n.º 41
0
def main():
    if len(sys.argv) < 3:
        exit("Usage: {0} <url> <quality>".format(sys.argv[0]))

    gi.require_version("Gst", "1.0")
    gobject.threads_init()
    gst.init(None)

    url = sys.argv[1]
    quality = sys.argv[2]

    livestreamer = Livestreamer()

    livestreamer.set_loglevel("info")
    livestreamer.set_logoutput(sys.stdout)

    try:
        streams = livestreamer.streams(url)
    except NoPluginError:
        exit("Livestreamer 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))

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

    stream = streams[quality]

    player = LivestreamerPlayer()

    player.play(stream)
Ejemplo n.º 42
0
    def __init__(self, filename, rc_module):
        """ Init and try to load a stream list, nothing about curses yet """

        self.db_was_read = False

        # Open the storage (create it if necessary
        try:
            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

        # 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
        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.rc_module = rc_module

        if 'LIVESTREAMER_COMMANDS' in dir(self.rc_module):
            self.cmd_list = list(map(shlex.split, self.rc_module.LIVESTREAMER_COMMANDS))
        else:
            self.cmd_list = [['livestreamer']]
        self.cmd_index = 0
        self.cmd = self.cmd_list[self.cmd_index]

        if 'DEFAULT_RESOLUTION' in dir(self.rc_module):
            self.default_res = self.rc_module.DEFAULT_RESOLUTION
        else:
            self.default_res = DEFAULT_RESOLUTION_HARD

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

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

        self.livestreamer = Livestreamer()
    def serveFile(self, fURL, sendData):
        if (sendData):
            fURL, quality = player.GetStreamUrl(unquote(fURL))
            session = Livestreamer()
            if '|' in fURL:
                    sp = fURL.split('|')
                    fURL = sp[0]
                    headers = dict(urlparse.parse_qsl(sp[1]))
                    session.set_option("http-headers", headers)
                    session.set_option("http-ssl-verify",False)
                    session.set_option("hls-segment-threads",3)
                    session.set_option("stream-segment-threads",3)
            try:
                #streams = session.streams(fURL)
                channel = session.resolve_url(fURL)
                streams = channel.get_streams()
            except Exception as ex:
                traceback.print_exc(file=sys.stdout)
                self.send_response(403)
            self.send_response(200)
            #print "XBMCLocalProxy: Sending headers..."
            self.end_headers()

            #print "XBMCLocalProxy: Sending data..."
            fileout = self.wfile
            try:
                stream = streams[quality]
                try:
                    response = stream.open()
                    buf = 'INIT'
                    while (buf != None and len(buf) > 0):
                        buf = response.read(200 * 1024)
                        fileout.write(buf)
                        fileout.flush()
                    response.close()
                    fileout.close()
                    #print time.asctime(), "Closing connection"
                except socket.error, e:
                    #print time.asctime(), "Client Closed the connection."
                    try:
                        response.close()
                        fileout.close()
                    except Exception, e:
                        return
                except Exception, e:
                    traceback.print_exc(file=sys.stdout)
                    response.close()
                    fileout.close()
Ejemplo n.º 44
0
	def __init__(self, master):
		self.master = master
		self.frame = tk.Frame(self.master)

		gobject.threads_init()
		gst.init(None)
		self.livestreamer = Livestreamer()
		self.livestreamer.set_loglevel("info")
		self.livestreamer.set_logoutput(sys.stdout)
		self.fd = None

		try:
			self.streams = self.livestreamer.streams('http://www.twitch.tv/saltybet')
		except NoPluginError:
			exit("Livestreamer failed to handle the url.")
		except PluginError as err:
			exit("Livestreamer plugin error: {}".format(err))

		if not self.streams:
			exit("No streams found.")

		if 'best' not in self.streams:
			exit("Unable to select livestreamer quality.")

		self.stream = self.streams['best']

		try:
			self.fd = self.stream.open()
		except SteamError as err:
			self.exit("Livestreamer failed to open stream.")

		self.init_gui()
		# self.login()

		self.window_id = self.video.winfo_id()

		self.player = gst.ElementFactory.make('playbin', None)
		self.player.set_property('video-sink', None)
		self.player.set_property('uri', 'appsrc://')

		self.player.connect('source-setup', self.on_source_setup)

		self.bus = self.player.get_bus()
		self.bus.add_signal_watch()
		self.bus.enable_sync_message_emission()
		self.bus.connect('sync-message::element', self.on_sync_message, self.window_id)
		self.bus.connect('message::eos', self.on_eos)
		self.bus.connect('message::error', self.on_error)

		self.player.set_state(gst.State.PLAYING)
Ejemplo n.º 45
0
def startRecording(model):
    try:
        model = model.lower()
        resp = requests.get('https://www.cam4.com/' + model, headers={'user-agent':'UserAgent'}).text.splitlines()
        videoPlayUrl = ""
        videoAppUrl = ""
        for line in resp:
            if "videoPlayUrl" in line:
                for part in line.split("&"):
                    if "videoPlayUrl" in part and videoPlayUrl == "":
                        videoPlayUrl = part[13:]
                    elif "videoAppUrl" in part and videoAppUrl == "":
                        videoAppUrl = part.split("//")[1]
        session = Livestreamer()
        session.set_option('http-headers', "referer=https://www.cam4.com/{}".format(model))
        streams = session.streams("hlsvariant://https://{}/amlst:{}_aac/playlist.m3u8?referer=www.cam4.com&timestamp={}"
          .format(videoAppUrl, videoPlayUrl, str(int(time.time() * 1000))))
        stream = streams["best"]
        fd = stream.open()
        ts = time.time()
        st = datetime.datetime.fromtimestamp(ts).strftime("%Y.%m.%d_%H.%M.%S")
        file = os.path.join(setting['save_directory'], model, "{st}_{model}.mp4".format(path=setting['save_directory'], model=model,
                                                            st=st))
        os.makedirs(os.path.join(setting['save_directory'], model), exist_ok=True)
        with open(file, 'wb') as f:
            recording.append(model)
            while True:
                try:
                    data = fd.read(1024)
                    f.write(data)
                except:
                    break
        if setting['postProcessingCommand']:
            processingQueue.put({'model': model, 'path': file})
    finally:
        if model in recording:
            recording.remove(model)
Ejemplo n.º 46
0
    def run(self):
        print('Starting ' + self.username)
        session = Livestreamer()
        session.set_option('http-headers',
                           'Client-ID=jzkbprff40iqj646a697cyrvl0zt2m6')
        streams = session.streams("http://twitch.tv/" + self.username)
        assert len(streams) != 0, 'Stream not open.'

        directory = os.path.join('images', self.username)
        try:
            os.makedirs(directory)
        except:
            pass

        qualities = streams.keys()
        stream = None
        if '360p' in qualities:
            stream = streams['360p']
        # elif 'medium' in qualities:
        #     stream = streams['medium']
        assert stream is not None, self.username + ': No valid stream quality found.'

        period = 10
        timer = time.time() + period
        data = b''
        with stream.open() as fd:
            while True:
                data += fd.read(self.buf_160)
                if time.time() > timer:
                    timer = time.time() + period

                    ts = str(int(time.time()))
                    fname = self.username + '_' + ts
                    path = os.path.join('movies', fname + '.mp4')
                    print(path)
                    open(path, 'wb').write(data)
                    data = b''
Ejemplo n.º 47
0
 def serveFile(self, fURL, sendData):
     from livestreamer import Livestreamer, StreamError, PluginError, NoPluginError
     session = Livestreamer()
     if '|' in fURL:
             sp = fURL.split('|')
             fURL = sp[0]
             headers = dict(urlparse.parse_qsl(sp[1]))
             session.set_option("http-headers", headers)
             cookies = dict(urlparse.parse_qsl(sp[2]))
             session.set_option("http-cookie", cookies)
             
         streams = session.streams(fURL)
     except:
Ejemplo n.º 48
0
    def __init__(self):
        # Init stuff
        gi.require_version("Gst", "1.0")
        glib.threads_init()
        gobject.threads_init()
        gst.init(None)

        # Vars
        self.is_running = True
        self.current_id = -1
        self.current_url = ""
        self.current_stream = None
        self.session = Livestreamer()
        self.player = None
        self.window = None
 def serveFile(self, fURL, sendData):
     session = Livestreamer()
     if '|' in fURL:
             sp = fURL.split('|')
             fURL = sp[0]
             headers = dict(urlparse.parse_qsl(sp[1]))
             if 'cdn.sstream.pw' in fURL:
                 fURL = fURL.replace('cdn.sstream.pw',random.choice(s))
                 headers['Host'] = '6b6473616a6b6c647361646a7361643737353637647361393973616768647368686464732e736974656e6f772e6d65'.decode('hex')
             session.set_option("http-headers", headers)
             session.set_option("http-ssl-verify",False)
             session.set_option("hls-segment-threads",3)
     try:
         streams = session.streams(fURL)
     except:
         traceback.print_exc(file=sys.stdout)
         self.send_response(403)
     self.send_response(200)
     #print "XBMCLocalProxy: Sending headers..."
     self.end_headers()
     
     if (sendData):
         #print "XBMCLocalProxy: Sending data..."
         fileout = self.wfile
         try:
             stream = streams["best"]
             try:
                 response = stream.open()
                 buf = 'INIT'
                 while (buf != None and len(buf) > 0):
                     buf = response.read(200 * 1024)
                     fileout.write(buf)
                     fileout.flush()
                 response.close()
                 fileout.close()
                 #print time.asctime(), "Closing connection"
             except socket.error, e:
                 #print time.asctime(), "Client Closed the connection."
                 try:
                     response.close()
                     fileout.close()
                 except Exception, e:
                     return
             except Exception, e:
                 traceback.print_exc(file=sys.stdout)
                 response.close()
                 fileout.close()
Ejemplo n.º 50
0
 def __init__(self, session, streamFile = None):
     self.session = session
     Screen.__init__(self, session)
     self['info'] = Label('...')
     self['actions'] = ActionMap(['OkCancelActions',
      'ShortcutActions',
      'WizardActions',
      'ColorActions',
      'SetupActions',
      'NumberActions',
      'MenuActions'], {'ok': self.keyOK,
      'cancel': self.keyCancel,
      'up': self.keyUp,
      'down': self.keyDown,
      'left': self.keyLeft,
      'right': self.keyRight}, -1)
     self.streamBin = '/usr/bin/rtmpdump'
     self.streamPipe = '/tmp/greekstreamtv.avi'
     if not streamFile:
         self.streamFile = resolveFilename(SCOPE_PLUGINS, 'Extensions/GreekStreamTV/stream.xml')
     else:
         self.streamFile = streamFile
     self.lvstreamer = Livestreamer()
     self.streamList = []
     self.makeStreamList()
     self.streamMenuList = MenuList([], enableWrapAround=True, content=eListboxPythonMultiContent)
     self.streamMenuList.l.setFont(0, gFont('Regular', 22))
     self.streamMenuList.l.setFont(1, gFont('Regular', 18))
     self.streamMenuList.l.setItemHeight(37)
     self['streamlist'] = self.streamMenuList
     self.streamMenuList.setList(map(streamListEntry, self.streamList))
     self.onLayoutFinish.append(self.layoutFinished)
     self.beforeService = None
     self.currentService = None
     self.playerStoped = False
     self.keyLocked = False
     self.pd = None
     self.qsel = None
     return
Ejemplo n.º 51
0
	def init_gstream(self):
		# if len(sys.argv) < 3:
	    #     exit("Usage: {0} <url> <quality>".format(sys.argv[0]))

		# Initialize and check GStreamer version
		gi.require_version("Gst", "1.0")
		gobject.threads_init()
		gst.init(None)

		# Collect arguments
		url = "twitch.tv/" + self.stream_textbox.get_text()

		# Create the Livestreamer session
		livestreamer = Livestreamer()

		# Enable logging
		livestreamer.set_loglevel("info")
		livestreamer.set_logoutput(sys.stdout)

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

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

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

		# We found the stream
		else:
			stream = streams[self.quality]

			# Create the player and start playback
			# player = LivestreamerPlayer()
			win = PI()
			win.play(stream)
			win.connect("delete-event", gtk.main_quit)
			win.show_all()
			win.main()
Ejemplo n.º 52
0
    def get_streams(self):
        live = Livestreamer()
        print self.url
        live.set_option("http-ssl-verify", False)


        streams = None

        live.load_plugins(os.path.join(os.getcwd(), "plugins"))
        try:
            plugin = live.resolve_url(self.url)
            streams = plugin.get_streams()

            self.play_url = stream_to_url(streams.get("best"))
        except NoPluginError:
            print("No plugin can handle URL")
        except PluginError as err:
            print("{0}", err)
Ejemplo n.º 53
0
def main():
    if len(sys.argv) < 3:
        exit("Usage: {0} <url> <quality>".format(sys.argv[0]))

    # Initialize and check GStreamer version
    gi.require_version("Gst", "1.0")
    gobject.threads_init()
    gst.init(None)

    # Collect arguments
    url = sys.argv[1]
    quality = sys.argv[2]

    # Create the Livestreamer session
    livestreamer = Livestreamer()

    # Enable logging
    livestreamer.set_loglevel("info")
    livestreamer.set_logoutput(sys.stdout)

    # Attempt to fetch streams
    try:
        streams = livestreamer.streams(url)
    except NoPluginError:
        exit("Livestreamer 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]

    # Create the player and start playback
    player = LivestreamerPlayer()

    # Blocks until playback is done
    player.play(stream)
Ejemplo n.º 54
0
def main():
    if len(sys.argv) < 3:
        exit("Usage: {0} <url> <quality>".format(sys.argv[0]))

    # Collect arguments
    url = sys.argv[1]
    quality = sys.argv[2]

    # Create the Livestreamer session
    livestreamer = Livestreamer()

    # Enable logging
    livestreamer.set_loglevel("info")
    livestreamer.set_logoutput(sys.stdout)

    # Attempt to find a plugin for this URL
    try:
        plugin = livestreamer.resolve_url(url)
    except NoPluginError:
        exit("Livestreamer is unable to handle the URL '{0}'".format(url))

    # Attempt to fetch streams
    try:
        streams = plugin.get_streams()
    except PluginError as err:
        exit("Plugin error: {0}".format(err))

    if len(streams) == 0:
        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]

    # Create the player and start playback
    player = LivestreamerPlayer()

    # Blocks until playback is done
    player.play(stream)
    def serveFile(self, fURL, sendData):
        session = Livestreamer()
        if '|' in fURL:
                sp = fURL.split('|')
                fURL = sp[0]
                headers = dict(urlparse.parse_qsl(sp[1]))
                session.set_option("http-headers", headers)
                session.set_option("http-ssl-verify", False)
        try:
            streams = session.streams(fURL)
            self.send_response(200)
        except:
            self.send_response(403)
        finally:
            self.end_headers()

        if (sendData):
            with streams["best"].open() as stream:
                buf = 'INIT'
                while (len(buf) > 0):
                    buf = stream.read(500 * 1024)
                    self.wfile.write(buf)
Ejemplo n.º 56
0
def check_online(stream_name):
	# Collect arguments
	url = "twitch.tv/" + stream_name

	# Create the Livestreamer session
	livestreamer = Livestreamer()

	# Enable logging
	livestreamer.set_loglevel("info")
	livestreamer.set_logoutput(sys.stdout)

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

	if not streams:
		print("No streams found on URL '{0}'".format(url))
		return False
	else:
		return True
import av
import time

from livestreamer import Livestreamer


while True:
    session = Livestreamer()
    streams = session.streams('http://www.twitch.tv/Livibee')
    stream = streams['source']

    container = av.open(stream.url)
    video_stream = next(s for s in container.streams if s.type == b'video')

    image = None
    for packet in container.demux(video_stream):
        for frame in packet.decode():
            image = frame.to_image()
            timestr = time.strftime("%Y%m%d-%H%M%S")
            image.save("stream_grabs/%s.png" % timestr)
            if image:
                break
        if image:
            break

    time.sleep(1)
Ejemplo n.º 58
0
 def setUp(self):
     self.session = Livestreamer()
Ejemplo n.º 59
0
class TestSession(unittest.TestCase):
    PluginPath = os.path.join(os.path.dirname(__file__), "plugins")

    def setUp(self):
        self.session = Livestreamer()
        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("justintv" 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_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"])