def __init__(self, frame): self.frame = frame self.initphase = True # don't respond to signals unless False self.config = frame.np.config builder = gtk.Builder() builder.add_from_file(join(dir_location, "fastconfigure.glade")) self.window = builder.get_object("FastConfigureAssistant") builder.connect_signals(self) self.kids = {} for i in builder.get_objects(): try: self.kids[widgetname(i)] = i except AttributeError: pass numpages = self.window.get_n_pages() for n in xrange(numpages): page = self.window.get_nth_page(n) template = self.window.get_page_title(page) self.window.set_page_title(page, template % {'page':(n+1), 'pages':numpages}) self.templates = { 'listenport': self.kids['listenport'].get_text(), } # Page specific, sharepage # the lsat column is the raw byte/unicode object for the folder (not shown) self.sharelist = gtk.ListStore(gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING) columns = InitialiseColumns(self.kids['shareddirectoriestree'], [_("Directory"), 0, "text"], [_("Size"), 0, "text"], [_("Files"), 0, "text"], [_("Dirs"), 0, "text"], [_("File types"), 0, "text"], ) self.kids['shareddirectoriestree'].set_model(self.sharelist) self.kids['shareddirectoriestree'].get_selection().set_mode(gtk.SELECTION_MULTIPLE) self.initphase = False
def mpris(self): from dbus import Interface player = self.NPCommand.get_text() dbus_mpris_service = u'org.mpris.MediaPlayer2.' dbus_mpris_player_service = u'org.mpris.MediaPlayer2.Player' dbus_mpris_path = u'/org/mpris/MediaPlayer2' dbus_property = u'org.freedesktop.DBus.Properties' if not player: names = self.bus.list_names() players = [] for name in names: if name.startswith(dbus_mpris_service): players.append(name[len(dbus_mpris_service):]) if not players: self.frame.logMessage(_("Could not find a suitable MPIS player.")) return None player = players[0] if len(players) > 1: self.frame.logMessage(_("Found multiple MPRIS players: %s. Using: %s") % (players, player)) else: self.frame.logMessage(_("Auto-detected MPRIS player: %s.") % player) try: player_obj = self.bus.get_object(dbus_mpris_service + player, dbus_mpris_path) player_property_obj = Interface(player_obj, dbus_interface=dbus_property) metadata = player_property_obj.Get(dbus_mpris_player_service, "Metadata") except Exception, exception: self.frame.logMessage(_("Something went wrong while querying %s: %s" % (player, exception))) return None
def OnTryClearQueued(self, widget): direction="up" win = OptionDialog(self.frame, _("Clear All Queued Uploads?"), modal=True, status=None, option=False, third="") win.connect("response", self.frame.on_clear_response, direction) win.set_title(_("Nicotine+")+": "+_("Clear Queued Transfers")) win.set_icon( self.frame.images["n"]) win.show()
def xmms(self): if not os.path.exists("/tmp/xmms-info"): self.frame.logMessage(_("ERROR: /tmp/xmms-info does not exist. Is the Infopipe plugin installed and is XMMS running?")) return None try: fsock = file("/tmp/xmms-info") do = fsock.read().split("\n") fsock.close() if len(do) == 0: self.frame.logMessage(_("ERROR: /tmp/xmms-info is empty. Is the Infopipe plugin installed and is XMMS running?")) infolist = [] for i in do: if i == "": continue infolist.append( i ) #protocol = infolist[0][29:] #version = infolist[1][25:] status = infolist[2][8:] #playlist_count = infolist[3][20:] #playlist_position = infolist[4][20:] #millisec_position = infolist[5][15:] position = infolist[6][10:] #millisec_time = infolist[7][15:] time = infolist[8][6:] bitrate = str(int(infolist[9][17:])/1024) frequency = infolist[10][20:] channels = infolist[11][10:] title = infolist[12][7:] filename = infolist[13][7:] self.title = { "title": "", "artist": "", "comment": "", "year": "", "album": "", "track":"", "nowplaying": title, "length": time, "bitrate": bitrate, "channels": channels, "position": position, "filename": filename, "status": status} return True except: return None
def MakeNewModel(self, list): self.shares = list self.selected_folder = None self.selected_files = [] self.files.clear() # self.DirStore.clear() self.DirStore=None self.totalsize = 0 self.FolderTreeView.set_model(None) self.DirStore = UglyTree([gobject.TYPE_STRING, gobject.TYPE_STRING], list) for dir, files in self.shares: for filedata in files: if filedata[2] < 18446744000000000000: self.totalsize += filedata[2] else: print "Unbelievable filesize: %s, %s" % (HumanizeBytes(filedata[2]), repr(filedata)) self.AmountShared.set_text(_("Shared: %s") % HumanizeBytes(self.totalsize)) self.NumDirectories.set_text(_("Dirs: %s") % len(self.shares)) self.FolderTreeView.set_model(self.DirStore) sel = self.FolderTreeView.get_selection() sel.unselect_all() # Select first directory sel.select_path((0,)) 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 __init__(self, parent): GenericAboutDialog.__init__(self, parent, _("About search filters")) label = gtk.Label(_("""Search filtering You can use this to refine which results are displayed. The full results from the server are always available if you clear all the search terms. You can filter by: Included text: Files are shown if they contain this text. Case is insensitive, but word order is important. 'Spears Brittany' will not show any 'Brittany Spears' Excluded text: As above, but files will not be displayed if the text matches Size: Shows results based on size. use > and < to find files larger or smaller. Files exactly the same as this term will always match. Use = to specify an exact match. Use k or m to specify kilo or megabytes. >10M will find files larger than 10 megabytes. <4000k will find files smaller than 4000k. Bitrate: Find files based on bitrate. Use < and > to find lower or higher. >192 finds 192 and higher, <192 finds 192 or lower. =192 only finds 192. for VBR, the average bitrate is used. Free slot: Show only those results from users which have at least one upload slot free. To set the filter, press Enter. This will apply to any existing results, and any more that are returned. To filter in a different way, just set the relevant terms. You do not need to do another search to apply a different filter.""")) label.set_justify(gtk.JUSTIFY_LEFT) label.set_selectable(True) self.vbox.pack_start(label) self.show_all()
def OnPrivateRooms(self, widget): if self.user == None or self.user == self.frame.np.config.sections["server"]["login"]: return False user = self.user items = [] popup = self.frame.userlist.Popup_Menu_PrivateRooms popup.clear() popup.set_user(self.user) #print self.roomsctrl.PrivateRooms for room in self.frame.chatrooms.roomsctrl.PrivateRooms: if not (self.frame.chatrooms.roomsctrl.IsPrivateRoomOwned(room) or self.frame.chatrooms.roomsctrl.IsPrivateRoomOperator(room)): continue if self.user in self.frame.chatrooms.roomsctrl.PrivateRooms[room]["users"]: items.append(("#" + _("Remove from private room %s" %room), popup.OnPrivateRoomRemoveUser, gtk.STOCK_REMOVE, room)) else: items.append(("#" + _("Add to private room %s" %room), popup.OnPrivateRoomAddUser, gtk.STOCK_ADD, room)) if self.frame.chatrooms.roomsctrl.IsPrivateRoomOwned(room): if self.user in self.frame.chatrooms.roomsctrl.PrivateRooms[room]["operators"]: items.append(("#" + _("Remove as operator of %s" %room), popup.OnPrivateRoomRemoveOperator, gtk.STOCK_REMOVE, room)) else: items.append(("#" + _("Add as operator of %s" %room), popup.OnPrivateRoomAddOperator, gtk.STOCK_ADD, room)) popup.setup(*items) return True
def __init__(self, frame, widget): self.frame = frame self.widget = widget self.transfers = [] self.list = None self.selected_transfers = [] self.selected_users = [] self.users = {} self.lastupdate = 0 self.finalupdatetimerid = None widget.get_selection().set_mode(gtk.SELECTION_MULTIPLE) columntypes = [gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_INT , gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_STRING, gobject.TYPE_INT, gobject.TYPE_INT, gobject.TYPE_INT, gobject.TYPE_BOOLEAN] self.transfersmodel = gtk.TreeStore(*columntypes) #self.transfersmodel = UglyTree(columntypes) self.cols = cols = InitialiseColumns(widget, [_("User"), 100, "text", self.CellDataFunc], [_("Filename"), 250, "text", self.CellDataFunc], [_("Status"), 140, "text", self.CellDataFunc], [_("Queue Position"), 50, "number", self.CellDataFunc], [_("Percent"), 70, "progress"], [_("Size"), 170, "text", self.CellDataFunc], [_("Speed"), 50, "number", self.CellDataFunc], [_("Time elapsed"), 70, "text", self.CellDataFunc], [_("Time left"), 70, "text", self.CellDataFunc], [_("Path"), 1000, "text", self.CellDataFunc], ) self.col_user, self.col_filename , self.col_status, self.col_position, self.col_percent, self.col_human_size, self.col_human_speed, self.col_time_elapsed, self.col_time_left, self.col_path = cols #, self.col_fullpath, self.col_int_status, self.col_int_speed, self.col_current_size, self.col_visible self.col_user.set_sort_column_id(0) self.col_filename.set_sort_column_id(1) self.col_status.set_sort_column_id(2) # Only view progress renderer on transfers, not user tree parents self.transfersmodel.set_sort_func(2, self.status_sort_func, 2) self.col_position.set_sort_column_id(3) self.transfersmodel.set_sort_func(3, int_sort_func, 3) self.col_percent.set_sort_column_id(11) self.col_percent.set_attributes(self.col_percent.get_cell_renderers()[0], value=4, visible=14) #self.col_position.set_attributes(self.col_position.get_cell_renderers()[0], visible=14) self.col_human_size.set_sort_column_id(12) self.col_human_speed.set_sort_column_id(6) self.col_time_elapsed.set_sort_column_id(7) self.col_time_left.set_sort_column_id(8) self.col_path.set_sort_column_id(9) self.transfersmodel.set_sort_func(11, self.progress_sort_func, 4) #self.transfersmodel.set_sort_func(11, self.progress_sort_func, 11) #self.transfersmodel.set_sort_func(12, self.progress_sort_func, 12) #self.transfersmodel.set_sort_func(13, self.progress_sort_func, 13) self.transfersmodel.set_sort_func(6, float_sort_func, 6) #self.frame.CreateIconButton(gtk.STOCK_INDENT, "stock", self.OnToggleTree, "Group by Users") #self.hbox1.pack_end(self.ToggleTree, False, False) widget.set_model(self.transfersmodel) self.UpdateColours()
def OnSearchMeta(self, widget): if not self.frame.np.transfers: return data = {} self.ResultsList.get_selection().selected_foreach(self.SelectedResultsAllData, data) if data != {}: self.MetaBox(title=_("Nicotine+: Search Results"), message=_("<b>Metadata</b> for Search Query: <i>%s</i>") % self.text, data=data, modal=True)
def GetUserSearchName(self, id): if id in self.usersearches: users = self.usersearches[id] if len(users) > 1: return _("Users") elif len(users) == 1: return users[0] return _("User")
def GetUserStatus(self, msg): if msg.user in self.users: tab = self.users[msg.user] tab.status = msg.status status = [_("Offline"), _("Away"), _("Online")][msg.status] if not self.frame.np.config.sections["ui"]["tab_status_icons"]: self.set_text(tab.Main, "%s (%s)" % (msg.user[:15], status)) else: self.set_text(tab.Main, msg.user) self.set_status_image(tab.Main, msg.status)
def bmpx(self): if self.bus is None: self.frame.logMessage(_("ERROR: DBus not available:")+" "+"BMPx"+ " "+ _("cannot be contacted")) return try: bmp_object = self.bus.get_object('org.beepmediaplayer.bmp', '/Core') bmp_iface = self.bus.Interface(bmp_object, 'org.beepmediaplayer.bmp') except Exception, error: self.frame.logMessage(_("ERROR while accessing the %(program)s DBus interface: %(error)s") % {"program": "BMPx", "error": error}) return
def TabPopup(self, id): popup = PopupMenu(self.frame) popup.setup( ("#" + _("Detach this tab"), self.searches[id][2].Detach, gtk.STOCK_REDO), ("#" + _("Close this tab"), self.searches[id][2].OnClose, gtk.STOCK_CLOSE), ) items = popup.get_children() return popup
def OnPopupMenuUsers(self, widget): self.selected_transfers = [] self.selected_users = [] self.widget.get_selection().selected_foreach(self.SelectedTransfersCallback) self.popup_menu_users.clear() if len(self.selected_users) > 0: items = [] self.selected_users.sort(key=str.lower) for user in self.selected_users: popup = PopupMenu(self.frame) popup.setup( ("#" + _("Send _message"), popup.OnSendMessage, gtk.STOCK_EDIT), ("#" + _("Show IP a_ddress"), popup.OnShowIPaddress, gtk.STOCK_NETWORK), ("#" + _("Get user i_nfo"), popup.OnGetUserInfo, gtk.STOCK_DIALOG_INFO), ("#" + _("Brow_se files"), popup.OnBrowseUser, gtk.STOCK_HARDDISK), ("#" + _("Gi_ve privileges"), popup.OnGivePrivileges, gtk.STOCK_JUMP_TO), ("", None), ("$" + _("_Add user to list"), popup.OnAddToList), ("$" + _("_Ban this user"), popup.OnBanUser), ("$" + _("_Ignore this user"), popup.OnIgnoreUser), ("#" + _("Select User's Transfers"), self.OnSelectUserTransfer, gtk.STOCK_INDEX), ) popup.set_user(user) items.append((1, user, popup, self.OnPopupMenuUser, popup)) self.popup_menu_users.setup(*items) return True
def OnSavePicture(self, widget): if self.image is None or self.image_pixbuf is None: return #pixbuf = self.image.get_pixbuf() filename = "%s %s.jpg" % (self.user, time.strftime("%Y-%m-%d %H:%M:%S")) pathname = os.path.join(self.frame.np.config.sections["transfers"]["downloaddir"], CleanFile(filename)) if not os.path.exists(pathname): self.image_pixbuf.save(pathname, "jpeg", {"quality": "100"}) log.add(_("Picture saved to %s") % pathname) else: log.add(_("Picture not saved, %s already exists.") % pathname)
def checklatest(frame): try: url = urllib.urlopen(latesturl) data = url.read().split("\n")[0] url.close() latest = makeversion(data) except Exception, m: dlg = gtk.MessageDialog(frame, 0, gtk.MESSAGE_ERROR, gtk.BUTTONS_OK, _("Could not retrieve version information!\nError: %s") % m) dlg.set_title(_("Check Latest Version")) dlg.run() dlg.destroy() return
def CreateTab(self, id, text, mode, remember = False): tab = Search(self, text, id, mode, remember) if mode: label = "(" + ("", _("Rooms"), _("Buddies"), self.GetUserSearchName(id))[mode] + ") " + text[:15] else: label = text[:20] self.append_page(tab.Main, label, tab.OnClose) search = [id, text, tab, mode, remember] self.searches[id] = search return search
def OnSearch(self): text = self.frame.SearchEntry.get_text().strip() if not text: return users = [] room = None if self.frame.SearchMethod.get_active_text() == _("Global"): mode = 0 elif self.frame.SearchMethod.get_active_text() == _("Rooms"): mode = 1 name = self.frame.RoomSearchCombo.child.get_text() # Space after Joined Rooms is important, so it doesn't conflict # with any possible real room if name != _("Joined Rooms ") and not name.isspace(): room = name elif self.frame.SearchMethod.get_active_text() == _("Buddies"): mode = 2 elif self.frame.SearchMethod.get_active_text() == _("User"): mode = 3 user = self.frame.UserSearchCombo.child.get_text().strip() if user != "" and not user.isspace(): users = [user] else: return else: mode = 0 feedback = None if mode == 0: feedback = self.frame.pluginhandler.OutgoingGlobalSearchEvent(text) if feedback != None: text = feedback[0] elif mode == 1: feedback = self.frame.pluginhandler.OutgoingRoomSearchEvent(room, text) if feedback != None: (room, text) = feedback elif mode == 2: feedback = self.frame.pluginhandler.OutgoingBuddySearchEvent(text) if feedback != None: text = feedback[0] elif mode == 3: feedback = self.frame.pluginhandler.OutgoingUserSearchEvent(users) if feedback != None: users = feedback[0] else: print "Unknown search mode, not using plugin system. Fix me!" feedback = True if feedback != None: self.DoSearch(text, mode, users, room) self.frame.SearchEntry.set_text("")
def OnGivePrivileges(self, widget): self.frame.np.queue.put(slskmessages.CheckPrivileges()) if self.frame.np.privileges_left is None: days = _("Unknown") else: days = self.frame.np.privileges_left // 60 // 60 // 24 text = InputDialog(self.frame.MainWindow, _("Give privileges")+" "+_("to %(user)s") %{"user": self.user}, _("Give how many days of global privileges to this user?") + " ("+ _("%(days)s days left") %{'days':days} +")" ) if text: try: days = int(text) self.frame.GivePrivileges(self.user, days) except Exception, e: print e
def OnDownloadMeta(self, widget): if not self.frame.np.transfers: return data = {} self.widget.get_selection().selected_foreach(self.SelectedResultsAllData, data) if data != {}: self.MetaBox( title=_("Nicotine+:") + " " + _("Downloads Metadata"), message=_("<b>Metadata</b> for Downloads"), data=data, modal=True, Search=False, )
def rhythmbox(self): from dbus import Interface if self.bus is None: self.frame.logMessage(_("ERROR: DBus not available:")+" "+"Rhythmbox"+ " "+ _("cannot be contacted")) return None try: proxyobj = self.bus.get_object("org.gnome.Rhythmbox", "/org/gnome/Rhythmbox/Shell") rbshell = Interface(proxyobj, "org.gnome.Rhythmbox.Shell") proxyobj = self.bus.get_object('org.gnome.Rhythmbox', '/org/gnome/Rhythmbox/Player') rbplayer = Interface(proxyobj, 'org.gnome.Rhythmbox.Player') except Exception, error: self.frame.logMessage(_("ERROR while accessing the %(program)s DBus interface: %(error)s") % {"program": "Rhythmbox", "error": error }) return None
def HumanSpeed(number): try: s = float(int(number)) if s >= 1000*1024*1024: r = _("%.2f GiB/s") % (s / (1024.0*1024.0*1024.0)) elif s >= 1000*1024: r = _("%.2f MiB/s") % (s / (1024.0*1024.0)) elif s >= 1000: r = _("%.2f KiB/s") % (s / 1024.0) else: r = _("%d B/s") % (number) return r except Exception, e: return number
def DownloadDirectoryRecursive(self, dir, prefix = ""): # Find all files and add them to list node = self.DirStore.on_get_iter(dir) if node == None or node == (0,0): return localdir = prefix + self.DirStore.GetValue(node) dirfiles = self.DirStore.GetData(node) files = [] for file in dirfiles: length = bitrate = None attrs = file[4] if attrs != []: bitrate = str(attrs[0]) if len(attrs) > 2 and attrs[2]: bitrate += _(" (vbr)") try: rl = int(attrs[1]) except ValueError: rl = 0 length = "%i:%02i" % (rl // 60, rl % 60) files.append(["\\".join([self.DirStore.GetPathString(dir), file[1]]), localdir, file[2], bitrate, length]) nchildren, node = self.DirStore.GetChildren(node) if nchildren != 0: while node is not None: files += self.DownloadDirectoryRecursive(self.DirStore.on_get_path(node), os.path.join(localdir, "")) node = self.DirStore.GetNext(node) return files
def lastfm(self): def lastfm_parse(buf): from time import time, altzone try: i = buf.index("<artist") i = buf[i+1:].index(">") + i + 2 j = buf[i:].index("<") + i artist = buf[i:j]; i = buf[j:].index("<name>") + j + 6 j = buf[i:].index("</name>") + i title = buf[i:j] i = buf[j:].index("<date") + j j = buf[i:].index('"') + i + 1 i = buf[j:].index('"') + j date = int(buf[j:i]) # utc utc_now = time() + altzone playing = utc_now - date < 300 return (playing, artist, title) except: return (None, None, None) try: from socket import socket, AF_INET, SOCK_STREAM except Exception, error: self.frame.logMessage(_("ERROR while loading socket module: %(error)s") % {"command": othercommand, "error": error}) return None
def OnUploadDirectoryTo(self, widget, recurse = 0): dir = self.selected_folder if dir is None or dir == (): return users = [] for entry in self.frame.np.config.sections["server"]["userlist"]: users.append(entry[0]) users.sort() user = input_box(self.frame, title=_("Nicotine: Upload Directory's Contents"), message=_('Enter the User you wish to upload to:'), default_text='', droplist=users) if user is None or user == "": return self.frame.np.ProcessRequestToPeer(user, slskmessages.UploadQueueNotification(None) ) self.UploadDirectoryTo(user, dir, recurse)
def updatepage(self, page): """Updates information on the given page with. Use _populate if possible""" if not page: return name = widgetname(page) if name == 'portpage': self.kids['listenport'].set_markup(_(self.templates['listenport']) % {'listenport':'<b>'+str(self.frame.np.waitport)+'</b>'})
def PressHeader(widget, event): if event.button != 3: return False columns = widget.get_parent().get_columns() visible_columns = [column for column in columns if column.get_visible()] one_visible_column = len(visible_columns) == 1 menu = gtk.Menu() pos = 1 for column in columns: title = column.get_title() if title == "": title = _("Column #%i") %pos item = gtk.CheckMenuItem(title) if column in visible_columns: item.set_active(True) if one_visible_column: item.set_sensitive(False) else: item.set_active(False) item.connect('activate', header_toggle, column) menu.append(item) pos += 1 menu.show_all() menu.popup(None, None, None, event.button, event.time) return True
def check_filter(self, row): filters = self.filters if not self.filtersCheck.get_active(): return True if filters[0] and not filters[0].search(row[2].lower()): return False if filters[1] and filters[1].search(row[2].lower()): return False if filters[2] and not self.checkDigit(filters[2], row[13]): return False if filters[3] and not self.checkDigit(filters[3], row[10], False): return False if filters[4] and row[6] != _("Y"): return False if filters[5]: for cc in filters[5]: if not cc: continue if row[12] is None: return False if cc[0] == "-": if row[12].upper() == cc[1:].upper(): return False elif cc.upper() != row[12].upper(): return False return True
def detach_tab(self, page, title=_("Nicotine+")): label = None if self.is_tab_detached(page): return for i in self.pages[:]: if i[0] == page: pagewidget, label_tab, status, label_tab_menu = i label = label_tab.label.get_text() label_tab.get_parent().remove(label_tab) break if label is None: return for i in self.detached_tabs: if i[0] == label or i[1] is page: return gtk.Notebook.remove_page(self, self.page_num(page)) window = gtk.Window() window.set_title(title) #window.add_accel_group(self.accel_group) window.set_icon(NICOTINE.images["n"]) window.resize(600, 400) vbox = gtk.VBox(False, spacing=5) vbox.set_border_width(5) vbox.pack_start(page) vbox.show() window.add(vbox) window.connect("destroy", self.OnTabWindowDestroy, page) window.connect("focus_in_event", self.OnFocusIn) window.connect("focus_out_event", self.OnFocusOut) self.detached_tabs.append([page, label, window, False]) window.show()
def AddToList(self, user): if user in [i[0] for i in self.userlist]: return row = [self.frame.GetStatusImage(0), None, user, "0", "0", False, False, False, _("Never seen"), "", 0, 0, 0, 0, ""] iter = self.usersmodel.append(row) self.userlist.append([user, "", _("Never seen"), iter, self.frame.GetUserFlag(user)]) self.SaveUserList() self.frame.np.queue.put(slskmessages.AddUser(user)) self.frame.np.queue.put(slskmessages.GetPeerAddress(user)) for widget in self.frame.BuddiesComboEntries: gobject.idle_add(widget.Append, user) if self.frame.np.config.sections["words"]["buddies"]: gobject.idle_add(self.frame.chatrooms.roomsctrl.UpdateCompletions) gobject.idle_add(self.frame.privatechats.UpdateCompletions)