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)
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
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 ()
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})
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)
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."
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
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)
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)
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)
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:
def serveFile(self, fURL, sendData): session = Livestreamer() if '|' in fURL: sp = fURL.split('|') fURL = sp[0] headers = dict(urlparse.parse_qsl(sp[1])) #print headers 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"] print streams 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()
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())
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)
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 serveFile(self, fURL, sendData): session = Livestreamer() if '|' in fURL: sp = fURL.split('|') fURL = sp[0] headers = dict(urlparse.parse_qsl(sp[1])) print 'LocalProxy: Headers : %s' % headers 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) print "LocalProxy: Streams %s" % streams except: traceback.print_exc() self.send_response(404) self.send_response(200) print "LocalProxy: Sending headers..." self.end_headers() if (sendData): print "LocalProxy: 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(), "LocalProxy: Closing connection" except socket.error, e: print time.asctime( ), "LocalProxy: Client Closed the connection." try: response.close() fileout.close() except Exception, e: return except Exception, e: traceback.print_exc() response.close() fileout.close()
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×tamp={}" .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)
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()
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)
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)
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()
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()
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) session.set_option("hls-segment-threads",2) 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()
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)
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)
class Stream(object): def __init__(self): # open session. self.session = Livestreamer() def find_stream(self, link): # find stream from link try: self.streams_dict = self.session.streams(link) # stream exist ? except NoPluginError: print "Link error" return -1 # stream online ? if not self.streams_dict: print "Streams is offline" return 0 return 1 # stream online def set_quality(self, quality): # set a stream quality self.quality = quality def get_stream_qualities(self): # return dict() of available stream quality return self.streams_dict.keys() def change_stream_quality(self, quality): # switch stream quality self.select_stream_quality(quality) self.stream_media = self.streams_dict[self.quality] def get_stream_file(self): # get the specific media file for selected quality try: return self.streams_dict[self.quality] except: print "Stream.get_stream_file: Shouldnt be called without a stream sets up."
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)
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]
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)
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×tamp={}" .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)
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''
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
def startRecording(modelData, num): global quality try: recording.append(modelData['tpl'][1].lower()) videoapi = requests.get( "https://www.camsoda.com/api/v1/video/vtoken/{model}?username=guest_{num}".format(model=modelData['tpl'][1], num=num), headers=headers) data2 = json.loads(videoapi.text) if int(data2['status']) == 1: server = data2['edge_servers'][0] link = "hlsvariant://https://{server}/cam/mp4:{stream_name}_h264_aac_{quality}/playlist.m3u8?token={token}".format(quality=quality, server=server, stream_name=data2['stream_name'], token=data2['token']) if not os.path.exists("{path}/{model}".format(path=save_directory, model=modelData['tpl'][1])): os.makedirs("{path}/{model}".format(path=save_directory, model=modelData['tpl'][1])) 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['tpl'][1], st=st), 'wb') as f: while True: try: data = fd.read(1024) f.write(data) except: recording.remove(modelData['tpl'][1].lower()) print("{} stream has ended".format(modelData['tpl'][1])) f.close() return() recording.remove(modelData['tpl'][1].lower()) print("{} stream has ended".format(modelData['tpl'][1])) except: recording.remove(modelData['tpl'][1].lower()) print("{} stream has ended".format(modelData['tpl'][1]))
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)
else: print "Randomly selecting a streamer..." streamer = random.choice(( "tsm_doublelift", "grossie_gore", "wingsofdeath" )) classifier = get_classifier() is_in_lol = False print "Waiting for streamer %s to join a game..." % streamer while True: session = Livestreamer() streams = session.streams('http://www.twitch.tv/%s' % streamer) if streams: 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() features = process_image(image) # save our old state before checking new state, only show message when state changes old_is_in_lol = is_in_lol
from livestreamer import Livestreamer session = Livestreamer() stream = session.streams("http://www.twitch.tv/starladder_cs_en") print("connected") stream = stream["source"] fd = stream.open() print("done") front = 0 rear = 0 with open("stream.dat", "wb") as f: while front < 1024 * 6000: data = fd.read(1024) f.write(data) front += 1024 print("writing") while True: if front == 1024 * 12000: f.seek(0) front = 0 if rear == 1024 * 12000: rear = 0 data = fd.read(1024) f.write(data) front += 1024 rear += 1024 print("writing")
class LivestreamerDumper(object): "Main class for dumping streams" def __init__(self, config_path): """LivestreamerDumper constructor Parameters: config_path: path to user config directory """ self.fd = None self.config_path = config_path 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)) def _load_config(self): "Load and parse config file, pass options to livestreamer" config = SafeConfigParser() config_file = os.path.join(self.config_path, 'settings.ini') config.read(config_file) for option, type in list(AVAILABLE_OPTIONS.items()): if config.has_option('DEFAULT', option): if type == 'int': value = config.getint('DEFAULT', option) if type == 'float': value = config.getfloat('DEFAULT', option) if type == 'bool': value = config.getboolean('DEFAULT', option) if type == 'str': value = config.get('DEFAULT', option) self.livestreamer.set_option(option, value) def get_title(self): """Returns the filename from URL (including extension), that may be: https://www.youtube.com/watch?v=ZEtEH-GIAJE -> '[Hatsune Miku] After Rain Sweet*Drops [English Sub] - YouTube.mp4' https://www.youtube.com/watch?v=ZEtEH-GIAJE -> 'watch_v=ZEtEH-GIAJE.mp4' The former case occurs when URL is a web page with <title> tags. The last case will occur in pages with malformed HTML or when you pass a non-HTML URL as a parameter (for example, a link to a direct HTML5 video). The extension will be detected according to the stream type, for example RTMPStream will always be '.flv'. The only format that may returns a wrong extension is HTTPStream, since there is no standard container in this case. We assume (for now) that every HTTPStream is '.mp4'. """ stream_type = self.stream.__class__.__name__ try: extension = VIDEO_EXTENSIONS[stream_type] except KeyError: print('No extension found...', file=sys.stderr) extension = '' r = requests.get(self.original_url) regex_result = _RE_PAGE_TITLE.search(r.text) if regex_result is not None: filename = regex_result.group(1) # Badly formatted HTML (e.g. no '<title>') else: # 'http://www.example.com/path1/path2?q=V1' -> # 'http', 'www.example.com', '/path1/path2', 'q=V1' split_url = urlsplit(self.original_url) # '/path1/path2' -> 'path2' filename = split_url.path.split('/')[-1] # 'path2' -> 'path2_q=V1' if split_url.query: filename = filename + '_' + split_url.query # Substitute invalid chars for '_' filename = _RE_INVALID_CHARS.sub('_', filename) # Since Windows (Explorer?) has a retarted limit for 255 chars for # filename, including the path, we need to limit the filename to a sane # size. In this case I am using 80 chars. return filename[:80] + extension def stop(self): "If stream is opened, close it" if self.fd: self.fd.close() self.fd = None def exit(self, msg=''): "Close an opened stream and call sys.exit(msg)." self.stop() sys.exit(msg) def dump(self, filepath): "Attempt to dump an opened stream to path *filepath*." common.ask_overwrite(filepath) filename = os.path.basename(filepath) file_size = 0 with open(filepath, 'ab') as f: try: while True: buf = self.fd.read(READ_BUFFER) if not buf: break f.write(buf) file_size = file_size + (READ_BUFFER / KB) print("Downloaded {} KB of file '{}'". format(file_size, filename), end='\r') except KeyboardInterrupt: self.exit("\nPartial download of file '{}'".format(filepath)) print("\nComplete download of file '{}'".format(filepath))
class Streamer(object): 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 run(self): # Graphics stuff. Start last! glib.timeout_add(500, self.run_checks) self.window = VideoWindow() self.window.run() def run_checks(self): if not self.is_running: return False self.test_skip() self.test_next() return True def test_skip(self): # Check for skips if self.current_id != -1 and self.player: skips = None try: skips = req_skips(self.current_id) except NetException: print("Connection timeout or something! Continuing ...") if skips and 'skip' in skips and skips['skip']: print("Skipping video {0} / '{1}'".format(self.current_id, self.current_url)) self.player.stop() def test_next(self): if not self.player or not self.player.is_playing(): video = None try: video = req_video() except NetException: print("Connection timeout or something! Continuing ...") if video and 'state' in video and video['state'] == 1: self.current_id = video['id'] self.current_url = video['url'] print("Switching to video {0} / '{1}'".format(self.current_id, self.current_url)) streams = None try: streams = self.session.streams(self.current_url) except NoPluginError: print("Livestreamer is unable to handle video {0} / '{1}'".format(self.current_id, self.current_url)) except PluginError as err: print("Livestreamer plugin error: {0}".format(err)) # Make sure there are streams available if not streams: print("Livestreamer found no streams {0} / '{1}'".format(self.current_id, self.current_url)) return # Pick the stream we want self.current_stream = streams[config.QUALITY] if not self.current_stream: print("There was no stream of quality '{0}' available on {1} / {2}".format(config.QUALITY, self.current_id, self.current_url)) return # Play! self.player = LivestreamerPlayer(self.window) if not self.player.play(self.current_stream): print("Failed to start playback.") else: print("Playback started.") def close(self): self.is_running = False self.window.close() if self.player: self.player.stop()
import av from livestreamer import Livestreamer from test_character_box import process_image from PIL import Image while True: session = Livestreamer() streams = session.streams('http://www.twitch.tv/anniebot') 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() image.show() image.save("stream_great_1.png") #import ipdb; ipdb.set_trace() process_image(image) if image: # Just wait until we see dem in game 5 times break if image: break import time;time.sleep(1)
class SaltyMainGUI: 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) def init_gui(self): self.master.title('SaltyDoctor') self.master.geometry('640x480') self.video = tk.Frame(self.master, bg='black') self.video.pack(side=tk.TOP, anchor=tk.N, expand=tk.YES, fill=tk.BOTH) self.mute_btn = tk.Button(self.master, text='Mute', command=self.mute_stream) self.mute_btn.pack() self.frame.pack() def shutdown(self): self.player.set_state(gst.State.NULL) self.master.destroy() def mute_stream(self): if self.player.get_property('mute'): self.player.set_property('mute', False) else: self.player.set_property('mute', True) def login(self): self.login_window = tk.Toplevel(self.master) self.app = SaltyLoginGUI(self.login_window) def on_source_setup(self, element, source): # print 'Source setup called.' source.connect("need-data", self.on_source_need_data) def on_source_need_data(self, source, length): try: data = self.fd.read(length) except IOError as err: exit('Failed to read data from stream.') if not data: source.emit('end-of-stream') return buf = gst.Buffer.new_wrapped(data) source.emit('push-buffer', buf) def on_sync_message(self, bus, message, window_id): # print 'On sync message called: ' + message.get_structure().get_name() if not message.get_structure() is None: if message.get_structure().get_name() == 'prepare-window-handle': # print 'Setting window xid' image_sink = message.src image_sink.set_property('force-aspect-ratio', True) image_sink.set_window_handle(self.window_id) if message.get_structure().get_name() == 'missing-plugin': print 'Gstreamer missing plugin: ' + gstpb.missing_plugin_message_get_description(message) def on_eos(self, bus, msg): self.stop() def on_error(self, bus, msg): error = msg.parse_error()[1] exit(error)
import cv2 import numpy as np import time from livestreamer import Livestreamer session = Livestreamer() session.set_option("http-headers", "Client-ID=jzkbprff40iqj646a697cyrvl0zt2m6") streams = session.streams("https://www.twitch.tv/___") stream = streams['best'] classificador = cv2.CascadeClassifier("./haarcascade-frontalface-default.xml") fname = "test.mpg" vid_file = open(fname,"wb") fd = stream.open() for i in range(0,2*2048): if i%256==0: print("Buffering...") new_bytes = fd.read(1024) vid_file.write(new_bytes) print("Done buffering.") cam = cv2.VideoCapture(fname) while True: ret, img = cam.read() try: if ret: imagemCinza = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) facesDetectadas = classificador.detectMultiScale(imagemCinza, scaleFactor=1.5, minSize=(100,100))
class Recorder: 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 def __get_live_streams(self): hls = self.options.get('hls_source') if hls: self.streams = self.session.streams('hlsvariant://{}'.format(hls)) def __get_stream(self): stream = self.streams['best'] stream_720 = self.streams.get('720p') stream_480 = self.streams.get('480p') if stream_720: return stream_720 elif stream_480: return stream_720 else: return stream def record(self): try: if not self.streams: print('{} No live'.format(self.__model)) return stream = self.__get_stream() fd = stream.open() ts = time() st = datetime.fromtimestamp(ts).strftime( "%Y.%m.%d_%H.%M.%S") # start time if not os.path.exists(self.save_directory): os.makedirs(self.save_directory) with open( "{path}/{st}_{model}.mp4".format(path=self.save_directory, model=self.__model, st=st), 'wb') as f: while self.__record_status: try: data = fd.read(1024) f.write(data) except Exception as exc: print(exc) f.close() return except Exception as exc: print(exc) def stop(self): self.__record_status = False
if from_stream: while client_id == "": authenticate_twitch_oauth() print( "Opening browser, copy the client_id from the url and paste it in..." ) client_id = input("Client ID: ") while stream_url == "": stream_url = input("Streamer URL: ") session = Livestreamer() session.set_option("http-headers", {"client-id": client_id}) session.set_option("hls-live-edge", 1) #streams = session.streams("https://www.twitch.tv/xyz") streams = session.streams(stream_url) if len(streams) == 0: print("No streams found on %s" % stream_url) exit() if "720p" in streams: print("Playing '720p' Stream") stream = streams["720p"] elif "1080p" in streams: print("Playing '1080p' Stream (WARNING THIS MIGHT BE LAGGY)") stream = streams["1080p"] else: for each in streams.keys(): print(each) stream = input("Choose a stream from above: ")
def startRecording(model): global postProcessingCommand global processingQueue try: gender = "" URL = "https://chaturbate.com/{}/".format(model) result = requests.get(URL, headers={'Connection': 'close'}) result = result.text for line in result.splitlines(): if "m3u8" in line: stream = line.split("'")[1] break soup = BeautifulSoup(result, 'lxml') soup = soup.find('div', {'id': "tabs_content_container"}) soup = soup.find('dl') for line in str(soup).splitlines(): if "<dt>Sex:</dt>" in line: gender = re.sub("<dt>Sex:</dt><dd>", "", line)[:-5] 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() now = datetime.datetime.now() filePath = directory_structure.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")) 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)