def setup_engine(self): encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]: connections_limit = int(self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting( "listen_port") != "" else 6881 if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.storageDirectory: keep_complete = False keep_incomplete = False else: keep_complete = True keep_incomplete = True dht_routers = ["router.bittorrent.com:6881", "router.utorrent.com:6881"] user_agent = '' self.engine = Engine(uri=file_url(localize_path(self.torrentFile)), download_path=self.storageDirectory, connections_limit=connections_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, user_agent=user_agent)
def get_files(t_url): engine = Engine(uri=t_url,download_path=temp_dir,bind_host='127.0.0.1',bind_port=5001) file_id = None files=[] try: with closing(engine): engine.start(0) files = engine.list(media_types=[MediaType.VIDEO]) n=files[0].name except Error as err: print "Error" print err return files
def setup_engine(self): #uri=None, binaries_path=None, platform=None, download_path=".", #bind_host='127.0.0.1', bind_port=5001, connections_limit=None, download_kbps=None, upload_kbps=None, #enable_dht=True, enable_lsd=True, enable_natpmp=True, enable_upnp=True, enable_scrape=False, #log_stats=False, encryption=Encryption.ENABLED, keep_complete=False, keep_incomplete=False, #keep_files=False, log_files_progress=False, log_overall_progress=False, log_pieces_progress=False, #listen_port=6881, use_random_port=False, max_idle_timeout=None, no_sparse=False, resume_file=None, #user_agent=None, startup_timeout=5, state_file=None, enable_utp=True, enable_tcp=True, #debug_alerts=False, logger=None, torrent_connect_boost=50, connection_speed=50, #peer_connect_timeout=15, request_timeout=20, min_reconnect_time=60, max_failcount=3, #dht_routers=None, trackers=None) encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED upload_limit = int(self.__settings__.getSetting("upload_limit"))*1024/8 if self.__settings__.getSetting( "upload_limit") != "" else 0 download_limit = int(self.__settings__.getSetting("download_limit"))*1024/8 if self.__settings__.getSetting( "download_limit") != "" else 0 if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]: connections_limit = int(self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting( "listen_port") != "" else 6881 if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory: keep_complete = False keep_incomplete = False keep_files = False resume_file = None else: keep_complete = True keep_incomplete = True keep_files = True resume_file=os.path.join(self.userStorageDirectory, 'torrents', os.path.basename(self.torrentUrl)+'.resume_data') enable_dht = self.__settings__.getSetting("enable_dht") == 'true' dht_routers = ["router.bittorrent.com:6881","router.utorrent.com:6881"] user_agent = 'uTorrent/2200(24683)' self.pre_buffer_bytes = int(self.__settings__.getSetting("pre_buffer_bytes"))*1024*1024 self.engine = Engine(uri=file_url(self.torrentUrl), download_path=self.userStorageDirectory, connections_limit=connections_limit, download_kbps=download_limit, upload_kbps=upload_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, keep_files=keep_files, user_agent=user_agent, resume_file=resume_file, enable_dht=enable_dht)
def setup_engine(self): encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]: connections_limit = int(self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting( "listen_port") != "" else 6881 if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.storageDirectory: keep_complete = False keep_incomplete = False else: keep_complete = True keep_incomplete = True dht_routers = ["router.bittorrent.com:6881", "router.utorrent.com:6881"] user_agent = 'uTorrent/2200(24683)' self.engine = Engine(uri=file_url(self.torrentFile), download_path=self.storageDirectory, connections_limit=connections_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, user_agent=user_agent)
def setup_engine(self): encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED upload_limit = int(self.__settings__.getSetting("upload_limit"))*1024/8 if self.__settings__.getSetting( "upload_limit") != "" else 0 download_limit = int(self.__settings__.getSetting("download_limit"))*1024/8 if self.__settings__.getSetting( "download_limit") != "" else 0 if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]: connections_limit = int(self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting( "listen_port") != "" else 6881 if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory: keep_complete = False keep_incomplete = False keep_files = False resume_file = None else: keep_complete = True keep_incomplete = True keep_files = True resume_file=os.path.join(self.userStorageDirectory, 'torrents', os.path.basename(self.torrentUrl)+'.resume_data') enable_dht = self.__settings__.getSetting("enable_dht") == 'true' dht_routers = ["router.bittorrent.com:6881","router.utorrent.com:6881"] user_agent = '' self.pre_buffer_bytes = int(self.__settings__.getSetting("pre_buffer_bytes"))*1024*1024 self.engine = Engine(uri=file_url(self.torrentUrl), download_path=self.userStorageDirectory, connections_limit=connections_limit, download_kbps=download_limit, upload_kbps=upload_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, keep_files=keep_files, user_agent=user_agent, resume_file=resume_file, enable_dht=enable_dht)
def setup_engine(self): #uri=None, binaries_path=None, platform=None, download_path=".", #bind_host='127.0.0.1', bind_port=5001, connections_limit=None, download_kbps=None, upload_kbps=None, #enable_dht=True, enable_lsd=True, enable_natpmp=True, enable_upnp=True, enable_scrape=False, #log_stats=False, encryption=Encryption.ENABLED, keep_complete=False, keep_incomplete=False, #keep_files=False, log_files_progress=False, log_overall_progress=False, log_pieces_progress=False, #listen_port=6881, use_random_port=False, max_idle_timeout=None, no_sparse=False, resume_file=None, #user_agent=None, startup_timeout=5, state_file=None, enable_utp=True, enable_tcp=True, #debug_alerts=False, logger=None, torrent_connect_boost=50, connection_speed=50, #peer_connect_timeout=15, request_timeout=20, min_reconnect_time=60, max_failcount=3, #dht_routers=None, trackers=None) encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED upload_limit = int(self.__settings__.getSetting("upload_limit"))*1024/8 if self.__settings__.getSetting( "upload_limit") != "" else 0 download_limit = int(self.__settings__.getSetting("download_limit"))*1024/8 if self.__settings__.getSetting( "download_limit") != "" else 0 if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]: connections_limit = int(self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting( "listen_port") != "" else 6881 if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory: keep_complete = False keep_incomplete = False keep_files = False resume_file = None else: keep_complete = True keep_incomplete = True keep_files = True resume_file=os.path.join(self.userStorageDirectory, 'torrents', os.path.basename(self.torrentUrl)+'.resume_data') dht_routers = ["router.bittorrent.com:6881","router.utorrent.com:6881"] user_agent = 'uTorrent/2200(24683)' self.pre_buffer_bytes = int(self.__settings__.getSetting("pre_buffer_bytes"))*1024*1024 self.engine = Engine(uri=file_url(self.torrentUrl), download_path=self.userStorageDirectory, connections_limit=connections_limit, download_kbps=download_limit, upload_kbps=upload_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, keep_files=keep_files, user_agent=user_agent, resume_file=resume_file)
def list(uri): # Create instance of Engine engine = Engine(uri) files = [] # Ensure we'll close engine on exception with closing(engine): # Start engine engine.start() # Wait until files received while not files and not xbmc.abortRequested: # Will list only video files in torrent files = engine.list(media_types=[MediaType.VIDEO]) # Check if there is loading torrent error and raise exception engine.check_torrent_error() xbmc.sleep(200) return files
def _AddTorrent(self, path): if filesystem.exists(path): if path.startswith(r'\\') or '://' in path: tempPath = xbmc.translatePath('special://temp').decode('utf-8') destPath = filesystem.join(tempPath, 't2h.torrent') filesystem.copyfile(path, destPath) path = destPath uri = path2url(path) else: uri = path self.debug('AddTorrent: ' + uri) add_trackers = [] if getSetting('add_tracker'): add_trackers.append(getSetting('add_tracker')) download_path = self.settings.storage_path if download_path == '': download_path = xbmc.translatePath('special://temp') self.debug('download_path: %s' % download_path) self.download_path = download_path encryption = self.debug_assignment( Encryption.ENABLED if getSetting('encryption') == 'true' else Encryption.DISABLED, 'encryption') upload_limit = self.debug_assignment( int(getSetting("upload_limit")) * 1024 if getSetting("upload_limit") != "" else 0, "upload_limit") download_limit = self.debug_assignment( int(getSetting("download_limit")) * 1024 if getSetting("download_limit") != "" else 0, "download_limit") if getSetting("connections_limit") not in ["", 0, "0"]: connections_limit = self.debug_assignment( int(getSetting("connections_limit")), "connections_limit") else: connections_limit = None use_random_port = self.debug_assignment( True if getSetting('use_random_port') == 'true' else False, 'use_random_port') listen_port = self.debug_assignment( int(getSetting("listen_port")) if getSetting("listen_port") != "" else 62881, "listen_port") if listen_port == 6881: use_random_port = True keep_files = getSetting('action_files').decode('utf-8') != u'удалить' args = { 'uri': uri, 'download_path': download_path, 'user_agent': user_agent, 'encryption': encryption, 'upload_kbps': upload_limit, 'download_kbps': download_limit, 'connections_limit': connections_limit, 'keep_incomplete': False, 'keep_complete': keep_files, 'keep_files': keep_files, 'dht_routers': dht_routers, 'use_random_port': use_random_port, 'listen_port': listen_port, 'log_files_progress': True, 'trackers': add_trackers, 'startup_timeout': 1000 } try: if keep_files: args['resume_file'] = filesystem.join( self.settings.torrents_path(), self.info_hash + '.resume') except BaseException as e: log.print_tb(e) if keep_files: args['resume_file'] = filesystem.join( download_path, self.info_hash + '.resume') if args.get('resume_file'): self.debug('resume file is: ' + args['resume_file']) self.engine = Engine(**args)
class Torrent2HTTPPlayer(TorrentPlayer): def debug(self, msg): try: import log log.debug('[Torrent2HTTPPlayer] %s' % msg) except: pass def debug_assignment(self, value, varname): try: self.debug('%s: %s' % (varname, str(value))) except: pass return value def __init__(self, settings): self.engine = None self.file_id = None self.settings = settings self.download_path = None self.pre_buffer_bytes = self.debug_assignment( int(getSetting('pre_buffer_bytes')) * 1024 * 1024, 'pre_buffer_bytes') self.debug('__init__') TorrentPlayer.__init__(self) def close(self): if self.engine != None: self.engine.close() self.engine = None self.debug('close') def __exit__(self): self.debug('__exit__') self.close() def _AddTorrent(self, path): if filesystem.exists(path): if path.startswith(r'\\') or '://' in path: tempPath = xbmc.translatePath('special://temp').decode('utf-8') destPath = filesystem.join(tempPath, 't2h.torrent') filesystem.copyfile(path, destPath) path = destPath uri = path2url(path) else: uri = path self.debug('AddTorrent: ' + uri) add_trackers = [] if getSetting('add_tracker'): add_trackers.append(getSetting('add_tracker')) download_path = self.settings.storage_path if download_path == '': download_path = xbmc.translatePath('special://temp') self.debug('download_path: %s' % download_path) self.download_path = download_path encryption = self.debug_assignment( Encryption.ENABLED if getSetting('encryption') == 'true' else Encryption.DISABLED, 'encryption') upload_limit = self.debug_assignment( int(getSetting("upload_limit")) * 1024 if getSetting("upload_limit") != "" else 0, "upload_limit") download_limit = self.debug_assignment( int(getSetting("download_limit")) * 1024 if getSetting("download_limit") != "" else 0, "download_limit") if getSetting("connections_limit") not in ["", 0, "0"]: connections_limit = self.debug_assignment( int(getSetting("connections_limit")), "connections_limit") else: connections_limit = None use_random_port = self.debug_assignment( True if getSetting('use_random_port') == 'true' else False, 'use_random_port') listen_port = self.debug_assignment( int(getSetting("listen_port")) if getSetting("listen_port") != "" else 62881, "listen_port") if listen_port == 6881: use_random_port = True keep_files = getSetting('action_files').decode('utf-8') != u'удалить' args = { 'uri': uri, 'download_path': download_path, 'user_agent': user_agent, 'encryption': encryption, 'upload_kbps': upload_limit, 'download_kbps': download_limit, 'connections_limit': connections_limit, 'keep_incomplete': False, 'keep_complete': keep_files, 'keep_files': keep_files, 'dht_routers': dht_routers, 'use_random_port': use_random_port, 'listen_port': listen_port, 'log_files_progress': True, 'trackers': add_trackers, 'startup_timeout': 1000 } try: if keep_files: args['resume_file'] = filesystem.join( self.settings.torrents_path(), self.info_hash + '.resume') except BaseException as e: log.print_tb(e) if keep_files: args['resume_file'] = filesystem.join( download_path, self.info_hash + '.resume') if args.get('resume_file'): self.debug('resume file is: ' + args['resume_file']) self.engine = Engine(**args) def CheckTorrentAdded(self): if self.engine: status = self.engine.status() self.engine.check_torrent_error(status) self.debug('CheckTorrentAdded') if status.state == State.CHECKING_FILES: self.debug('State.CHECKING_FILES') return False else: return TorrentPlayer.CheckTorrentAdded(self) return True def _GetLastTorrentData(self): while True: time.sleep(0.2) # Get torrent files list, filtered by video file type only files = self.engine.list() #(media_types=[MediaType.VIDEO]) # If torrent metadata is not loaded yet then continue if files is None: self.debug('files is None') continue self.debug('files len: ' + str(len(files))) # Torrent has no video files if not files or len(files) > 0: break info_hash = '' playable_items = [] for item in files: if TorrentPlayer.is_playable(item.name): playable_items.append({ 'index': item.index, 'name': item.name, 'size': long(item.size) }) return {'info_hash': info_hash, 'files': playable_items} def StartBufferFile(self, fileIndex): self._AddTorrent(self.path) self.download_path = None self.engine.start(fileIndex) self.file_id = fileIndex self.debug('StartBufferFile: %d' % fileIndex) def CheckBufferComplete(self): if not self.download_path is None: return True status = self.engine.status() self.debug('CheckBufferComplete: ' + str(status.state_str)) if status.state == State.DOWNLOADING: # Wait until minimum pre_buffer_bytes downloaded before we resolve URL to XBMC f_status = self.engine.file_status(self.file_id) self.debug('f_status.download %d' % f_status.download) if f_status.download >= self.pre_buffer_bytes: return True return status.state in [State.FINISHED, State.SEEDING] def GetBufferingProgress(self): f_status = self.engine.file_status(self.file_id) try: progress = int( round(float(f_status.download) / self.pre_buffer_bytes, 2) * 100) self.debug('GetBufferingProgress: %d' % progress) if progress > 99: progress = 99 except: progress = 0 return progress def updateCheckingProgress(self, progressBar): status = self.engine.status() percents = int(status.progress * 100) if percents > 99: percents = 99 progressBar.update(percents, u'Media Aggregator: проверка файлов...', ' ', ' ') def updateDialogInfo(self, progress, progressBar): f_status = self.engine.file_status(self.file_id) status = self.engine.status() if f_status is None or status is None: return dialogText = u'Загружено: ' + "%d MB / %d MB" % \ (int(f_status.download / 1024 / 1024), int(f_status.size / 1024 / 1024)) peersText = u' [%s: %s; %s: %s]' % (u'Сидов', status.num_seeds, u'Пиров', status.num_peers) speedsText = u'%s: %d Mbit/s; %s: %d Mbit/s' % ( u'Загрузка', int(status.download_rate / 1024 * 8), u'Отдача', int(status.upload_rate / 1024 * 8)) progressBar.update(progress, dialogText + ' ' + peersText, speedsText) def GetTorrentInfo(self): f_status = self.engine.file_status(self.file_id) status = self.engine.status() if f_status is None or status is None: return None try: return { 'downloaded': int(f_status.download / 1024 / 1024), 'size': int(f_status.size / 1024 / 1024), 'dl_speed': int(status.download_rate), 'ul_speed': int(status.upload_rate), 'num_seeds': status.num_seeds, 'num_peers': status.num_peers } except: pass return None def GetStreamURL(self, playable_item): if self.download_path is None: f_status = self.engine.file_status(self.file_id) self.debug('GetStreamURL: %s' % f_status.url) return f_status.url else: self.debug('GetStreamURL: %s' % self.download_path) return self.download_path
def sub_play(params): if params['r'][:4] == 'http': purl = urllib.unquote_plus(params['r']) item = xbmcgui.ListItem(path=purl) xbmcplugin.setResolvedUrl(handle, True, item) return if params['r'][:4] == 'myvi': url = urllib.unquote_plus(params['r']).replace('myvi', 'http') data = get_myvi_data(url) item = xbmcgui.ListItem(path=data['url']) xbmcplugin.setResolvedUrl(handle, True, item) return file_id = int(params.get('i', 0)) uri = sections['get_torrent'] + '/' + params['r'] + '/' + params['t'] torrent = get_html(uri) temp_name = os.path.join(xt('special://masterprofile'), 'shiza.torrent') temp_file = open( temp_name.decode('utf-8') if sys.platform == 'win32' else temp_name, "wb") temp_file.write(torrent) temp_file.close() uri = 'file://' + temp_name.replace('\\', '//') if addon.getSetting('Engine') == '1': sub_play_yatp(uri, file_id) return if addon.getSetting('Engine') == '2': sub_play_tam(temp_name, file_id) return if addon.getSetting('Engine') == '3': sub_play_elem(temp_name, file_id) return #, cwd=os.path.dirname(binary_path)) in torrent2html engine.py from torrent2http import State, Engine, MediaType progressBar = xbmcgui.DialogProgress() from contextlib import closing DDir = xt('special://masterprofile') progressBar.create('Torrent2Http', 'Запуск') # XBMC addon handle # handle = ... # Playable list item # listitem = ... # We can know file_id of needed video file on this step, if no, we'll try to detect one. # file_id = None # Flag will set to True when engine is ready to resolve URL to XBMC ready = False # Set pre-buffer size to 24Mb. This is a size of file that need to be downloaded before we resolve URL to XMBC pre_buffer_bytes = 24 * 1024 * 1024 engine = Engine(uri, download_path=DDir) with closing(engine): # Start engine and instruct torrent2http to begin download first file, # so it can start searching and connecting to peers engine.start(file_id) progressBar.update(0, 'Torrent2Http', 'Загрузка торрента', "") while not xbmc.abortRequested and not ready: xbmc.sleep(500) if progressBar.iscanceled(): ready = False break status = engine.status() # Check if there is loading torrent error and raise exception engine.check_torrent_error(status) # Trying to detect file_id if file_id is None: # Get torrent files list, filtered by video file type only files = engine.list(media_types=[MediaType.VIDEO]) # If torrent metadata is not loaded yet then continue if files is None: continue # Torrent has no video files if not files: progressBar.close() break # Select first matching file file_id = files[0].index file_status = files[0] else: # If we've got file_id already, get file status file_status = engine.file_status(file_id) # If torrent metadata is not loaded yet then continue if not file_status: continue if status.state == State.DOWNLOADING: # Wait until minimum pre_buffer_bytes downloaded before we resolve URL to XBMC if file_status.download >= pre_buffer_bytes: ready = True break #print file_status #downloadedSize = status.total_download / 1024 / 1024 getDownloadRate = status.download_rate / 1024 * 8 #getUploadRate = status.upload_rate / 1024 * 8 getSeeds = status.num_seeds progressBar.update( 100 * file_status.download / pre_buffer_bytes, 'Предварительная буферизация: ' + str(file_status.download / 1024 / 1024) + " MB", "Сиды: " + str(getSeeds), "Скорость: " + str(getDownloadRate)[:4] + ' Mbit/s') elif status.state in [State.FINISHED, State.SEEDING]: #progressBar.update(0, 'T2Http', 'We have already downloaded file', "") # We have already downloaded file ready = True break # Here you can update pre-buffer progress dialog, for example. # Note that State.CHECKING also need waiting until fully finished, so it better to use resume_file option # for engine to avoid CHECKING state if possible. # ... progressBar.update(0) progressBar.close() if ready: # Resolve URL to XBMC item = xbmcgui.ListItem(path=file_status.url) xbmcplugin.setResolvedUrl(handle, True, item) xbmc.sleep(3000) # Wait until playing finished or abort requested while not xbmc.abortRequested and xbmc.Player().isPlaying(): xbmc.sleep(500)
def play(uri, handle, file_id=0, DDir=""): if DDir == "": DDir = os.path.join(xbmc.translatePath("special://home/"), "userdata") progressBar.create('Torrent2Http', 'Запуск') # XBMC addon handle # handle = ... # Playable list item # listitem = ... # We can know file_id of needed video file on this step, if no, we'll try to detect one. # file_id = None # Flag will set to True when engine is ready to resolve URL to XBMC ready = False # Set pre-buffer size to 15Mb. This is a size of file that need to be downloaded before we resolve URL to XMBC pre_buffer_bytes = 15 * 1024 * 1024 engine = Engine(uri, download_path=DDir) with closing(engine): # Start engine and instruct torrent2http to begin download first file, # so it can start searching and connecting to peers engine.start(file_id) progressBar.update(0, 'Torrent2Http', 'Загрузка торрента', "") while not xbmc.abortRequested and not ready: xbmc.sleep(500) status = engine.status() # Check if there is loading torrent error and raise exception engine.check_torrent_error(status) # Trying to detect file_id if file_id is None: # Get torrent files list, filtered by video file type only files = engine.list(media_types=[MediaType.VIDEO]) # If torrent metadata is not loaded yet then continue if files is None: continue # Torrent has no video files if not files: break progressBar.close() # Select first matching file file_id = files[0].index file_status = files[0] else: # If we've got file_id already, get file status file_status = engine.file_status(file_id) # If torrent metadata is not loaded yet then continue if not file_status: continue if status.state == State.DOWNLOADING: # Wait until minimum pre_buffer_bytes downloaded before we resolve URL to XBMC if file_status.download >= pre_buffer_bytes: ready = True break print file_status progressBar.update( 100 * file_status.download / pre_buffer_bytes, 'Torrent2Http', xt('Предварительная буферизация: ' + str(file_status.download / 1024 / 1024) + " MB"), "") elif status.state in [State.FINISHED, State.SEEDING]: #progressBar.update(0, 'T2Http', 'We have already downloaded file', "") # We have already downloaded file ready = True break if progressBar.iscanceled(): progressBar.update(0) progressBar.close() break # Here you can update pre-buffer progress dialog, for example. # Note that State.CHECKING also need waiting until fully finished, so it better to use resume_file option # for engine to avoid CHECKING state if possible. # ... progressBar.update(0) progressBar.close() if ready: # Resolve URL to XBMC #listitem = xbmcgui.ListItem(path=file_status.url) #xbmcplugin.SetResolvedUrl(handle, True, listitem) xbmc.Player().play(file_status.url) # Wait until playing finished or abort requested while not xbmc.abortRequested and xbmc.Player().isPlaying(): xbmc.sleep(500)
def play(self, uri, item, subtitle=None, subtitle_provider=None): # torrent2http_options = { "uri": str(uri), # Files "download_path": xbmc.validatePath(xbmc.translatePath(__addon__.getSetting("download_path"))) or CACHE_DIR, "keep_files": __addon__.getSetting("keep_files") == 'true' and True or False, "keep_complete": __addon__.getSetting("keep_complete") == 'true' and True or False, "keep_incomplete": __addon__.getSetting("keep_incomplete") == 'true' and True or False, # Network "download_kbps": int(__addon__.getSetting("download_kbps")) or 0, "upload_kbps": int(__addon__.getSetting("upload_kbps")) or 0, "connections_limit": int(__addon__.getSetting("connections_limit")) or 200, "encryption": int(__addon__.getSetting("encryption")) or 1, # Port "listen_port": int(__addon__.getSetting("listen_port")) or 6881, "use_random_port": __addon__.getSetting("use_random_port") == 'true' and True or False, # Peers "torrent_connect_boost": int(__addon__.getSetting("torrent_connect_boost")) or 50, "connection_speed": int(__addon__.getSetting("connection_speed")) or 50, "peer_connect_timeout": int(__addon__.getSetting("peer_connect_timeout")) or 15, "min_reconnect_time": int(__addon__.getSetting("min_reconnect_time")) or 60, "max_failcount": int(__addon__.getSetting("max_failcount")) or 3, # Features "enable_tcp": __addon__.getSetting("enable_tcp") == 'true' and False or True, "enable_dht": __addon__.getSetting("enable_dht") == 'true' and False or True, "enable_lsd": __addon__.getSetting("enable_lsd") == 'true' and False or True, "enable_utp": __addon__.getSetting("enable_utp") == 'true' and False or True, "enable_scrape": __addon__.getSetting("enable_scrape") == 'true' and True or False, "enable_upnp": __addon__.getSetting("enable_upnp") == 'true' and False or True, "enable_natpmp": __addon__.getSetting("enable_natpmp") == 'true' and False or True, # Additional "trackers": not __addon__.getSetting("trackers") == "" and __addon__.getSetting['trackers'].split(',') or None, "dht_routers": not __addon__.getSetting("dht_routers") == "" and __addon__.getSetting['dht_routers'].split(',') or None, # Log / Debug "log_stats": __addon__.getSetting("debug") == 'true' and True or False, "debug_alerts": __addon__.getSetting("debug_alerts") == 'true' and True or False, # Bin "binaries_path": os.path.join(RESOURCES_PATH, 'bin') } # List item self.item = item ### if torrent2http_options['download_kbps'] <= 0: torrent2http_options['download_kbps'] = None if torrent2http_options['upload_kbps'] <= 0: torrent2http_options['upload_kbps'] = None elif torrent2http_options['upload_kbps'] < 15: notify(__addon__.getLocalizedString(30313)) torrent2http_options['upload_kbps'] = 15 __addon__.setSetting('upload_kbps', '15') log('(Player) Start the torrent2http file', xbmc.LOGDEBUG) with closing(Engine(**torrent2http_options)) as engine: # Start engine and instruct torrent2http to begin download first file engine.start(0) log('(Player) Pre-Loading the movie', xbmc.LOGDEBUG) ready = False with closing(SafeDialogProgress(delay_create=0)) as dialog: dialog.create(self.item['info']['title']) dialog.update(self.progressed, *self._get_status_lines()) file_id = None while not xbmc.abortRequested and not dialog.iscanceled(): xbmc.sleep(self.progressSleepTime) # Get status status = engine.status() # Check if there is loading error and raise exception engine.check_torrent_error(status) # We need a file id if file_id is None: # Get torrent files list, filtered by video file type only files = engine.list(media_types=[MediaType.VIDEO]) if files is None: continue # Torrent has no video files if not files: raise AnErrorOccurred(30316) # Select first matching file file_id = files[0].index file_status = files[0] # Get file status file_status = engine.file_status(file_id) if not file_status: continue if status.state == State.DOWNLOADING: self._calculate_progress(int(self.item['info'].get('duration', 0)), status, file_status) if self.progressed >= 100: ready = True break dialog.update(int(self.progressed), *self._get_status_lines(status)) continue if status.state in [State.FINISHED, State.SEEDING]: ready = True break if ready: log('(Player) Finished with pre-loading the movie', xbmc.LOGDEBUG) # Download subtitle if subtitle: log('(Player) Download subtitle', xbmc.LOGDEBUG) dialog.update(99, *[__addon__.getLocalizedString(30019), ' ', ' ']) path = file_status.save_path subtitle = subtitle_provider.download(subtitle, os.path.dirname(path), ".".join([os.path.splitext(os.path.basename(path))[0], self.item['stream_info']['subtitle']['language']])) dialog.update(100, *[__addon__.getLocalizedString(30020), ' ', ' ']) elif xbmc.abortRequested or dialog.iscanceled(): log('(Player) Pre-Loading was canceled or interrupted', xbmc.LOGDEBUG) if ready: # Resolve URL to XBMC self.item.update({"path": file_status.url}) # Starts the playback log('(Player) Start the playback', xbmc.LOGDEBUG) #xbmcplugin.setResolvedUrl(int(sys.argv[1]), True, self.item) plugin.set_resolved_url(self.item) for _ in xrange(60): if not self.isPlaying(): xbmc.sleep(1000) continue if subtitle: log('(Player) Adds the subtitle to the player', xbmc.LOGDEBUG) self.setSubtitles(subtitle) # Wait for the playback to finish log('(Player) Wait for the playback to finish', xbmc.LOGDEBUG) with closing(OverlayText()) as self.overlay: while not xbmc.abortRequested and self.isPlaying(): if self.overlay.isShowing(): self.overlay.setText("\n".join(self._get_status_lines(engine.status()))) xbmc.sleep(100) log('(Player) Playback is finished', xbmc.LOGDEBUG) if subtitle and torrent2http_options["keep_files"] == False and torrent2http_options["keep_complete"] == False and torrent2http_options["keep_incomplete"] == False: # Delete subtitle log('(Player) Delete subtitle', xbmc.LOGDEBUG) subtitle_provider.remove(subtitle) break else: log('(Player) Playback is terminated due to timeout', xbmc.LOGERROR)
class AnteoLoader: magnetLink = None engine = None torrentFile = None __plugin__ = sys.modules["__main__"].__plugin__ __settings__ = sys.modules["__main__"].__settings__ def __init__(self, storageDirectory='', torrentFile='', torrentFilesDirectory='torrents'): self.storageDirectory = storageDirectory self.torrentFilesPath = os.path.join(self.storageDirectory, torrentFilesDirectory) + os.sep if not is_writable(self.storageDirectory): xbmcgui.Dialog().ok(self.localize('Torrenter v2'), self.localize('Your storage path is not writable or not local! Please change it in settings!'), self.localize(self.storageDirectory)) sys.exit(1) #pre settings if re.match("^magnet\:.+$", torrentFile): self.magnetLink = torrentFile else: self.torrentFile = torrentFile def setup_engine(self): encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]: connections_limit = int(self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting( "listen_port") != "" else 6881 if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.storageDirectory: keep_complete = False keep_incomplete = False else: keep_complete = True keep_incomplete = True dht_routers = ["router.bittorrent.com:6881", "router.utorrent.com:6881"] user_agent = '' self.engine = Engine(uri=file_url(localize_path(self.torrentFile)), download_path=self.storageDirectory, connections_limit=connections_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, user_agent=user_agent) def localize(self, string): try: return Localization.localize(string) except: return string def getContentList(self): try: from SkorbaLoader import SkorbaLoader torrent = SkorbaLoader(self.storageDirectory, self.torrentFile) return torrent.getContentList() except: import traceback log(traceback.format_exc()) return self.getContentList_engine() def getContentList_engine(self): self.setup_engine() files = [] filelist = [] with closing(self.engine): self.engine.start() #media_types=[MediaType.VIDEO, MediaType.AUDIO, MediaType.SUBTITLES, MediaType.UNKNOWN] iterator = 0 text = Localization.localize('Magnet-link is converting') if self.magnetLink\ else Localization.localize('Opening torrent file') while not files and not xbmc.abortRequested and iterator < 100: files = self.engine.list() self.engine.check_torrent_error() if iterator==4: progressBar = xbmcgui.DialogProgress() progressBar.create(Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting')) elif iterator>4: progressBar.update(iterator, Localization.localize('Please Wait'),text+'.' * (iterator % 4), ' ') if progressBar.iscanceled(): progressBar.update(0) progressBar.close() return [] xbmc.sleep(500) iterator += 1 for fs in files: stringdata = {"title": ensure_str(fs.name), "size": fs.size, "ind": fs.index, 'offset': fs.offset} filelist.append(stringdata) return filelist def saveTorrent(self, torrentUrl): #if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl): if re.match("^magnet\:.+$", torrentUrl): self.magnetLink = torrentUrl self.magnetToTorrent(torrentUrl) self.magnetLink = None return self.torrentFile else: if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent') try: if not re.match("^[htps]+?://.+$|^://.+$", torrentUrl): log('xbmcvfs.File for %s' % torrentUrl) content = xbmcvfs.File(torrentUrl, "rb").read() else: log('request for %s' % torrentUrl) content = self.makeRequest(torrentUrl) localFile = xbmcvfs.File(torrentFile, "w+b") localFile.write(content) localFile.close() except Exception, e: log('Unable to rename torrent file from %s to %s in AnteoLoader::saveTorrent. Exception: %s' % (torrentUrl, torrentFile, str(e))) return if xbmcvfs.exists(torrentFile) and not os.path.exists(torrentFile): if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent') xbmcvfs.copy(torrentUrl, torrentFile) if os.path.exists(torrentFile): self.torrentFile = torrentFile return self.torrentFile
class AnteoPlayer(xbmc.Player): __plugin__ = sys.modules["__main__"].__plugin__ __settings__ = sys.modules["__main__"].__settings__ ROOT = sys.modules["__main__"].__root__ USERAGENT = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0" torrentFilesDirectory = 'torrents' debug = __settings__.getSetting('debug') == 'true' subs_dl = __settings__.getSetting('subs_dl') == 'true' seeding = __settings__.getSetting('keep_seeding') == 'true' and __settings__.getSetting('keep_files') == '1' seeding_status = False seeding_run = False ids_video = None episodeId = None fullSize = 0 watchedTime = 0 totalTime = 1 seek = 0 basename = '' def __init__(self, userStorageDirectory, torrentUrl, params={}): self.userStorageDirectory = userStorageDirectory self.torrentUrl = torrentUrl if not is_writable(self.userStorageDirectory): xbmcgui.Dialog().ok(Localization.localize('Torrenter v2'), Localization.localize('Your storage path is not writable or not local! Please change it in settings!'), self.storageDirectory) sys.exit(1) xbmc.Player.__init__(self) log("["+author+"Player] Initalized v"+__version__) self.params = params self.get = self.params.get self.contentId = int(self.get("url")) if self.get("seek"): self.seek = int(self.get("seek")) #self.torrent = AnteoLoader(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory) self.init() self.setup_engine() with closing(self.engine): self.engine.start(self.contentId) self.setup_nextep() while True: if self.buffer(): log('[AnteoPlayer]: ************************************* GOING LOOP') if self.setup_play(): WatchedHistoryDB().add(self.basename, self.torrentUrl, foldername(self.getContentList()[self.contentId]['title']), self.watchedTime, self.totalTime, self.contentId, self.fullSize) self.setup_subs() self.loop() WatchedHistoryDB().add(self.basename, self.torrentUrl, foldername(self.getContentList()[self.contentId]['title']), self.watchedTime, self.totalTime, self.contentId, self.fullSize) else: log('[AnteoPlayer]: ************************************* break') break log('[AnteoPlayer]: ************************************* GO NEXT?') if self.next_dl and self.next_contentId != False and isinstance(self.next_contentId, int) and self.iterator == 100: if not self.next_play: xbmc.sleep(3000) if not xbmcgui.Dialog().yesno( self.localize('[%sPlayer v%s] ' % (author, __version__)), self.localize('Would you like to play next episode?')): break self.contentId = self.next_contentId continue log('[AnteoPlayer]: ************************************* NO! break') showMessage(self.localize('Information'), self.localize('Stopping the torrent2http process...')) break xbmc.Player().stop() if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory: xbmc.sleep(1000) clearStorage(self.userStorageDirectory) showMessage(self.localize('Information'), self.localize('torrent2http process stopped.')) loadsw_onstop() # Reload Search Window def init(self): self.next_contentId = False self.display_name = '' self.downloadedSize = 0 self.dialog = xbmcgui.Dialog() self.on_playback_started = [] self.on_playback_resumed = [] self.on_playback_paused = [] self.on_playback_stopped = [] self.torrentUrl = self.torrentUrl def setup_engine(self): encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED upload_limit = int(self.__settings__.getSetting("upload_limit"))*1024/8 if self.__settings__.getSetting( "upload_limit") != "" else 0 download_limit = int(self.__settings__.getSetting("download_limit"))*1024/8 if self.__settings__.getSetting( "download_limit") != "" else 0 if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]: connections_limit = int(self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting( "listen_port") != "" else 6881 if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory: keep_complete = False keep_incomplete = False keep_files = False resume_file = None else: keep_complete = True keep_incomplete = True keep_files = True resume_file=os.path.join(self.userStorageDirectory, 'torrents', os.path.basename(self.torrentUrl)+'.resume_data') enable_dht = self.__settings__.getSetting("enable_dht") == 'true' dht_routers = ["router.bittorrent.com:6881","router.utorrent.com:6881"] user_agent = '' self.pre_buffer_bytes = int(self.__settings__.getSetting("pre_buffer_bytes"))*1024*1024 self.engine = Engine(uri=file_url(self.torrentUrl), download_path=self.userStorageDirectory, connections_limit=connections_limit, download_kbps=download_limit, upload_kbps=upload_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, keep_files=keep_files, user_agent=user_agent, resume_file=resume_file, enable_dht=enable_dht) def buffer(self): ready = False progressBar = xbmcgui.DialogProgress() progressBar.create('[%sPlayer v%s] ' % (author, __version__) + self.localize('Please Wait'), self.localize('Seeds searching.')) while not xbmc.abortRequested and not ready: xbmc.sleep(500) status = self.engine.status() self.print_debug(status) #self.print_fulldebug() self.engine.check_torrent_error(status) file_status = self.engine.file_status(self.contentId) if not file_status: continue self.fullSize = int(file_status.size / 1024 / 1024) downloadedSize = status.total_download / 1024 / 1024 getDownloadRate = status.download_rate / 1024 * 8 getUploadRate = status.upload_rate / 1024 * 8 getSeeds, getPeers = status.num_seeds, status.num_peers iterator = int(round(float(file_status.download) / self.pre_buffer_bytes, 2) * 100) if iterator > 99: iterator = 99 if status.state == State.CHECKING_FILES: iterator = int(status.progress*100) if iterator > 99: iterator = 99 progressBar.update(iterator, self.localize('Checking preloaded files...'), ' ', ' ') elif status.state == State.DOWNLOADING: dialogText = self.localize('Preloaded: ') + "%d MB / %d MB" % \ (int(downloadedSize), self.fullSize) peersText = ' [%s: %s; %s: %s]' % ( self.localize('Seeds'), getSeeds, self.localize('Peers'), getPeers) speedsText = '%s: %d Mbit/s; %s: %d Mbit/s' % ( self.localize('Downloading'), int(getDownloadRate), self.localize('Uploading'), int(getUploadRate)) progressBar.update(iterator, self.localize('Seeds searching.') + peersText, dialogText, speedsText) if file_status.download >= self.pre_buffer_bytes: ready = True break elif status.state in [State.FINISHED, State.SEEDING]: ready = True break else: progressBar.update(iterator, self.localize('UNKNOWN STATUS'), ' ', ' ') if progressBar.iscanceled(): self.iterator = 0 ready = False break progressBar.update(0) progressBar.close() return ready def setup_nextep(self): try: if self.get("url2"): debug("[setup_nextep]: url2") self.ids_video = urllib.unquote_plus(self.get("url2")).split(',') else: debug("[setup_nextep]: not url2") self.ids_video = self.get_ids() except: pass if self.__settings__.getSetting('next_dl') == 'true' and self.ids_video and len(self.ids_video)>1: self.next_dl = True else: self.next_dl = False self.next_play = self.__settings__.getSetting('next_play') == 'true' log('[AnteoPlayer]: next_dl - %s, next_play - %s, ids_video - %s' % (str(self.next_dl), str(self.next_play), str(self.ids_video))) def setup_play(self): file_status = self.engine.file_status(self.contentId) self.iterator = 0 self.watchedTime = 0 self.totalTime = 1 url = file_status.url label = os.path.basename(file_status.name) self.basename = label self.seeding_run = False listitem = xbmcgui.ListItem(label, path=url) if self.next_dl: next_contentId_index = self.ids_video.index(str(self.contentId)) + 1 if len(self.ids_video) > next_contentId_index: self.next_contentId = int(self.ids_video[next_contentId_index]) else: self.next_contentId = False log('[AnteoPlayer][setup_play]: next_contentId: '+str(self.next_contentId)) try: seasonId = self.get("seasonId") self.episodeId = self.get("episodeId") if not self.episodeId else int(self.episodeId) + 1 title = urllib.unquote_plus(self.get("title")) if self.get("title") else None if self.get("label") and self.episodeId == self.get("episodeId"): label = urllib.unquote_plus(self.get("label")) elif seasonId and self.episodeId and title: label = '%s S%02dE%02d.%s (%s)' % ( title, int(seasonId), int(self.episodeId), self.basename.split('.')[-1], self.basename) if seasonId and self.episodeId and label and title: listitem = xbmcgui.ListItem(label, path=url) listitem.setInfo(type='video', infoLabels={'title': label, 'episode': int(self.episodeId), 'season': int(seasonId), 'tvshowtitle': title}) except: log('[AnteoPlayer]: Operation INFO failed!') thumbnail = self.get("thumbnail") if thumbnail: listitem.setThumbnailImage(urllib.unquote_plus(thumbnail)) self.display_name = label if self.get('listitem'): listitem = self.get('listitem') listitem.setPath(url) player = xbmc.Player() player.play(url, listitem) xbmc.sleep(2000) # very important, do not edit this, podavan i = 0 while not xbmc.abortRequested and not self.isPlaying() and i < 150: xbmc.sleep(200) i += 1 log('[AnteoPlayer]: self.isPlaying() = %s, i = %d, xbmc.abortRequested - %s' % (str(self.isPlaying()), i, str(xbmc.abortRequested))) if not self.isPlaying() or xbmc.abortRequested: return False if self.seek > 0: log('[AnteoPlayer]: seekTime - '+str(self.seek)) self.seekTime(self.seek) return True def setup_subs(self): if self.subs_dl: file_status = self.engine.file_status(self.contentId) subs = [] filename = os.path.basename(file_status.name) sub_files = self.engine.list(media_types=[MediaType.SUBTITLES]) for i in sub_files: if isSubtitle(filename, i.name): subs.append(i) if subs: log("[AnteoPlayer][setup_subs]: Detected subtitles: %s" % str(subs)) for sub in subs: xbmc.Player().setSubtitles(sub.url) def loop(self): debug_counter = 0 pause = True with closing( OverlayText(w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y)) as overlay: with nested(self.attach(overlay.show, self.on_playback_paused), self.attach(overlay.hide, self.on_playback_resumed, self.on_playback_stopped)): while not xbmc.abortRequested and self.isPlaying(): #self.print_fulldebug() status = self.engine.status() file_status = self.engine.file_status(self.contentId) self.watchedTime = xbmc.Player().getTime() if self.iterator == 100 and debug_counter < 100: debug_counter += 1 else: self.totalTime = xbmc.Player().getTotalTime() self.print_debug(status) debug_counter=0 overlay.text = "\n".join(self._get_status_lines(status, file_status)) self.iterator = int(file_status.progress * 100) if pause and self.__settings__.getSetting("pause_onplay") == 'true': pause = False xbmc.Player().pause() log('[loop]: xbmc.Player().pause()') xbmc.sleep(1000) def onPlayBackStarted(self): for f in self.on_playback_started: f() log('[onPlayBackStarted]: '+(str(("video", "play", self.display_name)))) def onPlayBackResumed(self): for f in self.on_playback_resumed: f() self.onPlayBackStarted() def onPlayBackPaused(self): for f in self.on_playback_paused: f() log('[onPlayBackPaused]: '+(str(("video", "pause", self.display_name)))) def onPlayBackStopped(self): for f in self.on_playback_stopped: f() log('[onPlayBackStopped]: '+(str(("video", "stop", self.display_name)))) @contextmanager def attach(self, callback, *events): for event in events: event.append(callback) yield for event in events: event.remove(callback) def _get_status_lines(self, s, f): return [ ensure_str(self.display_name), "%.2f%% %s" % (f.progress * 100, self.localize(STATE_STRS[s.state])), "D:%.2f%s U:%.2f%s S:%d P:%d" % (s.download_rate, self.localize('kb/s'), s.upload_rate, self.localize('kb/s'), s.num_seeds, s.num_peers) ] def localize(self, string): try: return Localization.localize(string) except: return string def print_debug(self, status=None): #FileStatus = namedtuple('FileStatus', "name, save_path, url, size, offset, download, progress, index, media_type") #SessionStatus = namedtuple('SessionStatus', "name, state, state_str, error, progress, download_rate, upload_rate, " # "total_download, total_upload, num_peers, num_seeds, total_seeds, " # "total_peers") #log('[buffer] file_status:'+str(file_status)) #log('[buffer] status:'+str(status)) if not status: status = self.engine.status() self.engine.check_torrent_error(status) log('[AnteoPlayer]: %.2f%% complete (down: %.1f kb/s up: %.1f kb/s peers: %d) %s' % \ (status.progress * 100, status.download_rate, status.upload_rate, status.num_peers, status.state_str)) def print_fulldebug(self): status = self.engine.status() file_status = self.engine.file_status(self.contentId) log('[buffer] file_status:'+str(file_status)) log('[buffer] status:'+str(status)) def get_ids(self): contentList = [] for fs in self.engine.list(): contentList.append((fs.name, str(fs.index))) contentList = sorted(contentList, key=lambda x: x[0]) return get_ids_video(contentList) def getContentList(self): filelist = [] for fs in self.engine.list(): stringdata = {"title": ensure_str(fs.name), "size": fs.size, "ind": fs.index, 'offset': fs.offset} filelist.append(stringdata) return filelist
#selfile="file://"+get_tor(slink,ref) t=get_files(selfile) for f in t: url=build_url({'mode':'playtorrent', 'sname':f.name, 'sid':f.index, 'slink':selfile}) add_link(url,f.name) endoflist() else: print "no url entered" elif mode[0] == 'playtorrent': surl=args['slink'][0] sname=args['sname'][0] sid=int(args['sid'][0]) ready = False pre_buffer_bytes = 15*1024*1024 engine = Engine(uri=surl,download_path=temp_dir,bind_host='127.0.0.1',bind_port=5001) progress = xbmcgui.DialogProgress() progress.create('Downloading', 'Prebuffering...') try: with closing(engine): engine.start(sid) #xbmcgui.DialogProgress() while not xbmc.abortRequested and not ready and not progress.iscanceled(): xbmc.sleep(500) status = engine.status() print "Status:",status engine.check_torrent_error(status) files = engine.list(media_types=[MediaType.VIDEO]) file_status = engine.file_status(sid)
class AnteoPlayer(xbmc.Player): __plugin__ = sys.modules["__main__"].__plugin__ __settings__ = sys.modules["__main__"].__settings__ ROOT = sys.modules["__main__"].__root__ # .decode('utf-8').encode(sys.getfilesystemencoding()) USERAGENT = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0" torrentFilesDirectory = 'torrents' debug = __settings__.getSetting('debug') == 'true' subs_dl = __settings__.getSetting('subs_dl') == 'true' seeding = __settings__.getSetting('keep_seeding') == 'true' and __settings__.getSetting('keep_files') == '1' seeding_status = False seeding_run = False ids_video = None episodeId = None fullSize = 0 watchedTime = 0 totalTime = 1 seek = 0 basename = '' def __init__(self, userStorageDirectory, torrentUrl, params={}): self.userStorageDirectory = userStorageDirectory self.torrentUrl = torrentUrl xbmc.Player.__init__(self) log("[AnteoPlayer] Initalized") self.params = params self.get = self.params.get self.contentId = int(self.get("url")) if self.get("seek"): self.seek = int(self.get("seek")) #self.torrent = AnteoLoader(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory) self.init() self.setup_engine() with closing(self.engine): self.engine.start(self.contentId) self.setup_nextep() while True: if self.buffer(): log('[AnteoPlayer]: ************************************* GOING LOOP') if self.setup_play(): self.setup_subs() self.loop() WatchedHistoryDB().add(self.basename, self.watchedTime, self.totalTime, self.contentId, self.fullSize) else: log('[AnteoPlayer]: ************************************* break') break log('[AnteoPlayer]: ************************************* GO NEXT?') if self.next_dl and self.next_contentId != False and isinstance(self.next_contentId, int) and self.iterator == 100: if not self.next_play: xbmc.sleep(3000) if not xbmcgui.Dialog().yesno( self.localize('Torrent2HTTP'), self.localize('Would you like to play next episode?')): break self.contentId = self.next_contentId continue log('[AnteoPlayer]: ************************************* NO! break') break xbmc.Player().stop() if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory: xbmc.sleep(1000) clearStorage(self.userStorageDirectory) else: #if self.seeding_status: #showMessage(self.localize('Information'), # self.localize('Torrent is seeding. To stop it use Download Status.'), forced=True) #else: #if self.seeding: self.db_delete() showMessage(self.localize('Information'), self.localize('Torrent downloading is stopped.'), forced=True) def __exit__(self): log('on __exit__') if self.engine: self.engine.close() log('__exit__ worked!') def init(self): self.next_contentId = False self.display_name = '' self.downloadedSize = 0 self.dialog = xbmcgui.Dialog() self.on_playback_started = [] self.on_playback_resumed = [] self.on_playback_paused = [] self.on_playback_stopped = [] self.torrentUrl = self.torrentUrl def setup_engine(self): #uri=None, binaries_path=None, platform=None, download_path=".", #bind_host='127.0.0.1', bind_port=5001, connections_limit=None, download_kbps=None, upload_kbps=None, #enable_dht=True, enable_lsd=True, enable_natpmp=True, enable_upnp=True, enable_scrape=False, #log_stats=False, encryption=Encryption.ENABLED, keep_complete=False, keep_incomplete=False, #keep_files=False, log_files_progress=False, log_overall_progress=False, log_pieces_progress=False, #listen_port=6881, use_random_port=False, max_idle_timeout=None, no_sparse=False, resume_file=None, #user_agent=None, startup_timeout=5, state_file=None, enable_utp=True, enable_tcp=True, #debug_alerts=False, logger=None, torrent_connect_boost=50, connection_speed=50, #peer_connect_timeout=15, request_timeout=20, min_reconnect_time=60, max_failcount=3, #dht_routers=None, trackers=None) encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED upload_limit = int(self.__settings__.getSetting("upload_limit"))*1024/8 if self.__settings__.getSetting( "upload_limit") != "" else 0 download_limit = int(self.__settings__.getSetting("download_limit"))*1024/8 if self.__settings__.getSetting( "download_limit") != "" else 0 if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]: connections_limit = int(self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting( "listen_port") != "" else 6881 if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.userStorageDirectory: keep_complete = False keep_incomplete = False keep_files = False resume_file = None else: keep_complete = True keep_incomplete = True keep_files = True resume_file=os.path.join(self.userStorageDirectory, 'torrents', os.path.basename(self.torrentUrl)+'.resume_data') dht_routers = ["router.bittorrent.com:6881","router.utorrent.com:6881"] user_agent = 'uTorrent/2200(24683)' self.pre_buffer_bytes = int(self.__settings__.getSetting("pre_buffer_bytes"))*1024*1024 self.engine = Engine(uri=file_url(self.torrentUrl), download_path=self.userStorageDirectory, connections_limit=connections_limit, download_kbps=download_limit, upload_kbps=upload_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, keep_files=keep_files, user_agent=user_agent, resume_file=resume_file) def buffer(self): #self.pre_buffer_bytes = 30*1024*1024 #30 MB ready = False progressBar = xbmcgui.DialogProgress() progressBar.create(self.localize('Please Wait'), self.localize('Seeds searching.')) #if self.subs_dl: # subs = self.torrent.getSubsIds(os.path.basename(self.torrent.getFilePath(self.contentId))) # if len(subs) > 0: # for ind, title in subs: # self.torrent.continueSession(ind) while not xbmc.abortRequested and not ready: xbmc.sleep(500) status = self.engine.status() self.print_debug(status) #self.print_fulldebug() self.engine.check_torrent_error(status) file_status = self.engine.file_status(self.contentId) if not file_status: continue self.fullSize = int(file_status.size / 1024 / 1024) downloadedSize = status.total_download / 1024 / 1024 getDownloadRate = status.download_rate / 1024 * 8 getUploadRate = status.upload_rate / 1024 * 8 getSeeds, getPeers = status.num_seeds, status.num_peers iterator = int(round(float(file_status.download) / self.pre_buffer_bytes, 2) * 100) if iterator > 99: iterator = 99 if status.state == State.CHECKING_FILES: iterator = int(status.progress*100) if iterator > 99: iterator = 99 progressBar.update(iterator, self.localize('Checking preloaded files...'), ' ', ' ') elif status.state == State.DOWNLOADING: dialogText = self.localize('Preloaded: ') + "%d MB / %d MB" % \ (int(downloadedSize), self.fullSize) peersText = ' [%s: %s; %s: %s]' % ( self.localize('Seeds'), getSeeds, self.localize('Peers'), getPeers) speedsText = '%s: %d Mbit/s; %s: %d Mbit/s' % ( self.localize('Downloading'), int(getDownloadRate), self.localize('Uploading'), int(getUploadRate)) progressBar.update(iterator, self.localize('Seeds searching.') + peersText, dialogText, speedsText) if file_status.download >= self.pre_buffer_bytes: ready = True break elif status.state in [State.FINISHED, State.SEEDING]: ready = True break else: progressBar.update(iterator, self.localize('UNKNOWN STATUS'), ' ', ' ') if progressBar.iscanceled(): self.iterator = 0 ready = False break progressBar.update(0) progressBar.close() return ready def setup_nextep(self): try: if self.get("url2"): debug("[setup_nextep]: url2") self.ids_video = urllib.unquote_plus(self.get("url2")).split(',') else: debug("[setup_nextep]: not url2") self.ids_video = self.get_ids() except: pass if self.__settings__.getSetting('next_dl') == 'true' and self.ids_video and len(self.ids_video)>1: self.next_dl = True else: self.next_dl = False self.next_play = self.__settings__.getSetting('next_play') == 'true' log('[AnteoPlayer]: next_dl - %s, next_play - %s, ids_video - %s' % (str(self.next_dl), str(self.next_play), str(self.ids_video))) def setup_play(self): file_status = self.engine.file_status(self.contentId) self.iterator = 0 self.watchedTime = 0 self.totalTime = 1 url = file_status.url label = os.path.basename(file_status.name) self.basename = label self.seeding_run = False listitem = xbmcgui.ListItem(label, path=url) if self.next_dl: next_contentId_index = self.ids_video.index(str(self.contentId)) + 1 if len(self.ids_video) > next_contentId_index: self.next_contentId = int(self.ids_video[next_contentId_index]) else: self.next_contentId = False log('[AnteoPlayer][setup_play]: next_contentId: '+str(self.next_contentId)) try: seasonId = self.get("seasonId") self.episodeId = self.get("episodeId") if not self.episodeId else int(self.episodeId) + 1 title = urllib.unquote_plus(self.get("title")) if self.get("title") else None if self.get("label") and self.episodeId == self.get("episodeId"): label = urllib.unquote_plus(self.get("label")) elif seasonId and self.episodeId and title: label = '%s S%02dE%02d.%s (%s)' % ( title, int(seasonId), int(self.episodeId), self.basename.split('.')[-1], self.basename) if seasonId and self.episodeId and label and title: listitem = xbmcgui.ListItem(label, path=url) listitem.setInfo(type='video', infoLabels={'title': label, 'episode': int(self.episodeId), 'season': int(seasonId), 'tvshowtitle': title}) except: log('[AnteoPlayer]: Operation INFO failed!') thumbnail = self.get("thumbnail") if thumbnail: listitem.setThumbnailImage(urllib.unquote_plus(thumbnail)) self.display_name = label player = xbmc.Player() player.play(url, listitem) xbmc.sleep(2000) # very important, do not edit this, podavan if self.seek > 0: while not self.isPlaying(): xbmc.sleep(200) log('seekTime') log('[AnteoPlayer]: seekTime - '+str(self.seek)) self.seekTime(self.seek) return True def setup_subs(self): if self.subs_dl: file_status = self.engine.file_status(self.contentId) subs = [] filename = os.path.basename(file_status.name) sub_files = self.engine.list(media_types=[MediaType.SUBTITLES]) for i in sub_files: if isSubtitle(filename, i.name): subs.append(i) if subs: log("[AnteoPlayer][setup_subs]: Detected subtitles: %s" % str(subs)) for sub in subs: xbmc.Player().setSubtitles(sub.url) def loop(self): debug_counter=0 xbmc.sleep(1000) with closing( OverlayText(w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y)) as overlay: with nested(self.attach(overlay.show, self.on_playback_paused), self.attach(overlay.hide, self.on_playback_resumed, self.on_playback_stopped)): while not xbmc.abortRequested and self.isPlaying(): #self.print_fulldebug() status = self.engine.status() file_status = self.engine.file_status(self.contentId) self.watchedTime = xbmc.Player().getTime() self.totalTime = xbmc.Player().getTotalTime() if self.iterator == 100 and debug_counter < 100: debug_counter += 1 else: self.print_debug(status) debug_counter=0 overlay.text = "\n".join(self._get_status_lines(status, file_status)) self.iterator = int(file_status.progress * 100) xbmc.sleep(1000) #if not self.seeding_run and self.iterator == 100 and self.seeding: #self.seeding_run = True #self.seed(self.contentId) #self.seeding_status = True # xbmc.sleep(7000) def onPlayBackStarted(self): for f in self.on_playback_started: f() log('[onPlayBackStarted]: '+(str(("video", "play", self.display_name)))) def onPlayBackResumed(self): for f in self.on_playback_resumed: f() self.onPlayBackStarted() def onPlayBackPaused(self): for f in self.on_playback_paused: f() log('[onPlayBackPaused]: '+(str(("video", "pause", self.display_name)))) def onPlayBackStopped(self): for f in self.on_playback_stopped: f() log('[onPlayBackStopped]: '+(str(("video", "stop", self.display_name)))) @contextmanager def attach(self, callback, *events): for event in events: event.append(callback) yield for event in events: event.remove(callback) def _get_status_lines(self, s, f): return [ self.display_name, "%.2f%% %s" % (f.progress * 100, self.localize(STATE_STRS[s.state]).decode('utf-8')), "D:%.2f%s U:%.2f%s S:%d P:%d" % (s.download_rate, self.localize('kb/s').decode('utf-8'), s.upload_rate, self.localize('kb/s').decode('utf-8'), s.num_seeds, s.num_peers) ] def localize(self, string): try: return Localization.localize(string) except: return string def print_debug(self, status=None): #FileStatus = namedtuple('FileStatus', "name, save_path, url, size, offset, download, progress, index, media_type") #SessionStatus = namedtuple('SessionStatus', "name, state, state_str, error, progress, download_rate, upload_rate, " # "total_download, total_upload, num_peers, num_seeds, total_seeds, " # "total_peers") #log('[buffer] file_status:'+str(file_status)) #log('[buffer] status:'+str(status)) if not status: status = self.engine.status() self.engine.check_torrent_error(status) log('[AnteoPlayer]: %.2f%% complete (down: %.1f kb/s up: %.1f kb/s peers: %d) %s' % \ (status.progress * 100, status.download_rate, status.upload_rate, status.num_peers, status.state_str)) def print_fulldebug(self): status = self.engine.status() file_status = self.engine.file_status(self.contentId) log('[buffer] file_status:'+str(file_status)) log('[buffer] status:'+str(status)) def get_ids(self): contentList = [] for fs in self.engine.list(): contentList.append((fs.name, str(fs.index))) contentList = sorted(contentList, key=lambda x: x[0]) return get_ids_video(contentList)
class AnteoPlayer(xbmc.Player): __plugin__ = sys.modules["__main__"].__plugin__ __settings__ = sys.modules["__main__"].__settings__ ROOT = sys.modules[ "__main__"].__root__ # .decode('utf-8').encode(sys.getfilesystemencoding()) USERAGENT = "Mozilla/5.0 (Windows NT 6.1; rv:5.0) Gecko/20100101 Firefox/5.0" torrentFilesDirectory = 'torrents' debug = __settings__.getSetting('debug') == 'true' subs_dl = __settings__.getSetting('subs_dl') == 'true' seeding = __settings__.getSetting( 'keep_seeding') == 'true' and __settings__.getSetting( 'keep_files') == '1' seeding_status = False seeding_run = False ids_video = None episodeId = None fullSize = 0 watchedTime = 0 totalTime = 1 seek = 0 basename = '' def __init__(self, userStorageDirectory, torrentUrl, params={}): self.userStorageDirectory = userStorageDirectory self.torrentUrl = torrentUrl xbmc.Player.__init__(self) log("[AnteoPlayer] Initalized") self.params = params self.get = self.params.get self.contentId = int(self.get("url")) if self.get("seek"): self.seek = int(self.get("seek")) #self.torrent = AnteoLoader(self.userStorageDirectory, self.torrentUrl, self.torrentFilesDirectory) self.init() self.setup_engine() with closing(self.engine): self.engine.start(self.contentId) self.setup_nextep() while True: if self.buffer(): log('[AnteoPlayer]: ************************************* GOING LOOP' ) if self.setup_play(): self.setup_subs() self.loop() WatchedHistoryDB().add(self.basename, self.watchedTime, self.totalTime, self.contentId, self.fullSize) else: log('[AnteoPlayer]: ************************************* break' ) break log('[AnteoPlayer]: ************************************* GO NEXT?' ) if self.next_dl and isinstance( self.next_contentId, int) and self.iterator == 100: self.contentId = self.next_contentId continue log('[AnteoPlayer]: ************************************* NO! break' ) break xbmc.Player().stop() if '1' != self.__settings__.getSetting( "keep_files" ) and 'Saved Files' not in self.userStorageDirectory: xbmc.sleep(1000) clearStorage(self.userStorageDirectory) else: #if self.seeding_status: #showMessage(self.localize('Information'), # self.localize('Torrent is seeding. To stop it use Download Status.'), forced=True) #else: #if self.seeding: self.db_delete() showMessage(self.localize('Information'), self.localize('Torrent downloading is stopped.'), forced=True) def __exit__(self): log('on __exit__') if self.engine: self.engine.close() log('__exit__ worked!') def init(self): self.next_contentId = False self.display_name = '' self.downloadedSize = 0 self.dialog = xbmcgui.Dialog() self.on_playback_started = [] self.on_playback_resumed = [] self.on_playback_paused = [] self.on_playback_stopped = [] self.torrentUrl = self.torrentUrl def setup_engine(self): #uri=None, binaries_path=None, platform=None, download_path=".", #bind_host='127.0.0.1', bind_port=5001, connections_limit=None, download_kbps=None, upload_kbps=None, #enable_dht=True, enable_lsd=True, enable_natpmp=True, enable_upnp=True, enable_scrape=False, #log_stats=False, encryption=Encryption.ENABLED, keep_complete=False, keep_incomplete=False, #keep_files=False, log_files_progress=False, log_overall_progress=False, log_pieces_progress=False, #listen_port=6881, use_random_port=False, max_idle_timeout=None, no_sparse=False, resume_file=None, #user_agent=None, startup_timeout=5, state_file=None, enable_utp=True, enable_tcp=True, #debug_alerts=False, logger=None, torrent_connect_boost=50, connection_speed=50, #peer_connect_timeout=15, request_timeout=20, min_reconnect_time=60, max_failcount=3, #dht_routers=None, trackers=None) encryption = Encryption.ENABLED if self.__settings__.getSetting( 'encryption') == 'true' else Encryption.DISABLED upload_limit = int( self.__settings__.getSetting("upload_limit") ) * 1024 if self.__settings__.getSetting("upload_limit") != "" else 0 download_limit = int( self.__settings__.getSetting("download_limit") ) * 1024 if self.__settings__.getSetting("download_limit") != "" else 0 if self.__settings__.getSetting("connections_limit") not in [ "", 0, "0" ]: connections_limit = int( self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting( 'use_random_port') == 'true' else False listen_port = int( self.__settings__.getSetting("listen_port") ) if self.__settings__.getSetting("listen_port") != "" else 6881 if '1' != self.__settings__.getSetting( "keep_files" ) and 'Saved Files' not in self.userStorageDirectory: keep_complete = False keep_incomplete = False keep_files = False else: keep_complete = True keep_incomplete = True keep_files = True dht_routers = [ "router.bittorrent.com:6881", "router.utorrent.com:6881" ] user_agent = 'uTorrent/2200(24683)' self.pre_buffer_bytes = int( self.__settings__.getSetting("pre_buffer_bytes")) * 1024 * 1024 self.engine = Engine(uri=file_url(self.torrentUrl), download_path=self.userStorageDirectory, connections_limit=connections_limit, download_kbps=download_limit, upload_kbps=upload_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, keep_files=keep_files, user_agent=user_agent) def buffer(self): self.pre_buffer_bytes = 30 * 1024 * 1024 #30 MB ready = False progressBar = xbmcgui.DialogProgress() progressBar.create(self.localize('Please Wait'), self.localize('Seeds searching.')) #if self.subs_dl: # subs = self.torrent.getSubsIds(os.path.basename(self.torrent.getFilePath(self.contentId))) # if len(subs) > 0: # for ind, title in subs: # self.torrent.continueSession(ind) while not xbmc.abortRequested and not ready: xbmc.sleep(500) status = self.engine.status() self.print_debug(status) #self.print_fulldebug() self.engine.check_torrent_error(status) file_status = self.engine.file_status(self.contentId) if not file_status: continue self.fullSize = int(file_status.size / 1024 / 1024) downloadedSize = status.total_download / 1024 / 1024 getDownloadRate = status.download_rate / 1024 * 8 getUploadRate = status.upload_rate / 1024 * 8 getSeeds, getPeers = status.num_seeds, status.num_peers iterator = int( round(float(file_status.download) / self.pre_buffer_bytes, 2) * 100) if iterator > 99: iterator = 99 if status.state == State.CHECKING_FILES: iterator = int(status.progress * 100) if iterator > 99: iterator = 99 progressBar.update( iterator, self.localize('Checking preloaded files...'), ' ', ' ') elif status.state == State.DOWNLOADING: dialogText = self.localize('Preloaded: ') + "%d MB / %d MB" % \ (int(downloadedSize), self.fullSize) peersText = ' [%s: %s; %s: %s]' % (self.localize( 'Seeds'), getSeeds, self.localize('Peers'), getPeers) speedsText = '%s: %d Mbit/s; %s: %d Mbit/s' % ( self.localize('Downloading'), int(getDownloadRate), self.localize('Uploading'), int(getUploadRate)) #if self.debug: # peersText=peersText + ' ' + self.torrent.get_debug_info('dht_state') # dialogText=dialogText.replace(self.localize('Preloaded: '),'') + ' ' + self.torrent.get_debug_info('trackers_sum') progressBar.update( iterator, self.localize('Seeds searching.') + peersText, dialogText, speedsText) if file_status.download >= self.pre_buffer_bytes: ready = True break elif status.state in [State.FINISHED, State.SEEDING]: ready = True break else: progressBar.update(iterator, self.localize('UNKNOWN STATUS'), ' ', ' ') if progressBar.iscanceled(): self.iterator = 0 ready = False break progressBar.update(0) progressBar.close() return ready def setup_nextep(self): try: if self.get("url2"): debug("url2") self.ids_video = urllib.unquote_plus( self.get("url2")).split(',') else: debug("not url2") self.ids_video = self.get_ids() except: pass if self.__settings__.getSetting( 'next_dl') == 'true' and self.ids_video: self.next_dl = True else: self.next_dl = False log('[AnteoPlayer]: nextdl - %s, ids_video - %s' % (str(self.next_dl), str(self.ids_video))) def setup_play(self): file_status = self.engine.file_status(self.contentId) self.iterator = 0 self.watchedTime = 0 self.totalTime = 1 url = file_status.url label = os.path.basename(file_status.name) self.basename = label self.seeding_run = False subtitles = None listitem = xbmcgui.ListItem(label, path=url) if self.next_dl: next_contentId_index = self.ids_video.index(str( self.contentId)) + 1 if len(self.ids_video) > next_contentId_index: self.next_contentId = int(self.ids_video[next_contentId_index]) else: self.next_contentId = False log('[AnteoPlayer][setup_play]: next_contentId: ' + str(self.next_contentId)) try: seasonId = self.get("seasonId") self.episodeId = self.get( "episodeId") if not self.episodeId else int(self.episodeId) + 1 title = urllib.unquote_plus( self.get("title")) if self.get("title") else None if self.get("label") and self.episodeId == self.get("episodeId"): label = urllib.unquote_plus(self.get("label")) elif seasonId and self.episodeId and title: label = '%s S%02dE%02d.%s (%s)' % ( title, int(seasonId), int(self.episodeId), self.basename.split('.')[-1], self.basename) if seasonId and self.episodeId and label and title: listitem = xbmcgui.ListItem(label, path=url) listitem.setInfo(type='video', infoLabels={ 'title': label, 'episode': int(self.episodeId), 'season': int(seasonId), 'tvshowtitle': title }) except: log('[AnteoPlayer]: Operation INFO failed!') thumbnail = self.get("thumbnail") if thumbnail: listitem.setThumbnailImage(urllib.unquote_plus(thumbnail)) self.display_name = label player = xbmc.Player() player.play(url, listitem) xbmc.sleep(2000) # very important, do not edit this, podavan if self.seek > 0: while not self.isPlaying(): xbmc.sleep(200) log('seekTime') log('[AnteoPlayer]: seekTime - ' + str(self.seek)) self.seekTime(self.seek) return True def setup_subs(self): if self.subs_dl: file_status = self.engine.file_status(self.contentId) subs = [] filename = os.path.basename(file_status.name) sub_files = self.engine.list(media_types=[MediaType.SUBTITLES]) for i in sub_files: if isSubtitle(filename, i.name): subs.append(i) if subs: log("[AnteoPlayer][setup_subs]: Detected subtitles: %s" % str(subs)) for sub in subs: xbmc.Player().setSubtitles(sub.url) def loop(self): debug_counter = 0 xbmc.sleep(1000) with closing( OverlayText(w=OVERLAY_WIDTH, h=OVERLAY_HEIGHT, alignment=XBFONT_CENTER_X | XBFONT_CENTER_Y)) as overlay: with nested( self.attach(overlay.show, self.on_playback_paused), self.attach(overlay.hide, self.on_playback_resumed, self.on_playback_stopped)): while not xbmc.abortRequested and self.isPlaying(): #self.print_fulldebug() status = self.engine.status() file_status = self.engine.file_status(self.contentId) self.watchedTime = xbmc.Player().getTime() self.totalTime = xbmc.Player().getTotalTime() if self.iterator == 100 and debug_counter < 100: debug_counter += 1 else: self.print_debug(status) debug_counter = 0 overlay.text = "\n".join( self._get_status_lines(status, file_status)) self.iterator = int(file_status.progress * 100) xbmc.sleep(1000) #if not self.seeding_run and self.iterator == 100 and self.seeding: #self.seeding_run = True #self.seed(self.contentId) #self.seeding_status = True # xbmc.sleep(7000) def onPlayBackStarted(self): for f in self.on_playback_started: f() log('[onPlayBackStarted]: ' + (str(("video", "play", self.display_name)))) def onPlayBackResumed(self): for f in self.on_playback_resumed: f() self.onPlayBackStarted() def onPlayBackPaused(self): for f in self.on_playback_paused: f() log('[onPlayBackPaused]: ' + (str(("video", "pause", self.display_name)))) def onPlayBackStopped(self): for f in self.on_playback_stopped: f() log('[onPlayBackStopped]: ' + (str(("video", "stop", self.display_name)))) @contextmanager def attach(self, callback, *events): for event in events: event.append(callback) yield for event in events: event.remove(callback) def _get_status_lines(self, s, f): return [ self.display_name, "%.2f%% %s" % (f.progress * 100, self.localize( STATE_STRS[s.state]).decode('utf-8')), "D:%.2f%s U:%.2f%s S:%d P:%d" % (s.download_rate, self.localize('kb/s').decode('utf-8'), s.upload_rate, self.localize('kb/s').decode('utf-8'), s.num_seeds, s.num_peers) ] def localize(self, string): try: return Localization.localize(string) except: return string def print_debug(self, status=None): #FileStatus = namedtuple('FileStatus', "name, save_path, url, size, offset, download, progress, index, media_type") #SessionStatus = namedtuple('SessionStatus', "name, state, state_str, error, progress, download_rate, upload_rate, " # "total_download, total_upload, num_peers, num_seeds, total_seeds, " # "total_peers") #log('[buffer] file_status:'+str(file_status)) #log('[buffer] status:'+str(status)) if not status: status = self.engine.status() self.engine.check_torrent_error(status) log('[AnteoPlayer]: %.2f%% complete (down: %.1f kb/s up: %.1f kb/s peers: %d) %s' % \ (status.progress * 100, status.download_rate, status.upload_rate, status.num_peers, status.state_str)) def print_fulldebug(self): status = self.engine.status() file_status = self.engine.file_status(self.contentId) log('[buffer] file_status:' + str(file_status)) log('[buffer] status:' + str(status)) def get_ids(self): contentList = [] for fs in self.engine.list(): contentList.append((fs.name, str(fs.index))) contentList = sorted(contentList, key=lambda x: x[0]) return get_ids_video(contentList)
class AnteoLoader: magnetLink = None engine = None torrentFile = None __plugin__ = sys.modules["__main__"].__plugin__ __settings__ = sys.modules["__main__"].__settings__ def __init__(self, storageDirectory='', torrentFile='', torrentFilesDirectory='torrents'): self.storageDirectory = storageDirectory self.torrentFilesPath = os.path.join(self.storageDirectory, torrentFilesDirectory) + os.sep if not is_writable(self.storageDirectory): xbmcgui.Dialog().ok(self.localize('Torrenter v2'), self.localize('Your storage path is not writable or not local! Please change it in settings!'), self.localize(self.storageDirectory)) sys.exit(1) #pre settings if re.match("^magnet\:.+$", torrentFile): self.magnetLink = torrentFile else: self.torrentFile = torrentFile def __exit__(self): log('on __exit__') if self.engine: self.engine.close() log('__exit__ worked!') def setup_engine(self): encryption = Encryption.ENABLED if self.__settings__.getSetting('encryption') == 'true' else Encryption.DISABLED if self.__settings__.getSetting("connections_limit") not in ["",0,"0"]: connections_limit = int(self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting('use_random_port') == 'true' else False listen_port=int(self.__settings__.getSetting("listen_port")) if self.__settings__.getSetting( "listen_port") != "" else 6881 if '1' != self.__settings__.getSetting("keep_files") and 'Saved Files' not in self.storageDirectory: keep_complete = False keep_incomplete = False else: keep_complete = True keep_incomplete = True dht_routers = ["router.bittorrent.com:6881", "router.utorrent.com:6881"] user_agent = 'uTorrent/2200(24683)' self.engine = Engine(uri=file_url(self.torrentFile), download_path=self.storageDirectory, connections_limit=connections_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, user_agent=user_agent) def localize(self, string): try: return Localization.localize(string) except: return string def getContentList(self): self.setup_engine() files = [] filelist = [] with closing(self.engine): self.engine.start() #media_types=[MediaType.VIDEO, MediaType.AUDIO, MediaType.SUBTITLES, MediaType.UNKNOWN] iterator = 0 text = Localization.localize('Magnet-link is converting') if self.magnetLink\ else Localization.localize('Opening torrent file') while not files and not xbmc.abortRequested and iterator < 100: files = self.engine.list() self.engine.check_torrent_error() if iterator==4: progressBar = xbmcgui.DialogProgress() progressBar.create(Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting')) elif iterator>4: progressBar.update(iterator, Localization.localize('Please Wait'),text+'.' * (iterator % 4), ' ') if progressBar.iscanceled(): progressBar.update(0) progressBar.close() return [] xbmc.sleep(500) iterator += 1 for fs in files: stringdata = {"title": fs.name, "size": fs.size, "ind": fs.index, 'offset': fs.offset} filelist.append(stringdata) return filelist def saveTorrent(self, torrentUrl): if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl): if re.match("^magnet\:.+$", torrentUrl): self.magnetLink = torrentUrl self.magnetToTorrent(torrentUrl) self.magnetLink = None return self.torrentFile else: if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent') try: if not re.match("^http\:.+$", torrentUrl): content = xbmcvfs.File(torrentUrl, "rb").read() else: request = urllib2.Request(torrentUrl) request.add_header('Referer', torrentUrl) request.add_header('Accept-encoding', 'gzip') result = urllib2.urlopen(request) if result.info().get('Content-Encoding') == 'gzip': buf = StringIO(result.read()) f = gzip.GzipFile(fileobj=buf) content = f.read() else: content = result.read() localFile = xbmcvfs.File(torrentFile, "w+b") localFile.write(content) localFile.close() except Exception, e: print 'Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str( e) return else:
class AnteoLoader: magnetLink = None engine = None torrentFile = None __plugin__ = sys.modules["__main__"].__plugin__ __settings__ = sys.modules["__main__"].__settings__ def __init__(self, storageDirectory='', torrentFile='', torrentFilesDirectory='torrents'): self.storageDirectory = storageDirectory self.torrentFilesPath = os.path.join(self.storageDirectory, torrentFilesDirectory) + os.sep if not is_writable(self.storageDirectory): xbmcgui.Dialog().ok( self.localize('Torrenter v2'), self.localize( 'Your storage path is not writable or not local! Please change it in settings!' ), self.localize(self.storageDirectory)) sys.exit(1) #pre settings if re.match("^magnet\:.+$", torrentFile): self.magnetLink = torrentFile else: self.torrentFile = torrentFile def __exit__(self): log('on __exit__') if self.engine: self.engine.close() log('__exit__ worked!') def setup_engine(self): encryption = Encryption.ENABLED if self.__settings__.getSetting( 'encryption') == 'true' else Encryption.DISABLED if self.__settings__.getSetting("connections_limit") not in [ "", 0, "0" ]: connections_limit = int( self.__settings__.getSetting("connections_limit")) else: connections_limit = None use_random_port = True if self.__settings__.getSetting( 'use_random_port') == 'true' else False listen_port = int( self.__settings__.getSetting("listen_port") ) if self.__settings__.getSetting("listen_port") != "" else 6881 if '1' != self.__settings__.getSetting( "keep_files") and 'Saved Files' not in self.storageDirectory: keep_complete = False keep_incomplete = False else: keep_complete = True keep_incomplete = True dht_routers = [ "router.bittorrent.com:6881", "router.utorrent.com:6881" ] user_agent = 'uTorrent/2200(24683)' self.engine = Engine(uri=file_url(self.torrentFile), download_path=self.storageDirectory, connections_limit=connections_limit, encryption=encryption, keep_complete=keep_complete, keep_incomplete=keep_incomplete, dht_routers=dht_routers, use_random_port=use_random_port, listen_port=listen_port, user_agent=user_agent) def localize(self, string): try: return Localization.localize(string) except: return string def getContentList(self): self.setup_engine() files = [] filelist = [] with closing(self.engine): self.engine.start() #media_types=[MediaType.VIDEO, MediaType.AUDIO, MediaType.SUBTITLES, MediaType.UNKNOWN] iterator = 0 text = Localization.localize('Magnet-link is converting') if self.magnetLink\ else Localization.localize('Opening torrent file') while not files and not xbmc.abortRequested and iterator < 100: files = self.engine.list() self.engine.check_torrent_error() if iterator == 4: progressBar = xbmcgui.DialogProgress() progressBar.create( Localization.localize('Please Wait'), Localization.localize('Magnet-link is converting')) elif iterator > 4: progressBar.update(iterator, Localization.localize('Please Wait'), text + '.' * (iterator % 4), ' ') if progressBar.iscanceled(): progressBar.update(0) progressBar.close() return [] xbmc.sleep(500) iterator += 1 for fs in files: stringdata = { "title": fs.name, "size": fs.size, "ind": fs.index, 'offset': fs.offset } filelist.append(stringdata) return filelist def saveTorrent(self, torrentUrl): if not xbmcvfs.exists(torrentUrl) or re.match("^http.+$", torrentUrl): if re.match("^magnet\:.+$", torrentUrl): self.magnetLink = torrentUrl self.magnetToTorrent(torrentUrl) self.magnetLink = None return self.torrentFile else: if not xbmcvfs.exists(self.torrentFilesPath): xbmcvfs.mkdirs(self.torrentFilesPath) torrentFile = os.path.join(self.torrentFilesPath, self.md5(torrentUrl) + '.torrent') try: if not re.match("^http\:.+$", torrentUrl): content = xbmcvfs.File(torrentUrl, "rb").read() else: request = urllib2.Request(torrentUrl) request.add_header('Referer', torrentUrl) request.add_header('Accept-encoding', 'gzip') result = urllib2.urlopen(request) if result.info().get('Content-Encoding') == 'gzip': buf = StringIO(result.read()) f = gzip.GzipFile(fileobj=buf) content = f.read() else: content = result.read() localFile = xbmcvfs.File(torrentFile, "w+b") localFile.write(content) localFile.close() except Exception, e: print 'Unable to save torrent file from "' + torrentUrl + '" to "' + torrentFile + '" in Torrent::saveTorrent' + '. Exception: ' + str( e) return else: