def sendRequest(self): if not self._user.hub: self.setStatus(self.STATUS_ERROR) DCWorker.getWorker().getQueue().removeItem(self) return self._user.hub.requireConnection(self._user.nick)
def __init__(self, user): if not user.hub: raise UserZombieError EventGenerator.__init__(self) DCFileList.__init__(self) self._user = user item = DCItem() item.userNick = user.nick item.path = "MyList.DcLst" self.lock.acquire() self.num = DCUserList.tmpnum DCUserList.tmpnum += 1 self.lock.release() filename = DCWorker.getWorker().getSettings().download + os.sep + self.FILENAME_TEMPLATE % self.num try: os.unlink(filename) except OSError: pass DCQueueItem.__init__(self, item, self.FILENAME_TEMPLATE % self.num) self.completed = 0 self._status = self.STATUS_INIT DCWorker.getWorker().getQueue().registerListener(self)
def __init__(self): self.lock = Lock() self.list = [] retr = DCHublistRetriever() retr.registerListener(self) self.lock.acquire() DCWorker.getWorker().addJob(retr)
def parseHandshakeCmd(self, cmd): if cmd[0] != "$": return 0 cmd = cmd[1:] try: pos = cmd.index(" ") cmdname = cmd[:pos] except ValueError: return 0 if cmdname == "MyNick": self._remoteNick = cmd[pos+1:] elif cmdname == "Lock": if self._remoteNick == None: return 0 key = solveChallenge(cmd[pos+1:]) if len(key) == 0: return 0 item, source = DCWorker.getWorker().getQueue().getItemByNick(self._remoteNick) if item == None: self.sendCmd("Direction", "Upload", "30000") self._type = DCXfer.TYPE_UPLOAD else: self.sendCmd("Direction", "Download", "30000") self._type = DCXfer.TYPE_DOWNLOAD self.sendCmd("Key", key) elif cmdname == "Key": pass elif cmdname == "Direction": try: direction = cmd[pos+1:cmd.rindex(' ')] except ValueError: return 0 if self.type == DCXfer.TYPE_DOWNLOAD: if direction != "Upload": return 0 else: if direction != "Download": return 0 x = DCWorker.getWorker().getXferListener() if self.type == DCXfer.TYPE_DOWNLOAD: x.createDownload(self) else: x.createUpload(self) self.setStatus(DCXfer.STATUS_STOPPING+1) return 0 elif cmdname == "Capabilities": #DCTC specific command; ignore it return 1 else: return 0 return 1
def stop(self): if self._status == 1: DCWorker.getWorker().getSearchWorker().deregisterSearch(self) self._status = 2 self.lock.acquire() for listener in self.listeners: listener.onSearchStop(self) self.lock.release()
def setStatusRunning(self, source): self.lock.acquire() if self._status != self.STATUS_WAITING: retval = 0 else: self._status = self.STATUS_RUNNING self._xfer = source retval = 1 self.lock.release() if retval: DCWorker.getWorker().getQueue().onItemStatus(self) return retval
def removeItem(self, item): try: self.opLock.acquire() self._items.remove(item) DCWorker.getWorker().xferListener.stopXfer(item) self.saveTime = time.time() + self.SAVE_DELAY self.opLock.release() except ValueError: self.opLock.release() return self.fireEvent(self.EVENT_REMOVED, item)
def setStatusCompleted(self, source): self.lock.acquire() if self._xfer != source: retval = 0 else: self._status = self.STATUS_COMPLETED self._progress = 100 self._xfer = None retval = 1 self.lock.release() if retval: DCWorker.getWorker().getQueue().onItemStatus(self) return retval
def parseCmd(self, cmd): if cmd[0] != "$": return 0 cmd = cmd[1:] try: pos = cmd.index(" ") cmdname = cmd[:pos] except ValueError: #MaxedOut return 0 if cmdname == "FileLength": if not self._item.setStatusRunning(self): return 0 try: size = long(cmd[pos+1:]) if self._item.size == -1L: self._item.setSize(size) self._sizeRemaining = size elif size != self._item.size: self._item.removeSource(self._remoteNick) raise ValueError() except ValueError: return 0 self.sendCmd("Send") try: self.file = open(self._item.getPath(), "a+b") self.file.seek(-self.rollbackCounter, 2) if self._sizeRemaining != self._item.size - self.file.tell(): raise IOError() except IOError: return 0 self.setStatus(3) self.notified = 1 DCWorker.getWorker().getXferListener().onNewXfer(self) elif cmdname == "Error": self._item.removeSource(self._remoteNick) return 0 else: return 0 return 1
def sendMsg(self, msg): if self.address != self.hub.getAddress(): #TODO: alert user return self.hub.sendMsg(msg, self.nick) self.appendMsg('<%s> %s\n' % (DCWorker.getWorker().getUser().nick, msg))
def __init__(self, sources=None): EventGenerator.__init__(self) if sources == None: sources = DCWorker.getWorker().getSettings().hublists self.sources = [] for addr in sources: i = urlparse(addr) if i[0] != "http": raise IllegalProtocolError() pos = i[1].rfind(":") if pos != -1: try: host = (i[1][:pos], int(i[1][pos + 1])) except ValueError: raise IllegalPortError() else: host = (i[1], 80) self.sources.append((host, i[2])) self.status = 0 self._hubs = {} self.sock = None self.timestamp = 0
def __init__(self, item, path = None): if isinstance(item, DCItem): self._sources = [DCQueueItemSource(item.userNick, item.path)] base = DCWorker.getWorker().getSettings().download if path: self._path = os.path.abspath(base + os.sep + path) if len(self._path) < len(base): raise IllegalLocalPathError if self._path[:len(base)] != base: raise IllegalLocalPathError else: self._path = base + os.sep + item.path[item.path.rindex('\\')+1:] self._status = self.STATUS_WAITING self._progress = 0 elif isinstance(item, DCSerializedQueueItem): self._path = item.path self._status = item.status self._progress = item.progress self._sources = item.sources else: raise IllegalItem self._size = item.size self._xfer = None self._timestamp = 0 self._retries = 0 self.lock = Lock()
def buildInfo(self): user = DCWorker.getWorker().getUser() info = "$ALL " + self.userNick + " " if user.description != None: info += user.description info += "$ $" if user.connection == DCUser.CONN_56K: info += "56Kbps" elif user.connection == DCUser.CONN_SATELLITE: info += "Satellite" elif user.connection == DCUser.CONN_DSL: info += "DSL" elif user.connection == DCUser.CONN_CABLE: info += "Cable" elif user.connection == DCUser.CONN_T1: info += "LAN(T1)" elif user.connection == DCUser.CONN_T3: info += "LAN(T3)" info += chr(self.userStatus) + "$" if user.email != None: info += user.email info += "$" if user.share == -1: info += "0" else: info += str(user.share) info += "$" return info
def OnInit(self): global wnd worker = DCWorker.getWorker() try: worker.loadSettings("settings.xml") except ParseError, e: print e return 0
def requireConnection(self, nick): self.opLock.acquire() worker = DCWorker.getWorker() if worker.getSettings().active: self.cmdQueue.append('$ConnectToMe %s %s:%d|' % (nick, worker.getLocalAddress(), worker.getSettings().port)) else: self.cmdQueue.append('$RevConnectToMe %s %s|' % (self.userNick, nick)) self.opLock.release()
def poll(self): if self.status == 0: if self.sock != None: try: conn, addr = self.sock.accept() DCWorker.getWorker().addJob(DCXfer(AsyncSocket(conn))) except error: pass elif self.status == 1: if self.sock != None: self.sock.close() self.status = 2 return 1 else: return 1 return 0
def poll(self): if self._status == self.STATUS_INIT: self._status = self.STATUS_WAITING DCWorker.getWorker().getQueue().addQueueItem(self) elif self._status >= self.STATUS_ERROR: if self.num < 0: return 1 if self._status == self.STATUS_ERROR or self._status == self.STATUS_STOPPED: DCWorker.getWorker().getQueue().removeItem(self) filename = DCWorker.getWorker().getSettings().download + os.sep + self.FILENAME_TEMPLATE % self.num try: os.unlink(filename) except OSError: pass self.num = -1 return 1 return 0
def __init__(self, parent, id): wxPanel.__init__(self, parent, id) self.xfers = [] self.lock = Lock() self.sortAlgos = [ None, (DCXfer.getType, icmp), (self.getXferPath, cmp), (self.getXferProgress, icmp), (DCXfer.getSpeed, icmp), (self.xferEta, cmp), (self.xferEta, icmp), (DCXfer.getSpeed, cmp), (self.getXferProgress, cmp), (self.getXferPath, icmp), (DCXfer.getType, cmp) ] self.sortAlgo = 3 self.list = wxListCtrl(self, 1, style = wxLC_REPORT | wxLC_VRULES) self.menu = wxMenu() self.list.InsertColumn(0, "Type") self.list.InsertColumn(1, "File") self.list.InsertColumn(2, "Progress", wxLIST_FORMAT_RIGHT) self.list.InsertColumn(3, "Speed", wxLIST_FORMAT_RIGHT) self.list.InsertColumn(4, "ETA", wxLIST_FORMAT_RIGHT) self.list.SetColumnWidth(0, 20) vLayout = wxBoxSizer(wxVERTICAL) vLayout.Add(self.list, 1, wxEXPAND) self.SetSizer(vLayout) self.Layout() EVT_LIST_COL_CLICK(self, 1, self.setSortAlgo) EVT_LIST_ITEM_ACTIVATED(self.list, 1, self.closeXfer) self.Connect(1, 1, wxEVT_NULL, self.insertXfer) self.Connect(2, 2, wxEVT_NULL, self.removeXfer) self.Connect(3, 3, wxEVT_NULL, self.updateXfers) DCWorker.getWorker().getXferListener().registerListener(self)
def onMsg(self, event): text = self.msg.GetValue() if len(text) == 0: return if text[0] == '/': if text[1:] == 'away': hub = self.info.getJob() hub.setAway(not (hub.userStatus & DCHub.USER_AWAY_FLAG)) elif text[1:] == 'info': self.info.getJob().updateInfo() elif text[1:] == 'refresh': DCWorker.getWorker().refreshLocalList() else: self.addLogRow((DCHub.LOG_ERROR, 'Unknown command \'%s\'.' % text[1:])) elif text[0] == '<': try: pos = text.find('>') if pos == -1: dialog = wxMessageDialog(self, "Invalid private chat text.", "Error", wxICON_ERROR) dialog.ShowModal() raise 0 nick = text[1:pos] if self.info.getJob().getUserByNick(nick) == None: dialog = wxMessageDialog(self, "No user with that nick.", "Error", wxICON_ERROR) dialog.ShowModal() raise 0 text = text[pos+1:] except: text = None self.msg.SetValue('') if text: getMainWnd().getChat(nick, self.info.getJob()).sendMsg(text) return else: self.info.getJob().sendMsg(text) self.msg.SetValue('')
def __init__(self, parent, id): wxPanel.__init__(self, parent, id) self.sortAlgo = 3 self.sortAlgos = [ None, (DCQueueItem.getPath, cmp), (DCQueueItem.getStatus, icmp), (DCQueueItem.getProgress, icmp), (DCQueueItem.getSize, icmp), (DCQueueItem.getSize, cmp), (DCQueueItem.getProgress, cmp), (DCQueueItem.getStatus, cmp), (DCQueueItem.getPath, icmp) ] self.items = [] self.list = wxListCtrl(self, 1, style = wxLC_REPORT | wxLC_SINGLE_SEL | wxLC_VRULES) self.list.InsertColumn(0, "File") self.list.InsertColumn(1, "Status") self.list.InsertColumn(2, "Progress", wxLIST_FORMAT_RIGHT) self.list.InsertColumn(3, "Size", wxLIST_FORMAT_RIGHT) vLayout = wxBoxSizer(wxVERTICAL) vLayout.Add(self.list, 1, wxEXPAND) self.SetSizer(vLayout) self.Layout() EVT_LIST_COL_CLICK(self, 1, self.setSortAlgo) EVT_LIST_ITEM_ACTIVATED(self, 1, self.onClose) self.Connect(1, 1, wxEVT_NULL, self.insertItem) self.Connect(2, 2, wxEVT_NULL, self.updateItem) self.Connect(3, 3, wxEVT_NULL, self.removeItem) queue = DCWorker.getWorker().getQueue() for item in queue.getItems(): self.onNewItem(queue, item) queue.registerListener(self) DCWorker.getWorker().getXferListener().registerListener(self)
def onResultOptions(self, event): pnt = event.GetPoint() result = self.results[event.GetIndex()] self.list.SetItemState(event.GetIndex(), wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED) menu = wxMenu() menu.Append(10000, "Queue") menu.Append(10001, "Path") alt, items, pos = wxMenu(), [], 0 for item in DCWorker.getWorker().getQueue().getItems(): if item.getStatus() != DCQueueItem.STATUS_COMPLETED and result.size == item.getSize(): alt.Append(pos, os.path.basename(item.getPath())) items.append(item) pos += 1 if pos > 0: menu.AppendMenu(1, "Source for", alt) self.list.PopupMenu(menu, pnt) if self.menuId == -1: return elif self.menuId == 10000: try: DCWorker.getWorker().getQueue().addItem(result) except ItemAlreadyAddedError: dialog = wxMessageDialog(self, "Item already queued.", "Error", wxICON_ERROR) dialog.ShowModal() elif self.menuId == 10001: wxMessageBox(result.path) else: try: items[self.menuId].addSource(result) except ExistingSourceError: pass except ItemNotMatching: dialog = wxMessageDialog(self, "Source is not matching.", "Error", wxICON_ERROR) dialog.ShowModal() self.menuId = -1
def getOnlineSources(self): self.lock.acquire() nicks = [] for source in self._sources: nicks.append(source._nick) self.lock.release() aux = [] for nick in nicks: for user in DCWorker.getWorker().getUsersByNick(nick): aux.append(user) return aux
def start(self, nodelay=0): if self._pattern == None: raise PatternNotSetError() res = DCWorker.getWorker().getSearchWorker().registerSearch(self, nodelay) if res: self.lock.acquire() for listener in self.listeners: listener.onSearchStart(self) self.lock.release() self._status = 1 return res
def addSource(self, item): if self._size != item.size: raise ItemNotMatching self.lock.acquire() for source in self._sources: if source.nick == item.userNick and source.path == item.path: self.lock.release() raise ExistingSourceError self._sources.append(DCQueueItemSource(item.userNick, item.path)) self._timestamp = 0 statusUpd = 0 if self._status == DCQueueItem.STATUS_ERROR: self._status = DCQueueItem.STATUS_WAITING statusUpd = 1 self.lock.release() DCWorker.getWorker().getQueue().onItemSourceChange(self) if statusUpd: DCWorker.getWorker().getQueue().onItemStatus(self)
def parseList(self): try: filename = DCWorker.getWorker().getSettings().download + os.sep + self.FILENAME_TEMPLATE % self.num r = LineReader(He3Decoder().decode(filename)) self._list = self.populate(r, 0, self) self.setStatus(self.STATUS_COMPLETED) except IOError: self.setStatus(self.STATUS_ERROR) except ValueError: self.setStatus(self.STATUS_ERROR) except He3FormatError: self.setStatus(self.STATUS_ERROR)
def poll(self): if self.status == 0: try: self.sock.poll() if self.sock.isConnected(): self.sendCmd("MyNick", DCWorker.getWorker().getUser().nick) self.sendCmd("Lock", "N*o=@:Tl,valyp=6d3weUQbDBV\U,W(9^?fb.dsqEn);3&7+, Pk=%@h0(oH]Nk(UZ)XE") self.setStatus(1) except socket.error: self.setStatus(self.STATUS_STOPPING) return 0 elif self.status == 1: if time.time() - self.timer > self.HANDSHAKE_TIMEOUT: self.setStatus(self.STATUS_STOPPING) return 0 try: self.sock.poll() if not self.sock.connected: raise socket.error except socket.error: self.setStatus(self.STATUS_STOPPING) return 0 data = self.sock.recv() cmds = data.split("|") if self._remoteNick == None and len(cmds) > 0 and len(cmds[0]) > 0 and cmds[0][0] != '$': del cmds[0] for i in cmds: if len(i) > 0: if not self.parseHandshakeCmd(i): self.setStatus(self.STATUS_STOPPING) return 0 elif self.status == DCXfer.STATUS_STOPPING: try: self.sock.close() if not self.sock.poll(): return 0 except socket.error: pass self.status = DCXfer.STATUS_STOPPING + 1 return 1 else: return 1 return 0
def __init__(self, addr): EventGenerator.__init__(self) self._addr = None self._status = 0 self.logged = 0 self.userNick = DCWorker.getWorker().user.nick self.userStatus = DCHub.USER_NORMAL self.delay = None self._users = {} self._log = [] self.opLock = Lock() self._addr = self.parseAddress(addr) self.reset()
def startSearch(self, search, active): self.opLock.acquire() worker = DCWorker.getWorker() cmd = '$Search ' if active: cmd += '%s:%d ' % (worker.getLocalAddress(), worker.getSettings().port) else: cmd += 'Hub:%s ' % self.userNick cmd += 'F?F?0?1?' for i in search.getPattern().split(' '): cmd += i + "$" self.cmdQueue.append(cmd[:-1] + '|') self.opLock.release()
def poll(self): if self.status == 1: self._item, source = DCWorker.getWorker().getQueue().getItemByNick(self._remoteNick) if self._item == None or self._item.status != DCQueueItem.STATUS_WAITING: self.setStatus(DCXfer.STATUS_STOPPING) return 0 try: file = open(self._item.getPath(), "rb") file.seek(0, 2) restart = file.tell() file.close() except IOError: restart = 0 if self._item.size == restart: self._item.setStatusCompleted(self) self.setStatus(DCXfer.STATUS_STOPPING) return 0 self.rollbackCounter = min(self.ROLLBACK, restart) restart -= self.rollbackCounter self.sendCmd("Get", source.path + "$" + str(restart+1)) self._sizeRemaining = self._item.size - restart self.timer = time.time() self.setStatus(2) elif self.status == 2: if time.time() - self.timer > self.HANDSHAKE_TIMEOUT: self.setStatus(DCXfer.STATUS_STOPPING) return 0 try: self.sock.poll() if not self.sock.connected: raise socket.error except socket.error, e: self.setStatus(DCXfer.STATUS_STOPPING) return 0 data = self.sock.recv() cmds = data.split("|") for i in cmds: if len(i) > 0: if not self.parseCmd(i): self.setStatus(DCXfer.STATUS_STOPPING) return 0
def removeSource(self, nick): self.lock.acquire() aux = None for i in range(0, len(self._sources)): if self._sources[i].nick == nick: aux = self._sources[i] del self._sources[i] break self.lock.release() worker = DCWorker.getWorker() if aux: worker.xferListener.stopXfer(self, aux) if len(self._sources) == 0: self._status = self.STATUS_ERROR worker.getQueue().onItemStatus(self) worker.getQueue().onItemSourceChange(self)