def MakeNewModel(self, list): self.shares = list self.selected_folder = None self.selected_files = [] self.directories.clear() self.files.clear() self.DirStore.clear() # Compute the number of shared dirs and total size self.totalsize = 0 for dir, files in self.shares: for filedata in files: if filedata[2] < 18446744000000000000: self.totalsize += filedata[2] else: print("Unbelievable filesize: %s, %s" % (HumanSize(filedata[2]), repr(filedata))) self.AmountShared.set_text(_("Shared: %s") % HumanSize(self.totalsize)) self.NumDirectories.set_text(_("Dirs: %s") % len(self.shares)) # Generate the directory tree and select first directory currentdir = self.BrowseGetDirs() sel = self.FolderTreeView.get_selection() sel.unselect_all() if currentdir in self.directories: path = self.DirStore.get_path(self.directories[currentdir]) if path is not None: sel.select_path(path) self.FolderTreeView.set_sensitive(True) self.FileTreeView.set_sensitive(True) self.SaveButton.set_sensitive(True) if self.ExpandButton.get_active(): self.FolderTreeView.expand_all() else: self.FolderTreeView.collapse_all()
def _addsharedir(self, directory): subdirs, files, size, extensions = dirstats(directory[1]) exts = [] for ext, count in extensions.items(): exts.append((count, ext)) exts.sort(reverse=True) extstring = ", ".join( ["%s %s" % (count, ext) for count, ext in exts[:5]]) if len(exts) > 5: extstring += ", ..." GLib.idle_add(self._updatedirstats, directory, HumanSize(size), files, subdirs, extstring)
def _updatedirstats(self, directory, size, files, subdirs, extensions): iter = self.sharelist.get_iter_first() while iter is not None: if directory[1] == self.sharelist.get_value(iter, 6): self.sharelist.insert(0, [ directory[0], directory[1], HumanSize(size), str(files), str(subdirs), extensions, directory[1] ]) self.sharelist.remove(iter) return iter = self.sharelist.iter_next(iter)
def SetDirectory(self, directory): self.selected_folder = directory self.FileStore.clear() self.files.clear() found_dir = False for d, f in self.shares: if d == directory: found_dir = True files = f break if not found_dir: return for file in files: # Filename, HSize, Bitrate, HLength, Size, Length, RawFilename rl = 0 try: size = int(file[2]) # Some clients send incorrect file sizes if size < 0 or size > maxsize: size = 0 except ValueError: size = 0 f = [file[1], HumanSize(size)] h_bitrate, bitrate, h_length = GetResultBitrateLength(size, file[4]) f += [h_bitrate, h_length] f += [int(size), rl, file[1]] try: self.files[f[0]] = self.FileStore.append(f) except Exception as msg: error = _("Error while attempting to display folder '%(folder)s', reported error: %(error)s" % {'folder': directory, 'error': msg}) self.frame.logMessage(error)
def SetDirectory(self, directory): self.selected_folder = directory self.FileStore.clear() self.files.clear() found_dir = False for d, f in self.shares: if d == directory: found_dir = True files = f break if not found_dir: return for file in files: # Filename, HSize, Bitrate, HLength, Size, Length, RawFilename rl = 0 try: size = int(file[2]) # Some clients send incorrect file sizes if size < 0 or size > maxsize: size = 0 except ValueError: size = 0 f = [file[1], HumanSize(size)] h_bitrate, bitrate, h_length = GetResultBitrateLength( size, file[4]) f += [h_bitrate, h_length] f += [int(size), rl, file[1]] try: self.files[f[0]] = self.FileStore.append(f) except Exception: displayTraceback()
def SelectedResultsAllData(self, model, path, iter, data): if iter in self.selected_users: return user = model.get_value(iter, 0) filename = model.get_value(iter, 2) fullname = model.get_value(iter, 10) size = speed = "0" length = None queue = immediate = num = country = bitratestr = "" for transfer in self.frame.np.transfers.downloads: if transfer.user == user and fullname == transfer.filename: size = HumanSize(transfer.size) try: speed = str(int(transfer.speed)) speed += _(" KB/s") except Exception: pass bitratestr = str(transfer.bitrate) length = str(transfer.length) break else: return directory = fullname.rsplit("\\", 1)[0] data[len(data)] = { "user": user, "fn": fullname, "position": num, "filename": filename, "directory": directory, "size": size, "speed": speed, "queue": queue, "immediate": immediate, "bitrate": bitratestr, "length": length, "country": country }
def AddUserResults(self, msg, user, country): if user in self.users: return self.users.add(user) counter = len(self.all_data) + 1 inqueue = msg.inqueue ulspeed = msg.ulspeed h_speed = HumanSpeed(ulspeed) if msg.freeulslots: imdl = "Y" inqueue = 0 else: imdl = "N" h_queue = Humanize(inqueue) append = False maxstoredresults = self.Searches.maxstoredresults for result in msg.list: if counter > maxstoredresults: break fullpath = result[1] fullpath_lower = fullpath.lower() if any(word in fullpath_lower for word in self.searchterm_words_ignore): """ Filter out results with filtered words (e.g. nicotine -music) """ log.add(_("Filtered out excluded search result " + fullpath + " from user " + user), 2) continue if not any(word in fullpath_lower for word in self.searchterm_words_include): """ Some users may send us wrong results, filter out such ones """ log.add(_("Filtered out inexact or incorrect search result " + fullpath + " from user " + user), 2) continue fullpath_split = reversed(fullpath.split('\\')) name = next(fullpath_split) directory = '\\'.join(fullpath_split) size = result[2] h_size = HumanSize(size) h_bitrate, bitrate, h_length = GetResultBitrateLength(size, result[4]) self.append([counter, user, self.get_flag(user, country), imdl, h_speed, h_queue, directory, name, h_size, h_bitrate, h_length, bitrate, fullpath, country, size, ulspeed, inqueue]) append = True counter += 1 if append: # If this search wasn't initiated by us (e.g. wishlist), and the results aren't spoofed, show tab if not self.showtab: self.Searches.ShowTab(self, self.id, self.text, self.mode) self.showtab = True # Update counter self.Counter.set_text("Results: %d/%d" % (self.numvisibleresults, len(self.all_data))) # Update tab notification self.frame.Searches.request_changed(self.Main) if self.frame.MainNotebook.get_current_page() != self.frame.MainNotebook.page_num(self.frame.searchvbox): self.frame.SearchTabLabel.get_child().set_image(self.frame.images["online"])
def update_specific(self, transfer=None): fn = transfer.filename user = transfer.user shortfn = fn.split("\\")[-1] currentbytes = transfer.currentbytes place = transfer.place hspeed = helapsed = "" if currentbytes is None: currentbytes = 0 status = transfer.status hstatus = self.TranslateStatus(status) try: size = int(transfer.size) if size < 0 or size > maxsize: size = 0 except TypeError: size = 0 hsize = "%s / %s" % (HumanSize(currentbytes), HumanSize(size)) if transfer.modifier: hsize += " (%s)" % transfer.modifier speed = transfer.speed or 0 elapsed = transfer.timeelapsed or 0 left = transfer.timeleft if speed > 0: # transfer.speed is in KB speed = float(speed) * 1024 hspeed = HumanSpeed(speed) if elapsed > 0: helapsed = self.frame.np.transfers.getTime(elapsed) try: icurrentbytes = int(currentbytes) if icurrentbytes == int(transfer.size): percent = 100 else: percent = ((100 * icurrentbytes) / int(size)) except Exception: icurrentbytes = 0 percent = 0 filecount = 1 # Modify old transfer if transfer.iter is not None: if self.TreeUsers == 1: # Group by folder, path not visible path = None else: path = '/'.join(reversed(transfer.path.split('/'))) self.transfersmodel.set(transfer.iter, 1, path, 2, shortfn, 3, hstatus, 4, str(place), 5, percent, 6, str(hsize), 7, hspeed, 8, helapsed, 9, left, 11, status, 12, size, 13, currentbytes, 14, speed, 15, elapsed, 17, place) else: if self.TreeUsers > 0: # Group by folder or user if user not in self.users: # Create Parent if it doesn't exist # ProgressRender not visible (last column sets 4th column) self.users[user] = self.transfersmodel.append( None, [ user, "", "", "", "", 0, "", "", "", "", "", "", 0, 0, 0, 0, filecount, 0 ]) parent = self.users[user] if self.TreeUsers == 1: # Group by folder """ Paths can be empty if files are downloaded individually, make sure we don't add files to the wrong user in the TreeView """ path = transfer.path user_path = user + path reverse_path = '/'.join(reversed(path.split('/'))) if user_path not in self.paths: self.paths[user_path] = self.transfersmodel.append( self.users[user], [ user, reverse_path, "", "", "", 0, "", "", "", "", "", "", 0, 0, 0, 0, filecount, 0 ]) parent = self.paths[user_path] else: # No grouping if user not in self.users: # Insert dummy value. We use this list to get the total number of users self.users[user] = 0 parent = None # Add a new transfer if self.TreeUsers == 1: # Group by folder, path not visible path = None else: path = '/'.join(reversed(transfer.path.split('/'))) iter = self.transfersmodel.append( parent, (user, path, shortfn, status, str(place), percent, str(hsize), hspeed, helapsed, left, fn, transfer.status, size, icurrentbytes, speed, elapsed, filecount, place)) transfer.iter = iter # Expand path if parent is not None: path = self.transfersmodel.get_path(iter) self.expand(path)
def update_parent_row(self, initer): speed = 0.0 percent = totalsize = position = 0 hspeed = helapsed = left = "" elapsed = 0 filecount = 0 salientstatus = "" extensions = {} iter = self.transfersmodel.iter_children(initer) while iter is not None: status = self.transfersmodel.get_value(iter, 11) if salientstatus in ( '', "Finished", "Filtered"): # we prefer anything over ''/finished salientstatus = status filename = self.transfersmodel.get_value(iter, 10) parts = filename.rsplit('.', 1) if len(parts) == 2: ext = parts[1] try: extensions[ext.lower()] += 1 except KeyError: extensions[ext.lower()] = 1 if status == "Filtered": # We don't want to count filtered files when calculating the progress iter = self.transfersmodel.iter_next(iter) continue elapsed += self.transfersmodel.get_value(iter, 15) totalsize += self.transfersmodel.get_value(iter, 12) position += self.transfersmodel.get_value(iter, 13) filecount += self.transfersmodel.get_value(iter, 16) if status == "Transferring": speed += float(self.transfersmodel.get_value(iter, 14)) left = self.transfersmodel.get_value(iter, 9) if status in ("Transferring", "Banned", "Getting address", "Establishing connection"): salientstatus = status iter = self.transfersmodel.iter_next(iter) if totalsize > 0: percent = ((100 * position) / totalsize) if speed > 0: hspeed = HumanSpeed(speed) left = self.frame.np.transfers.getTime( (totalsize - position) / speed / 1024) if elapsed > 0: helapsed = self.frame.np.transfers.getTime(elapsed) if len(extensions) == 0: extensions = "" elif len(extensions) == 1: extensions = " (" + self.extension_list_template % { 'ext': list(extensions.keys())[0] } + ")" else: extensionlst = [(extensions[key], key) for key in extensions] extensionlst.sort(reverse=True) extensions = " (" + ", ".join( [str(count) + " " + ext for (count, ext) in extensionlst]) + ")" self.transfersmodel.set( initer, 2, self.files_template % {'number': filecount} + extensions, 3, self.TranslateStatus(salientstatus), 5, percent, 6, "%s / %s" % (HumanSize(position), HumanSize(totalsize)), 7, hspeed, 8, helapsed, 9, left, 11, salientstatus, 12, totalsize, 13, position, 14, speed, 15, elapsed, 16, filecount, )
def update_specific(self, transfer=None): if transfer not in self.list: return fn = transfer.filename user = transfer.user shortfn = fn.split("\\")[-1] currentbytes = transfer.currentbytes place = transfer.place if currentbytes is None: currentbytes = 0 key = [user, fn] status = HumanSize(self.TranslateStatus(transfer.status)) istatus = self.get_status_index(transfer.status) try: size = int(transfer.size) except TypeError: size = 0 hsize = "%s / %s" % (HumanSize(currentbytes), HumanSize(size)) if transfer.modifier: hsize += " (%s)" % transfer.modifier try: speed = "%.1f" % transfer.speed except TypeError: speed = str(transfer.speed) elap = transfer.timeelapsed left = str(transfer.timeleft) if speed == "None": speed = "" else: # transfer.speed is in KB speed = float(speed) * 1024 if elap is None: elap = 0 elap = self.frame.np.transfers.getTime(elap) if left == "None": left = "" try: icurrentbytes = int(currentbytes) if icurrentbytes == int(transfer.size): percent = 100 else: percent = ((100 * icurrentbytes) / int(size)) except Exception as e: # noqa: F841 icurrentbytes = 0 percent = 0 # Modify old transfer for i in self.transfers: if i[0] != key: continue if i[2] != transfer: continue self.transfersmodel.set(i[1], 1, shortfn, 2, status, 3, str(place), 4, percent, 5, str(hsize), 6, HumanSpeed(speed), 7, elap, 8, left, 9, transfer.path, 11, istatus, 12, size, 13, currentbytes, 15, str(speed)) break else: newparent = False if self.TreeUsers: if user not in self.users: # Create Parent if it doesn't exist # ProgressRender not visible (last column sets 4th column) self.users[user] = self.transfersmodel.append( None, [ user, "", "", "", 0, "", "", "", "", "", "", 0, 0, 0, False, "" ]) newparent = True parent = self.users[user] else: parent = None # Add a new transfer path = transfer.path iter = self.transfersmodel.append(parent, [ user, shortfn, status, str(place), percent, str(hsize), HumanSpeed(speed), elap, left, path, fn, istatus, size, icurrentbytes, True, str(speed) ]) # Expand path path = self.transfersmodel.get_path(iter) self.transfers.append([key, iter, transfer]) if newparent: self.expandcollapse(self.transfersmodel.get_path(parent))
def _update(self, transfer=None, forced=True): now = time() if forced: self.lastupdate = time() # ...we're working... if transfer is not None: self.update_specific(transfer) elif self.list is not None: # This seems to me to be O(n^2), perhaps constructing a temp. dict # from self.list would be better? for i in self.transfers[:]: for j in self.list: if [j.user, j.filename] == i[0]: break else: # Remove transfers from treeview that aren't in the transfer list self.transfersmodel.remove(i[1]) self.transfers.remove(i) for i in self.list: self.update_specific(i) # The rest is just summarizing so it's not too important. # It's fairly CPU intensive though, so we only do it if we haven't updated it recently if not forced and (now - self.lastupdate) < self.MINIMUM_GUI_DELAY: if not self.finalupdatetimerid: self.finalupdatetimerid = True # I'm not sure if gobject returns fast enough self.finalupdatetimerid = gobject.timeout_add( self.MINIMUM_GUI_DELAY_SLEEP, self.finalupdate, self.update) return self.lastupdate = time() # ...we're working... # Remove empty parent rows for (username, user) in [x for x in self.users.items()]: if not self.transfersmodel.iter_has_child(user): self.transfersmodel.remove(user) del self.users[username] else: files = self.transfersmodel.iter_n_children(user) ispeed = 0.0 percent = totalsize = position = 0 elapsed = left = "" elap = 0 salientstatus = "" extensions = {} for f in range(files): iter = self.transfersmodel.iter_nth_child(user, f) filename = self.transfersmodel.get_value(iter, 10) parts = filename.rsplit('.', 1) if len(parts) == 2: ext = parts[1] try: extensions[ext.lower()] += 1 except KeyError: extensions[ext.lower()] = 1 for transfer in self.list: if [transfer.user, transfer.filename] == [ username, filename ] and transfer.timeelapsed is not None: elap += transfer.timeelapsed break totalsize += self.transfersmodel.get_value(iter, 12) position += self.transfersmodel.get_value(iter, 13) status = self.transfersmodel.get_value(iter, 2) if status == _("Transferring"): str_speed = self.transfersmodel.get_value(iter, 15) if str_speed != "": ispeed += float(str_speed) left = self.transfersmodel.get_value(iter, 8) if salientstatus in ( '', _("Finished") ): # we prefer anything over ''/finished salientstatus = status if status in (_("Transferring"), _("Banned"), _("Getting address"), _("Establishing connection")): salientstatus = status try: speed = "%.1f" % ispeed except TypeError: speed = str(ispeed) if totalsize > 0: percent = ((100 * position) / totalsize) if ispeed <= 0.0: left = "∞" else: left = self.frame.np.transfers.getTime( (totalsize - position) / ispeed / 1024) elapsed = self.frame.np.transfers.getTime(elap) if len(extensions) == 0: extensions = "Unknown" elif len(extensions) == 1: extensions = _("All %(ext)s") % { 'ext': list(extensions.keys())[0] } else: extensionlst = [(extensions[key], key) for key in extensions] extensionlst.sort(reverse=True) extensions = ", ".join([ str(count) + " " + ext for (count, ext) in extensionlst ]) self.transfersmodel.set( user, 1, _("%(number)2s files ") % {'number': files} + " (" + extensions + ")", 2, salientstatus, 4, percent, 5, "%s / %s" % (HumanSize(position), HumanSize(totalsize)), 6, HumanSpeed(speed), 7, elapsed, 8, left, 12, ispeed, 14, True, 15, speed) self.lastupdate = time() # ...and we're done