def update(self, download): # azu-state self.state_azu = download.getState() # and auto stopped (sharekill) if self.state_azu == Transfer.AZ_STOPPED and self.sf.running == "1" and float(self.sf.percent_done) >= 100.0: printMessage("Torrent autostopped by Azureus %s " % self.sf.percent_done) self.log("Torrent autostopped by Azureus %s " % self.sf.percent_done) # stat self.statShutdown(download) # set state self.state = Transfer.STATE_MAP[self.state_azu] # only when running if self.state == Transfer.TF_RUNNING: # stat self.statRunning(download) else: if self.state_azu != Transfer.AZ_STOPPED: printMessage(self.name + ": update() state_azu=%d" % self.state_azu)
def writeStatFile(self): try: # get plugin-config try: config_object = self.interface.getPluginconfig() config_ok = 1 except: printMessage( "getPluginconfig: Ignoring Incompatible Plugin Config :") printException() config_ok = 0 #return True if config_ok == 1: # get vars coreVars = [ \ config_object.CORE_PARAM_INT_MAX_ACTIVE, \ config_object.CORE_PARAM_INT_MAX_ACTIVE_SEEDING, \ config_object.CORE_PARAM_INT_MAX_CONNECTIONS_GLOBAL, \ config_object.CORE_PARAM_INT_MAX_CONNECTIONS_PER_TORRENT, \ config_object.CORE_PARAM_INT_MAX_DOWNLOAD_SPEED_KBYTES_PER_SEC, \ config_object.CORE_PARAM_INT_MAX_DOWNLOADS, \ config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_KBYTES_PER_SEC, \ config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_SEEDING_KBYTES_PER_SEC, \ config_object.CORE_PARAM_INT_MAX_UPLOADS, \ config_object.CORE_PARAM_INT_MAX_UPLOADS_SEEDING \ ] coreParams = {} for coreVar in coreVars: try: coreParams[coreVar] = config_object.getIntParameter( coreVar, 0) printError("writeStatFile2: %s %s" % (coreVar, coreParams[coreVar])) except: printException() coreParams[coreVar] = 0 continue # write file try: f = open(self.flu_fileStat, 'w') f.write("%s\n" % self.azu_host) f.write("%d\n" % self.azu_port) f.write("%s\n" % self.azu_version_str) if config_ok == 1: for coreVar in coreVars: f.write("%d\n" % coreParams[coreVar]) f.flush() f.close() return True except: printError("Failed to write statfile %s " % self.flu_fileStat) printException() except: printMessage("Failed to get Plugin-Config.") printException() return False
def update(self, download): # azu-state self.state_azu = download.getState() # and auto stopped (sharekill) if self.state_azu == Transfer.AZ_STOPPED and self.sf.running == "1" and float( self.sf.percent_done) >= 100.0: printMessage("Torrent autostopped by Azureus %s " % self.sf.percent_done) self.log("Torrent autostopped by Azureus %s " % self.sf.percent_done) # stat self.statShutdown(download) # set state self.state = Transfer.STATE_MAP[self.state_azu] # only when running if self.state == Transfer.TF_RUNNING: # stat self.statRunning(download) else: if self.state_azu != Transfer.AZ_STOPPED: printMessage(self.name + ": update() state_azu=%d" % self.state_azu)
def setRateU(self, download, rate): try: download.setUploadRateLimitBytesPerSecond((int(rate) << 10)) return True except: printMessage("Failed to set upload-rate.") printException() return False
def setRateD(self, download, rate): try: download.setMaximumDownloadKBPerSecond(int(rate)) return True except: printMessage("Failed to set download-rate.") printException() return False
def setRateD(self, rate): try: config_object = self.interface.getPluginconfig() config_object.set_download_speed_limit(rate) return True except: printMessage("Failed to set download-rate.") printException() return False
def log(self, message): printMessage(message) try: f = open(self.fileLog, "a+") f.write(getOutput(message)) f.flush() f.close() except Exception, e: printError("Failed to write log-file %s" % self.fileLog)
def writeStatFile(self): try: # get plugin-config try: config_object = self.interface.getPluginconfig() config_ok = 1 except: printMessage("getPluginconfig: Ignoring Incompatible Plugin Config :") printException() config_ok = 0 #return True if config_ok == 1: # get vars coreVars = [ \ config_object.CORE_PARAM_INT_MAX_ACTIVE, \ config_object.CORE_PARAM_INT_MAX_ACTIVE_SEEDING, \ config_object.CORE_PARAM_INT_MAX_CONNECTIONS_GLOBAL, \ config_object.CORE_PARAM_INT_MAX_CONNECTIONS_PER_TORRENT, \ config_object.CORE_PARAM_INT_MAX_DOWNLOAD_SPEED_KBYTES_PER_SEC, \ config_object.CORE_PARAM_INT_MAX_DOWNLOADS, \ config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_KBYTES_PER_SEC, \ config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_SEEDING_KBYTES_PER_SEC, \ config_object.CORE_PARAM_INT_MAX_UPLOADS, \ config_object.CORE_PARAM_INT_MAX_UPLOADS_SEEDING \ ] coreParams = {} for coreVar in coreVars: try: coreParams[coreVar] = config_object.getIntParameter(coreVar, 0) printError("writeStatFile2: %s %s" % (coreVar, coreParams[coreVar])) except: printException() coreParams[coreVar] = 0 continue # write file try: f = open(self.flu_fileStat, 'w') f.write("%s\n" % self.azu_host) f.write("%d\n" % self.azu_port) f.write("%s\n" % self.azu_version_str) if config_ok == 1: for coreVar in coreVars: f.write("%d\n" % coreParams[coreVar]) f.flush() f.close() return True except: printError("Failed to write statfile %s " % self.flu_fileStat) printException() except: printMessage("Failed to get Plugin-Config.") printException() return False
def setRateU(self, rate): try: config_object = self.interface.getPluginconfig() config_object.set_upload_speed_limit(rate) return True except: printMessage("Failed to set upload-rate.") printException() return False
def removeTransfer(self, tname): printMessage("removing transfer %s ..." % tname) try: self.downloads[tname].remove() return True except: printMessage("exception when removing transfer:") printException() return False
def loadTransfers(self): printMessage("loading transfers...") self.transfers = [] try: for fileName in os.listdir(self.flu_pathTransfers): self.transfers.append(Transfer(self.tf_pathTransfers, self.flu_pathTransfers, fileName)) return True except: return False
def reload(self): printMessage("reloading...") # delete-requests self.processDeleteRequests() # run-requests self.processRunRequests() # transfers self.loadTransfers()
def loadTransfers(self): printMessage("loading transfers...") self.transfers = [] try: for fileName in os.listdir(self.flu_pathTransfers): self.transfers.append( Transfer(self.tf_pathTransfers, self.flu_pathTransfers, fileName)) return True except: return False
def updateDownloads(self): printMessage("updateDownloads() getDownloads...") # slow azu_dls = self.dm.getDownloads() # then fast for download in azu_dls: try: tfile = (os.path.split(str(download.getTorrentFileName())))[1] self.downloads[tfile] = download except: continue self.needUpdate = 0 printMessage("updateDownloads() done")
def initialize(self): # meta-file printMessage("loading transfer %s and stat..." % self.name) self.tf = TransferFile(self.fileMeta) # stat-file self.sf = StatFile(self.fileStat) # verbose # printMessage("transfer loaded.") # return return True
def writeStatFile(self): try: # get plugin-config config_object = self.interface.getPluginconfig() # get vars coreVars = [ config_object.CORE_PARAM_INT_MAX_ACTIVE, config_object.CORE_PARAM_INT_MAX_ACTIVE_SEEDING, config_object.CORE_PARAM_INT_MAX_CONNECTIONS_GLOBAL, config_object.CORE_PARAM_INT_MAX_CONNECTIONS_PER_TORRENT, config_object.CORE_PARAM_INT_MAX_DOWNLOAD_SPEED_KBYTES_PER_SEC, config_object.CORE_PARAM_INT_MAX_DOWNLOADS, config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_KBYTES_PER_SEC, config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_SEEDING_KBYTES_PER_SEC, config_object.CORE_PARAM_INT_MAX_UPLOADS, config_object.CORE_PARAM_INT_MAX_UPLOADS_SEEDING, ] coreParams = {} for coreVar in coreVars: try: coreParams[coreVar] = config_object.getIntParameter(coreVar, 0) except: coreParams[coreVar] = 0 printException() # write file try: f = open(self.flu_fileStat, "w") f.write("%s\n" % self.azu_host) f.write("%d\n" % self.azu_port) f.write("%s\n" % self.azu_version_str) for coreVar in coreVars: f.write("%d\n" % coreParams[coreVar]) f.flush() f.close() return True except: printError("Failed to write statfile %s " % self.flu_fileStat) printException() except: printMessage("Failed to get Plugin-Config.") printException() return False
def addTransfer(self, tname): printMessage("adding new transfer %s ..." % tname) try: # transfer-object transfer = Transfer(self.tf_pathTransfers, self.flu_pathTransfers, tname) # torrent-object torrent = self.interface.getTorrentManager().createFromBEncodedFile(transfer.fileTorrent) # file-objects fileSource = dopal.aztypes.wrap_file(transfer.fileTorrent) fileTarget = dopal.aztypes.wrap_file(transfer.tf.savepath) # add self.dm.addDownload(torrent, fileSource, fileTarget) # return return True except: printMessage("exception when adding transfer:") printException() return False
def checkAzuConnection(self): # con valid try: if self.connection.is_connection_valid(): return True else: raise # con not valid except: # out printMessage( "connection to Azureus-server lost, reconnecting to %s:%d ..." % (self.azu_host, self.azu_port) ) # try to reconnect for i in range(FluAzuD.MAX_RECONNECT_TRIES): # sleep time.sleep(i << 2) # out printMessage("reconnect-try %d ..." % (i + 1)) # establish con try: self.connection.establish_connection(True) printMessage("established connection to Azureus-server") except: printError("Error establishing connection to Azureus-server") printException() continue # interface try: self.interface = self.connection.get_plugin_interface() except LinkError, error: printError("Error getting interface object") printException() self.interface = None continue # download-manager try: self.dm = None self.dm = self.interface.getDownloadManager() if self.dm is None: raise else: return True except: printError("Error getting Download-Manager object") continue # seems like azu is down. give up printError("no connection after %d tries, i give up, azu is gone" % FluAzuD.MAX_RECONNECT_TRIES) return False
def processDeleteRequests(self): printMessage("processing delete-requests...") # read requests requests = [] try: for fileName in os.listdir(self.flu_pathTransfersDel): # add requests.append(fileName) # del file delFile = self.flu_pathTransfersDel + fileName try: os.remove(delFile) except: printError("Failed to delete file : %s" % delFile) except: return False # process requests if len(requests) > 0: for fileName in requests: printMessage("deleting %s ..." % fileName) # update downloads self.downloads = {} self.updateDownloads() # remove if needed if fileName in self.downloads: # remove transfer self.removeTransfer(fileName) # del file delFile = self.flu_pathTransfers + fileName try: os.remove(delFile) except: printError("Failed to delete file : %s" % delFile) # return return True
def addTransfer(self, tname): printMessage("adding new transfer %s ..." % tname) try: # transfer-object transfer = Transfer(self.tf_pathTransfers, self.flu_pathTransfers, tname) # torrent-object torrent = self.interface.getTorrentManager( ).createFromBEncodedFile(transfer.fileTorrent) # file-objects fileSource = dopal.aztypes.wrap_file(transfer.fileTorrent) fileTarget = dopal.aztypes.wrap_file(transfer.tf.savepath) # add self.dm.addDownload(torrent, fileSource, fileTarget) # return return torrent except: printMessage("exception when adding transfer:") printException() return False
def initialize(self): # out printMessage("initializing transfer %s ..." % self.name) # meta-file printMessage("loading transfer-file %s ..." % self.fileMeta) self.tf = TransferFile(self.fileMeta) # stat-file printMessage("loading statfile %s ..." % self.fileStat) self.sf = StatFile(self.fileStat) # verbose printMessage("transfer loaded.") # return return True
def processCommandStack(self): if os.path.isfile(self.flu_fileCommand): # process file printMessage("Processing command-file %s ..." % self.flu_fileCommand) try: # read file to mem try: f = open(self.flu_fileCommand, 'r') data = f.read() f.close() except: printError("Failed to read command-file : %s" % self.flu_fileCommand) raise # delete file try: os.remove(self.flu_fileCommand) except: printError("Failed to delete command-file : %s" % self.flu_fileCommand) # exec commands if len(data) > 0: commands = data.split("\n") if len(commands) > 0: for command in commands: if len(command) > 0: try: # exec, early out when reading a quit-command if self.execCommand(command): return True except: printError("Failed to exec command: %s" % command) else: printMessage("No commands found.") else: printMessage("No commands found.") except: printError("Failed to process command-stack : %s" % self.flu_fileCommand) return False
def shutdown(self): printMessage("fluazu shutting down...") # delete stat-file if exists if os.path.isfile(self.flu_fileStat): try: printMessage("deleting stat-file %s ..." % self.flu_fileStat) os.remove(self.flu_fileStat) except: printError("Failed to delete stat-file %s " % self.flu_fileStat) # delete pid-file if exists if os.path.isfile(self.flu_filePid): try: printMessage("deleting pid-file %s ..." % self.flu_filePid) os.remove(self.flu_filePid) except: printError("Failed to delete pid-file %s " % self.flu_filePid)
def processCommandStack(self): if os.path.isfile(self.flu_fileCommand): # process file printMessage("Processing command-file %s ..." % self.flu_fileCommand) try: # read file to mem try: f = open(self.flu_fileCommand, "r") data = f.read() f.close() except: printError("Failed to read command-file : %s" % self.flu_fileCommand) raise # delete file try: os.remove(self.flu_fileCommand) except: printError("Failed to delete command-file : %s" % self.flu_fileCommand) # exec commands if len(data) > 0: commands = data.split("\n") if len(commands) > 0: for command in commands: if len(command) > 0: try: # exec, early out when reading a quit-command if self.execCommand(command): return True except: printError("Failed to exec command: %s" % command) else: printMessage("No commands found.") else: printMessage("No commands found.") except: printError("Failed to process command-stack : %s" % self.flu_fileCommand) return False
def changeSetting(self, key, val): try: # get plugin-config config_object = self.interface.getPluginconfig() # core-keys coreKeys = { "CORE_PARAM_INT_MAX_ACTIVE": config_object.CORE_PARAM_INT_MAX_ACTIVE, "CORE_PARAM_INT_MAX_ACTIVE_SEEDING": config_object.CORE_PARAM_INT_MAX_ACTIVE_SEEDING, "CORE_PARAM_INT_MAX_CONNECTIONS_GLOBAL": config_object.CORE_PARAM_INT_MAX_CONNECTIONS_GLOBAL, "CORE_PARAM_INT_MAX_CONNECTIONS_PER_TORRENT": config_object.CORE_PARAM_INT_MAX_CONNECTIONS_PER_TORRENT, "CORE_PARAM_INT_MAX_DOWNLOAD_SPEED_KBYTES_PER_SEC": config_object.CORE_PARAM_INT_MAX_DOWNLOAD_SPEED_KBYTES_PER_SEC, "CORE_PARAM_INT_MAX_DOWNLOADS": config_object.CORE_PARAM_INT_MAX_DOWNLOADS, "CORE_PARAM_INT_MAX_UPLOAD_SPEED_KBYTES_PER_SEC": config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_KBYTES_PER_SEC, "CORE_PARAM_INT_MAX_UPLOAD_SPEED_SEEDING_KBYTES_PER_SEC": config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_SEEDING_KBYTES_PER_SEC, "CORE_PARAM_INT_MAX_UPLOADS": config_object.CORE_PARAM_INT_MAX_UPLOADS, "CORE_PARAM_INT_MAX_UPLOADS_SEEDING": config_object.CORE_PARAM_INT_MAX_UPLOADS_SEEDING, } if key not in coreKeys: printMessage("settings-key unknown: %s" % key) return False # change setting try: config_object.setIntParameter(coreKeys[key], int(val)) return True except: printMessage("Failed to change setting %s to %s" % (key, val)) printException() return False except: printMessage("Failed to get Plugin-Config.") printException() return False
def changeSetting(self, key, val): try: # get plugin-config config_object = self.interface.getPluginconfig() # core-keys coreKeys = { \ 'CORE_PARAM_INT_MAX_ACTIVE': config_object.CORE_PARAM_INT_MAX_ACTIVE, \ 'CORE_PARAM_INT_MAX_ACTIVE_SEEDING': config_object.CORE_PARAM_INT_MAX_ACTIVE_SEEDING, \ 'CORE_PARAM_INT_MAX_CONNECTIONS_GLOBAL': config_object.CORE_PARAM_INT_MAX_CONNECTIONS_GLOBAL, \ 'CORE_PARAM_INT_MAX_CONNECTIONS_PER_TORRENT': config_object.CORE_PARAM_INT_MAX_CONNECTIONS_PER_TORRENT, \ 'CORE_PARAM_INT_MAX_DOWNLOAD_SPEED_KBYTES_PER_SEC': config_object.CORE_PARAM_INT_MAX_DOWNLOAD_SPEED_KBYTES_PER_SEC, \ 'CORE_PARAM_INT_MAX_DOWNLOADS': config_object.CORE_PARAM_INT_MAX_DOWNLOADS, \ 'CORE_PARAM_INT_MAX_UPLOAD_SPEED_KBYTES_PER_SEC': config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_KBYTES_PER_SEC, \ 'CORE_PARAM_INT_MAX_UPLOAD_SPEED_SEEDING_KBYTES_PER_SEC': config_object.CORE_PARAM_INT_MAX_UPLOAD_SPEED_SEEDING_KBYTES_PER_SEC, \ 'CORE_PARAM_INT_MAX_UPLOADS': config_object.CORE_PARAM_INT_MAX_UPLOADS, \ 'CORE_PARAM_INT_MAX_UPLOADS_SEEDING': config_object.CORE_PARAM_INT_MAX_UPLOADS_SEEDING \ } if key not in coreKeys: printMessage("settings-key unknown: %s" % key) return False # change setting try: config_object.setIntParameter(coreKeys[key], int(val)) return True except: printMessage("Failed to change setting %s to %s" % (key, val)) printException() return False except: printMessage("Failed to get Plugin-Config.") printException() return False
def run(self, path, host, port, secure, username, password): printMessage("fluazu starting up:") # set vars self.tf_path = path self.tf_pathTransfers = self.tf_path + '.transfers/' self.flu_path = self.tf_path + '.fluazu/' self.flu_fileCommand = self.flu_path + 'fluazu.cmd' self.flu_filePid = self.flu_path + 'fluazu.pid' self.flu_fileStat = self.flu_path + 'fluazu.stat' self.flu_pathTransfers = self.flu_path + 'cur/' self.flu_pathTransfersRun = self.flu_path + 'run/' self.flu_pathTransfersDel = self.flu_path + 'del/' self.azu_host = host self.azu_port = int(port) self.azu_pathTransfers = '/www/.azureus/torrents/' if secure == '1': self.azu_secure = True else: self.azu_secure = False self.azu_user = username self.azu_pass = password self.needUpdate = 1 self.needUpdateAll = 1 self.needUpdateStat = 1 # more vars printMessage("flu-path: %s" % str(self.flu_path)) printMessage("azu-host: %s" % str(self.azu_host)) printMessage("azu-port: %s" % str(self.azu_port)) printMessage("azu-secure: %s" % str(self.azu_secure)) if len(self.azu_user) > 0: printMessage("azu-user: %s" % str(self.azu_user)) printMessage("azu-pass: %s" % str(self.azu_pass)) # initialize if not self.initialize(): printError( "there were problems initializing fluazu, shutting down...") self.shutdown() return 1 # main return self.main()
def execCommand(self, command): # op-code opCode = command[0] # q if opCode == "q": printMessage("command: stop-request, setting shutdown-flag...") return True # r elif opCode == "r": printMessage("command: reload-request, reloading...") self.reload() return False # u elif opCode == "u": if len(command) < 2: printMessage("invalid rate.") return False rateNew = command[1:] printMessage("command: setting upload-rate to %s ..." % rateNew) self.setRateU(int(rateNew)) return False # d elif opCode == "d": if len(command) < 2: printMessage("invalid rate.") return False rateNew = command[1:] printMessage("command: setting download-rate to %s ..." % rateNew) self.setRateD(int(rateNew)) return False # s elif opCode == "s": try: if len(command) < 3: raise workLoad = command[1:] sets = workLoad.split(":") setKey = sets[0] setVal = sets[1] if len(setKey) < 1 or len(setVal) < 1: raise printMessage("command: changing setting %s to %s ..." % (setKey, setVal)) if self.changeSetting(setKey, setVal): self.writeStatFile() return False except: printMessage("invalid setting.") return False # default else: printMessage("op-code unknown: %s" % opCode) return False
def run(self, path, host, port, secure, username, password): printMessage("fluazu starting up:") # set vars self.tf_path = path self.tf_pathTransfers = self.tf_path + '.transfers/' self.flu_path = self.tf_path + '.fluazu/' self.flu_fileCommand = self.flu_path + 'fluazu.cmd' self.flu_filePid = self.flu_path + 'fluazu.pid' self.flu_fileStat = self.flu_path + 'fluazu.stat' self.flu_pathTransfers = self.flu_path + 'cur/' self.flu_pathTransfersRun = self.flu_path + 'run/' self.flu_pathTransfersDel = self.flu_path + 'del/' self.azu_host = host self.azu_port = int(port) self.azu_pathTransfers = '/www/.azureus/torrents/' if secure == '1': self.azu_secure = True else: self.azu_secure = False self.azu_user = username self.azu_pass = password self.needUpdate = 1 self.needUpdateAll = 1 self.needUpdateStat = 1 # more vars printMessage("flu-path: %s" % str(self.flu_path)) printMessage("azu-host: %s" % str(self.azu_host)) printMessage("azu-port: %s" % str(self.azu_port)) printMessage("azu-secure: %s" % str(self.azu_secure)) if len(self.azu_user) > 0: printMessage("azu-user: %s" % str(self.azu_user)) printMessage("azu-pass: %s" % str(self.azu_pass)) # initialize if not self.initialize(): printError("there were problems initializing fluazu, shutting down...") self.shutdown() return 1 # main return self.main()
def statShutdown(self, download, error=None): # set some values self.sf.running = Transfer.TF_STOPPED self.sf.down_speed = "" self.sf.up_speed = "" self.sf.transferowner = self.tf.transferowner self.sf.seeds = "" self.sf.peers = "" # self.sf.sharing = "" # self.sf.seedlimit = "" try: # stats if not hasattr(download, 'getStats'): printMessage( "statShutdown() download has not available stats.") return False # stats try: stats = download.getStats() # done if download.isComplete(): self.sf.percent_done = str(100) self.sf.time_left = "Download Succeeded!" # not done else: try: pctf = float(stats.getCompleted()) pctf /= 10 pcts = "-" + str(pctf) pctf = float(pcts) pctf -= 100 self.sf.percent_done = str(pctf) except: printException() self.sf.time_left = "Transfer Stopped" # uptotal try: self.sf.uptotal = str(stats.getUploaded()) except: printException() # downtotal try: self.sf.downtotal = str(stats.getDownloaded()) except: printException() except: printException() # size try: self.sf.size = str(download.getTorrent().getSize()) except: printException() # error if error is not None: self.sf.time_left = "Error: %s" % error # write return self.sf.write() except: printException() return False
def checkDirs(self): # tf-paths if not os.path.isdir(self.tf_path): printError("Invalid path-dir: %s" % self.tf_path) return False if not os.path.isdir(self.tf_pathTransfers): printError("Invalid tf-transfers-dir: %s" % self.tf_pathTransfers) return False # flu-paths if not os.path.isdir(self.flu_path): try: printMessage("flu-main-path %s does not exist, trying to create ..." % self.flu_path) os.mkdir(self.flu_path, 0700) printMessage("done.") except: printError("Failed to create flu-main-path %s" % self.flu_path) return False if not os.path.isdir(self.flu_pathTransfers): try: printMessage("flu-transfers-path %s does not exist, trying to create ..." % self.flu_pathTransfers) os.mkdir(self.flu_pathTransfers, 0700) printMessage("done.") except: printError("Failed to create flu-main-path %s" % self.flu_pathTransfers) return False if not os.path.isdir(self.flu_pathTransfersRun): try: printMessage( "flu-transfers-run-path %s does not exist, trying to create ..." % self.flu_pathTransfersRun ) os.mkdir(self.flu_pathTransfersRun, 0700) printMessage("done.") except: printError("Failed to create flu-main-path %s" % self.flu_pathTransfersRun) return False if not os.path.isdir(self.flu_pathTransfersDel): try: printMessage( "flu-transfers-del-path %s does not exist, trying to create ..." % self.flu_pathTransfersDel ) os.mkdir(self.flu_pathTransfersDel, 0700) printMessage("done.") except: printError("Failed to create flu-main-path %s" % self.flu_pathTransfersDel) return False # return return True
def checkAzuConnection(self): # con valid try: if self.connection.is_connection_valid(): return True else: raise # con not valid except: # out printMessage( "connection to Azureus-server lost, reconnecting to %s:%d ..." % (self.azu_host, self.azu_port)) # try to reconnect for i in range(FluAzuD.MAX_RECONNECT_TRIES): # sleep time.sleep(i << 2) # out printMessage("reconnect-try %d ..." % (i + 1)) # establish con try: self.connection.establish_connection(True) printMessage("established connection to Azureus-server") except: printError( "Error establishing connection to Azureus-server") printException() continue # interface try: self.interface = self.connection.get_plugin_interface() except LinkError, error: printError("Error getting interface object") printException() self.interface = None continue # download-manager try: self.dm = None self.dm = self.interface.getDownloadManager() if self.dm is None: raise else: return True except: printError("Error getting Download-Manager object") continue # seems like azu is down. give up printError("no connection after %d tries, i give up, azu is gone" % FluAzuD.MAX_RECONNECT_TRIES) return False
def processRunRequests(self): printMessage("processing run-requests... %s" % self.flu_pathTransfersRun) # read requests requests = [] try: for fileName in os.listdir(self.flu_pathTransfersRun): inputFile = self.flu_pathTransfersRun + fileName outputFile = self.flu_pathTransfers + fileName # move file + add to requests try: # read file to mem f = open(inputFile, 'r') data = f.read() f.close() # delete os.remove(inputFile) # write file f = open(outputFile, 'w') f.write(data) f.flush() f.close() # add requests.append(fileName) except: printError("Failed to move file : %s" % inputFile) except: return False # process requests if len(requests) > 0: try: # update downloads #self.downloads = {} #self.updateDownloads() for fileName in requests: # add if needed if fileName not in self.downloads: try: # add torrent = self.addTransfer(fileName) except: printError( "exception when adding new transfer %s" % fileName) raise # downloads tries = 0 while torrent and ( tries < 10) and fileName not in self.downloads: download = self.dm.getDownload(torrent) if (torrent and download): self.downloads[fileName] = download self.needUpdate = 1 break else: printMessage( "download %s missing, update downloads..." % torrent) # sleep + increment time.sleep(0.5) tries += 1 # start transfer if fileName in self.downloads: try: transfer = Transfer(self.tf_pathTransfers, self.flu_pathTransfers, fileName) transfer.start(self.downloads[fileName]) except: printError( "exception when starting new transfer %s" % fileName) raise else: printError( "download %s not in azureus-downloads, cannot start it." % fileName) except: printMessage("exception when processing run-requests:") printException() # return return True
def loadCurrentNotInVuze(self): printMessage("loading missing transfers... %s" % self.flu_pathTransfers) needReload = 0 requests = [] try: vuzePathExists = os.path.isdir(self.azu_pathTransfers) for fileName in os.listdir(self.flu_pathTransfers): if os.path.isfile(self.tf_pathTransfers + fileName): if vuzePathExists and not os.path.isfile( self.azu_pathTransfers + fileName): # add to vuze (but dont start) #printMessage("adding missing transfer... %s" % fileName) #requests.append(fileName) try: os.remove(self.flu_pathTransfers + fileName + ".cmd") except: printMessage("ignoring existing cmd file... %s" % fileName) needReload = 1 else: if os.path.isfile(self.tf_pathTransfers + fileName + ".pid"): try: printMessage("cleaning transfer pid... %s" % fileName) os.remove(self.tf_pathTransfers + fileName + ".pid") except: printError( "exception when cleaning old transfer %s" % fileName + ".pid") continue except: return False # process requests if len(requests) > 0: try: # update downloads #self.downloads = {} #self.updateDownloads() for fileName in requests: # add if needed if fileName not in self.downloads: try: # add torrent = self.addTransfer(fileName) except: printError( "exception when adding new transfer %s" % fileName) raise # downloads tries = 0 while torrent and ( tries < 10) and fileName not in self.downloads: download = self.dm.getDownload(torrent) if (torrent and download): self.downloads[fileName] = download self.needUpdate = 1 break else: printMessage( "download %s missing, update downloads..." % torrent) # sleep + increment time.sleep(0.5) tries += 1 # start transfer if fileName in self.downloads: try: transfer = Transfer(self.tf_pathTransfers, self.flu_pathTransfers, fileName) #transfer.start(self.downloads[fileName]) except: printError( "exception when starting new transfer %s" % fileName) raise else: printError( "download %s not in azureus-downloads, cannot start it." % fileName) except: printMessage("exception when processing run-requests:") printException() if needReload == 1: self.reload() # return return True
def initialize(self): # flu # check dirs if not self.checkDirs(): printError("Error checking dirs. path: %s" % self.tf_path) return False # write pid-file self.pid = (str(os.getpid())).strip() printMessage("writing pid-file %s (%s)" % (self.flu_filePid, self.pid)) try: pidFile = open(self.flu_filePid, "w") pidFile.write(self.pid + "\n") pidFile.flush() pidFile.close() except: printError("Failed to write pid-file %s (%s)" % (self.flu_filePid, self.pid)) return False # delete command-file if exists if os.path.isfile(self.flu_fileCommand): try: printMessage("removing command-file %s ..." % self.flu_fileCommand) os.remove(self.flu_fileCommand) except: printError("Failed to delete commandfile %s" % self.flu_fileCommand) return False # load transfers self.loadTransfers() # azu printMessage("connecting to Azureus-Server (%s:%d)..." % (self.azu_host, self.azu_port)) # set connection details connection_details = {} connection_details["host"] = self.azu_host connection_details["port"] = self.azu_port connection_details["secure"] = self.azu_secure if len(self.azu_user) > 0: connection_details["user"] = self.azu_user connection_details["password"] = self.azu_pass # make connection try: self.connection = make_connection(**connection_details) self.connection.is_persistent_connection = True self.interface = self.connection.get_plugin_interface() except: printError("could not connect to Azureus-Server") printException() return False # azureus version self.azu_version_str = str(self.connection.get_azureus_version()) self.azu_version_str = self.azu_version_str.replace(", ", ".") self.azu_version_str = self.azu_version_str.replace("(", "") self.azu_version_str = self.azu_version_str.replace(")", "") printMessage("connected. Azureus-Version: %s" % self.azu_version_str) # download-manager self.dm = self.interface.getDownloadManager() if self.dm is None: printError("Error getting Download-Manager object") return False # write stat-file and return return self.writeStatFile()
def loadCurrentNotInVuze(self): printMessage("loading missing transfers... %s" % self.flu_pathTransfers) needReload = 0 requests = [] try: vuzePathExists = os.path.isdir(self.azu_pathTransfers); for fileName in os.listdir(self.flu_pathTransfers): if os.path.isfile(self.tf_pathTransfers + fileName): if vuzePathExists and not os.path.isfile(self.azu_pathTransfers + fileName): # add to vuze (but dont start) #printMessage("adding missing transfer... %s" % fileName) #requests.append(fileName) try: os.remove(self.flu_pathTransfers + fileName + ".cmd") except: printMessage("ignoring existing cmd file... %s" % fileName) needReload = 1 else: if os.path.isfile(self.tf_pathTransfers + fileName + ".pid"): try: printMessage("cleaning transfer pid... %s" % fileName) os.remove(self.tf_pathTransfers + fileName + ".pid") except: printError("exception when cleaning old transfer %s" % fileName+ ".pid") continue except: return False # process requests if len(requests) > 0: try: # update downloads #self.downloads = {} #self.updateDownloads() for fileName in requests: # add if needed if fileName not in self.downloads: try: # add torrent = self.addTransfer(fileName) except: printError("exception when adding new transfer %s" % fileName) raise # downloads tries = 0 while torrent and (tries < 10) and fileName not in self.downloads: download = self.dm.getDownload(torrent) if (torrent and download): self.downloads[fileName] = download self.needUpdate=1 break else: printMessage("download %s missing, update downloads..." % torrent) # sleep + increment time.sleep(0.5) tries += 1 # start transfer if fileName in self.downloads: try: transfer = Transfer(self.tf_pathTransfers, self.flu_pathTransfers, fileName) #transfer.start(self.downloads[fileName]) except: printError("exception when starting new transfer %s" % fileName) raise else: printError("download %s not in azureus-downloads, cannot start it." % fileName) except: printMessage("exception when processing run-requests:") printException() if needReload == 1: self.reload() # return return True
def run(self, path, host, port, secure, username, password): printMessage("fluazu starting up:") # set vars self.tf_path = path self.tf_pathTransfers = self.tf_path + ".transfers/" self.flu_path = self.tf_path + ".fluazu/" self.flu_fileCommand = self.flu_path + "fluazu.cmd" self.flu_filePid = self.flu_path + "fluazu.pid" self.flu_fileStat = self.flu_path + "fluazu.stat" self.flu_pathTransfers = self.flu_path + "cur/" self.flu_pathTransfersRun = self.flu_path + "run/" self.flu_pathTransfersDel = self.flu_path + "del/" self.azu_host = host self.azu_port = int(port) if secure == "1": self.azu_secure = True else: self.azu_secure = False self.azu_user = username self.azu_pass = password # more vars printMessage("flu-path: %s" % str(self.flu_path)) printMessage("azu-host: %s" % str(self.azu_host)) printMessage("azu-port: %s" % str(self.azu_port)) printMessage("azu-secure: %s" % str(self.azu_secure)) if len(self.azu_user) > 0: printMessage("azu-user: %s" % str(self.azu_user)) printMessage("azu-pass: %s" % str(self.azu_pass)) # initialize if not self.initialize(): printError("there were problems initializing fluazu, shutting down...") self.shutdown() return 1 # main return self.main()
def statShutdown(self, download, error=None): # set some values self.sf.running = Transfer.TF_STOPPED self.sf.down_speed = "" self.sf.up_speed = "" self.sf.transferowner = self.tf.transferowner self.sf.seeds = "" self.sf.peers = "" # self.sf.sharing = "" # self.sf.seedlimit = "" try: # stats if not hasattr(download, "getStats"): printMessage("statShutdown() download has not available stats.") return False # stats try: stats = download.getStats() # done if download.isComplete(): self.sf.percent_done = str(100) self.sf.time_left = "Download Succeeded!" # not done else: try: pctf = float(stats.getCompleted()) pctf /= 10 pcts = "-" + str(pctf) pctf = float(pcts) pctf -= 100 self.sf.percent_done = str(pctf) except: printException() self.sf.time_left = "Transfer Stopped" # uptotal try: self.sf.uptotal = str(stats.getUploaded()) except: printException() # downtotal try: self.sf.downtotal = str(stats.getDownloaded()) except: printException() except: printException() # size try: self.sf.size = str(download.getTorrent().getSize()) except: printException() # error if error is not None: self.sf.time_left = "Error: %s" % error # write return self.sf.write() except: printException() return False
def execCommand(self, command): # op-code opCode = command[0] # q if opCode == 'q': printMessage("command: stop-request, setting shutdown-flag...") return True # r elif opCode == 'r': printMessage("command: reload-request, reloading...") self.reload() return False # u elif opCode == 'u': if len(command) < 2: printMessage("invalid rate.") return False rateNew = command[1:] printMessage("command: setting upload-rate to %s ..." % rateNew) self.setRateU(int(rateNew)) return False # d elif opCode == 'd': if len(command) < 2: printMessage("invalid rate.") return False rateNew = command[1:] printMessage("command: setting download-rate to %s ..." % rateNew) self.setRateD(int(rateNew)) return False # s elif opCode == 's': try: if len(command) < 3: raise workLoad = command[1:] sets = workLoad.split(":") setKey = sets[0] setVal = sets[1] if len(setKey) < 1 or len(setVal) < 1: raise printMessage("command: changing setting %s to %s ..." % (setKey, setVal)) if self.changeSetting(setKey, setVal): self.writeStatFile() return False except: printMessage("invalid setting.") return False # default else: printMessage("op-code unknown: %s" % opCode) return False
def main(self): nloop = 0 self.getActiveUsers() # main-loop while self.running > 0: actifs = self.getActiveUsers() if actifs == 0: printMessage("flubart inactive, sleeping (no tf_log HIT) ...") while (actifs == 0): time.sleep(2) actifs = self.getActiveUsers() printMessage("flubart wake up (tf_log HIT=%d) ..." % actifs) printMessage("loop") nloop = (nloop + 1) % 400 if (nloop == 50): self.needUpdateAll = 1 if (nloop % 50) == 0: self.needUpdate = 1 if (nloop % 10) == 0: self.needUpdateStat = 1 # check if connection still valid, shutdown if it is not if not self.checkAzuConnection(): # shutdown self.shutdown() # return return 1 # update downloads (slow) if (self.needUpdate == 1): printMessage("update downloads") self.updateDownloads() if (nloop == 1): self.loadCurrentNotInVuze() # update downloading torrents (slow) if (self.needUpdateStat == 1): # update transfers printMessage("update stat") for transfer in self.transfers: if transfer.name in self.downloads: if self.needUpdateAll == 1 or transfer.needFastUpdate( ): # update transfer.update(self.downloads[transfer.name]) #printMessage(transfer.name + " %d " % transfer.state_azu) else: if "_" + transfer.name in self.downloads: printMessage(" found lost transfer: " + transfer.name + " = _" + transfer.name) transfer.name = "_" + transfer.name transfer.update(self.downloads[transfer.name]) else: if (transfer.state_azu != 7): printMessage(" not in transfers: " + transfer.name + " %d " % transfer.state_azu) #self.downloads[tfile] #for download in self.downloads: # printMessage(download) self.needUpdateStat = 0 self.needUpdateAll = 0 #printMessage("processCommandStack") # inner loop which check if there is a command file to run for i in range(15): # process daemon command stack (fast) CTRL+C ? if self.processCommandStack(): # shutdown self.running = 0 break # process transfers command stacks for transfer in self.transfers: if transfer.isRunning(): if transfer.processCommandStack( self.downloads[transfer.name]): self.needUpdateStat = 1 # update downloads (too slow) self.needUpdate = 1 # sleep time.sleep(0.1) printMessage("shutdown") # shutdown self.shutdown() # return return 0
def main(self): nloop = 0 self.getActiveUsers() # main-loop while self.running > 0: actifs = self.getActiveUsers() if actifs == 0: printMessage("flubart inactive, sleeping (no tf_log HIT) ...") while (actifs == 0): time.sleep(2) actifs = self.getActiveUsers() printMessage("flubart wake up (tf_log HIT=%d) ..." % actifs) printMessage("loop") nloop = (nloop + 1) % 400 if (nloop == 50): self.needUpdateAll = 1 if (nloop % 50) == 0: self.needUpdate = 1 if (nloop % 10) == 0: self.needUpdateStat = 1 # check if connection still valid, shutdown if it is not if not self.checkAzuConnection(): # shutdown self.shutdown() # return return 1 # update downloads (slow) if (self.needUpdate == 1): printMessage("update downloads") self.updateDownloads() if (nloop == 1): self.loadCurrentNotInVuze() # update downloading torrents (slow) if (self.needUpdateStat == 1): # update transfers printMessage("update stat") for transfer in self.transfers: if transfer.name in self.downloads: if self.needUpdateAll == 1 or transfer.needFastUpdate(): # update transfer.update(self.downloads[transfer.name]) #printMessage(transfer.name + " %d " % transfer.state_azu) else: if "_"+transfer.name in self.downloads: printMessage(" found lost transfer: " + transfer.name + " = _" + transfer.name) transfer.name = "_"+transfer.name transfer.update(self.downloads[transfer.name]) else: if (transfer.state_azu != 7): printMessage(" not in transfers: " + transfer.name + " %d " % transfer.state_azu) #self.downloads[tfile] #for download in self.downloads: # printMessage(download) self.needUpdateStat = 0 self.needUpdateAll = 0 #printMessage("processCommandStack") # inner loop which check if there is a command file to run for i in range(15): # process daemon command stack (fast) CTRL+C ? if self.processCommandStack(): # shutdown self.running = 0 break; # process transfers command stacks for transfer in self.transfers: if transfer.isRunning(): if transfer.processCommandStack(self.downloads[transfer.name]): self.needUpdateStat = 1; # update downloads (too slow) self.needUpdate = 1; # sleep time.sleep(0.1) printMessage("shutdown") # shutdown self.shutdown() # return return 0
def checkDirs(self): # tf-paths if not os.path.isdir(self.tf_path): printError("Invalid path-dir: %s" % self.tf_path) return False if not os.path.isdir(self.tf_pathTransfers): printError("Invalid tf-transfers-dir: %s" % self.tf_pathTransfers) return False # flu-paths if not os.path.isdir(self.flu_path): try: printMessage( "flu-main-path %s does not exist, trying to create ..." % self.flu_path) os.mkdir(self.flu_path, 0700) printMessage("done.") except: printError("Failed to create flu-main-path %s" % self.flu_path) return False if not os.path.isdir(self.flu_pathTransfers): try: printMessage( "flu-transfers-path %s does not exist, trying to create ..." % self.flu_pathTransfers) os.mkdir(self.flu_pathTransfers, 0700) printMessage("done.") except: printError("Failed to create flu-main-path %s" % self.flu_pathTransfers) return False if not os.path.isdir(self.flu_pathTransfersRun): try: printMessage( "flu-transfers-run-path %s does not exist, trying to create ..." % self.flu_pathTransfersRun) os.mkdir(self.flu_pathTransfersRun, 0700) printMessage("done.") except: printError("Failed to create flu-main-path %s" % self.flu_pathTransfersRun) return False if not os.path.isdir(self.flu_pathTransfersDel): try: printMessage( "flu-transfers-del-path %s does not exist, trying to create ..." % self.flu_pathTransfersDel) os.mkdir(self.flu_pathTransfersDel, 0700) printMessage("done.") except: printError("Failed to create flu-main-path %s" % self.flu_pathTransfersDel) return False # return return True
def processRunRequests(self): printMessage("processing run-requests...") # read requests requests = [] try: for fileName in os.listdir(self.flu_pathTransfersRun): inputFile = self.flu_pathTransfersRun + fileName outputFile = self.flu_pathTransfers + fileName # move file + add to requests try: # read file to mem f = open(inputFile, "r") data = f.read() f.close() # delete os.remove(inputFile) # write file f = open(outputFile, "w") f.write(data) f.flush() f.close() # add requests.append(fileName) except: printError("Failed to move file : %s" % inputFile) except: return False # process requests if len(requests) > 0: try: # update downloads self.downloads = {} self.updateDownloads() for fileName in requests: # add if needed if fileName not in self.downloads: try: # add self.addTransfer(fileName) except: printError("exception when adding new transfer %s" % fileName) raise # downloads tries = 0 while tries < 5 and fileName not in self.downloads: # if fileName not in self.downloads: printMessage("download %s missing, update downloads..." % fileName) self.updateDownloads() # sleep + increment time.sleep(1) tries += 1 # start transfer if fileName in self.downloads: try: transfer = Transfer(self.tf_pathTransfers, self.flu_pathTransfers, fileName) transfer.start(self.downloads[fileName]) except: printError("exception when starting new transfer %s" % fileName) raise else: printError("download %s not in azureus-downloads, cannot start it." % fileName) except: printMessage("exception when processing run-requests:") printException() # return return True
def initialize(self): # flu # check dirs if not self.checkDirs(): printError("Error checking dirs. path: %s" % self.tf_path) return False # write pid-file self.pid = (str(os.getpid())).strip() printMessage("writing pid-file %s (%s)" % (self.flu_filePid, self.pid)) try: pidFile = open(self.flu_filePid, 'w') pidFile.write(self.pid + "\n") pidFile.flush() pidFile.close() except: printError("Failed to write pid-file %s (%s)" % (self.flu_filePid, self.pid)) return False # delete command-file if exists if os.path.isfile(self.flu_fileCommand): try: printMessage("removing command-file %s ..." % self.flu_fileCommand) os.remove(self.flu_fileCommand) except: printError("Failed to delete commandfile %s" % self.flu_fileCommand) return False # load transfers self.loadTransfers() # azu printMessage("connecting to Azureus-Server (%s:%d)..." % (self.azu_host, self.azu_port)) # set connection details connection_details = {} connection_details['host'] = self.azu_host connection_details['port'] = self.azu_port connection_details['secure'] = self.azu_secure if len(self.azu_user) > 0: connection_details['user'] = self.azu_user connection_details['password'] = self.azu_pass # make connection try: self.connection = make_connection(**connection_details) self.connection.is_persistent_connection = True self.interface = self.connection.get_plugin_interface() except: printError("could not connect to Azureus-Server") printException() return False # azureus version self.azu_version_str = str(self.connection.get_azureus_version()) self.azu_version_str = self.azu_version_str.replace(", ", ".") self.azu_version_str = self.azu_version_str.replace("(", "") self.azu_version_str = self.azu_version_str.replace(")", "") printMessage("connected. Azureus-Version: %s" % self.azu_version_str) # download-manager self.dm = self.interface.getDownloadManager() if self.dm is None: printError("Error getting Download-Manager object") return False # write stat-file and return return self.writeStatFile()