id int64 0 458k | file_name stringlengths 4 119 | file_path stringlengths 14 227 | content stringlengths 24 9.96M | size int64 24 9.96M | language stringclasses 1 value | extension stringclasses 14 values | total_lines int64 1 219k | avg_line_length float64 2.52 4.63M | max_line_length int64 5 9.91M | alphanum_fraction float64 0 1 | repo_name stringlengths 7 101 | repo_stars int64 100 139k | repo_forks int64 0 26.4k | repo_open_issues int64 0 2.27k | repo_license stringclasses 12 values | repo_extraction_date stringclasses 433 values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
30,400 | i18n.py | nicotine-plus_nicotine-plus/pynicotine/i18n.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gettext
import locale
import os
import sys
CURRENT_PATH = os.path.dirname(os.path.realpath(__file__))
BASE_PATH = os.path.normpath(os.path.join(CURRENT_PATH, ".."))
LOCALE_PATH = os.path.join(CURRENT_PATH, "locale")
TRANSLATION_DOMAIN = "nicotine"
LANGUAGES = (
("ca", "Català"),
("de", "Deutsch"),
("en", "English"),
("es_CL", "Español (Chile)"),
("es_ES", "Español (España)"),
("et", "Eesti"),
("fr", "Français"),
("hu", "Magyar"),
("it", "Italiano"),
("lv", "Latviešu"),
("nl", "Nederlands"),
("pl", "Polski"),
("pt_BR", "Português (Brasil)"),
("pt_PT", "Português (Portugal)"),
("ru", "Русский"),
("tr", "Türkçe"),
("uk", "Українська"),
("zh_CN", "汉语")
)
def _set_system_language(language=None):
"""Extracts the default system locale/language and applies it on systems that
don't set the 'LC_ALL/LANGUAGE' environment variables by default (Windows,
macOS)"""
default_locale = None
if sys.platform == "win32":
import ctypes
windll = ctypes.windll.kernel32
if not default_locale:
default_locale = locale.windows_locale.get(windll.GetUserDefaultLCID())
if not language and "LANGUAGE" not in os.environ:
language = locale.windows_locale.get(windll.GetUserDefaultUILanguage())
elif sys.platform == "darwin":
import plistlib
os_preferences_path = os.path.join(
os.path.expanduser("~"), "Library", "Preferences", ".GlobalPreferences.plist")
try:
with open(os_preferences_path, "rb") as file_handle:
os_preferences = plistlib.load(file_handle)
except Exception as error:
os_preferences = {}
print(f"Cannot load global preferences: {error}")
# macOS provides locales with additional @ specifiers, e.g. en_GB@rg=US (region).
# Remove them, since they are not supported.
default_locale = next(iter(os_preferences.get("AppleLocale", "").split("@", maxsplit=1)))
if default_locale.endswith("_ES"):
# *_ES locale is currently broken on macOS (crashes when sorting strings).
# Disable it for now.
default_locale = "pt_PT"
if not language and "LANGUAGE" not in os.environ:
languages = os_preferences.get("AppleLanguages", [""])
language = next(iter(languages)).replace("-", "_")
if default_locale:
os.environ["LC_ALL"] = default_locale
if language:
os.environ["LANGUAGE"] = language
def apply_translations(language=None):
# Use the same language as the rest of the system
_set_system_language(language)
# Install translations for Python
gettext.install(TRANSLATION_DOMAIN, LOCALE_PATH)
| 3,565 | Python | .py | 86 | 35.348837 | 97 | 0.658401 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,401 | privatechat.py | nicotine-plus_nicotine-plus/pynicotine/privatechat.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import pynicotine
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.logfacility import log
from pynicotine.slskmessages import MessageAcked
from pynicotine.slskmessages import MessageUser
from pynicotine.slskmessages import MessageUsers
from pynicotine.slskmessages import SayChatroom
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import censor_text
from pynicotine.utils import find_whole_word
class PrivateChat:
__slots__ = ("completions", "private_message_queue", "away_message_users", "users")
CTCP_VERSION = "\x01VERSION\x01"
def __init__(self):
self.completions = set()
self.private_message_queue = {}
self.away_message_users = set()
self.users = set()
for event_name, callback in (
("message-user", self._message_user),
("peer-address", self._get_peer_address),
("quit", self._quit),
("server-login", self._server_login),
("server-disconnect", self._server_disconnect),
("start", self._start),
("user-status", self._user_status)
):
events.connect(event_name, callback)
def _start(self):
if not config.sections["privatechat"]["store"]:
# Clear list of previously open chats if we don't want to restore them
config.sections["privatechat"]["users"].clear()
return
for username in config.sections["privatechat"]["users"]:
if isinstance(username, str) and username not in self.users:
self.show_user(username, switch_page=False, remembered=True)
self.update_completions()
def _quit(self):
self.remove_all_users(is_permanent=False)
self.completions.clear()
def _server_login(self, msg):
if not msg.success:
return
for username in self.users:
core.users.watch_user(username, context="privatechat") # Get notified of user status
def _server_disconnect(self, _msg):
self.private_message_queue.clear()
self.away_message_users.clear()
self.update_completions()
def add_user(self, username):
if username in self.users:
return
self.users.add(username)
if username not in config.sections["privatechat"]["users"]:
config.sections["privatechat"]["users"].insert(0, username)
def remove_user(self, username, is_permanent=True):
if is_permanent and username in config.sections["privatechat"]["users"]:
config.sections["privatechat"]["users"].remove(username)
self.users.remove(username)
core.users.unwatch_user(username, context="privatechat")
events.emit("private-chat-remove-user", username)
def remove_all_users(self, is_permanent=True):
for username in self.users.copy():
self.remove_user(username, is_permanent)
def show_user(self, username, switch_page=True, remembered=False):
self.add_user(username)
events.emit("private-chat-show-user", username, switch_page, remembered)
core.users.watch_user(username, context="privatechat")
def clear_private_messages(self, username):
events.emit("clear-private-messages", username)
def private_message_queue_add(self, msg):
"""Queue a private message until we've received a user's IP address."""
username = msg.user
if username not in self.private_message_queue:
self.private_message_queue[username] = [msg]
else:
self.private_message_queue[username].append(msg)
def send_automatic_message(self, username, message):
self.send_message(username, f"[Automatic Message] {message}")
def echo_message(self, username, message, message_type="local"):
events.emit("echo-private-message", username, message, message_type)
def send_message(self, username, message):
user_text = core.pluginhandler.outgoing_private_chat_event(username, message)
if user_text is None:
return
username, message = user_text
if config.sections["words"]["replacewords"] and message != self.CTCP_VERSION:
for word, replacement in config.sections["words"]["autoreplaced"].items():
message = message.replace(str(word), str(replacement))
core.send_message_to_server(MessageUser(username, message))
core.pluginhandler.outgoing_private_chat_notification(username, message)
events.emit("message-user", MessageUser(username, message))
def send_message_users(self, target, message):
if not message:
return
users = None
if target == "buddies":
users = set(core.buddies.users)
elif target == "downloading":
users = core.uploads.get_downloading_users()
if users:
core.send_message_to_server(MessageUsers(users, message))
def _get_peer_address(self, msg):
"""Server code 3.
Received a user's IP address, process any queued private
messages and check if the IP is ignored
"""
username = msg.user
if username not in self.private_message_queue:
return
for queued_msg in self.private_message_queue[username][:]:
self.private_message_queue[username].remove(queued_msg)
queued_msg.user = username
events.emit("message-user", queued_msg, queued_message=True)
def _user_status(self, msg):
"""Server code 7."""
if msg.user == core.users.login_username and msg.status != UserStatus.AWAY:
# Reset list of users we've sent away messages to when the away session ends
self.away_message_users.clear()
if msg.status == UserStatus.OFFLINE:
self.private_message_queue.pop(msg.user, None)
def get_message_type(self, text, is_outgoing_message):
if text.startswith("/me "):
return "action"
if is_outgoing_message:
return "local"
if core.users.login_username and find_whole_word(core.users.login_username.lower(), text.lower()) > -1:
return "hilite"
return "remote"
def _message_user(self, msg, queued_message=False):
"""Server code 22."""
is_outgoing_message = (msg.message_id is None)
username = msg.user
tag_username = (core.users.login_username if is_outgoing_message else username)
message = msg.message
timestamp = msg.timestamp if not msg.is_new_message else None
if not is_outgoing_message:
if not queued_message:
log.add_chat(_("Private message from user '%(user)s': %(message)s"), {
"user": username,
"message": message
})
core.send_message_to_server(MessageAcked(msg.message_id))
if username == "server":
start_str = "The room you are trying to enter ("
if message.startswith(start_str) and ") " in message:
# Redirect message to chat room tab if join wasn't successful
msg.user = None
room = message[len(start_str):message.rfind(") ")]
events.emit("say-chat-room", SayChatroom(room=room, message=message, user=username))
return
else:
# Check ignore status for all other users except "server"
if core.network_filter.is_user_ignored(username):
msg.user = None
return
user_address = core.users.addresses.get(username)
if user_address is not None:
if core.network_filter.is_user_ip_ignored(username):
msg.user = None
return
elif not queued_message:
# Ask for user's IP address and queue the private message until we receive the address
if username not in self.private_message_queue:
core.users.request_ip_address(username)
self.private_message_queue_add(msg)
msg.user = None
return
user_text = core.pluginhandler.incoming_private_chat_event(username, message)
if user_text is None:
msg.user = None
return
self.show_user(username, switch_page=False)
_username, msg.message = user_text
message = msg.message
msg.message_type = self.get_message_type(message, is_outgoing_message)
is_action_message = (msg.message_type == "action")
is_ctcp_version = (message == self.CTCP_VERSION)
# SEND CLIENT VERSION to user if the following string is sent
if is_ctcp_version:
msg.message = message = "CTCP VERSION"
if is_action_message:
message = message.replace("/me ", "", 1)
if not is_outgoing_message and config.sections["words"]["censorwords"]:
message = censor_text(message, censored_patterns=config.sections["words"]["censored"])
if is_action_message:
msg.formatted_message = msg.message = f"* {tag_username} {message}"
else:
msg.formatted_message = f"[{tag_username}] {message}"
if config.sections["logging"]["privatechat"] or username in config.sections["logging"]["private_chats"]:
log.write_log_file(
folder_path=log.private_chat_folder_path,
basename=username, text=msg.formatted_message, timestamp=timestamp
)
if is_outgoing_message:
return
core.pluginhandler.incoming_private_chat_notification(username, msg.message)
if is_ctcp_version and not config.sections["server"]["ctcpmsgs"]:
self.send_message(username, f"{pynicotine.__application_name__} {pynicotine.__version__}")
if not msg.is_new_message:
# Message was sent while offline, don't auto-reply
return
autoreply = config.sections["server"]["autoreply"]
if (autoreply and core.users.login_status == UserStatus.AWAY
and username not in self.away_message_users):
self.send_automatic_message(username, autoreply)
self.away_message_users.add(username)
def update_completions(self):
self.completions.clear()
self.completions.add(config.sections["server"]["login"])
if config.sections["words"]["roomnames"]:
self.completions.update(core.chatrooms.server_rooms)
if config.sections["words"]["buddies"]:
self.completions.update(core.buddies.users)
if config.sections["words"]["commands"]:
self.completions.update(core.pluginhandler.get_command_list("private_chat"))
events.emit("private-chat-completions", self.completions.copy())
| 11,845 | Python | .py | 236 | 39.639831 | 112 | 0.638337 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,402 | utils.py | nicotine-plus_nicotine-plus/pynicotine/utils.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2020 Lene Preuss <lene.preuss@gmail.com>
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2007 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
# COPYRIGHT (C) 2001-2003 Alexander Kanavin
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
UINT32_LIMIT = 4294967295
UINT64_LIMIT = 18446744073709551615
FILE_SIZE_SUFFIXES = ["B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB"]
PUNCTUATION = [ # ASCII and Unicode punctuation
"!", '"', "#", "$", "%", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";",
"<", "=", ">", "?", "@", "[", "\\", "]", "^", "_", "`", "{", "|", "}", "~",
"\u00A1", "\u00A7", "\u00AB", "\u00B6", "\u00B7", "\u00BB", "\u00BF", "\u037E", "\u0387",
"\u055A", "\u055B", "\u055C", "\u055D", "\u055E", "\u055F", "\u0589", "\u058A", "\u05BE",
"\u05C0", "\u05C3", "\u05C6", "\u05F3", "\u05F4", "\u0609", "\u060A", "\u060C", "\u060D",
"\u061B", "\u061D", "\u061E", "\u061F", "\u066A", "\u066B", "\u066C", "\u066D", "\u06D4",
"\u0700", "\u0701", "\u0702", "\u0703", "\u0704", "\u0705", "\u0706", "\u0707", "\u0708",
"\u0709", "\u070A", "\u070B", "\u070C", "\u070D", "\u07F7", "\u07F8", "\u07F9", "\u0830",
"\u0831", "\u0832", "\u0833", "\u0834", "\u0835", "\u0836", "\u0837", "\u0838", "\u0839",
"\u083A", "\u083B", "\u083C", "\u083D", "\u083E", "\u085E", "\u0964", "\u0965", "\u0970",
"\u09FD", "\u0A76", "\u0AF0", "\u0C77", "\u0C84", "\u0DF4", "\u0E4F", "\u0E5A", "\u0E5B",
"\u0F04", "\u0F05", "\u0F06", "\u0F07", "\u0F08", "\u0F09", "\u0F0A", "\u0F0B", "\u0F0C",
"\u0F0D", "\u0F0E", "\u0F0F", "\u0F10", "\u0F11", "\u0F12", "\u0F14", "\u0F3A", "\u0F3B",
"\u0F3C", "\u0F3D", "\u0F85", "\u0FD0", "\u0FD1", "\u0FD2", "\u0FD3", "\u0FD4", "\u0FD9",
"\u0FDA", "\u104A", "\u104B", "\u104C", "\u104D", "\u104E", "\u104F", "\u10FB", "\u1360",
"\u1361", "\u1362", "\u1363", "\u1364", "\u1365", "\u1366", "\u1367", "\u1368", "\u1400",
"\u166E", "\u169B", "\u169C", "\u16EB", "\u16EC", "\u16ED", "\u1735", "\u1736", "\u17D4",
"\u17D5", "\u17D6", "\u17D8", "\u17D9", "\u17DA", "\u1800", "\u1801", "\u1802", "\u1803",
"\u1804", "\u1805", "\u1806", "\u1807", "\u1808", "\u1809", "\u180A", "\u1944", "\u1945",
"\u1A1E", "\u1A1F", "\u1AA0", "\u1AA1", "\u1AA2", "\u1AA3", "\u1AA4", "\u1AA5", "\u1AA6",
"\u1AA8", "\u1AA9", "\u1AAA", "\u1AAB", "\u1AAC", "\u1AAD", "\u1B5A", "\u1B5B", "\u1B5C",
"\u1B5D", "\u1B5E", "\u1B5F", "\u1B60", "\u1B7D", "\u1B7E", "\u1BFC", "\u1BFD", "\u1BFE",
"\u1BFF", "\u1C3B", "\u1C3C", "\u1C3D", "\u1C3E", "\u1C3F", "\u1C7E", "\u1C7F", "\u1CC0",
"\u1CC1", "\u1CC2", "\u1CC3", "\u1CC4", "\u1CC5", "\u1CC6", "\u1CC7", "\u1CD3", "\u2010",
"\u2011", "\u2012", "\u2013", "\u2014", "\u2015", "\u2016", "\u2017", "\u2018", "\u2019",
"\u201A", "\u201B", "\u201C", "\u201D", "\u201E", "\u201F", "\u2020", "\u2021", "\u2022",
"\u2023", "\u2024", "\u2025", "\u2026", "\u2027", "\u2030", "\u2031", "\u2032", "\u2033",
"\u2034", "\u2035", "\u2036", "\u2037", "\u2038", "\u2039", "\u203A", "\u203B", "\u203C",
"\u203D", "\u203E", "\u203F", "\u2040", "\u2041", "\u2042", "\u2043", "\u2045", "\u2046",
"\u2047", "\u2048", "\u2049", "\u204A", "\u204B", "\u204C", "\u204D", "\u204E", "\u204F",
"\u2050", "\u2051", "\u2053", "\u2054", "\u2055", "\u2056", "\u2057", "\u2058", "\u2059",
"\u205A", "\u205B", "\u205C", "\u205D", "\u205E", "\u207D", "\u207E", "\u208D", "\u208E",
"\u2308", "\u2309", "\u230A", "\u230B", "\u2329", "\u232A", "\u2768", "\u2769", "\u276A",
"\u276B", "\u276C", "\u276D", "\u276E", "\u276F", "\u2770", "\u2771", "\u2772", "\u2773",
"\u2774", "\u2775", "\u27C5", "\u27C6", "\u27E6", "\u27E7", "\u27E8", "\u27E9", "\u27EA",
"\u27EB", "\u27EC", "\u27ED", "\u27EE", "\u27EF", "\u2983", "\u2984", "\u2985", "\u2986",
"\u2987", "\u2988", "\u2989", "\u298A", "\u298B", "\u298C", "\u298D", "\u298E", "\u298F",
"\u2990", "\u2991", "\u2992", "\u2993", "\u2994", "\u2995", "\u2996", "\u2997", "\u2998",
"\u29D8", "\u29D9", "\u29DA", "\u29DB", "\u29FC", "\u29FD", "\u2CF9", "\u2CFA", "\u2CFB",
"\u2CFC", "\u2CFE", "\u2CFF", "\u2D70", "\u2E00", "\u2E01", "\u2E02", "\u2E03", "\u2E04",
"\u2E05", "\u2E06", "\u2E07", "\u2E08", "\u2E09", "\u2E0A", "\u2E0B", "\u2E0C", "\u2E0D",
"\u2E0E", "\u2E0F", "\u2E10", "\u2E11", "\u2E12", "\u2E13", "\u2E14", "\u2E15", "\u2E16",
"\u2E17", "\u2E18", "\u2E19", "\u2E1A", "\u2E1B", "\u2E1C", "\u2E1D", "\u2E1E", "\u2E1F",
"\u2E20", "\u2E21", "\u2E22", "\u2E23", "\u2E24", "\u2E25", "\u2E26", "\u2E27", "\u2E28",
"\u2E29", "\u2E2A", "\u2E2B", "\u2E2C", "\u2E2D", "\u2E2E", "\u2E30", "\u2E31", "\u2E32",
"\u2E33", "\u2E34", "\u2E35", "\u2E36", "\u2E37", "\u2E38", "\u2E39", "\u2E3A", "\u2E3B",
"\u2E3C", "\u2E3D", "\u2E3E", "\u2E3F", "\u2E40", "\u2E41", "\u2E42", "\u2E43", "\u2E44",
"\u2E45", "\u2E46", "\u2E47", "\u2E48", "\u2E49", "\u2E4A", "\u2E4B", "\u2E4C", "\u2E4D",
"\u2E4E", "\u2E4F", "\u2E52", "\u2E53", "\u2E54", "\u2E55", "\u2E56", "\u2E57", "\u2E58",
"\u2E59", "\u2E5A", "\u2E5B", "\u2E5C", "\u2E5D", "\u3001", "\u3002", "\u3003", "\u3008",
"\u3009", "\u300A", "\u300B", "\u300C", "\u300D", "\u300E", "\u300F", "\u3010", "\u3011",
"\u3014", "\u3015", "\u3016", "\u3017", "\u3018", "\u3019", "\u301A", "\u301B", "\u301C",
"\u301D", "\u301E", "\u301F", "\u3030", "\u303D", "\u30A0", "\u30FB", "\uA4FE", "\uA4FF",
"\uA60D", "\uA60E", "\uA60F", "\uA673", "\uA67E", "\uA6F2", "\uA6F3", "\uA6F4", "\uA6F5",
"\uA6F6", "\uA6F7", "\uA874", "\uA875", "\uA876", "\uA877", "\uA8CE", "\uA8CF", "\uA8F8",
"\uA8F9", "\uA8FA", "\uA8FC", "\uA92E", "\uA92F", "\uA95F", "\uA9C1", "\uA9C2", "\uA9C3",
"\uA9C4", "\uA9C5", "\uA9C6", "\uA9C7", "\uA9C8", "\uA9C9", "\uA9CA", "\uA9CB", "\uA9CC",
"\uA9CD", "\uA9DE", "\uA9DF", "\uAA5C", "\uAA5D", "\uAA5E", "\uAA5F", "\uAADE", "\uAADF",
"\uAAF0", "\uAAF1", "\uABEB", "\uFD3E", "\uFD3F", "\uFE10", "\uFE11", "\uFE12", "\uFE13",
"\uFE14", "\uFE15", "\uFE16", "\uFE17", "\uFE18", "\uFE19", "\uFE30", "\uFE31", "\uFE32",
"\uFE33", "\uFE34", "\uFE35", "\uFE36", "\uFE37", "\uFE38", "\uFE39", "\uFE3A", "\uFE3B",
"\uFE3C", "\uFE3D", "\uFE3E", "\uFE3F", "\uFE40", "\uFE41", "\uFE42", "\uFE43", "\uFE44",
"\uFE45", "\uFE46", "\uFE47", "\uFE48", "\uFE49", "\uFE4A", "\uFE4B", "\uFE4C", "\uFE4D",
"\uFE4E", "\uFE4F", "\uFE50", "\uFE51", "\uFE52", "\uFE54", "\uFE55", "\uFE56", "\uFE57",
"\uFE58", "\uFE59", "\uFE5A", "\uFE5B", "\uFE5C", "\uFE5D", "\uFE5E", "\uFE5F", "\uFE60",
"\uFE61", "\uFE62", "\uFE63", "\uFE64", "\uFE65", "\uFE66", "\uFE68", "\uFE6A", "\uFE6B",
"\uFF01", "\uFF02", "\uFF03", "\uFF05", "\uFF06", "\uFF07", "\uFF08", "\uFF09", "\uFF0A",
"\uFF0B", "\uFF0C", "\uFF0D", "\uFF0E", "\uFF0F", "\uFF1A", "\uFF1B", "\uFF1C", "\uFF1D",
"\uFF1E", "\uFF1F", "\uFF20", "\uFF3B", "\uFF3C", "\uFF3D", "\uFF3F", "\uFF5B", "\uFF5C",
"\uFF5D", "\uFF5E", "\uFF5F", "\uFF60", "\uFF61", "\uFF62", "\uFF63", "\uFF64", "\uFF65",
"\U00010100", "\U00010101", "\U00010102", "\U0001039F", "\U000103D0", "\U0001056F", "\U00010857",
"\U0001091F", "\U0001093F", "\U00010A50", "\U00010A51", "\U00010A52", "\U00010A53", "\U00010A54",
"\U00010A55", "\U00010A56", "\U00010A57", "\U00010A58", "\U00010A7F", "\U00010AF0", "\U00010AF1",
"\U00010AF2", "\U00010AF3", "\U00010AF4", "\U00010AF5", "\U00010AF6", "\U00010B39", "\U00010B3A",
"\U00010B3B", "\U00010B3C", "\U00010B3D", "\U00010B3E", "\U00010B3F", "\U00010B99", "\U00010B9A",
"\U00010B9B", "\U00010B9C", "\U00010EAD", "\U00010F55", "\U00010F56", "\U00010F57", "\U00010F58",
"\U00010F59", "\U00010F86", "\U00010F87", "\U00010F88", "\U00010F89", "\U00011047", "\U00011048",
"\U00011049", "\U0001104A", "\U0001104B", "\U0001104C", "\U0001104D", "\U000110BB", "\U000110BC",
"\U000110BE", "\U000110BF", "\U000110C0", "\U000110C1", "\U00011140", "\U00011141", "\U00011142",
"\U00011143", "\U00011174", "\U00011175", "\U000111C5", "\U000111C6", "\U000111C7", "\U000111C8",
"\U000111CD", "\U000111DB", "\U000111DD", "\U000111DE", "\U000111DF", "\U00011238", "\U00011239",
"\U0001123A", "\U0001123B", "\U0001123C", "\U0001123D", "\U000112A9", "\U0001144B", "\U0001144C",
"\U0001144D", "\U0001144E", "\U0001144F", "\U0001145A", "\U0001145B", "\U0001145D", "\U000114C6",
"\U000115C1", "\U000115C2", "\U000115C3", "\U000115C4", "\U000115C5", "\U000115C6", "\U000115C7",
"\U000115C8", "\U000115C9", "\U000115CA", "\U000115CB", "\U000115CC", "\U000115CD", "\U000115CE",
"\U000115CF", "\U000115D0", "\U000115D1", "\U000115D2", "\U000115D3", "\U000115D4", "\U000115D5",
"\U000115D6", "\U000115D7", "\U00011641", "\U00011642", "\U00011643", "\U00011660", "\U00011661",
"\U00011662", "\U00011663", "\U00011664", "\U00011665", "\U00011666", "\U00011667", "\U00011668",
"\U00011669", "\U0001166A", "\U0001166B", "\U0001166C", "\U000116B9", "\U0001173C", "\U0001173D",
"\U0001173E", "\U0001183B", "\U00011944", "\U00011945", "\U00011946", "\U000119E2", "\U00011A3F",
"\U00011A40", "\U00011A41", "\U00011A42", "\U00011A43", "\U00011A44", "\U00011A45", "\U00011A46",
"\U00011A9A", "\U00011A9B", "\U00011A9C", "\U00011A9E", "\U00011A9F", "\U00011AA0", "\U00011AA1",
"\U00011AA2", "\U00011B00", "\U00011B01", "\U00011B02", "\U00011B03", "\U00011B04", "\U00011B05",
"\U00011B06", "\U00011B07", "\U00011B08", "\U00011B09", "\U00011C41", "\U00011C42", "\U00011C43",
"\U00011C44", "\U00011C45", "\U00011C70", "\U00011C71", "\U00011EF7", "\U00011EF8", "\U00011F43",
"\U00011F44", "\U00011F45", "\U00011F46", "\U00011F47", "\U00011F48", "\U00011F49", "\U00011F4A",
"\U00011F4B", "\U00011F4C", "\U00011F4D", "\U00011F4E", "\U00011F4F", "\U00011FFF", "\U00012470",
"\U00012471", "\U00012472", "\U00012473", "\U00012474", "\U00012FF1", "\U00012FF2", "\U00016A6E",
"\U00016A6F", "\U00016AF5", "\U00016B37", "\U00016B38", "\U00016B39", "\U00016B3A", "\U00016B3B",
"\U00016B44", "\U00016E97", "\U00016E98", "\U00016E99", "\U00016E9A", "\U00016FE2", "\U0001BC9F",
"\U0001DA87", "\U0001DA88", "\U0001DA89", "\U0001DA8A", "\U0001DA8B", "\U0001E95E", "\U0001E95F"
]
ILLEGALPATHCHARS = [
# ASCII printable characters
"?", ":", ">", "<", "|", "*", '"',
# ASCII control characters
"\u0000", "\u0001", "\u0002", "\u0003", "\u0004", "\u0005", "\u0006", "\u0007", "\u0008",
"\u0009", "\u000A", "\u000B", "\u000C", "\u000D", "\u000E", "\u000F", "\u0010", "\u0011",
"\u0012", "\u0013", "\u0014", "\u0015", "\u0016", "\u0017", "\u0018", "\u0019", "\u001A",
"\u001B", "\u001C", "\u001D", "\u001E", "\u001F"
]
ILLEGALFILECHARS = ["\\", "/"] + ILLEGALPATHCHARS
LONG_PATH_PREFIX = "\\\\?\\"
REPLACEMENTCHAR = "_"
TRANSLATE_PUNCTUATION = str.maketrans(dict.fromkeys(PUNCTUATION, " "))
def clean_file(basename):
for char in ILLEGALFILECHARS:
if char in basename:
basename = basename.replace(char, REPLACEMENTCHAR)
# Filename can never end with a period or space on Windows machines
basename = basename.rstrip(". ")
if not basename:
basename = REPLACEMENTCHAR
return basename
def clean_path(path):
path = os.path.normpath(path)
# Without hacks it is (up to Vista) not possible to have more
# than 26 drives mounted, so we can assume a '[a-zA-Z]:\' prefix
# for drives - we shouldn't escape that
drive = ""
if len(path) >= 3 and path[1] == ":" and path[2] == os.sep:
drive = path[:3]
path = path[3:]
for char in ILLEGALPATHCHARS:
if char in path:
path = path.replace(char, REPLACEMENTCHAR)
path = "".join([drive, path])
# Path can never end with a period or space on Windows machines
path = path.rstrip(". ")
return path
def encode_path(path, prefix=True):
"""Converts a file path to bytes for processing by the system.
On Windows, also append prefix to enable extended-length path.
"""
if sys.platform == "win32" and prefix:
path = path.replace("/", "\\")
if path.startswith("\\\\"):
path = "UNC" + path[1:]
path = LONG_PATH_PREFIX + path
return path.encode("utf-8")
def human_length(seconds):
minutes, seconds = divmod(int(seconds), 60)
hours, minutes = divmod(minutes, 60)
days, hours = divmod(hours, 24)
if days > 0:
return f"{days}:{hours:02d}:{minutes:02d}:{seconds:02d}"
if hours > 0:
return f"{hours}:{minutes:02d}:{seconds:02d}"
return f"{minutes}:{seconds:02d}"
def _human_speed_or_size(number, unit=None):
if unit == "B":
return humanize(number)
for suffix in FILE_SIZE_SUFFIXES:
if number < 1024:
if number > 999:
return f"{number:.4g} {suffix}"
return f"{number:.3g} {suffix}"
number /= 1024
return str(number)
def human_speed(speed):
return _human_speed_or_size(speed) + "/s"
def human_size(filesize, unit=None):
return _human_speed_or_size(filesize, unit)
def humanize(number):
return f"{number:n}"
def factorize(filesize, base=1024):
"""Converts filesize string with a given unit into raw integer size,
defaults to binary for "k", "m", "g" suffixes (KiB, MiB, GiB)"""
if not filesize:
return None, None
filesize = filesize.lower()
if filesize.endswith("b"):
base = 1000 # Byte suffix detected, prepare to use decimal if necessary
filesize = filesize[:-1]
if filesize.endswith("i"):
base = 1024 # Binary requested, stop using decimal
filesize = filesize[:-1]
if filesize.endswith("g"):
factor = pow(base, 3)
filesize = filesize[:-1]
elif filesize.endswith("m"):
factor = pow(base, 2)
filesize = filesize[:-1]
elif filesize.endswith("k"):
factor = base
filesize = filesize[:-1]
else:
factor = 1
try:
return int(float(filesize) * factor), factor
except ValueError:
return None, factor
def truncate_string_byte(string, byte_limit, encoding="utf-8", ellipsize=False):
"""Truncates a string to fit inside a byte limit."""
string_bytes = string.encode(encoding)
if len(string_bytes) <= byte_limit:
# Nothing to do, return original string
return string
if ellipsize:
ellipsis_char = "…".encode(encoding)
string_bytes = string_bytes[:max(byte_limit - len(ellipsis_char), 0)].rstrip() + ellipsis_char
else:
string_bytes = string_bytes[:byte_limit]
return string_bytes.decode(encoding, "ignore")
def unescape(string):
"""Removes quotes from the beginning and end of strings, and unescapes
it."""
string = string.encode("latin-1", "backslashreplace").decode("unicode-escape")
try:
if (string[0] == string[-1]) and string.startswith(("'", '"')):
return string[1:-1]
except IndexError:
pass
return string
def find_whole_word(word, text):
"""Returns start position of a whole word that is not in a subword."""
if word not in text:
return -1
word_boundaries = [" "] + PUNCTUATION
len_text = len(text)
len_word = len(word)
start = after = 0
whole = False
while not whole and start > -1:
start = text.find(word, after)
after = start + len_word
whole = ((text[after] if after < len_text else " ") in word_boundaries
and (text[start - 1] if start > 0 else " ") in word_boundaries)
return start if whole else -1
def censor_text(text, censored_patterns, filler="*"):
for word in censored_patterns:
word = str(word)
text = text.replace(word, filler * len(word))
return text
def execute_command(command, replacement=None, background=True, returnoutput=False,
hidden=False, placeholder="$"):
"""Executes a string with commands, with partial support for bash-style
quoting and pipes.
The different parts of the command should be separated by spaces, a double
quotation mark can be used to embed spaces in an argument.
Pipes can be created using the bar symbol (|).
If background is false the function will wait for all the launched
processes to end before returning.
If hidden is true, any window created by the command will be hidden
(on Windows).
If the 'replacement' argument is given, every occurrence of 'placeholder'
will be replaced by 'replacement'.
If the command ends with the ampersand symbol background
will be set to True. This should only be done by the request of the user,
if you want background to be true set the function argument.
The only expected error to be thrown is the RuntimeError in case something
goes wrong while executing the command.
Example commands:
* "C:\\Program Files\\WinAmp\\WinAmp.exe" --xforce "--title=My Window Title"
* mplayer $
* echo $ | flite -t
"""
# pylint: disable=consider-using-with
from subprocess import PIPE, Popen
# Example command: "C:\Program Files\WinAmp\WinAmp.exe" --xforce "--title=My Title" $ | flite -t
if returnoutput:
background = False
command = command.strip()
startupinfo = None
if hidden and sys.platform == "win32":
from subprocess import STARTF_USESHOWWINDOW, STARTUPINFO
# Hide console window on Windows
startupinfo = STARTUPINFO()
startupinfo.dwFlags |= STARTF_USESHOWWINDOW
if command.endswith("&"):
command = command[:-1]
if returnoutput:
from pynicotine.logfacility import log
log.add("Yikes, I was asked to return output but I'm also asked to launch "
"the process in the background. returnoutput gets precedent.")
else:
background = True
unparsed = command
arguments = []
while unparsed.count('"') > 1:
(pre, argument, post) = unparsed.split('"', 2)
if pre:
arguments += pre.rstrip(" ").split(" ")
arguments.append(argument)
unparsed = post.lstrip(" ")
if unparsed:
arguments += unparsed.split(" ")
# arguments is now: ['C:\Program Files\WinAmp\WinAmp.exe', '--xforce', '--title=My Title', '$', '|', 'flite', '-t']
subcommands = []
current = []
for argument in arguments:
if argument == "|":
subcommands.append(current)
current = []
else:
current.append(argument)
subcommands.append(current)
# subcommands is now: [['C:\Program Files\WinAmp\WinAmp.exe', '--xforce', '--title=My Title', '$'], ['flite', '-t']]
if replacement:
for i, _ in enumerate(subcommands):
subcommands[i] = [x.replace(placeholder, replacement) for x in subcommands[i]]
# Chaining commands...
finalstdout = None
if returnoutput:
finalstdout = PIPE
procs = []
try:
if len(subcommands) == 1: # no need to fool around with pipes
procs.append(Popen(subcommands[0], startupinfo=startupinfo, stdout=finalstdout))
else:
procs.append(Popen(subcommands[0], startupinfo=startupinfo, stdout=PIPE))
for subcommand in subcommands[1:-1]:
procs.append(Popen(subcommand, startupinfo=startupinfo, stdin=procs[-1].stdout,
stdout=PIPE))
procs.append(Popen(subcommands[-1], startupinfo=startupinfo, stdin=procs[-1].stdout,
stdout=finalstdout))
if not background and not returnoutput:
procs[-1].wait()
except Exception as error:
command = subcommands[len(procs)]
command_no = len(procs) + 1
num_commands = len(subcommands)
raise RuntimeError(
f"Problem while executing command {command} ({command_no} of "
f"{num_commands}): {error}") from error
if not returnoutput:
return True
return procs[-1].communicate()[0]
def _try_open_uri(uri):
if sys.platform not in {"darwin", "win32"}:
try:
from gi.repository import Gio # pylint: disable=import-error
Gio.AppInfo.launch_default_for_uri(uri)
return
except Exception:
# Fall back to webbrowser module
pass
import webbrowser
if not webbrowser.open(uri):
raise webbrowser.Error("No known URI provider available")
def _open_path(path, is_folder=False, create_folder=False, create_file=False):
"""Currently used to either open a folder or play an audio file.
Tries to run a user-specified command first, and falls back to the system
default.
"""
if path is None:
return False
try:
from pynicotine.config import config
path = os.path.abspath(path)
path_encoded = encode_path(path)
_path, separator, extension = path.rpartition(".")
protocol_command = None
protocol_handlers = config.sections["urls"]["protocols"]
file_manager_command = config.sections["ui"]["filemanager"]
if separator:
from pynicotine.shares import FileTypes
if "." + extension in protocol_handlers:
protocol = "." + extension
elif extension in FileTypes.AUDIO:
protocol = "audio"
elif extension in FileTypes.IMAGE:
protocol = "image"
elif extension in FileTypes.VIDEO:
protocol = "video"
elif extension in FileTypes.DOCUMENT:
protocol = "document"
elif extension in FileTypes.TEXT:
protocol = "text"
elif extension in FileTypes.ARCHIVE:
protocol = "archive"
else:
protocol = None
protocol_command = protocol_handlers.get(protocol)
if not os.path.exists(path_encoded):
if create_folder:
os.makedirs(path_encoded)
elif create_file:
with open(path_encoded, "w", encoding="utf-8"):
# Create empty file
pass
else:
raise FileNotFoundError("File path does not exist")
if is_folder and "$" in file_manager_command:
execute_command(file_manager_command, path)
elif protocol_command:
execute_command(protocol_command, path)
elif sys.platform == "win32":
os.startfile(path_encoded) # pylint: disable=no-member
elif sys.platform == "darwin":
execute_command("open $", path)
else:
_try_open_uri("file:///" + path)
except Exception as error:
from pynicotine.logfacility import log
log.add(_("Cannot open file path %(path)s: %(error)s"), {"path": path, "error": error})
return False
return True
def open_file_path(file_path, create_file=False):
return _open_path(path=file_path, create_file=create_file)
def open_folder_path(folder_path, create_folder=False):
return _open_path(path=folder_path, is_folder=True, create_folder=create_folder)
def open_uri(uri):
"""Open a URI in an external (web) browser.
The given argument has to be a properly formed URI including the
scheme (fe. HTTP).
"""
from pynicotine.config import config
try:
# Situation 1, user defined a way of handling the protocol
protocol = uri[:uri.find(":")]
if not protocol.startswith(".") and protocol not in {"audio", "image", "video", "document", "text", "archive"}:
protocol_handlers = config.sections["urls"]["protocols"]
protocol_command = protocol_handlers.get(protocol + "://") or protocol_handlers.get(protocol)
if protocol_command:
execute_command(protocol_command, uri)
return True
if protocol == "slsk":
from pynicotine.core import core
core.userbrowse.open_soulseek_url(uri.strip())
return True
# Situation 2, user did not define a way of handling the protocol
_try_open_uri(uri)
return True
except Exception as error:
from pynicotine.logfacility import log
log.add(_("Cannot open URL %(url)s: %(error)s"), {"url": uri, "error": error})
return False
def load_file(file_path, load_func, use_old_file=False):
try:
if use_old_file:
file_path = f"{file_path}.old"
elif os.path.isfile(encode_path(f"{file_path}.old")):
file_path_encoded = encode_path(file_path)
if not os.path.isfile(file_path_encoded):
raise OSError("*.old file is present but main file is missing")
if os.path.getsize(file_path_encoded) <= 0:
# Empty files should be considered broken/corrupted
raise OSError("*.old file is present but main file is empty")
return load_func(file_path)
except Exception as error:
from pynicotine.logfacility import log
log.add(_("Something went wrong while reading file %(filename)s: %(error)s"),
{"filename": file_path, "error": error})
if not use_old_file:
# Attempt to load data from .old file
log.add(_("Attempting to load backup of file %s"), file_path)
return load_file(file_path, load_func, use_old_file=True)
return None
def write_file_and_backup(path, callback, protect=False):
from pynicotine.logfacility import log
path_encoded = encode_path(path)
path_old_encoded = encode_path(f"{path}.old")
# Back up old file to path.old
try:
if os.path.exists(path_encoded) and os.stat(path_encoded).st_size > 0:
os.replace(path_encoded, path_old_encoded)
if protect:
os.chmod(path_old_encoded, 0o600)
except Exception as error:
log.add(_("Unable to back up file %(path)s: %(error)s"), {
"path": path,
"error": error
})
return
# Save new file
if protect:
oldumask = os.umask(0o077)
try:
with open(path_encoded, "w", encoding="utf-8") as file_handle:
callback(file_handle)
# Force write to file immediately in case of hard shutdown
file_handle.flush()
os.fsync(file_handle.fileno())
log.add_debug("Backed up and saved file %s", path)
except Exception as error:
log.add(_("Unable to save file %(path)s: %(error)s"), {
"path": path,
"error": error
})
# Attempt to restore file
try:
if os.path.exists(path_old_encoded):
os.replace(path_old_encoded, path_encoded)
except Exception as second_error:
log.add(_("Unable to restore previous file %(path)s: %(error)s"), {
"path": path,
"error": second_error
})
if protect:
os.umask(oldumask)
# Debugging #
def debug(*args):
"""Prints debugging info."""
from pynicotine.logfacility import log
truncated_args = [arg[:200] if isinstance(arg, str) else arg for arg in args]
log.add("*" * 8, truncated_args)
def strace(function):
"""Decorator for debugging."""
from itertools import chain
from pynicotine.logfacility import log
def newfunc(*args, **kwargs):
name = function.__name__
log.add(f"{name}({', '.join(repr(x) for x in chain(args, list(kwargs.values())))})")
retvalue = function(*args, **kwargs)
log.add(f"{name}({', '.join(repr(x) for x in chain(args, list(kwargs.values())))}): {repr(retvalue)}")
return retvalue
return newfunc
| 28,643 | Python | .py | 546 | 44.858974 | 120 | 0.589951 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,403 | downloads.py | nicotine-plus_nicotine-plus/pynicotine/downloads.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2016 Mutnick <muhing@yahoo.com>
# COPYRIGHT (C) 2013 eLvErDe <gandalf@le-vert.net>
# COPYRIGHT (C) 2008-2012 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2009 hedonist <ak@sensi.org>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
# COPYRIGHT (C) 2001-2003 Alexander Kanavin
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import shutil
import time
try:
# Try faster module import first, if available
from _md5 import md5 # pylint: disable=import-private-name
except ImportError:
from hashlib import md5
from collections import defaultdict
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.logfacility import log
from pynicotine.slskmessages import ConnectionType
from pynicotine.slskmessages import DownloadFile
from pynicotine.slskmessages import FileOffset
from pynicotine.slskmessages import FolderContentsRequest
from pynicotine.slskmessages import increment_token
from pynicotine.slskmessages import initial_token
from pynicotine.slskmessages import PlaceInQueueRequest
from pynicotine.slskmessages import QueueUpload
from pynicotine.slskmessages import SetDownloadLimit
from pynicotine.slskmessages import TransferDirection
from pynicotine.slskmessages import TransferRejectReason
from pynicotine.slskmessages import TransferResponse
from pynicotine.slskmessages import UserStatus
from pynicotine.transfers import Transfer
from pynicotine.transfers import Transfers
from pynicotine.transfers import TransferStatus
from pynicotine.utils import execute_command
from pynicotine.utils import clean_file
from pynicotine.utils import clean_path
from pynicotine.utils import encode_path
from pynicotine.utils import truncate_string_byte
class RequestedFolder:
__slots__ = ("username", "folder_path", "download_folder_path", "request_timer_id", "has_retried",
"legacy_attempt")
def __init__(self, username, folder_path, download_folder_path):
self.username = username
self.folder_path = folder_path
self.download_folder_path = download_folder_path
self.request_timer_id = None
self.has_retried = False
self.legacy_attempt = False
class Downloads(Transfers):
__slots__ = ("_requested_folders", "_requested_folder_token", "_folder_basename_byte_limits",
"_pending_queue_messages", "_download_queue_timer_id", "_retry_connection_downloads_timer_id",
"_retry_io_downloads_timer_id")
def __init__(self):
super().__init__(name="downloads")
self._requested_folders = defaultdict(dict)
self._requested_folder_token = initial_token()
self._folder_basename_byte_limits = {}
self._pending_queue_messages = {}
self._download_queue_timer_id = None
self._retry_connection_downloads_timer_id = None
self._retry_io_downloads_timer_id = None
for event_name, callback in (
("download-file-error", self._download_file_error),
("file-connection-closed", self._file_connection_closed),
("file-transfer-init", self._file_transfer_init),
("file-download-progress", self._file_download_progress),
("folder-contents-response", self._folder_contents_response),
("peer-connection-closed", self._peer_connection_closed),
("peer-connection-error", self._peer_connection_error),
("place-in-queue-response", self._place_in_queue_response),
("set-connection-stats", self._set_connection_stats),
("shares-ready", self._shares_ready),
("transfer-request", self._transfer_request),
("upload-denied", self._upload_denied),
("upload-failed", self._upload_failed),
("user-status", self._user_status)
):
events.connect(event_name, callback)
def _start(self):
super()._start()
self.update_download_filters()
def _quit(self):
self._delete_stale_incomplete_downloads()
super()._quit()
self._folder_basename_byte_limits.clear()
def _server_login(self, msg):
if not msg.success:
return
super()._server_login(msg)
# Request queue position of queued downloads every 5 minutes
self._download_queue_timer_id = events.schedule(
delay=300, callback=self._request_queue_positions, repeat=True)
# Retry downloads failed due to connection issues every 3 minutes
self._retry_connection_downloads_timer_id = events.schedule(
delay=180, callback=self._retry_failed_connection_downloads, repeat=True)
# Retry downloads failed due to file I/O errors every 15 minutes
self._retry_io_downloads_timer_id = events.schedule(
delay=900, callback=self._retry_failed_io_downloads, repeat=True)
def _server_disconnect(self, msg):
super()._server_disconnect(msg)
for timer_id in (
self._download_queue_timer_id,
self._retry_connection_downloads_timer_id,
self._retry_io_downloads_timer_id
):
events.cancel_scheduled(timer_id)
for user_requested_folders in self._requested_folders.values():
for requested_folder in user_requested_folders.values():
if requested_folder.request_timer_id is None:
continue
events.cancel_scheduled(requested_folder.request_timer_id)
requested_folder.request_timer_id = None
self._requested_folders.clear()
# Load Transfers #
def _get_transfer_list_file_path(self):
downloads_file_1_4_2 = os.path.join(config.data_folder_path, "config.transfers.pickle")
downloads_file_1_4_1 = os.path.join(config.data_folder_path, "transfers.pickle")
if os.path.exists(encode_path(self.transfers_file_path)):
# New file format
return self.transfers_file_path
if os.path.exists(encode_path(downloads_file_1_4_2)):
# Nicotine+ 1.4.2+
return downloads_file_1_4_2
if os.path.exists(encode_path(downloads_file_1_4_1)):
# Nicotine <=1.4.1
return downloads_file_1_4_1
# Fall back to new file format
return self.transfers_file_path
def _load_transfers(self):
load_func = self._load_transfers_file
transfers_file_path = self._get_transfer_list_file_path()
if transfers_file_path != self.transfers_file_path:
load_func = self._load_legacy_transfers_file
for transfer in self._get_stored_transfers(transfers_file_path, load_func):
self._append_transfer(transfer)
if transfer.status == TransferStatus.USER_LOGGED_OFF:
# Mark transfer as failed in order to resume it when connected
self._fail_transfer(transfer)
# Filters/Limits #
def update_download_filters(self):
failed = {}
outfilter = "(\\\\("
download_filters = sorted(config.sections["transfers"]["downloadfilters"])
# Get Filters from config file and check their escaped status
# Test if they are valid regular expressions and save error messages
for item in download_filters:
dfilter, escaped = item
if escaped:
dfilter = re.escape(dfilter)
dfilter = dfilter.replace("\\*", ".*")
try:
re.compile(f"({dfilter})")
outfilter += dfilter
if item is not download_filters[-1]:
outfilter += "|"
except re.error as error:
failed[dfilter] = error
outfilter += ")$)"
try:
re.compile(outfilter)
except re.error as error:
# Strange that individual filters _and_ the composite filter both fail
log.add(_("Error: Download Filter failed! Verify your filters. Reason: %s"), error)
config.sections["transfers"]["downloadregexp"] = ""
return
config.sections["transfers"]["downloadregexp"] = outfilter
# Send error messages for each failed filter to log window
if not failed:
return
errors = ""
for dfilter, error in failed.items():
errors += f"Filter: {dfilter} Error: {error} "
log.add(_("Error: %(num)d Download filters failed! %(error)s "), {"num": len(failed), "error": errors})
def update_transfer_limits(self):
events.emit("update-download-limits")
use_speed_limit = config.sections["transfers"]["use_download_speed_limit"]
if use_speed_limit == "primary":
speed_limit = config.sections["transfers"]["downloadlimit"]
elif use_speed_limit == "alternative":
speed_limit = config.sections["transfers"]["downloadlimitalt"]
else:
speed_limit = 0
core.send_message_to_network_thread(SetDownloadLimit(speed_limit))
# Transfer Actions #
def _update_transfer(self, transfer, update_parent=True):
events.emit("update-download", transfer, update_parent)
def _enqueue_transfer(self, transfer, bypass_filter=False):
username = transfer.username
virtual_path = transfer.virtual_path
size = transfer.size
if not bypass_filter and config.sections["transfers"]["enablefilters"]:
try:
downloadregexp = re.compile(config.sections["transfers"]["downloadregexp"], flags=re.IGNORECASE)
if downloadregexp.search(virtual_path) is not None:
log.add_transfer("Filtering: %s", virtual_path)
if not self._auto_clear_transfer(transfer):
self._abort_transfer(transfer, status=TransferStatus.FILTERED)
return False
except re.error:
pass
if UserStatus.OFFLINE in (core.users.login_status, core.users.statuses.get(username)):
# Either we are offline or the user we want to download from is
self._abort_transfer(transfer, status=TransferStatus.USER_LOGGED_OFF)
return False
log.add_transfer("Adding file %s from user %s to download queue", (virtual_path, username))
_file_path, file_exists = self.get_complete_download_file_path(
username, virtual_path, size, transfer.folder_path)
if file_exists:
self._finish_transfer(transfer)
return False
super()._enqueue_transfer(transfer)
msg = QueueUpload(virtual_path, transfer.legacy_attempt)
if not core.shares.initialized:
# Remain queued locally until our shares have initialized, to prevent invalid
# messages about not sharing any files
self._pending_queue_messages[transfer] = msg
else:
core.send_message_to_peer(username, msg)
return True
def _enqueue_limited_transfers(self, username):
num_limited_transfers = 0
queue_size_limit = self._user_queue_limits.get(username)
if queue_size_limit is None:
return
for download in self.failed_users.get(username, {}).copy().values():
if download.status != TransferRejectReason.QUEUED:
continue
if num_limited_transfers >= queue_size_limit:
# Only enqueue a small number of downloads at a time
return
self._unfail_transfer(download)
if self._enqueue_transfer(download):
self._update_transfer(download)
num_limited_transfers += 1
# No more limited downloads
del self._user_queue_limits[username]
def _dequeue_transfer(self, transfer):
super()._dequeue_transfer(transfer)
if transfer in self._pending_queue_messages:
del self._pending_queue_messages[transfer]
def _file_downloaded_actions(self, username, file_path):
if config.sections["notifications"]["notification_popup_file"]:
core.notifications.show_download_notification(
_("%(file)s downloaded from %(user)s") % {
"user": username,
"file": os.path.basename(file_path)
},
title=_("File Downloaded")
)
command = config.sections["transfers"]["afterfinish"]
if command:
try:
execute_command(command, file_path, hidden=True)
log.add(_("Executed: %s"), command)
except Exception as error:
log.add(_("Executing '%(command)s' failed: %(error)s"), {
"command": command,
"error": error
})
def _folder_downloaded_actions(self, username, folder_path):
if not folder_path:
return
if folder_path == self.get_default_download_folder(username):
return
for downloads in (
self.queued_users.get(username, {}),
self.active_users.get(username, {}),
self.failed_users.get(username, {})
):
for download in downloads.values():
if download.folder_path == folder_path:
return
events.emit("folder-download-finished", folder_path)
if config.sections["notifications"]["notification_popup_folder"]:
core.notifications.show_download_notification(
_("%(folder)s downloaded from %(user)s") % {
"user": username,
"folder": folder_path
},
title=_("Folder Downloaded")
)
command = config.sections["transfers"]["afterfolder"]
if command:
try:
execute_command(command, folder_path, hidden=True)
log.add(_("Executed on folder: %s"), command)
except Exception as error:
log.add(_("Executing '%(command)s' failed: %(error)s"), {
"command": command,
"error": error
})
def _move_finished_transfer(self, transfer, incomplete_file_path):
download_folder_path = transfer.folder_path or self.get_default_download_folder(transfer.username)
download_folder_path_encoded = encode_path(download_folder_path)
download_basename = self.get_download_basename(transfer.virtual_path, download_folder_path, avoid_conflict=True)
download_file_path = os.path.join(download_folder_path, download_basename)
try:
if not os.path.isdir(download_folder_path_encoded):
os.makedirs(download_folder_path_encoded)
shutil.move(incomplete_file_path, encode_path(download_file_path))
except OSError as error:
log.add(
_("Couldn't move '%(tempfile)s' to '%(file)s': %(error)s"), {
"tempfile": incomplete_file_path.decode("utf-8", "replace"),
"file": download_file_path,
"error": error
}
)
self._abort_transfer(transfer, status=TransferStatus.DOWNLOAD_FOLDER_ERROR)
core.notifications.show_download_notification(
str(error), title=_("Download Folder Error"), high_priority=True
)
return None
return download_file_path
def _finish_transfer(self, transfer):
username = transfer.username
virtual_path = transfer.virtual_path
already_exists = transfer.file_handle is None
incomplete_file_path = transfer.file_handle.name if not already_exists else None
super()._finish_transfer(transfer)
if not already_exists:
download_file_path = self._move_finished_transfer(transfer, incomplete_file_path)
if download_file_path is None:
# Download was not moved successfully
return
if not self._auto_clear_transfer(transfer):
self._update_transfer(transfer)
if already_exists:
log.add_transfer("File %s is already downloaded", virtual_path)
return
core.statistics.append_stat_value("completed_downloads", 1)
# Attempt to show notification and execute commands
self._file_downloaded_actions(username, download_file_path)
self._folder_downloaded_actions(username, transfer.folder_path)
core.pluginhandler.download_finished_notification(username, virtual_path, download_file_path)
log.add_download(
_("Download finished: user %(user)s, file %(file)s"), {
"user": username,
"file": virtual_path
}
)
def _abort_transfer(self, transfer, status=None, denied_message=None, update_parent=True):
if transfer.file_handle is not None:
log.add_download(
_("Download aborted, user %(user)s file %(file)s"), {
"user": transfer.username,
"file": transfer.virtual_path
}
)
super()._abort_transfer(transfer, status=status, denied_message=denied_message)
if status:
events.emit("abort-download", transfer, status, update_parent)
def _clear_transfer(self, transfer, denied_message=None, update_parent=True):
virtual_path = transfer.virtual_path
username = transfer.username
log.add_transfer("Clearing download %s from user %s", (virtual_path, username))
try:
super()._clear_transfer(transfer, denied_message=denied_message)
except KeyError:
log.add("FIXME: failed to remove download %s from user %s, not present in list",
(virtual_path, username))
events.emit("clear-download", transfer, update_parent)
def _delete_stale_incomplete_downloads(self):
if not self._allow_saving_transfers:
return
incomplete_download_folder_path = self.get_incomplete_download_folder()
if not incomplete_download_folder_path.startswith(config.data_folder_path):
# Only delete incomplete downloads inside Nicotine+'s data folder
return
allowed_incomplete_file_paths = {
encode_path(self.get_incomplete_download_file_path(transfer.username, transfer.virtual_path))
for transfer in self.transfers.values()
if transfer.current_byte_offset and transfer.status != TransferStatus.FINISHED
}
prefix = b"INCOMPLETE"
prefix_len = len(prefix)
md5_len = 32
md5_regex = re.compile(b"[0-9a-f]{32}", re.IGNORECASE)
try:
with os.scandir(encode_path(incomplete_download_folder_path)) as entries:
for entry in entries:
if entry.is_dir():
continue
if entry.path in allowed_incomplete_file_paths:
continue
basename = entry.name
# Skip files that are not incomplete downloads
if (not basename.startswith(prefix)
or len(basename) <= (prefix_len + md5_len)
or not md5_regex.match(basename[prefix_len:prefix_len + md5_len])):
continue
# Incomplete file no longer has a download associated with it. Delete it.
try:
os.remove(entry.path)
log.add_transfer("Deleted stale incomplete download %s", entry.path)
except OSError as error:
log.add_transfer("Cannot delete incomplete download %s: %s", (entry.path, error))
except OSError as error:
log.add_transfer("Cannot read incomplete download folder: %s", error)
def _request_queue_positions(self):
for download in self.queued_transfers:
core.send_message_to_peer(
download.username,
PlaceInQueueRequest(download.virtual_path, download.legacy_attempt)
)
def _retry_failed_connection_downloads(self):
statuses = {
TransferStatus.CONNECTION_CLOSED, TransferStatus.CONNECTION_TIMEOUT, TransferRejectReason.PENDING_SHUTDOWN}
for failed_downloads in self.failed_users.copy().values():
for download in failed_downloads.copy().values():
if download.status not in statuses:
continue
self._unfail_transfer(download)
if self._enqueue_transfer(download):
self._update_transfer(download)
def _retry_failed_io_downloads(self):
statuses = {
TransferStatus.DOWNLOAD_FOLDER_ERROR, TransferStatus.LOCAL_FILE_ERROR, TransferRejectReason.FILE_READ_ERROR}
for failed_downloads in self.failed_users.copy().values():
for download in failed_downloads.copy().values():
if download.status not in statuses:
continue
self._unfail_transfer(download)
if self._enqueue_transfer(download):
self._update_transfer(download)
def can_upload(self, username):
transfers = config.sections["transfers"]
if not transfers["remotedownloads"]:
return False
if transfers["uploadallowed"] == 1:
# Everyone
return True
if transfers["uploadallowed"] == 2 and username in core.buddies.users:
# Buddies
return True
if transfers["uploadallowed"] == 3:
# Trusted buddies
user_data = core.buddies.users.get(username)
if user_data and user_data.is_trusted:
return True
return False
def get_folder_destination(self, username, folder_path, root_folder_path=None, download_folder_path=None):
# Remove parent folders of the requested folder from path
parent_folder_path = root_folder_path if root_folder_path else folder_path
removed_parent_folders = parent_folder_path.rpartition("\\")[0]
target_folders = folder_path.replace(removed_parent_folders, "").lstrip("\\").replace("\\", os.sep)
# Check if a custom download location was specified
if not download_folder_path:
requested_folder = self._requested_folders.get(username, {}).get(folder_path)
if requested_folder is not None and requested_folder.download_folder_path:
download_folder_path = requested_folder.download_folder_path
else:
download_folder_path = self.get_default_download_folder(username)
# Merge download path with target folder name
return os.path.join(download_folder_path, target_folders)
def get_default_download_folder(self, username=None):
download_folder_path = os.path.normpath(os.path.expandvars(config.sections["transfers"]["downloaddir"]))
# Check if username subfolders should be created for downloads
if username and config.sections["transfers"]["usernamesubfolders"]:
download_folder_path = os.path.join(download_folder_path, clean_file(username))
return download_folder_path
def get_incomplete_download_folder(self):
return os.path.normpath(os.path.expandvars(config.sections["transfers"]["incompletedir"]))
def get_basename_byte_limit(self, folder_path):
max_bytes = self._folder_basename_byte_limits.get(folder_path)
if max_bytes is None:
try:
max_bytes = os.statvfs(encode_path(folder_path)).f_namemax
except (AttributeError, OSError):
max_bytes = 255
self._folder_basename_byte_limits[folder_path] = max_bytes
return max_bytes
def get_download_basename(self, virtual_path, download_folder_path, avoid_conflict=False):
"""Returns the download basename for a virtual file path."""
max_bytes = self.get_basename_byte_limit(download_folder_path)
basename = clean_file(virtual_path.rpartition("\\")[-1])
basename_no_extension, separator, extension = basename.rpartition(".")
extension = separator + extension
basename_limit = max_bytes - len(extension.encode())
basename_no_extension = truncate_string_byte(basename_no_extension, max(0, basename_limit))
if basename_limit < 0:
extension = truncate_string_byte(extension, max_bytes)
corrected_basename = basename_no_extension + extension
if not avoid_conflict:
return corrected_basename
counter = 1
while os.path.exists(encode_path(os.path.join(download_folder_path, corrected_basename))):
corrected_basename = f"{basename_no_extension} ({counter}){extension}"
counter += 1
return corrected_basename
def get_complete_download_file_path(self, username, virtual_path, size, download_folder_path=None):
"""Returns the download path of a complete download, if available."""
if not download_folder_path:
download_folder_path = self.get_default_download_folder(username)
basename = self.get_download_basename(virtual_path, download_folder_path)
basename_no_extension, separator, extension = basename.rpartition(".")
extension = separator + extension
download_file_path = os.path.join(download_folder_path, basename)
file_exists = False
counter = 1
while os.path.exists(encode_path(download_file_path)):
if os.stat(encode_path(download_file_path)).st_size == size:
# Found a previous download with a matching file size
file_exists = True
break
basename = f"{basename_no_extension} ({counter}){extension}"
download_file_path = os.path.join(download_folder_path, basename)
counter += 1
return download_file_path, file_exists
def get_incomplete_download_file_path(self, username, virtual_path):
"""Returns the path to store a download while it's still
transferring."""
md5sum = md5()
md5sum.update((virtual_path + username).encode())
prefix = f"INCOMPLETE{md5sum.hexdigest()}"
# Ensure file name length doesn't exceed file system limit
incomplete_folder_path = self.get_incomplete_download_folder()
max_bytes = self.get_basename_byte_limit(incomplete_folder_path)
basename = clean_file(virtual_path.rpartition("\\")[-1])
basename_no_extension, separator, extension = basename.rpartition(".")
extension = separator + extension
basename_limit = max_bytes - len(prefix) - len(extension.encode())
basename_no_extension = truncate_string_byte(basename_no_extension, max(0, basename_limit))
if basename_limit < 0:
extension = truncate_string_byte(extension, max_bytes - len(prefix))
return os.path.join(incomplete_folder_path, prefix + basename_no_extension + extension)
def get_current_download_file_path(self, transfer):
"""Returns the current file path of a download."""
file_path, file_exists = self.get_complete_download_file_path(
transfer.username, transfer.virtual_path, transfer.size, transfer.folder_path)
if file_exists or transfer.status == TransferStatus.FINISHED:
return file_path
return self.get_incomplete_download_file_path(transfer.username, transfer.virtual_path)
def enqueue_folder(self, username, folder_path, download_folder_path=None):
requested_folder = self._requested_folders.get(username, {}).get(folder_path)
if requested_folder is None:
self._requested_folders[username][folder_path] = requested_folder = RequestedFolder(
username, folder_path, download_folder_path
)
# First timeout is shorter to get a response sooner in case the first request
# failed. Second timeout is longer in case the response is delayed.
timeout = 60 if requested_folder.has_retried else 15
if requested_folder.request_timer_id is not None:
events.cancel_scheduled(requested_folder.request_timer_id)
requested_folder.request_timer_id = None
requested_folder.request_timer_id = events.schedule(
delay=timeout, callback=self._requested_folder_timeout, callback_args=(requested_folder,)
)
log.add_transfer("Requesting contents of folder %s from user %s", (folder_path, username))
self._requested_folder_token = increment_token(self._requested_folder_token)
core.send_message_to_peer(
username, FolderContentsRequest(
folder_path, self._requested_folder_token, legacy_client=requested_folder.legacy_attempt
)
)
def enqueue_download(self, username, virtual_path, folder_path=None, size=0, file_attributes=None,
bypass_filter=False):
transfer = self.transfers.get(username + virtual_path)
if folder_path:
folder_path = clean_path(folder_path)
else:
folder_path = self.get_default_download_folder(username)
if transfer is not None and transfer.folder_path != folder_path and transfer.status == TransferStatus.FINISHED:
# Only one user + virtual path transfer possible at a time, remove the old one
self._clear_transfer(transfer, update_parent=False)
transfer = None
if transfer is not None:
# Duplicate download found, stop here
return
transfer = Transfer(username, virtual_path, folder_path, size, file_attributes)
self._append_transfer(transfer)
if self._enqueue_transfer(transfer, bypass_filter=bypass_filter):
self._update_transfer(transfer)
def retry_download(self, transfer, bypass_filter=False):
username = transfer.username
active_downloads = self.active_users.get(username, {}).values()
if transfer in active_downloads or transfer.status == TransferStatus.FINISHED:
# Don't retry active or finished downloads
return
self._dequeue_transfer(transfer)
self._unfail_transfer(transfer)
if self._enqueue_transfer(transfer, bypass_filter=bypass_filter):
self._update_transfer(transfer)
def retry_downloads(self, downloads):
num_downloads = len(downloads)
for download in downloads:
# Provide a way to bypass download filters in case the user actually wants a file.
# To avoid accidentally bypassing filters, ensure that only a single file is selected,
# and it has the "Filtered" status.
bypass_filter = (num_downloads == 1 and download.status == TransferStatus.FILTERED)
self.retry_download(download, bypass_filter)
def abort_downloads(self, downloads, status=TransferStatus.PAUSED):
ignored_statuses = {status, TransferStatus.FINISHED}
for download in downloads:
if download.status not in ignored_statuses:
self._abort_transfer(download, status=status, update_parent=False)
events.emit("abort-downloads", downloads, status)
def clear_downloads(self, downloads=None, statuses=None, clear_deleted=False):
if downloads is None:
# Clear all downloads
downloads = self.transfers.copy().values()
else:
downloads = downloads.copy()
for download in downloads:
if statuses and download.status not in statuses:
continue
if clear_deleted:
if download.status != TransferStatus.FINISHED:
continue
_file_path, file_exists = self.get_complete_download_file_path(
download.username, download.virtual_path, download.size, download.folder_path)
if file_exists:
continue
self._clear_transfer(download, update_parent=False)
events.emit("clear-downloads", downloads, statuses, clear_deleted)
# Events #
def _shares_ready(self, _successful):
"""Send any QueueUpload messages we delayed while our shares were
initializing.
"""
for transfer, msg in self._pending_queue_messages.items():
core.send_message_to_peer(transfer.username, msg)
self._pending_queue_messages.clear()
def _user_status(self, msg):
"""Server code 7."""
username = msg.user
if username not in core.users.watched:
# Skip redundant status updates from users in joined rooms
return
if msg.status == UserStatus.OFFLINE:
for users in (self.queued_users, self.failed_users):
for download in users.get(username, {}).copy().values():
self._abort_transfer(download, status=TransferStatus.USER_LOGGED_OFF)
for download in self.active_users.get(username, {}).copy().values():
if download.status != TransferStatus.TRANSFERRING:
self._abort_transfer(download, status=TransferStatus.USER_LOGGED_OFF)
self._online_users.discard(username)
return
# No need to check transfers on away status change
if username in self._online_users:
return
# User logged in, resume "User logged off" transfers
for download in self.failed_users.get(username, {}).copy().values():
self._unfail_transfer(download)
if self._enqueue_transfer(download):
self._update_transfer(download)
self._online_users.add(username)
def _set_connection_stats(self, download_bandwidth=0, **_unused):
self.total_bandwidth = download_bandwidth
def _peer_connection_error(self, username, conn_type, msgs, is_offline=False, is_timeout=True):
if not msgs:
return
if conn_type not in {ConnectionType.FILE, ConnectionType.PEER}:
return
failed_msg_types = {QueueUpload, PlaceInQueueRequest}
for msg in msgs:
if msg.__class__ in failed_msg_types:
self._cant_connect_queue_file(username, msg.file, is_offline, is_timeout)
def _peer_connection_closed(self, username, conn_type, msgs=None):
self._peer_connection_error(username, conn_type, msgs, is_timeout=False)
def _cant_connect_queue_file(self, username, virtual_path, is_offline, is_timeout):
"""We can't connect to the user, either way (QueueUpload, PlaceInQueueRequest)."""
download = self.queued_users.get(username, {}).get(virtual_path)
if download is None:
return
if is_offline:
status = TransferStatus.USER_LOGGED_OFF
elif is_timeout:
status = TransferStatus.CONNECTION_TIMEOUT
else:
status = TransferStatus.CONNECTION_CLOSED
log.add_transfer("Download attempt for file %s from user %s failed with status %s",
(virtual_path, username, status))
self._abort_transfer(download, status=status)
def _requested_folder_timeout(self, requested_folder):
if requested_folder.request_timer_id is None:
return
requested_folder.request_timer_id = None
username = requested_folder.username
folder_path = requested_folder.folder_path
if requested_folder.has_retried:
log.add_transfer("Folder content request for folder %s from user %s timed out, "
"giving up", (folder_path, username))
del self._requested_folders[username][folder_path]
return
log.add_transfer("Folder content request for folder %s from user %s timed out, "
"retrying", (folder_path, username))
requested_folder.has_retried = True
self.enqueue_folder(username, folder_path, requested_folder.download_folder_path)
def _folder_contents_response(self, msg, check_num_files=True):
"""Peer code 37."""
username = msg.username
folder_path = msg.dir
if username not in self._requested_folders:
return
requested_folder = self._requested_folders[username].get(msg.dir)
if requested_folder is None:
return
log.add_transfer("Received response for folder content request for folder %s "
"from user %s", (folder_path, username))
if requested_folder.request_timer_id is not None:
events.cancel_scheduled(requested_folder.request_timer_id)
requested_folder.request_timer_id = None
if not msg.list and not requested_folder.legacy_attempt:
log.add_transfer("Folder content response is empty. Trying legacy latin-1 request.")
requested_folder.legacy_attempt = True
self.enqueue_folder(username, folder_path, requested_folder.download_folder_path)
return
for i_folder_path, files in msg.list.items():
if i_folder_path != folder_path:
continue
num_files = len(files)
if check_num_files and num_files > 100:
check_num_files = False
events.emit(
"download-large-folder", username, folder_path, num_files,
self._folder_contents_response, (msg, check_num_files)
)
return
destination_folder_path = self.get_folder_destination(username, folder_path)
log.add_transfer("Attempting to download files in folder %s for user %s. "
"Destination path: %s", (folder_path, username, destination_folder_path))
for _code, basename, file_size, _ext, file_attributes, *_unused in files:
virtual_path = folder_path.rstrip("\\") + "\\" + basename
self.enqueue_download(
username, virtual_path, folder_path=destination_folder_path, size=file_size,
file_attributes=file_attributes)
del self._requested_folders[username][folder_path]
def _transfer_request(self, msg):
"""Peer code 40."""
if msg.direction != TransferDirection.UPLOAD:
return
username = msg.username
response = self._transfer_request_downloads(msg)
log.add_transfer("Responding to download request with token %s for file %s "
"from user: %s, allowed: %s, reason: %s",
(response.token, msg.file, username, response.allowed, response.reason))
core.send_message_to_peer(username, response)
def _transfer_request_downloads(self, msg):
username = msg.username
virtual_path = msg.file
size = msg.filesize
token = msg.token
log.add_transfer("Received download request with token %s for file %s from user %s",
(token, virtual_path, username))
download = (self.queued_users.get(username, {}).get(virtual_path)
or self.failed_users.get(username, {}).get(virtual_path))
if download is not None:
# Remote peer is signaling a transfer is ready, attempting to download it
# If the file is larger than 2GB, the SoulseekQt client seems to
# send a malformed file size (0 bytes) in the TransferRequest response.
# In that case, we rely on the cached, correct file size we received when
# we initially added the download.
self._unfail_transfer(download)
self._dequeue_transfer(download)
if size > 0:
if download.size != size:
# The remote user's file contents have changed since we queued the download
download.size_changed = True
download.size = size
self._activate_transfer(download, token)
self._update_transfer(download)
return TransferResponse(allowed=True, token=token)
download = self.transfers.get(username + virtual_path)
cancel_reason = TransferRejectReason.CANCELLED
if download is not None:
if download.status == TransferStatus.FINISHED:
# SoulseekQt sends "Complete" as the reason for rejecting the download if it exists
cancel_reason = TransferRejectReason.COMPLETE
elif self.can_upload(username):
# Check if download exists in our default download folder
_file_path, file_exists = self.get_complete_download_file_path(username, virtual_path, size)
if file_exists:
cancel_reason = TransferRejectReason.COMPLETE
else:
# If this file is not in your download queue, then it must be
# a remotely initiated download and someone is manually uploading to you
parent_folder_path = virtual_path.replace("/", "\\").split("\\")[-2]
received_folder_path = os.path.normpath(os.path.expandvars(config.sections["transfers"]["uploaddir"]))
folder_path = os.path.join(received_folder_path, username, parent_folder_path)
transfer = Transfer(username, virtual_path, folder_path, size)
self._append_transfer(transfer)
self._activate_transfer(transfer, token)
self._update_transfer(transfer)
return TransferResponse(allowed=True, token=token)
log.add_transfer("Denied file request: user %s, message %s", (username, msg))
return TransferResponse(allowed=False, reason=cancel_reason, token=token)
def _transfer_timeout(self, transfer):
if transfer.request_timer_id is None:
return
log.add_transfer("Download %s with token %s for user %s timed out",
(transfer.virtual_path, transfer.token, transfer.username))
super()._transfer_timeout(transfer)
def _download_file_error(self, username, token, error):
"""Networking thread encountered a local file error for download."""
download = self.active_users.get(username, {}).get(token)
if download is None:
return
self._abort_transfer(download, status=TransferStatus.LOCAL_FILE_ERROR)
log.add(_("Download I/O error: %s"), error)
def _file_transfer_init(self, msg):
"""A peer is requesting to start uploading a file to us."""
if msg.is_outgoing:
# Upload init message sent to ourselves, ignore
return
username = msg.username
token = msg.token
download = self.active_users.get(username, {}).get(token)
if download is None or download.sock is not None:
return
virtual_path = download.virtual_path
incomplete_folder_path = self.get_incomplete_download_folder()
sock = download.sock = msg.sock
need_update = True
download_started = False
log.add_transfer("Received file download init with token %s for file %s from user %s",
(token, virtual_path, username))
try:
incomplete_folder_path_encoded = encode_path(incomplete_folder_path)
if not os.path.isdir(incomplete_folder_path_encoded):
os.makedirs(incomplete_folder_path_encoded)
incomplete_file_path = self.get_incomplete_download_file_path(username, virtual_path)
file_handle = open(encode_path(incomplete_file_path), "ab+") # pylint: disable=consider-using-with
try:
import fcntl
try:
fcntl.lockf(file_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
except OSError as error:
log.add(_("Can't get an exclusive lock on file - I/O error: %s"), error)
except ImportError:
pass
if download.size_changed:
# Remote user sent a different file size than we originally requested,
# wipe any existing data in the incomplete file to avoid corruption
file_handle.truncate(0)
# Seek to the end of the file for resuming the download
offset = file_handle.seek(0, os.SEEK_END)
except OSError as error:
log.add(_("Cannot save file in %(folder_path)s: %(error)s"), {
"folder_path": incomplete_folder_path,
"error": error
})
self._abort_transfer(download, status=TransferStatus.DOWNLOAD_FOLDER_ERROR)
core.notifications.show_download_notification(
str(error), title=_("Download Folder Error"), high_priority=True)
need_update = False
else:
download.file_handle = file_handle
download.last_byte_offset = offset
download.start_time = time.monotonic() - download.time_elapsed
download.retry_attempt = False
core.statistics.append_stat_value("started_downloads", 1)
download_started = True
log.add_download(
_("Download started: user %(user)s, file %(file)s"), {
"user": username,
"file": file_handle.name.decode("utf-8", "replace")
}
)
if download.size > offset:
download.status = TransferStatus.TRANSFERRING
core.send_message_to_network_thread(DownloadFile(
sock=sock, token=token, file=file_handle, leftbytes=(download.size - offset)
))
core.send_message_to_peer(username, FileOffset(sock, offset))
else:
self._finish_transfer(download)
need_update = False
if need_update:
self._update_transfer(download)
if download_started:
# Must be emitted after the final update to prevent inconsistent state
core.pluginhandler.download_started_notification(username, virtual_path, incomplete_file_path)
def _upload_denied(self, msg):
"""Peer code 50."""
username = msg.username
virtual_path = msg.file
reason = msg.reason
queued_downloads = self.queued_users.get(username, {})
download = queued_downloads.get(virtual_path)
if download is None:
return
if reason in TransferStatus.__dict__.values():
# Don't allow internal statuses as reason
reason = TransferRejectReason.CANCELLED
if reason == TransferRejectReason.FILE_NOT_SHARED and not download.legacy_attempt:
# The peer is possibly using an old client that doesn't support Unicode
# (Soulseek NS). Attempt to request file name encoded as latin-1 once.
log.add_transfer("User %s responded with reason '%s' for download request %s. "
"Attempting to request file as latin-1.", (username, reason, virtual_path))
self._dequeue_transfer(download)
download.legacy_attempt = True
if self._enqueue_transfer(download):
self._update_transfer(download)
return
if (reason in {TransferRejectReason.TOO_MANY_FILES, TransferRejectReason.TOO_MANY_MEGABYTES}
or reason.startswith("User limit of")):
# Make limited downloads appear as queued, and automatically resume them later
reason = TransferRejectReason.QUEUED
self._user_queue_limits[username] = max(5, len(queued_downloads) - 1)
self._abort_transfer(download, status=reason)
self._update_transfer(download)
log.add_transfer("Download request denied by user %s for file %s. Reason: %s",
(username, virtual_path, msg.reason))
def _upload_failed(self, msg):
"""Peer code 46."""
username = msg.username
virtual_path = msg.file
download = self.transfers.get(username + virtual_path)
if download is None:
return
if (download.token not in self.active_users.get(username, {})
and virtual_path not in self.failed_users.get(username, {})
and virtual_path not in self.queued_users.get(username, {})):
return
if download.status in {TransferStatus.DOWNLOAD_FOLDER_ERROR, TransferStatus.LOCAL_FILE_ERROR}:
# Local error, no need to retry
return
if not download.retry_attempt:
# Attempt to request file name encoded as latin-1 once
# We mark download as failed when aborting it, to avoid a redundant request
# to unwatch the user. Need to call _unfail_transfer() to undo this.
self._abort_transfer(download, status=TransferStatus.CONNECTION_CLOSED)
self._unfail_transfer(download)
download.legacy_attempt = download.retry_attempt = True
if self._enqueue_transfer(download):
self._update_transfer(download)
return
# Already failed once previously, give up
self._abort_transfer(download, status=TransferStatus.CONNECTION_CLOSED)
download.retry_attempt = False
log.add_transfer("Upload attempt by user %s for file %s failed. Reason: %s",
(virtual_path, username, download.status))
def _file_download_progress(self, username, token, bytes_left, speed=None):
"""A file download is in progress."""
download = self.active_users.get(username, {}).get(token)
if download is None:
return
if download.request_timer_id is not None:
events.cancel_scheduled(download.request_timer_id)
download.request_timer_id = None
self._update_transfer_progress(
download, stat_id="downloaded_size",
current_byte_offset=(download.size - bytes_left), speed=speed
)
self._update_transfer(download)
def _file_connection_closed(self, username, token, sock, **_unused):
"""A file download connection has closed for any reason."""
download = self.active_users.get(username, {}).get(token)
if download is None:
return
if download.sock != sock:
return
if download.current_byte_offset is not None and download.current_byte_offset >= download.size:
self._finish_transfer(download)
return
if core.users.statuses.get(download.username) == UserStatus.OFFLINE:
status = TransferStatus.USER_LOGGED_OFF
else:
status = TransferStatus.CANCELLED
self._abort_transfer(download, status=status)
def _place_in_queue_response(self, msg):
"""Peer code 44.
The peer tells us our place in queue for a particular transfer
"""
username = msg.username
virtual_path = msg.filename
download = self.queued_users.get(username, {}).get(virtual_path)
if download is None:
return
download.queue_position = msg.place
self._update_transfer(download, update_parent=False)
| 52,621 | Python | .py | 994 | 41.145875 | 120 | 0.633715 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,404 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/__init__.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
__application_name__ = "Nicotine+"
__application_id__ = "org.nicotine_plus.Nicotine"
__version__ = "3.3.7.dev1"
__author__ = "Nicotine+ Team"
__copyright__ = """© 2004–2024 Nicotine+ Contributors
© 2003–2004 Nicotine Contributors
© 2001–2003 PySoulSeek Contributors"""
__website_url__ = "https://nicotine-plus.org"
__privileges_url__ = "https://www.slsknet.org/qtlogin.php?username=%s"
__port_checker_url__ = "https://www.slsknet.org/porttest.php?port=%s"
__issue_tracker_url__ = "https://github.com/nicotine-plus/nicotine-plus/issues"
__translations_url__ = "https://nicotine-plus.org/doc/TRANSLATIONS"
import io
import os
import sys
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.i18n import LOCALE_PATH
from pynicotine.i18n import apply_translations
from pynicotine.logfacility import log
def check_arguments():
"""Parse command line arguments specified by the user."""
import argparse
parser = argparse.ArgumentParser(
prog="nicotine", description=_("Graphical client for the Soulseek peer-to-peer network"),
epilog=_("Website: %s") % __website_url__, add_help=False
)
# Visible arguments
parser.add_argument(
"-h", "--help", action="help",
help=_("show this help message and exit")
)
parser.add_argument(
"-c", "--config", metavar=_("file"),
help=_("use non-default configuration file")
)
parser.add_argument(
"-u", "--user-data", metavar=_("dir"),
help=_("alternative directory for user data and plugins")
)
parser.add_argument(
"-s", "--hidden", action="store_true",
help=_("start the program without showing window")
)
parser.add_argument(
"-b", "--bindip", metavar=_("ip"),
help=_("bind sockets to the given IP (useful for VPN)")
)
parser.add_argument(
"-l", "--port", metavar=_("port"), type=int,
help=_("listen on the given port")
)
parser.add_argument(
"-r", "--rescan", action="store_true",
help=_("rescan shared files")
)
parser.add_argument(
"-n", "--headless", action="store_true",
help=_("start the program in headless mode (no GUI)")
)
parser.add_argument(
"-v", "--version", action="version", version=f"{__application_name__} {__version__}",
help=_("display version and exit")
)
# Disables critical error dialog; used for integration tests
parser.add_argument("--ci-mode", action="store_true", help=argparse.SUPPRESS)
args = parser.parse_args()
multi_instance = False
if args.config:
config.set_config_file(args.config)
# Since a custom config was specified, allow another instance of the application to open
multi_instance = True
if args.user_data:
config.set_data_folder(args.user_data)
core.cli_interface_address = args.bindip
core.cli_listen_port = args.port
return args.headless, args.hidden, args.ci_mode, args.rescan, multi_instance
def check_python_version():
# Require minimum Python version
python_version = (3, 6)
if sys.version_info < python_version:
return _("""You are using an unsupported version of Python (%(old_version)s).
You should install Python %(min_version)s or newer.""") % {
"old_version": ".".join(str(x) for x in sys.version_info[:3]),
"min_version": ".".join(str(x) for x in python_version)
}
return None
def set_up_python():
is_frozen = getattr(sys, "frozen", False)
# Always use UTF-8 for print()
if sys.stdout is not None:
sys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding="utf-8", line_buffering=True)
if is_frozen:
import multiprocessing
# Set up paths for frozen binaries (Windows and macOS)
executable_folder = os.path.dirname(sys.executable)
os.environ["SSL_CERT_FILE"] = os.path.join(executable_folder, "lib/cert.pem")
# Support file scanning process in frozen binaries
multiprocessing.freeze_support()
def rename_process(new_name, debug_info=False):
errors = []
# Renaming ourselves for pkill et al.
try:
import ctypes
# GNU/Linux style
libc = ctypes.CDLL(None)
libc.prctl(15, new_name, 0, 0, 0)
except Exception as error:
errors.append(error)
errors.append("Failed GNU/Linux style")
try:
import ctypes
# BSD style
libc = ctypes.CDLL(None)
libc.setproctitle(new_name)
except Exception as second_error:
errors.append(second_error)
errors.append("Failed BSD style")
if debug_info and errors:
msg = ["Errors occurred while trying to change process name:"]
for i in errors:
msg.append(str(i))
log.add("\n".join(msg))
def rescan_shares():
exit_code = 0
if not core.shares.rescan_shares(use_thread=False):
log.add("--------------------------------------------------")
log.add(_("Failed to scan shares. Please close other Nicotine+ instances and try again."))
exit_code = 1
core.quit()
return exit_code
def run():
"""Run application and return its exit code."""
set_up_python()
rename_process(b"nicotine")
headless, hidden, ci_mode, rescan, multi_instance = check_arguments()
error = check_python_version()
if error:
print(error)
return 1
core.init_components(enabled_components={"cli", "shares"} if rescan else None)
# Dump tracebacks for C modules (in addition to pure Python code)
try:
import faulthandler
faulthandler.enable()
except Exception as error:
log.add(f"Faulthandler module could not be enabled. Error: {error}")
if not os.path.isdir(LOCALE_PATH):
log.add("Translation files (.mo) are unavailable, using default English strings")
if rescan:
return rescan_shares()
# Initialize GTK-based GUI
if not headless:
from pynicotine import gtkgui as application
exit_code = application.run(hidden, ci_mode, multi_instance)
if exit_code is not None:
return exit_code
# Run without a GUI
from pynicotine import headless as application
return application.run()
apply_translations()
| 7,134 | Python | .py | 178 | 33.994382 | 98 | 0.660717 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,405 | events.py | nicotine-plus_nicotine-plus/pynicotine/events.py | # COPYRIGHT (C) 2022-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import time
from collections import defaultdict
from collections import deque
from threading import Thread
EVENT_NAMES = {
# General
"check-latest-version",
"cli-command",
"cli-prompt-finished",
"confirm-quit",
"enable-message-queue",
"log-message",
"queue-network-message",
"quit",
"schedule-quit",
"set-connection-stats",
"setup",
"start",
"thread-callback",
# Users
"admin-message",
"change-password",
"check-privileges",
"connect-to-peer",
"invalid-password",
"invalid-username",
"peer-address",
"privileged-users",
"server-disconnect",
"server-login",
"server-reconnect",
"user-country",
"user-stats",
"user-status",
"watch-user",
# Notification messages
"show-notification",
"show-chatroom-notification",
"show-download-notification",
"show-private-chat-notification",
"show-search-notification",
# Buddy list
"add-buddy",
"buddy-note",
"buddy-notify",
"buddy-last-seen",
"buddy-prioritized",
"buddy-trusted",
"remove-buddy",
# Chatrooms
"clear-room-messages",
"echo-room-message",
"global-room-message",
"join-room",
"leave-room",
"private-room-add-operator",
"private-room-add-user",
"private-room-added",
"private-room-operator-added",
"private-room-operator-removed",
"private-room-operators",
"private-room-remove-operator",
"private-room-remove-user",
"private-room-removed",
"private-room-toggle",
"private-room-users",
"remove-room",
"room-completions",
"room-list",
"say-chat-room",
"show-room",
"ticker-add",
"ticker-remove",
"ticker-state",
"user-joined-room",
"user-left-room",
# Interests
"add-dislike",
"add-interest",
"global-recommendations",
"item-recommendations",
"item-similar-users",
"recommendations",
"remove-dislike",
"remove-interest",
"similar-users",
# Network filter
"ban-user",
"ban-user-ip",
"ignore-user",
"ignore-user-ip",
"unban-user",
"unban-user-ip",
"unignore-user",
"unignore-user-ip",
# Private chat
"clear-private-messages",
"echo-private-message",
"message-user",
"private-chat-completions",
"private-chat-remove-user",
"private-chat-show-user",
# Search
"add-search",
"add-wish",
"excluded-search-phrases",
"file-search-request-distributed",
"file-search-request-server",
"file-search-response",
"remove-search",
"remove-wish",
"set-wishlist-interval",
"show-search",
# Statistics
"update-stat",
# Shares
"folder-contents-request",
"shared-file-list-progress",
"shared-file-list-request",
"shared-file-list-response",
"shares-preparing",
"shares-ready",
"shares-scanning",
"shares-unavailable",
"user-browse-remove-user",
"user-browse-show-user",
# Transfers
"abort-download",
"abort-downloads",
"abort-upload",
"abort-uploads",
"clear-download",
"clear-downloads",
"clear-upload",
"clear-uploads",
"download-connection-closed",
"download-file-error",
"download-large-folder",
"file-connection-closed",
"file-download-progress",
"file-transfer-init",
"file-upload-progress",
"folder-contents-response",
"folder-download-finished",
"peer-connection-closed",
"peer-connection-error",
"place-in-queue-request",
"place-in-queue-response",
"queue-upload",
"transfer-request",
"transfer-response",
"update-download",
"update-download-limits",
"update-upload",
"update-upload-limits",
"upload-denied",
"upload-failed",
"upload-file-error",
"uploads-shutdown-request",
"uploads-shutdown-cancel",
# User info
"user-info-progress",
"user-info-remove-user",
"user-info-request",
"user-info-response",
"user-info-show-user",
"user-interests",
}
class SchedulerEvent:
__slots__ = ("event_id", "next_time", "delay", "repeat", "callback", "callback_args")
def __init__(self, event_id, next_time=None, delay=None, repeat=None,
callback=None, callback_args=None):
self.event_id = event_id
self.next_time = next_time
self.delay = delay
self.repeat = repeat
self.callback = callback
self.callback_args = callback_args
class ThreadEvent:
__slots__ = ("event_name", "args", "kwargs")
def __init__(self, event_name, args, kwargs):
self.event_name = event_name
self.args = args
self.kwargs = kwargs
class Events:
__slots__ = ("_callbacks", "_thread_events", "_pending_scheduler_events", "_scheduler_events",
"_scheduler_event_id", "_is_active")
SCHEDULER_MAX_IDLE = 1
def __init__(self):
self._callbacks = defaultdict(list)
self._thread_events = deque()
self._pending_scheduler_events = deque()
self._scheduler_events = {}
self._scheduler_event_id = 0
self._is_active = False
def enable(self):
if self._is_active:
return
self._is_active = True
for event_name, callback in (
("quit", self._quit),
("thread-callback", self._thread_callback)
):
self.connect(event_name, callback)
Thread(target=self._run_scheduler, name="SchedulerThread", daemon=True).start()
def connect(self, event_name, function):
if event_name not in EVENT_NAMES:
raise ValueError(f"Unknown event {event_name}")
self._callbacks[event_name].append(function)
def disconnect(self, event_name, function):
self._callbacks[event_name].remove(function)
def emit(self, event_name, *args, **kwargs):
callbacks = self._callbacks[event_name]
if event_name == "quit":
# Event and log modules register callbacks first, but need to quit last
callbacks.reverse()
for function in callbacks:
function(*args, **kwargs)
def emit_main_thread(self, event_name, *args, **kwargs):
self._thread_events.append(ThreadEvent(event_name, args, kwargs))
def invoke_main_thread(self, callback, *args, **kwargs):
self.emit_main_thread("thread-callback", callback, *args, **kwargs)
def schedule(self, delay, callback, callback_args=None, repeat=False):
self._scheduler_event_id += 1
next_time = (time.monotonic() + delay)
if callback_args is None:
callback_args = ()
self._pending_scheduler_events.append(
SchedulerEvent(self._scheduler_event_id, next_time, delay, repeat, callback, callback_args)
)
return self._scheduler_event_id
def cancel_scheduled(self, event_id):
self._pending_scheduler_events.append(SchedulerEvent(event_id, next_time=None))
def process_thread_events(self):
"""Called by the main loop 10 times per second to emit thread events in
the main thread.
Return value indicates if the main loop should continue
processing events.
"""
if not self._thread_events:
if not self._is_active:
return False
return True
event_list = []
while self._thread_events:
event_list.append(self._thread_events.popleft())
for event in event_list:
self.emit(event.event_name, *event.args, **event.kwargs)
return True
def _run_scheduler(self):
while self._is_active:
# Scheduled events additions/removals from other threads
while self._pending_scheduler_events:
event = self._pending_scheduler_events.popleft()
if event.next_time is not None:
self._scheduler_events[event.event_id] = event
continue
self._scheduler_events.pop(event.event_id, None)
# No scheduled events
if not self._scheduler_events:
time.sleep(self.SCHEDULER_MAX_IDLE)
continue
# Retrieve upcoming event
event = min(self._scheduler_events.values(), key=lambda event: event.next_time)
event_time = event.next_time
current_time = time.monotonic()
sleep_time = (event_time - current_time)
if sleep_time > 0:
time.sleep(min(sleep_time, self.SCHEDULER_MAX_IDLE))
continue
self.invoke_main_thread(event.callback, *event.callback_args)
if event.repeat:
event.next_time = (event_time + event.delay)
continue
self._scheduler_events.pop(event.event_id, None)
def _thread_callback(self, callback, *args, **kwargs):
callback(*args, **kwargs)
def _quit(self):
# Ensure any remaining events are processed
self.process_thread_events()
self._is_active = False
self._callbacks.clear()
self._pending_scheduler_events.clear()
self._scheduler_events.clear()
events = Events()
| 10,005 | Python | .py | 302 | 26.231788 | 103 | 0.634296 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,406 | chatrooms.py | nicotine-plus_nicotine-plus/pynicotine/chatrooms.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.logfacility import log
from pynicotine.slskmessages import JoinGlobalRoom
from pynicotine.slskmessages import JoinRoom
from pynicotine.slskmessages import LeaveGlobalRoom
from pynicotine.slskmessages import LeaveRoom
from pynicotine.slskmessages import PrivateRoomAddOperator
from pynicotine.slskmessages import PrivateRoomAddUser
from pynicotine.slskmessages import PrivateRoomCancelMembership
from pynicotine.slskmessages import PrivateRoomDisown
from pynicotine.slskmessages import PrivateRoomRemoveOperator
from pynicotine.slskmessages import PrivateRoomRemoveUser
from pynicotine.slskmessages import PrivateRoomToggle
from pynicotine.slskmessages import RoomList
from pynicotine.slskmessages import RoomTickerSet
from pynicotine.slskmessages import SayChatroom
from pynicotine.utils import censor_text
from pynicotine.utils import find_whole_word
class JoinedRoom:
__slots__ = ("name", "is_private", "users", "tickers")
def __init__(self, name, is_private=False):
self.name = name
self.is_private = is_private
self.users = set()
self.tickers = {}
class PrivateRoom:
__slots__ = ("name", "owner", "members", "operators")
def __init__(self, name):
self.name = name
self.owner = None
self.members = set()
self.operators = set()
class ChatRooms:
__slots__ = ("completions", "server_rooms", "joined_rooms", "private_rooms")
# Trailing spaces to avoid conflict with regular rooms
GLOBAL_ROOM_NAME = "Public "
ROOM_NAME_MAX_LENGTH = 24
def __init__(self):
self.completions = set()
self.server_rooms = set()
self.joined_rooms = {}
self.private_rooms = {}
for event_name, callback in (
("global-room-message", self._global_room_message),
("join-room", self._join_room),
("leave-room", self._leave_room),
("private-room-add-operator", self._private_room_add_operator),
("private-room-add-user", self._private_room_add_user),
("private-room-added", self._private_room_added),
("private-room-operator-added", self._private_room_operator_added),
("private-room-operator-removed", self._private_room_operator_removed),
("private-room-operators", self._private_room_operators),
("private-room-remove-operator", self._private_room_remove_operator),
("private-room-remove-user", self._private_room_remove_user),
("private-room-removed", self._private_room_removed),
("private-room-toggle", self._private_room_toggle),
("private-room-users", self._private_room_users),
("quit", self._quit),
("room-list", self._room_list),
("say-chat-room", self._say_chat_room),
("server-login", self._server_login),
("server-disconnect", self._server_disconnect),
("start", self._start),
("ticker-add", self._ticker_add),
("ticker-remove", self._ticker_remove),
("ticker-state", self._ticker_state),
("user-joined-room", self._user_joined_room),
("user-left-room", self._user_left_room)
):
events.connect(event_name, callback)
def _start(self):
for room in config.sections["server"]["autojoin"]:
if isinstance(room, str):
self.show_room(room, is_private=(room in self.private_rooms), switch_page=False, remembered=True)
def _quit(self):
self.remove_all_rooms(is_permanent=False)
self.completions.clear()
def _server_login(self, msg):
if not msg.success:
return
# Request a complete room list. A limited room list not including blacklisted rooms and
# rooms with few users is automatically sent when logging in, but subsequent room list
# requests contain all rooms.
self.request_room_list()
self.request_private_room_toggle(config.sections["server"]["private_chatrooms"])
for room in self.joined_rooms:
if room == self.GLOBAL_ROOM_NAME:
core.send_message_to_server(JoinGlobalRoom())
else:
core.send_message_to_server(JoinRoom(room))
def _server_disconnect(self, _msg):
for room_obj in self.joined_rooms.values():
room_obj.tickers.clear()
room_obj.users.clear()
self.server_rooms.clear()
self.private_rooms.clear()
self.update_completions()
def show_room(self, room, is_private=False, switch_page=True, remembered=False):
room_obj = self.joined_rooms.get(room)
if room_obj is None:
self.joined_rooms[room] = room_obj = JoinedRoom(name=room, is_private=is_private)
if room not in config.sections["server"]["autojoin"]:
position = 0 if room == self.GLOBAL_ROOM_NAME else -1
config.sections["server"]["autojoin"].insert(position, room)
if not room_obj.users:
if room == self.GLOBAL_ROOM_NAME:
core.send_message_to_server(JoinGlobalRoom())
else:
core.send_message_to_server(JoinRoom(room, is_private))
events.emit("show-room", room, is_private, switch_page, remembered)
def remove_room(self, room, is_permanent=True):
if room not in self.joined_rooms:
return
if room == self.GLOBAL_ROOM_NAME:
core.send_message_to_server(LeaveGlobalRoom())
else:
core.send_message_to_server(LeaveRoom(room))
room_obj = self.joined_rooms.pop(room)
for username in room_obj.users:
core.users.unwatch_user(username, context=f"chatrooms_{room}")
if is_permanent:
if room in config.sections["columns"]["chat_room"]:
del config.sections["columns"]["chat_room"][room]
if room in config.sections["server"]["autojoin"]:
config.sections["server"]["autojoin"].remove(room)
events.emit("remove-room", room)
def remove_all_rooms(self, is_permanent=True):
for room in self.joined_rooms.copy():
self.remove_room(room, is_permanent)
@classmethod
def sanitize_room_name(cls, room):
"""Sanitize room name according to server requirements."""
# Replace non-ASCII characters
room = room.strip().encode("ascii", errors="replace").decode()
# Remove two or more consecutive spaces
room = " ".join(room.split())
# Limit to 24 characters
room = room[:cls.ROOM_NAME_MAX_LENGTH]
return room
def clear_room_messages(self, room):
events.emit("clear-room-messages", room)
def echo_message(self, room, message, message_type="local"):
events.emit("echo-room-message", room, message, message_type)
def send_message(self, room, message):
if room not in self.joined_rooms:
return
event = core.pluginhandler.outgoing_public_chat_event(room, message)
if event is None:
return
room, message = event
if config.sections["words"]["replacewords"]:
for word, replacement in config.sections["words"]["autoreplaced"].items():
message = message.replace(str(word), str(replacement))
core.send_message_to_server(SayChatroom(room, message))
core.pluginhandler.outgoing_public_chat_notification(room, message)
def add_user_to_private_room(self, room, username):
core.send_message_to_server(PrivateRoomAddUser(room, username))
def add_operator_to_private_room(self, room, username):
core.send_message_to_server(PrivateRoomAddOperator(room, username))
def remove_user_from_private_room(self, room, username):
core.send_message_to_server(PrivateRoomRemoveUser(room, username))
def remove_operator_from_private_room(self, room, username):
core.send_message_to_server(PrivateRoomRemoveOperator(room, username))
def is_private_room_owned(self, room):
private_room = self.private_rooms.get(room)
return private_room is not None and private_room.owner == core.users.login_username
def is_private_room_member(self, room):
return room in self.private_rooms
def is_private_room_operator(self, room):
private_room = self.private_rooms.get(room)
return private_room is not None and core.users.login_username in private_room.operators
def request_room_list(self):
core.send_message_to_server(RoomList())
def request_private_room_disown(self, room):
if not self.is_private_room_owned(room):
return
core.send_message_to_server(PrivateRoomDisown(room))
del self.private_rooms[room]
def request_private_room_cancel_membership(self, room):
if not self.is_private_room_member(room):
return
core.send_message_to_server(PrivateRoomCancelMembership(room))
del self.private_rooms[room]
def request_private_room_toggle(self, enabled):
core.send_message_to_server(PrivateRoomToggle(enabled))
def request_update_ticker(self, room, message):
core.send_message_to_server(RoomTickerSet(room, message))
def _update_room_user(self, room_obj, user_data):
username = user_data.username
room_obj.users.add(username)
core.users.watch_user(username, context=f"chatrooms_{room_obj.name}", is_implicit=True)
watched_user = core.users.watched[username]
watched_user.upload_speed = user_data.avgspeed
watched_user.files = user_data.files
watched_user.folders = user_data.dirs
core.users.statuses[username] = user_data.status
# Request user's IP address, so we can get the country and ignore messages by IP
if username not in core.users.addresses:
core.users.request_ip_address(username)
# Replace server-provided country with our own
if username in core.users.countries:
user_data.country = core.users.countries[username]
def _update_private_room(self, room, owner=None, members=None, operators=None):
private_room = self.private_rooms.get(room)
if private_room is None:
private_room = self.private_rooms[room] = PrivateRoom(room)
if owner:
private_room.owner = owner
if members:
for member in members:
private_room.members.add(member)
if operators:
for operator in operators:
private_room.operators.add(operator)
def _join_room(self, msg):
"""Server code 14."""
room_obj = self.joined_rooms.get(msg.room)
if room_obj is None:
# Reject unsolicited room join messages from the server
core.send_message_to_server(LeaveRoom(msg.room))
return
room_obj.is_private = msg.private
self.server_rooms.add(msg.room)
if msg.private:
self._update_private_room(msg.room, owner=msg.owner, operators=msg.operators)
for user_data in msg.users:
self._update_room_user(room_obj, user_data)
core.pluginhandler.join_chatroom_notification(msg.room)
def _leave_room(self, msg):
"""Server code 15."""
room_obj = self.joined_rooms.get(msg.room)
if room_obj is not None:
for username in room_obj.users:
core.users.unwatch_user(username, context=f"chatrooms_{msg.room}")
room_obj.users.clear()
core.pluginhandler.leave_chatroom_notification(msg.room)
def _private_room_users(self, msg):
"""Server code 133."""
self._update_private_room(msg.room, members=msg.users)
def _private_room_add_user(self, msg):
"""Server code 134."""
private_room = self.private_rooms.get(msg.room)
if private_room is not None:
private_room.members.add(msg.user)
def _private_room_remove_user(self, msg):
"""Server code 135."""
private_room = self.private_rooms.get(msg.room)
if private_room is not None:
private_room.members.discard(msg.user)
def _private_room_added(self, msg):
"""Server code 139."""
if msg.room in self.private_rooms:
return
self._update_private_room(msg.room)
if msg.room in self.joined_rooms:
# Room tab previously opened, join room now
self.show_room(msg.room, is_private=True, switch_page=False)
log.add(_("You have been added to a private room: %(room)s"), {"room": msg.room})
def _private_room_removed(self, msg):
"""Server code 140."""
if msg.room in self.private_rooms:
del self.private_rooms[msg.room]
def _private_room_toggle(self, msg):
"""Server code 141."""
config.sections["server"]["private_chatrooms"] = msg.enabled
def _private_room_add_operator(self, msg):
"""Server code 143."""
private_room = self.private_rooms.get(msg.room)
if private_room is not None:
private_room.operators.add(msg.user)
def _private_room_remove_operator(self, msg):
"""Server code 144."""
private_room = self.private_rooms.get(msg.room)
if private_room is not None:
private_room.operators.discard(msg.user)
def _private_room_operator_added(self, msg):
"""Server code 145."""
private_room = self.private_rooms.get(msg.room)
if private_room is not None:
private_room.operators.add(core.users.login_username)
def _private_room_operator_removed(self, msg):
"""Server code 146."""
private_room = self.private_rooms.get(msg.room)
if private_room is not None:
private_room.operators.discard(core.users.login_username)
def _private_room_operators(self, msg):
"""Server code 148."""
self._update_private_room(msg.room, operators=msg.operators)
def _global_room_message(self, msg):
"""Server code 152."""
self._say_chat_room(msg, is_global=True)
def _room_list(self, msg):
"""Server code 64."""
for room, _user_count in msg.rooms:
self.server_rooms.add(room)
for room, _user_count in msg.ownedprivaterooms:
self._update_private_room(room, owner=core.users.login_username)
for room, _user_count in msg.otherprivaterooms:
self._update_private_room(room)
if config.sections["words"]["roomnames"]:
self.update_completions()
core.privatechat.update_completions()
def get_message_type(self, user, text):
if text.startswith("/me "):
return "action"
if user == core.users.login_username:
return "local"
if core.users.login_username and find_whole_word(core.users.login_username.lower(), text.lower()) > -1:
return "hilite"
return "remote"
def _say_chat_room(self, msg, is_global=False):
"""Server code 13."""
room = msg.room
username = msg.user
if not is_global:
if room not in self.joined_rooms:
msg.room = None
return
log.add_chat(_("Chat message from user '%(user)s' in room '%(room)s': %(message)s"), {
"user": username,
"room": room,
"message": msg.message
})
if username != "server":
if core.network_filter.is_user_ignored(username):
msg.room = None
return
if core.network_filter.is_user_ip_ignored(username):
msg.room = None
return
event = core.pluginhandler.incoming_public_chat_event(room, username, msg.message)
if event is None:
msg.room = None
return
_room, _username, msg.message = event
else:
room = self.GLOBAL_ROOM_NAME
message = msg.message
msg.message_type = self.get_message_type(username, message)
is_action_message = (msg.message_type == "action")
if is_action_message:
message = message.replace("/me ", "", 1)
if config.sections["words"]["censorwords"] and username != core.users.login_username:
message = censor_text(message, censored_patterns=config.sections["words"]["censored"])
if is_action_message:
msg.formatted_message = msg.message = f"* {username} {message}"
else:
msg.formatted_message = f"[{username}] {message}"
if is_global:
msg.formatted_message = f"{msg.room} | {msg.formatted_message}"
if config.sections["logging"]["chatrooms"] or room in config.sections["logging"]["rooms"]:
log.write_log_file(
folder_path=log.room_folder_path,
basename=room, text=msg.formatted_message
)
if is_global:
core.pluginhandler.public_room_message_notification(msg.room, username, msg.message)
else:
core.pluginhandler.incoming_public_chat_notification(room, username, msg.message)
def _user_joined_room(self, msg):
"""Server code 16."""
room_obj = self.joined_rooms.get(msg.room)
if room_obj is None:
msg.room = None
return
self._update_room_user(room_obj, msg.userdata)
core.pluginhandler.user_join_chatroom_notification(msg.room, msg.userdata.username)
def _user_left_room(self, msg):
"""Server code 17."""
room_obj = self.joined_rooms.get(msg.room)
if room_obj is None:
msg.room = None
return
username = msg.username
room_obj.users.discard(username)
core.users.unwatch_user(username, context=f"chatrooms_{msg.room}")
core.pluginhandler.user_leave_chatroom_notification(msg.room, username)
def _ticker_state(self, msg):
"""Server code 113."""
room_obj = self.joined_rooms.get(msg.room)
if room_obj is None:
msg.room = None
return
room_obj.tickers.clear()
for username, message in msg.msgs:
if core.network_filter.is_user_ignored(username) or \
core.network_filter.is_user_ip_ignored(username):
# User ignored, ignore ticker message
continue
room_obj.tickers[username] = message
def _ticker_add(self, msg):
"""Server code 114."""
room_obj = self.joined_rooms.get(msg.room)
if room_obj is None:
msg.room = None
return
username = msg.user
if core.network_filter.is_user_ignored(username) or core.network_filter.is_user_ip_ignored(username):
# User ignored, ignore Ticker messages
return
room_obj.tickers[username] = msg.msg
def _ticker_remove(self, msg):
"""Server code 115."""
room_obj = self.joined_rooms.get(msg.room)
if room_obj is None:
msg.room = None
return
room_obj.tickers.pop(msg.user, None)
def update_completions(self):
self.completions.clear()
self.completions.add(config.sections["server"]["login"])
if config.sections["words"]["roomnames"]:
self.completions.update(self.server_rooms)
if config.sections["words"]["buddies"]:
self.completions.update(core.buddies.users)
if config.sections["words"]["commands"]:
self.completions.update(core.pluginhandler.get_command_list("chatroom"))
events.emit("room-completions", self.completions.copy())
| 20,789 | Python | .py | 437 | 37.771167 | 113 | 0.63882 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,407 | core.py | nicotine-plus_nicotine-plus/pynicotine/core.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import threading
import pynicotine
from pynicotine.config import config
from pynicotine.events import events
from pynicotine.logfacility import log
class Core:
"""Core handles initialization, quitting, as well as the various components
used by the application.
"""
__slots__ = ("shares", "users", "network_filter", "statistics", "search", "downloads",
"uploads", "interests", "userbrowse", "userinfo", "buddies", "privatechat",
"chatrooms", "pluginhandler", "now_playing", "portmapper", "notifications",
"update_checker", "_network_thread", "cli_interface_address",
"cli_listen_port", "enabled_components")
def __init__(self):
self.shares = None
self.users = None
self.network_filter = None
self.statistics = None
self.search = None
self.downloads = None
self.uploads = None
self.interests = None
self.userbrowse = None
self.userinfo = None
self.buddies = None
self.privatechat = None
self.chatrooms = None
self.pluginhandler = None
self.now_playing = None
self.portmapper = None
self.notifications = None
self.update_checker = None
self._network_thread = None
self.cli_interface_address = None
self.cli_listen_port = None
self.enabled_components = set()
def init_components(self, enabled_components=None):
# Enable all components by default
if enabled_components is None:
enabled_components = {
"error_handler", "signal_handler", "cli", "portmapper", "network_thread", "shares", "users",
"notifications", "network_filter", "now_playing", "statistics", "update_checker",
"search", "downloads", "uploads", "interests", "userbrowse", "userinfo", "buddies",
"chatrooms", "privatechat", "pluginhandler"
}
self.enabled_components = enabled_components
if "error_handler" in enabled_components:
self._init_error_handler()
if "signal_handler" in enabled_components:
self._init_signal_handler()
if "cli" in enabled_components:
from pynicotine.cli import cli
cli.enable_logging()
config.load_config()
events.enable()
for event_name, callback in (
("quit", self._quit),
("server-reconnect", self.connect)
):
events.connect(event_name, callback)
script_folder_path = os.path.dirname(__file__)
log.add(_("Loading %(program)s %(version)s"), {
"program": "Python",
"version": sys.version.split()[0]
})
log.add_debug("Using %s executable: %s", ("Python", sys.executable))
log.add(_("Loading %(program)s %(version)s"), {
"program": pynicotine.__application_name__,
"version": pynicotine.__version__
})
log.add_debug("Using %s executable: %s", (pynicotine.__application_name__, script_folder_path))
if "portmapper" in enabled_components:
from pynicotine.portmapper import PortMapper
self.portmapper = PortMapper()
if "network_thread" in enabled_components:
from pynicotine.slskproto import NetworkThread
self._network_thread = NetworkThread()
else:
events.connect("schedule-quit", self._schedule_quit)
if "shares" in enabled_components:
# Initialized before "users" component in order to send share stats to server
# before watching our username, otherwise we get outdated stats back.
from pynicotine.shares import Shares
self.shares = Shares()
if "users" in enabled_components:
from pynicotine.users import Users
self.users = Users()
if "notifications" in enabled_components:
from pynicotine.notifications import Notifications
self.notifications = Notifications()
if "network_filter" in enabled_components:
from pynicotine.networkfilter import NetworkFilter
self.network_filter = NetworkFilter()
if "now_playing" in enabled_components:
from pynicotine.nowplaying import NowPlaying
self.now_playing = NowPlaying()
if "statistics" in enabled_components:
from pynicotine.transfers import Statistics
self.statistics = Statistics()
if "update_checker" in enabled_components:
self.update_checker = UpdateChecker()
if "search" in enabled_components:
from pynicotine.search import Search
self.search = Search()
if "downloads" in enabled_components:
from pynicotine.downloads import Downloads
self.downloads = Downloads()
if "uploads" in enabled_components:
from pynicotine.uploads import Uploads
self.uploads = Uploads()
if "interests" in enabled_components:
from pynicotine.interests import Interests
self.interests = Interests()
if "userbrowse" in enabled_components:
from pynicotine.userbrowse import UserBrowse
self.userbrowse = UserBrowse()
if "userinfo" in enabled_components:
from pynicotine.userinfo import UserInfo
self.userinfo = UserInfo()
if "buddies" in enabled_components:
from pynicotine.buddies import Buddies
self.buddies = Buddies()
if "chatrooms" in enabled_components:
from pynicotine.chatrooms import ChatRooms
self.chatrooms = ChatRooms()
if "privatechat" in enabled_components:
from pynicotine.privatechat import PrivateChat
self.privatechat = PrivateChat()
if "pluginhandler" in enabled_components:
from pynicotine.pluginsystem import PluginHandler
self.pluginhandler = PluginHandler()
def _init_signal_handler(self):
"""Handle Ctrl+C and "kill" exit gracefully."""
import signal
for signal_type in (signal.SIGINT, signal.SIGTERM):
signal.signal(signal_type, self.quit)
def _init_error_handler(self):
def thread_excepthook(args):
sys.excepthook(*args[:3])
if hasattr(threading, "excepthook"):
threading.excepthook = thread_excepthook
return
# Workaround for Python <= 3.7
init_thread = threading.Thread.__init__
def init_thread_excepthook(self, *args, **kwargs):
init_thread(self, *args, **kwargs)
run_thread = self.run
def run_with_excepthook(*args2, **kwargs2):
try:
run_thread(*args2, **kwargs2)
except Exception:
thread_excepthook(sys.exc_info())
self.run = run_with_excepthook
threading.Thread.__init__ = init_thread_excepthook
def start(self):
if "cli" in self.enabled_components:
from pynicotine.cli import cli
cli.enable_prompt()
events.emit("start")
def setup(self):
events.emit("setup")
def confirm_quit(self):
events.emit("confirm-quit")
def quit(self, signal_type=None, _frame=None):
import signal
log.add(_("Quitting %(program)s %(version)s, %(status)s…"), {
"program": pynicotine.__application_name__,
"version": pynicotine.__version__,
"status": _("terminating") if signal_type == signal.SIGTERM else _("application closing")
})
# Allow the networking thread to finish up before quitting
events.emit("schedule-quit")
def _schedule_quit(self):
events.emit("quit")
def _quit(self):
self._network_thread = None
self.shares = None
self.users = None
self.portmapper = None
self.notifications = None
self.network_filter = None
self.now_playing = None
self.statistics = None
self.update_checker = None
self.search = None
self.downloads = None
self.uploads = None
self.interests = None
self.userbrowse = None
self.userinfo = None
self.buddies = None
self.chatrooms = None
self.privatechat = None
self.pluginhandler = None
config.write_configuration()
log.add(_("Quit %(program)s %(version)s!"), {
"program": pynicotine.__application_name__,
"version": pynicotine.__version__
})
def connect(self):
if config.need_config():
log.add(_("You need to specify a username and password before connecting…"))
self.setup()
return
from pynicotine.slskmessages import ServerConnect
events.emit("enable-message-queue")
self.send_message_to_network_thread(ServerConnect(
addr=config.sections["server"]["server"],
login=(config.sections["server"]["login"], config.sections["server"]["passw"]),
interface_name=config.sections["server"]["interface"],
interface_address=self.cli_interface_address,
listen_port=self.cli_listen_port or config.sections["server"]["portrange"][0],
portmapper=self.portmapper
))
def disconnect(self):
from pynicotine.slskmessages import ServerDisconnect
self.send_message_to_network_thread(ServerDisconnect())
def send_message_to_network_thread(self, message):
"""Sends message to the networking thread to inform about something."""
events.emit("queue-network-message", message)
def send_message_to_server(self, message):
"""Sends message to the server."""
events.emit("queue-network-message", message)
def send_message_to_peer(self, username, message):
"""Sends message to a peer."""
message.username = username
events.emit("queue-network-message", message)
class UpdateChecker:
__slots__ = ("_thread",)
def __init__(self):
self._thread = None
def check(self):
if self._thread and self._thread.is_alive():
return
self._thread = threading.Thread(target=self._check, name="UpdateChecker", daemon=True)
self._thread.start()
def _check(self):
try:
error_message = None
h_latest_version, latest_version = self.retrieve_latest_version()
current_version = self.create_integer_version(pynicotine.__version__)
is_outdated = (current_version < latest_version)
except Exception as error:
error_message = str(error)
h_latest_version = None
is_outdated = False
events.emit_main_thread("check-latest-version", h_latest_version, is_outdated, error_message)
@staticmethod
def create_integer_version(version):
major, minor, patch = version.split(".")[:3]
stable = 1
if "dev" in version or "rc" in version:
# Example: 2.0.1.dev1
# A dev version will be one less than a stable version
stable = 0
return (int(major) << 24) + (int(minor) << 16) + (int(patch.split("rc", 1)[0]) << 8) + stable
@classmethod
def retrieve_latest_version(cls):
import json
from urllib.request import urlopen
with urlopen("https://pypi.org/pypi/nicotine-plus/json", timeout=5) as response:
response_body = response.read().decode("utf-8", "replace")
data = json.loads(response_body)
h_latest_version = data["info"]["version"]
latest_version = cls.create_integer_version(h_latest_version)
return h_latest_version, latest_version
core = Core()
| 12,714 | Python | .py | 287 | 34.466899 | 108 | 0.627109 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,408 | networkfilter.py | nicotine-plus_nicotine-plus/pynicotine/networkfilter.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from bisect import bisect_left
from socket import inet_aton
from struct import Struct
from sys import intern
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
UINT32_UNPACK = Struct(">I").unpack_from
class NetworkFilter:
"""Functions related to banning and ignoring users."""
__slots__ = ("ip_ban_requested", "ip_ignore_requested", "_ip_range_values", "_ip_range_countries",
"_loaded_ip_country_data")
COUNTRIES = {
"AD": _("Andorra"),
"AE": _("United Arab Emirates"),
"AF": _("Afghanistan"),
"AG": _("Antigua & Barbuda"),
"AI": _("Anguilla"),
"AL": _("Albania"),
"AM": _("Armenia"),
"AO": _("Angola"),
"AQ": _("Antarctica"),
"AR": _("Argentina"),
"AS": _("American Samoa"),
"AT": _("Austria"),
"AU": _("Australia"),
"AW": _("Aruba"),
"AX": _("Åland Islands"),
"AZ": _("Azerbaijan"),
"BA": _("Bosnia & Herzegovina"),
"BB": _("Barbados"),
"BD": _("Bangladesh"),
"BE": _("Belgium"),
"BF": _("Burkina Faso"),
"BG": _("Bulgaria"),
"BH": _("Bahrain"),
"BI": _("Burundi"),
"BJ": _("Benin"),
"BL": _("Saint Barthelemy"),
"BM": _("Bermuda"),
"BN": _("Brunei Darussalam"),
"BO": _("Bolivia"),
"BQ": _("Bonaire, Sint Eustatius and Saba"),
"BR": _("Brazil"),
"BS": _("Bahamas"),
"BT": _("Bhutan"),
"BV": _("Bouvet Island"),
"BW": _("Botswana"),
"BY": _("Belarus"),
"BZ": _("Belize"),
"CA": _("Canada"),
"CC": _("Cocos (Keeling) Islands"),
"CD": _("Democratic Republic of Congo"),
"CF": _("Central African Republic"),
"CG": _("Congo"),
"CH": _("Switzerland"),
"CI": _("Ivory Coast"),
"CK": _("Cook Islands"),
"CL": _("Chile"),
"CM": _("Cameroon"),
"CN": _("China"),
"CO": _("Colombia"),
"CR": _("Costa Rica"),
"CU": _("Cuba"),
"CV": _("Cabo Verde"),
"CW": _("Curaçao"),
"CX": _("Christmas Island"),
"CY": _("Cyprus"),
"CZ": _("Czechia"),
"DE": _("Germany"),
"DJ": _("Djibouti"),
"DK": _("Denmark"),
"DM": _("Dominica"),
"DO": _("Dominican Republic"),
"DZ": _("Algeria"),
"EC": _("Ecuador"),
"EE": _("Estonia"),
"EG": _("Egypt"),
"EH": _("Western Sahara"),
"ER": _("Eritrea"),
"ES": _("Spain"),
"ET": _("Ethiopia"),
"EU": _("Europe"),
"FI": _("Finland"),
"FJ": _("Fiji"),
"FK": _("Falkland Islands (Malvinas)"),
"FM": _("Micronesia"),
"FO": _("Faroe Islands"),
"FR": _("France"),
"GA": _("Gabon"),
"GB": _("Great Britain"),
"GD": _("Grenada"),
"GE": _("Georgia"),
"GF": _("French Guiana"),
"GG": _("Guernsey"),
"GH": _("Ghana"),
"GI": _("Gibraltar"),
"GL": _("Greenland"),
"GM": _("Gambia"),
"GN": _("Guinea"),
"GP": _("Guadeloupe"),
"GQ": _("Equatorial Guinea"),
"GR": _("Greece"),
"GS": _("South Georgia & South Sandwich Islands"),
"GT": _("Guatemala"),
"GU": _("Guam"),
"GW": _("Guinea-Bissau"),
"GY": _("Guyana"),
"HK": _("Hong Kong"),
"HM": _("Heard & McDonald Islands"),
"HN": _("Honduras"),
"HR": _("Croatia"),
"HT": _("Haiti"),
"HU": _("Hungary"),
"ID": _("Indonesia"),
"IE": _("Ireland"),
"IL": _("Israel"),
"IM": _("Isle of Man"),
"IN": _("India"),
"IO": _("British Indian Ocean Territory"),
"IQ": _("Iraq"),
"IR": _("Iran"),
"IS": _("Iceland"),
"IT": _("Italy"),
"JE": _("Jersey"),
"JM": _("Jamaica"),
"JO": _("Jordan"),
"JP": _("Japan"),
"KE": _("Kenya"),
"KG": _("Kyrgyzstan"),
"KH": _("Cambodia"),
"KI": _("Kiribati"),
"KM": _("Comoros"),
"KN": _("Saint Kitts & Nevis"),
"KP": _("North Korea"),
"KR": _("South Korea"),
"KW": _("Kuwait"),
"KY": _("Cayman Islands"),
"KZ": _("Kazakhstan"),
"LA": _("Laos"),
"LB": _("Lebanon"),
"LC": _("Saint Lucia"),
"LI": _("Liechtenstein"),
"LK": _("Sri Lanka"),
"LR": _("Liberia"),
"LS": _("Lesotho"),
"LT": _("Lithuania"),
"LU": _("Luxembourg"),
"LV": _("Latvia"),
"LY": _("Libya"),
"MA": _("Morocco"),
"MC": _("Monaco"),
"MD": _("Moldova"),
"ME": _("Montenegro"),
"MF": _("Saint Martin"),
"MG": _("Madagascar"),
"MH": _("Marshall Islands"),
"MK": _("North Macedonia"),
"ML": _("Mali"),
"MM": _("Myanmar"),
"MN": _("Mongolia"),
"MO": _("Macau"),
"MP": _("Northern Mariana Islands"),
"MQ": _("Martinique"),
"MR": _("Mauritania"),
"MS": _("Montserrat"),
"MT": _("Malta"),
"MU": _("Mauritius"),
"MV": _("Maldives"),
"MW": _("Malawi"),
"MX": _("Mexico"),
"MY": _("Malaysia"),
"MZ": _("Mozambique"),
"NA": _("Namibia"),
"NC": _("New Caledonia"),
"NE": _("Niger"),
"NF": _("Norfolk Island"),
"NG": _("Nigeria"),
"NI": _("Nicaragua"),
"NL": _("Netherlands"),
"NO": _("Norway"),
"NP": _("Nepal"),
"NR": _("Nauru"),
"NU": _("Niue"),
"NZ": _("New Zealand"),
"OM": _("Oman"),
"PA": _("Panama"),
"PE": _("Peru"),
"PF": _("French Polynesia"),
"PG": _("Papua New Guinea"),
"PH": _("Philippines"),
"PK": _("Pakistan"),
"PL": _("Poland"),
"PM": _("Saint Pierre & Miquelon"),
"PN": _("Pitcairn"),
"PR": _("Puerto Rico"),
"PS": _("State of Palestine"),
"PT": _("Portugal"),
"PW": _("Palau"),
"PY": _("Paraguay"),
"QA": _("Qatar"),
"RE": _("Réunion"),
"RO": _("Romania"),
"RS": _("Serbia"),
"RU": _("Russia"),
"RW": _("Rwanda"),
"SA": _("Saudi Arabia"),
"SB": _("Solomon Islands"),
"SC": _("Seychelles"),
"SD": _("Sudan"),
"SE": _("Sweden"),
"SG": _("Singapore"),
"SH": _("Saint Helena"),
"SI": _("Slovenia"),
"SJ": _("Svalbard & Jan Mayen Islands"),
"SK": _("Slovak Republic"),
"SL": _("Sierra Leone"),
"SM": _("San Marino"),
"SN": _("Senegal"),
"SO": _("Somalia"),
"SR": _("Suriname"),
"SS": _("South Sudan"),
"ST": _("Sao Tome & Principe"),
"SV": _("El Salvador"),
"SX": _("Sint Maarten"),
"SY": _("Syria"),
"SZ": _("Eswatini"),
"TC": _("Turks & Caicos Islands"),
"TD": _("Chad"),
"TF": _("French Southern Territories"),
"TG": _("Togo"),
"TH": _("Thailand"),
"TJ": _("Tajikistan"),
"TK": _("Tokelau"),
"TL": _("Timor-Leste"),
"TM": _("Turkmenistan"),
"TN": _("Tunisia"),
"TO": _("Tonga"),
"TR": _("Türkiye"),
"TT": _("Trinidad & Tobago"),
"TV": _("Tuvalu"),
"TW": _("Taiwan"),
"TZ": _("Tanzania"),
"UA": _("Ukraine"),
"UG": _("Uganda"),
"UM": _("U.S. Minor Outlying Islands"),
"US": _("United States"),
"UY": _("Uruguay"),
"UZ": _("Uzbekistan"),
"VA": _("Holy See (Vatican City State)"),
"VC": _("Saint Vincent & The Grenadines"),
"VE": _("Venezuela"),
"VG": _("British Virgin Islands"),
"VI": _("U.S. Virgin Islands"),
"VN": _("Viet Nam"),
"VU": _("Vanuatu"),
"WF": _("Wallis & Futuna"),
"WS": _("Samoa"),
"YE": _("Yemen"),
"YT": _("Mayotte"),
"ZA": _("South Africa"),
"ZM": _("Zambia"),
"ZW": _("Zimbabwe")
}
def __init__(self):
self.ip_ban_requested = {}
self.ip_ignore_requested = {}
self._ip_range_values = ()
self._ip_range_countries = ()
self._loaded_ip_country_data = False
for event_name, callback in (
("peer-address", self._get_peer_address),
("quit", self._quit),
("server-disconnect", self._server_disconnect)
):
events.connect(event_name, callback)
def _populate_ip_country_data(self):
if self._loaded_ip_country_data:
return
data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), "external", "data")
with open(os.path.join(data_path, "ip_country_data.csv"), "r", encoding="utf-8") as file_handle:
for line in file_handle:
line = line.strip()
if not line or line.startswith("#"):
continue
if self._ip_range_values:
# String interning to reduce memory usage of duplicate strings
self._ip_range_countries = tuple(intern(x) for x in line.split(","))
break
self._ip_range_values = tuple(int(x) for x in line.split(","))
self._loaded_ip_country_data = True
def _server_disconnect(self, _msg):
self.ip_ban_requested.clear()
self.ip_ignore_requested.clear()
def _quit(self):
self._ip_range_values = ()
self._ip_range_countries = ()
self._loaded_ip_country_data = False
# IP Filter List Management #
def _request_ip(self, username, action, request_list):
"""Ask for the IP address of an unknown user.
Once a GetPeerAddress response arrives, either
ban_unban_user_ip_callback or ignore_unignore_user_ip_callback
is called.
"""
if username not in request_list:
request_list[username] = action
core.users.request_ip_address(username)
def _add_user_ip_to_list(self, ip_list, username=None, ip_address=None):
"""Add the current IP address and username of a user to a list."""
if not username:
# Try to get a username from currently active connections
username = self.get_online_username(ip_address)
elif not self.is_ip_address(ip_address):
# Try to get a known address for the user, use username as placeholder otherwise
ip_addresses = self._get_user_ip_addresses(username, ip_list, request_action="add")
ip_address = next(iter(ip_addresses), f"? ({username})")
if not ip_address:
return None
if ip_address not in ip_list or (username and ip_list[ip_address] != username):
ip_list[ip_address] = username or ""
config.write_configuration()
return ip_address
def _remove_user_ips_from_list(self, ip_list, username=None, ip_addresses=None):
"""Remove the previously saved IP address of a user from a list."""
if not ip_addresses:
# Try to get a known address for the user
ip_addresses = self._get_user_ip_addresses(username, ip_list, request_action="remove")
for ip_address in ip_addresses:
if ip_address in ip_list:
del ip_list[ip_address]
config.write_configuration()
return ip_addresses
# IP List Lookup Functions #
@staticmethod
def _get_previous_user_ip_addresses(username, ip_list):
"""Retrieve IP address of a user previously saved in an IP list."""
ip_addresses = set()
if username not in ip_list.values():
# User is not listed, skip iteration
return ip_addresses
for ip_address, i_username in ip_list.items():
if username == i_username:
ip_addresses.add(ip_address)
return ip_addresses
def _get_user_ip_addresses(self, username, ip_list, request_action):
"""Returns the known IP addresses of a user, requests one otherwise."""
ip_addresses = set()
if request_action == "add":
# Get current IP for user, if known
online_address = core.users.addresses.get(username)
if online_address:
online_ip_address, _port = online_address
ip_addresses.add(online_ip_address)
elif request_action == "remove":
# Remove all known IP addresses for user
ip_addresses = self._get_previous_user_ip_addresses(username, ip_list)
if ip_addresses:
return ip_addresses
# User's IP address is unknown, request it from the server
if ip_list == config.sections["server"]["ipblocklist"]:
request_list = self.ip_ban_requested
else:
request_list = self.ip_ignore_requested
self._request_ip(username, request_action, request_list)
return ip_addresses
@staticmethod
def get_online_username(ip_address):
"""Try to match a username from watched and known connections, for
updating an IP list item if the username is unspecified."""
for username, user_address in core.users.addresses.items():
user_ip_address, _user_port = user_address
if ip_address == user_ip_address:
return username
return None
def get_country_code(self, ip_address):
if not self._loaded_ip_country_data:
self._populate_ip_country_data()
if not self._ip_range_countries:
return ""
ip_num, = UINT32_UNPACK(inet_aton(ip_address))
ip_index = bisect_left(self._ip_range_values, ip_num)
country_code = self._ip_range_countries[ip_index]
return country_code
@staticmethod
def is_ip_address(ip_address, allow_zero=True, allow_wildcard=True):
"""Check if the given value is an IPv4 address or not."""
if not ip_address or ip_address is None or ip_address.count(".") != 3:
return False
if not allow_zero and ip_address == "0.0.0.0":
# User is offline if ip_address "0.0.0.0" (not None!)
return False
for part in ip_address.split("."):
if allow_wildcard and part == "*":
continue
if not part.isdigit():
return False
if int(part) > 255:
return False
return True
# IP Filter Rule Processing #
def _check_user_ip_filtered(self, ip_list, username=None, ip_address=None):
"""Check if an IP address is present in a list."""
if username and username in ip_list.values():
# Username is present in the list, so we want to filter it
return True
if not ip_address:
address = core.users.addresses.get(username)
if not address:
# Username not listed and is offline, so we can't filter it
return False
ip_address, _port = address
if ip_address in ip_list:
# IP filtered
return True
s_address = ip_address.split(".")
for address in ip_list:
if "*" not in address:
# No Wildcard in IP rule
continue
# Wildcard in IP rule
parts = address.split(".")
seg = 0
for part in parts:
# Stop if there's no wildcard or matching string number
if part not in {s_address[seg], "*"}:
break
seg += 1
# Last time around
if seg == 4:
# Wildcard filter, add actual IP address and username into list
self._add_user_ip_to_list(ip_list, username, ip_address)
return True
# Not filtered
return False
# Callbacks #
def _update_saved_user_ip_addresses(self, ip_list, username, ip_address):
"""Check if a user's IP address has changed and update the lists."""
previous_ip_addresses = self._get_previous_user_ip_addresses(username, ip_list)
if not previous_ip_addresses:
# User is not filtered
return
ip_address_placeholder = f"? ({username})"
if ip_address_placeholder in previous_ip_addresses:
self._remove_user_ips_from_list(ip_list, ip_addresses=[ip_address_placeholder])
if ip_address not in previous_ip_addresses:
self._add_user_ip_to_list(ip_list, username, ip_address)
def _get_peer_address(self, msg):
"""Server code 3."""
username = msg.user
ip_address = msg.ip_address
if ip_address == "0.0.0.0":
# User is offline
return
# If the IP address changed, make sure our IP ban/ignore list reflects this
self._update_saved_user_ip_addresses(config.sections["server"]["ipblocklist"], username, ip_address)
self._update_saved_user_ip_addresses(config.sections["server"]["ipignorelist"], username, ip_address)
# Check pending "add" and "remove" requests for IP-based filtering of previously offline users
self._ban_unban_user_ip_callback(username, ip_address)
self._ignore_unignore_user_ip_callback(username, ip_address)
# Banning #
def ban_user(self, username):
if not self.is_user_banned(username):
config.sections["server"]["banlist"].append(username)
config.write_configuration()
events.emit("ban-user", username)
def unban_user(self, username):
if self.is_user_banned(username):
config.sections["server"]["banlist"].remove(username)
config.write_configuration()
events.emit("unban-user", username)
def ban_user_ip(self, username=None, ip_address=None):
ip_address = self._add_user_ip_to_list(
config.sections["server"]["ipblocklist"], username, ip_address)
events.emit("ban-user-ip", username, ip_address)
return ip_address
def unban_user_ip(self, username=None, ip_address=None):
ip_addresses = {ip_address} if ip_address else set()
ip_addresses = self._remove_user_ips_from_list(
config.sections["server"]["ipblocklist"], username, ip_addresses)
events.emit("unban-user-ip", username, ip_addresses)
return ip_addresses
def _ban_unban_user_ip_callback(self, username, ip_address):
request = self.ip_ban_requested.pop(username, None)
if request == "add":
self.ban_user_ip(username, ip_address)
elif request == "remove":
self.unban_user_ip(username, ip_address)
def is_user_banned(self, username):
return username in config.sections["server"]["banlist"]
def is_user_ip_banned(self, username=None, ip_address=None):
return self._check_user_ip_filtered(
config.sections["server"]["ipblocklist"], username, ip_address)
# Ignoring #
def ignore_user(self, username):
if not self.is_user_ignored(username):
config.sections["server"]["ignorelist"].append(username)
config.write_configuration()
events.emit("ignore-user", username)
def unignore_user(self, username):
if self.is_user_ignored(username):
config.sections["server"]["ignorelist"].remove(username)
config.write_configuration()
events.emit("unignore-user", username)
def ignore_user_ip(self, username=None, ip_address=None):
ip_address = self._add_user_ip_to_list(
config.sections["server"]["ipignorelist"], username, ip_address)
events.emit("ignore-user-ip", username, ip_address)
return ip_address
def unignore_user_ip(self, username=None, ip_address=None):
ip_addresses = {ip_address} if ip_address else set()
ip_addresses = self._remove_user_ips_from_list(
config.sections["server"]["ipignorelist"], username, ip_addresses)
events.emit("unignore-user-ip", username, ip_addresses)
return ip_addresses
def _ignore_unignore_user_ip_callback(self, username, ip_address):
request = self.ip_ignore_requested.pop(username, None)
if request == "add":
self.ignore_user_ip(username, ip_address)
elif request == "remove":
self.unignore_user_ip(username, ip_address)
def is_user_ignored(self, username):
return username in config.sections["server"]["ignorelist"]
def is_user_ip_ignored(self, username=None, ip_address=None):
return self._check_user_ip_filtered(
config.sections["server"]["ipignorelist"], username, ip_address)
| 21,789 | Python | .py | 544 | 30.455882 | 109 | 0.53778 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,409 | logfacility.py | nicotine-plus_nicotine-plus/pynicotine/logfacility.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import time
from collections import deque
from pynicotine.config import config
from pynicotine.events import events
from pynicotine.slskmessages import DistribEmbeddedMessage
from pynicotine.slskmessages import DistribSearch
from pynicotine.slskmessages import EmbeddedMessage
from pynicotine.slskmessages import UnknownPeerMessage
from pynicotine.utils import clean_file
from pynicotine.utils import encode_path
from pynicotine.utils import open_file_path
class LogFile:
__slots__ = ("path", "handle", "last_active")
def __init__(self, path, handle):
self.path = path
self.handle = handle
self.last_active = time.monotonic()
class LogLevel:
DEFAULT = "default"
DOWNLOAD = "download"
UPLOAD = "upload"
SEARCH = "search"
CHAT = "chat"
CONNECTION = "connection"
MESSAGE = "message"
TRANSFER = "transfer"
MISCELLANEOUS = "miscellaneous"
class Logger:
__slots__ = ("debug_file_name", "downloads_file_name", "uploads_file_name", "debug_folder_path",
"transfer_folder_path", "room_folder_path", "private_chat_folder_path",
"_log_levels", "_log_files")
PREFIXES = {
LogLevel.DOWNLOAD: "Download",
LogLevel.UPLOAD: "Upload",
LogLevel.SEARCH: "Search",
LogLevel.CHAT: "Chat",
LogLevel.CONNECTION: "Conn",
LogLevel.MESSAGE: "Msg",
LogLevel.TRANSFER: "Transfer",
LogLevel.MISCELLANEOUS: "Misc"
}
EXCLUDED_MSGS = {
DistribEmbeddedMessage,
DistribSearch,
EmbeddedMessage,
UnknownPeerMessage
}
def __init__(self):
current_date_time = time.strftime("%Y-%m-%d_%H-%M-%S")
self.debug_file_name = f"debug_{current_date_time}"
self.downloads_file_name = f"downloads_{current_date_time}"
self.uploads_file_name = f"uploads_{current_date_time}"
self.debug_folder_path = None
self.transfer_folder_path = None
self.room_folder_path = None
self.private_chat_folder_path = None
self._log_levels = {LogLevel.DEFAULT}
self._log_files = {}
events.connect("quit", self._close_log_files)
events.schedule(delay=10, callback=self._close_inactive_log_files, repeat=True)
# Log Levels #
def init_log_levels(self):
self._log_levels = {LogLevel.DEFAULT}
for level in config.sections["logging"]["debugmodes"]:
self._log_levels.add(level)
def add_log_level(self, log_level, is_permanent=True):
self._log_levels.add(log_level)
if not is_permanent:
return
log_levels = config.sections["logging"]["debugmodes"]
if log_level not in log_levels:
log_levels.append(log_level)
def remove_log_level(self, log_level, is_permanent=True):
self._log_levels.discard(log_level)
if not is_permanent:
return
log_levels = config.sections["logging"]["debugmodes"]
if log_level in log_levels:
log_levels.remove(log_level)
# Log Files #
def _get_log_file(self, folder_path, basename, should_create_file=True):
file_path = os.path.join(folder_path, clean_file(f"{basename}.log"))
log_file = self._log_files.get(file_path)
if log_file is not None:
return log_file
folder_path_encoded = encode_path(folder_path)
file_path_encoded = encode_path(file_path)
if not should_create_file and not os.path.isfile(file_path_encoded):
return log_file
if not os.path.exists(folder_path_encoded):
os.makedirs(folder_path_encoded)
log_file = self._log_files[file_path] = LogFile(
path=file_path, handle=open(file_path_encoded, "ab+")) # pylint: disable=consider-using-with
# Disable file access for outsiders
os.chmod(file_path_encoded, 0o600)
return log_file
def write_log_file(self, folder_path, basename, text, timestamp=None):
folder_path = os.path.normpath(folder_path)
try:
log_file = self._get_log_file(folder_path, basename)
timestamp_format = config.sections["logging"]["log_timestamp"]
if timestamp_format:
timestamp = time.strftime(timestamp_format, time.localtime(timestamp))
text = f"{timestamp} {text}\n"
else:
text += "\n"
log_file.handle.write(text.encode("utf-8", "replace"))
log_file.last_active = time.monotonic()
except Exception as error:
# Avoid infinite recursion
should_log_file = (folder_path != self.debug_folder_path)
self._add(_('Couldn\'t write to log file "%(filename)s": %(error)s'), {
"filename": os.path.join(folder_path, clean_file(f"{basename}.log")),
"error": error
}, should_log_file=should_log_file)
def _close_log_file(self, log_file):
try:
log_file.handle.close()
except OSError as error:
self.add_debug('Failed to close log file "%(filename)s": %(error)s', {
"filename": log_file.path,
"error": error
})
del self._log_files[log_file.path]
def _close_log_files(self):
for log_file in self._log_files.copy().values():
self._close_log_file(log_file)
def _close_inactive_log_files(self):
current_time = time.monotonic()
for log_file in self._log_files.copy().values():
if (current_time - log_file.last_active) >= 10:
self._close_log_file(log_file)
def _normalize_folder_path(self, folder_path):
return os.path.normpath(os.path.expandvars(folder_path))
def update_folder_paths(self):
self.debug_folder_path = self._normalize_folder_path(config.sections["logging"]["debuglogsdir"])
self.transfer_folder_path = self._normalize_folder_path(config.sections["logging"]["transferslogsdir"])
self.room_folder_path = self._normalize_folder_path(config.sections["logging"]["roomlogsdir"])
self.private_chat_folder_path = self._normalize_folder_path(config.sections["logging"]["privatelogsdir"])
def open_log(self, folder_path, basename):
self._handle_log(folder_path, basename, self.open_log_callback)
def read_log(self, folder_path, basename, num_lines):
lines = None
log_file = None
try:
log_file = self._get_log_file(folder_path, basename, should_create_file=False)
if log_file is not None:
# Read the number of lines specified from the beginning of the file,
# then go back to the end of the file to append new lines
log_file.handle.seek(0)
lines = deque(log_file.handle, num_lines)
log_file.handle.seek(0, os.SEEK_END)
except Exception as error:
self._add(_("Cannot access log file %(path)s: %(error)s"), {
"path": os.path.join(folder_path, clean_file(f"{basename}.log")),
"error": error
})
if log_file is not None:
self._close_log_file(log_file)
return lines
def delete_log(self, folder_path, basename):
self._handle_log(folder_path, basename, self.delete_log_callback)
def _handle_log(self, folder_path, basename, callback):
folder_path_encoded = encode_path(folder_path)
file_path = os.path.join(folder_path, clean_file(f"{basename}.log"))
try:
if not os.path.isdir(folder_path_encoded):
os.makedirs(folder_path_encoded)
callback(file_path)
except Exception as error:
self._add(_("Cannot access log file %(path)s: %(error)s"), {"path": file_path, "error": error})
def open_log_callback(self, file_path):
open_file_path(file_path, create_file=True)
def delete_log_callback(self, file_path):
os.remove(encode_path(file_path))
def log_transfer(self, basename, msg, msg_args=None):
if not config.sections["logging"]["transfers"]:
return
if msg_args:
msg %= msg_args
self.write_log_file(folder_path=self.transfer_folder_path, basename=basename, text=msg)
# Log Messages #
def _format_log_message(self, level, msg, msg_args):
prefix = self.PREFIXES.get(level)
if msg_args is not None:
msg %= msg_args
if prefix:
msg = f"[{prefix}] {msg}"
return msg
def _add(self, msg, msg_args=None, title=None, level=LogLevel.DEFAULT, should_log_file=True):
msg = self._format_log_message(level, msg, msg_args)
if should_log_file and config.sections["logging"].get("debug_file_output", False):
events.invoke_main_thread(
self.write_log_file, folder_path=self.debug_folder_path,
basename=self.debug_file_name, text=msg)
try:
timestamp_format = config.sections["logging"].get("log_timestamp", "%x %X")
events.emit("log-message", timestamp_format, msg, title, level)
except Exception as error:
try:
print(f"Log callback failed: {level} {msg}\n{error}", flush=True)
except OSError:
# stdout is gone, prevent future errors
sys.stdout = open(os.devnull, "w", encoding="utf-8") # pylint: disable=consider-using-with
def add(self, msg, msg_args=None, title=None):
self._add(msg, msg_args, title)
def add_download(self, msg, msg_args=None):
level = LogLevel.DOWNLOAD
self.log_transfer(self.downloads_file_name, msg, msg_args)
if level in self._log_levels:
self._add(msg, msg_args, level=level)
def add_upload(self, msg, msg_args=None):
level = LogLevel.UPLOAD
self.log_transfer(self.uploads_file_name, msg, msg_args)
if level in self._log_levels:
self._add(msg, msg_args, level=level)
def add_search(self, msg, msg_args=None):
level = LogLevel.SEARCH
if level in self._log_levels:
self._add(msg, msg_args, level=level)
def add_chat(self, msg, msg_args=None):
level = LogLevel.CHAT
if level in self._log_levels:
self._add(msg, msg_args, level=level)
def add_conn(self, msg, msg_args=None):
level = LogLevel.CONNECTION
if level in self._log_levels:
self._add(msg, msg_args, level=level)
def add_msg_contents(self, msg, is_outgoing=False):
level = LogLevel.MESSAGE
if level not in self._log_levels:
return
# Compile message contents
if msg.__class__ in self.EXCLUDED_MSGS:
return
msg_direction = "OUT" if is_outgoing else "IN"
msg = f"{msg_direction}: {msg}"
msg_args = None
self._add(msg, msg_args, level=level)
def add_transfer(self, msg, msg_args=None):
level = LogLevel.TRANSFER
if level in self._log_levels:
self._add(msg, msg_args, level=level)
def add_debug(self, msg, msg_args=None):
level = LogLevel.MISCELLANEOUS
if level in self._log_levels:
self._add(msg, msg_args, level=level)
log = Logger()
| 12,180 | Python | .py | 267 | 36.449438 | 113 | 0.631552 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,410 | transfers.py | nicotine-plus_nicotine-plus/pynicotine/transfers.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2016 Mutnick <muhing@yahoo.com>
# COPYRIGHT (C) 2013 eLvErDe <gandalf@le-vert.net>
# COPYRIGHT (C) 2008-2012 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2009 hedonist <ak@sensi.org>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
# COPYRIGHT (C) 2001-2003 Alexander Kanavin
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
import os
import time
from ast import literal_eval
from collections import defaultdict
from os.path import normpath
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.logfacility import log
from pynicotine.slskmessages import CloseConnection
from pynicotine.slskmessages import FileAttribute
from pynicotine.slskmessages import UploadDenied
from pynicotine.utils import encode_path
from pynicotine.utils import load_file
from pynicotine.utils import write_file_and_backup
class TransferStatus:
QUEUED = "Queued"
GETTING_STATUS = "Getting status"
TRANSFERRING = "Transferring"
PAUSED = "Paused"
CANCELLED = "Cancelled"
FILTERED = "Filtered"
FINISHED = "Finished"
USER_LOGGED_OFF = "User logged off"
CONNECTION_CLOSED = "Connection closed"
CONNECTION_TIMEOUT = "Connection timeout"
DOWNLOAD_FOLDER_ERROR = "Download folder error"
LOCAL_FILE_ERROR = "Local file error"
class Transfer:
"""This class holds information about a single transfer."""
__slots__ = ("sock", "username", "virtual_path",
"folder_path", "token", "size", "file_handle", "start_time",
"current_byte_offset", "last_byte_offset", "transferred_bytes_total",
"speed", "avg_speed", "time_elapsed", "time_left", "modifier",
"queue_position", "file_attributes", "iterator", "status",
"legacy_attempt", "retry_attempt", "size_changed", "request_timer_id")
def __init__(self, username, virtual_path=None, folder_path=None, size=0, file_attributes=None,
status=None, current_byte_offset=None):
self.username = username
self.virtual_path = virtual_path
self.folder_path = folder_path
self.size = size
self.status = status
self.current_byte_offset = current_byte_offset
self.file_attributes = file_attributes
self.sock = None
self.file_handle = None
self.token = None
self.queue_position = 0
self.modifier = None
self.request_timer_id = None
self.start_time = None
self.last_byte_offset = None
self.transferred_bytes_total = 0
self.speed = 0
self.avg_speed = 0
self.time_elapsed = 0
self.time_left = 0
self.iterator = None
self.legacy_attempt = False
self.retry_attempt = False
self.size_changed = False
if file_attributes is None:
self.file_attributes = {}
class Transfers:
__slots__ = ("transfers", "queued_transfers", "queued_users", "active_users",
"failed_users", "transfers_file_path", "total_bandwidth", "_name",
"_allow_saving_transfers", "_online_users", "_user_queue_limits",
"_user_queue_sizes")
def __init__(self, name):
self.transfers = {}
self.queued_transfers = {}
self.queued_users = defaultdict(dict)
self.active_users = defaultdict(dict)
self.failed_users = defaultdict(dict)
self.transfers_file_path = os.path.join(config.data_folder_path, f"{name}.json")
self.total_bandwidth = 0
self._name = name
self._allow_saving_transfers = False
self._online_users = set()
self._user_queue_limits = defaultdict(int)
self._user_queue_sizes = defaultdict(int)
for event_name, callback in (
("quit", self._quit),
("server-login", self._server_login),
("server-disconnect", self._server_disconnect),
("start", self._start)
):
events.connect(event_name, callback)
def _start(self):
self._load_transfers()
self._allow_saving_transfers = True
# Save list of transfers every 3 minutes
events.schedule(delay=180, callback=self._save_transfers, repeat=True)
self.update_transfer_limits()
def _quit(self):
self._save_transfers()
self._allow_saving_transfers = False
self.transfers.clear()
self.failed_users.clear()
def _server_login(self, msg):
if not msg.success:
return
# Watch transfers for user status updates
for username in self.failed_users:
core.users.watch_user(username, context=self._name)
self.update_transfer_limits()
def _server_disconnect(self, _msg):
for users in (self.queued_users, self.active_users, self.failed_users):
for transfers in users.copy().values():
for transfer in transfers.copy().values():
self._abort_transfer(transfer, status=TransferStatus.USER_LOGGED_OFF)
self.queued_transfers.clear()
self.queued_users.clear()
self.active_users.clear()
self._online_users.clear()
self._user_queue_limits.clear()
self._user_queue_sizes.clear()
self.total_bandwidth = 0
# Load Transfers #
@staticmethod
def _load_transfers_file(transfers_file):
"""Loads a file of transfers in json format."""
transfers_file = encode_path(transfers_file)
if not os.path.isfile(transfers_file):
return None
with open(transfers_file, encoding="utf-8") as handle:
return json.load(handle)
@staticmethod
def _load_legacy_transfers_file(transfers_file):
"""Loads a download queue file in pickle format (legacy)"""
transfers_file = encode_path(transfers_file)
if not os.path.isfile(transfers_file):
return None
with open(transfers_file, "rb") as handle:
from pynicotine.shares import RestrictedUnpickler
return RestrictedUnpickler(handle, encoding="utf-8").load()
def _load_transfers(self):
raise NotImplementedError
def _load_file_attributes(self, num_attributes, transfer_row):
if num_attributes < 7:
return None
loaded_file_attributes = transfer_row[6]
if not loaded_file_attributes:
return None
if isinstance(loaded_file_attributes, dict):
# Found dictionary with file attributes (Nicotine+ >=3.3.0).
# JSON stores file attribute types as strings, convert them back to integers.
return {int(k): v for k, v in loaded_file_attributes.items()}
try:
# Check if a dictionary is represented in string format
return {int(k): v for k, v in literal_eval(loaded_file_attributes).items()}
except (AttributeError, ValueError):
pass
# Legacy bitrate/duration strings (Nicotine+ <3.3.0)
file_attributes = {}
bitrate = str(loaded_file_attributes)
is_vbr = (" (vbr)" in bitrate)
try:
file_attributes[FileAttribute.BITRATE] = int(bitrate.replace(" (vbr)", ""))
if is_vbr:
file_attributes[FileAttribute.VBR] = int(is_vbr)
except ValueError:
# No valid bitrate value found
pass
if num_attributes < 8:
return file_attributes
loaded_length = str(transfer_row[7])
if ":" not in loaded_length:
return file_attributes
# Convert HH:mm:ss to seconds
seconds = 0
for part in loaded_length.split(":"):
seconds = seconds * 60 + int(part, 10)
file_attributes[FileAttribute.DURATION] = seconds
return file_attributes
def _get_stored_transfers(self, transfers_file_path, load_func, load_only_finished=False):
transfer_rows = load_file(transfers_file_path, load_func)
if not transfer_rows:
return
allowed_statuses = {TransferStatus.PAUSED, TransferStatus.FILTERED, TransferStatus.FINISHED}
normalized_paths = {}
for transfer_row in transfer_rows:
num_attributes = len(transfer_row)
if num_attributes < 3:
continue
# Username / virtual path / folder path
username = transfer_row[0]
if not isinstance(username, str):
continue
virtual_path = transfer_row[1]
if not isinstance(virtual_path, str):
continue
folder_path = transfer_row[2]
if not isinstance(folder_path, str):
continue
if folder_path:
# Normalize and cache path
if folder_path not in normalized_paths:
folder_path = normalized_paths[folder_path] = normpath(folder_path)
else:
folder_path = normalized_paths[folder_path]
# Status
if num_attributes >= 4:
status = transfer_row[3]
if status == "Aborted":
status = TransferStatus.PAUSED
if load_only_finished and status != TransferStatus.FINISHED:
continue
if status not in allowed_statuses:
status = TransferStatus.USER_LOGGED_OFF
# Size / offset
size = 0
current_byte_offset = None
if num_attributes >= 5:
loaded_size = transfer_row[4]
if loaded_size:
try:
size = loaded_size // 1
except TypeError:
pass
if num_attributes >= 6:
loaded_byte_offset = transfer_row[5]
if loaded_byte_offset:
try:
current_byte_offset = loaded_byte_offset // 1
except TypeError:
pass
# File attributes
file_attributes = self._load_file_attributes(num_attributes, transfer_row)
yield (
Transfer(
username, virtual_path, folder_path, size, file_attributes, status,
current_byte_offset
)
)
# File Actions #
@staticmethod
def _close_file(transfer):
file_handle = transfer.file_handle
transfer.file_handle = None
if file_handle is None:
return
try:
file_handle.close()
except Exception as error:
file_path = file_handle.name.decode("utf-8", "replace")
log.add_transfer("Failed to close file %s: %s", (file_path, error))
# User Actions #
def _unwatch_stale_user(self, username):
"""Unwatches a user when status updates are no longer required, i.e.
no transfers remain, or all remaining transfers are
finished/filtered/paused.
"""
for users in (self.active_users, self.queued_users, self.failed_users):
if username in users:
return
core.users.unwatch_user(username, context=self._name)
# Limits #
def update_transfer_limits(self):
raise NotImplementedError
# Events #
def _transfer_timeout(self, transfer):
self._abort_transfer(transfer, status=TransferStatus.CONNECTION_TIMEOUT)
# Transfer Actions #
def _append_transfer(self, transfer):
self.transfers[transfer.username + transfer.virtual_path] = transfer
def _abort_transfer(self, transfer, status=None, denied_message=None):
username = transfer.username
virtual_path = transfer.virtual_path
transfer.legacy_attempt = False
transfer.size_changed = False
if transfer.sock is not None:
core.send_message_to_network_thread(CloseConnection(transfer.sock))
if transfer.file_handle is not None:
self._close_file(transfer)
elif denied_message and virtual_path in self.queued_users.get(username, {}):
core.send_message_to_peer(
username, UploadDenied(virtual_path, denied_message))
self._deactivate_transfer(transfer)
self._dequeue_transfer(transfer)
self._unfail_transfer(transfer)
if status:
transfer.status = status
if status not in {TransferStatus.FINISHED, TransferStatus.FILTERED, TransferStatus.PAUSED}:
self._fail_transfer(transfer)
# Only attempt to unwatch user after the transfer status is fully set
self._unwatch_stale_user(username)
def _update_transfer(self, transfer):
raise NotImplementedError
def _update_transfer_progress(self, transfer, stat_id, current_byte_offset=None, speed=None):
size = transfer.size
transfer.status = TransferStatus.TRANSFERRING
transfer.time_elapsed = time_elapsed = (time.monotonic() - transfer.start_time)
transfer.time_left = 0
if current_byte_offset is None:
return
transfer.current_byte_offset = current_byte_offset
transferred_fragment_size = current_byte_offset - transfer.last_byte_offset
transfer.last_byte_offset = current_byte_offset
if transferred_fragment_size > 0:
transfer.transferred_bytes_total += transferred_fragment_size
core.statistics.append_stat_value(stat_id, transferred_fragment_size)
transfer.avg_speed = max(0, int(transfer.transferred_bytes_total // max(1, time_elapsed)))
if speed is not None:
if speed <= 0:
transfer.speed = transfer.avg_speed
else:
transfer.speed = speed
if transfer.speed > 0 and size > current_byte_offset:
transfer.time_left = (size - current_byte_offset) // transfer.speed
def _finish_transfer(self, transfer):
self._deactivate_transfer(transfer)
self._close_file(transfer)
self._unwatch_stale_user(transfer.username)
transfer.status = TransferStatus.FINISHED
transfer.current_byte_offset = transfer.size
def _auto_clear_transfer(self, transfer):
if config.sections["transfers"][f"autoclear_{self._name}"]:
self._clear_transfer(transfer)
return True
return False
def _clear_transfer(self, transfer, denied_message=None):
self._abort_transfer(transfer, denied_message=denied_message)
del self.transfers[transfer.username + transfer.virtual_path]
def _enqueue_transfer(self, transfer):
core.users.watch_user(transfer.username, context=self._name)
transfer.status = TransferStatus.QUEUED
self.queued_users[transfer.username][transfer.virtual_path] = transfer
self.queued_transfers[transfer] = None
self._user_queue_sizes[transfer.username] += transfer.size
def _enqueue_limited_transfers(self, username):
# Optional method
pass
def _dequeue_transfer(self, transfer):
username = transfer.username
virtual_path = transfer.virtual_path
if virtual_path not in self.queued_users.get(username, {}):
return
self._user_queue_sizes[username] -= transfer.size
del self.queued_transfers[transfer]
del self.queued_users[username][virtual_path]
if self._user_queue_sizes[username] <= 0:
del self._user_queue_sizes[username]
if not self.queued_users[username]:
del self.queued_users[username]
# No more queued transfers, resume limited transfers if present
self._enqueue_limited_transfers(username)
transfer.queue_position = 0
def _activate_transfer(self, transfer, token):
core.users.watch_user(transfer.username, context=self._name)
transfer.status = TransferStatus.GETTING_STATUS
transfer.token = token
transfer.speed = transfer.avg_speed = 0
transfer.queue_position = 0
# When our port is closed, certain clients can take up to ~30 seconds before they
# initiate a 'F' connection, since they only send an indirect connection request after
# attempting to connect to our port for a certain time period.
# Known clients: Nicotine+ 2.2.0 - 3.2.0, 2 s; Soulseek NS, ~20 s; soulseeX, ~30 s.
# To account for potential delays while initializing the connection, add 15 seconds
# to the timeout value.
transfer.request_timer_id = events.schedule(
delay=45, callback=self._transfer_timeout, callback_args=(transfer,))
self.active_users[transfer.username][token] = transfer
def _deactivate_transfer(self, transfer):
username = transfer.username
token = transfer.token
if token is None or token not in self.active_users.get(username, {}):
return
del self.active_users[username][token]
if not self.active_users[username]:
del self.active_users[username]
if transfer.speed > 0:
self.total_bandwidth = max(0, self.total_bandwidth - transfer.speed)
if transfer.request_timer_id is not None:
events.cancel_scheduled(transfer.request_timer_id)
transfer.request_timer_id = None
transfer.speed = transfer.avg_speed
transfer.sock = None
transfer.token = None
def _fail_transfer(self, transfer):
self.failed_users[transfer.username][transfer.virtual_path] = transfer
def _unfail_transfer(self, transfer):
username = transfer.username
virtual_path = transfer.virtual_path
if virtual_path not in self.failed_users.get(username, {}):
return
del self.failed_users[username][virtual_path]
if not self.failed_users[username]:
del self.failed_users[username]
# Saving #
def _iter_transfer_rows(self):
"""Get a list of transfers to dump to file."""
for transfer in self.transfers.values():
yield [
transfer.username, transfer.virtual_path, transfer.folder_path, transfer.status, transfer.size,
transfer.current_byte_offset, transfer.file_attributes
]
def _save_transfers_callback(self, file_handle):
# Dump every transfer to the file individually to avoid large memory usage
json_encoder = json.JSONEncoder(check_circular=False, ensure_ascii=False)
is_first_item = True
file_handle.write("[")
for row in self._iter_transfer_rows():
if is_first_item:
is_first_item = False
else:
file_handle.write(",\n")
file_handle.write(json_encoder.encode(row))
file_handle.write("]")
def _save_transfers(self):
"""Save list of transfers."""
if not self._allow_saving_transfers:
# Don't save if transfers didn't load properly!
return
config.create_data_folder()
write_file_and_backup(self.transfers_file_path, self._save_transfers_callback)
class Statistics:
__slots__ = ("session_stats",)
def __init__(self):
self.session_stats = {}
for event_name, callback in (
("quit", self._quit),
("start", self._start)
):
events.connect(event_name, callback)
def _start(self):
# Only populate total since date on first run
if (not config.sections["statistics"]["since_timestamp"]
and config.sections["statistics"] == config.defaults["statistics"]):
config.sections["statistics"]["since_timestamp"] = int(time.time())
for stat_id in config.defaults["statistics"]:
self.session_stats[stat_id] = 0 if stat_id != "since_timestamp" else int(time.time())
def _quit(self):
self.session_stats.clear()
def append_stat_value(self, stat_id, stat_value):
self.session_stats[stat_id] += stat_value
config.sections["statistics"][stat_id] += stat_value
self._update_stat(stat_id)
def _update_stat(self, stat_id):
session_stat_value = self.session_stats[stat_id]
total_stat_value = config.sections["statistics"][stat_id]
events.emit("update-stat", stat_id, session_stat_value, total_stat_value)
def update_stats(self):
for stat_id in self.session_stats:
self._update_stat(stat_id)
def reset_stats(self):
for stat_id in config.defaults["statistics"]:
stat_value = 0 if stat_id != "since_timestamp" else int(time.time())
self.session_stats[stat_id] = config.sections["statistics"][stat_id] = stat_value
self.update_stats()
| 21,804 | Python | .py | 477 | 35.752621 | 111 | 0.635486 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,411 | slskmessages.py | nicotine-plus_nicotine-plus/pynicotine/slskmessages.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2009-2011 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2007-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
# COPYRIGHT (C) 2001-2003 Alexander Kanavin
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import zlib
try:
# Try faster module import first, if available
from _md5 import md5 # pylint: disable=import-private-name
except ImportError:
from hashlib import md5
from operator import itemgetter
from random import randint
from socket import inet_aton
from socket import inet_ntoa
from struct import Struct
from pynicotine.utils import UINT32_LIMIT
from pynicotine.utils import human_length
# This module contains message classes, that networking and UI thread
# exchange. Basically there are three types of messages: internal messages,
# server messages and p2p messages (between clients).
INT32_UNPACK = Struct("<i").unpack_from
DOUBLE_UINT32_UNPACK = Struct("<II").unpack_from
UINT16_UNPACK = Struct("<H").unpack_from
UINT32_UNPACK = Struct("<I").unpack_from
UINT64_UNPACK = Struct("<Q").unpack_from
BOOL_PACK = Struct("?").pack
UINT8_PACK = Struct("B").pack
INT32_PACK = Struct("<i").pack
UINT32_PACK = Struct("<I").pack
UINT64_PACK = Struct("<Q").pack
SEARCH_TOKENS_ALLOWED = set()
def initial_token():
"""Return a random token in a large enough range to effectively prevent
conflicting tokens between sessions."""
return randint(0, UINT32_LIMIT // 1000)
def increment_token(token):
"""Increment a token used by file search, transfer and connection
requests."""
if token < 0 or token >= UINT32_LIMIT:
# Protocol messages use unsigned integers for tokens
token = 0
token += 1
return token
# Constants #
class MessageType:
INTERNAL = "N"
INIT = "I"
SERVER = "S"
PEER = "P"
FILE = "F"
DISTRIBUTED = "D"
class ConnectionType:
SERVER = "S"
PEER = "P"
FILE = "F"
DISTRIBUTED = "D"
class LoginFailure:
USERNAME = "INVALIDUSERNAME"
PASSWORD = "INVALIDPASS"
VERSION = "INVALIDVERSION"
class UserStatus:
OFFLINE = 0
AWAY = 1
ONLINE = 2
class TransferDirection:
DOWNLOAD = 0
UPLOAD = 1
class TransferRejectReason:
QUEUED = "Queued"
COMPLETE = "Complete"
CANCELLED = "Cancelled"
FILE_READ_ERROR = "File read error."
FILE_NOT_SHARED = "File not shared."
BANNED = "Banned"
PENDING_SHUTDOWN = "Pending shutdown."
TOO_MANY_FILES = "Too many files"
TOO_MANY_MEGABYTES = "Too many megabytes"
DISALLOWED_EXTENSION = "Disallowed extension"
class FileAttribute:
BITRATE = 0
DURATION = 1
VBR = 2
ENCODER = 3
SAMPLE_RATE = 4
BIT_DEPTH = 5
# Internal Messages #
class InternalMessage:
__slots__ = ()
__excluded_attrs__ = {}
msg_type = MessageType.INTERNAL
def __str__(self):
attrs = {s: getattr(self, s) for s in self.__slots__ if s not in self.__excluded_attrs__}
return f"<{self.msg_type} - {self.__class__.__name__}> {attrs}"
class CloseConnection(InternalMessage):
__slots__ = ("sock",)
def __init__(self, sock=None):
self.sock = sock
class ServerConnect(InternalMessage):
"""Sent to the networking thread to establish a server connection."""
__slots__ = ("addr", "login", "interface_name", "interface_address", "listen_port",
"portmapper")
__excluded_attrs__ = {"login"}
def __init__(self, addr=None, login=None, interface_name=None, interface_address=None,
listen_port=None, portmapper=None):
self.addr = addr
self.login = login
self.interface_name = interface_name
self.interface_address = interface_address
self.listen_port = listen_port
self.portmapper = portmapper
class ServerDisconnect(InternalMessage):
__slots__ = ("manual_disconnect",)
def __init__(self, manual_disconnect=False):
self.manual_disconnect = manual_disconnect
class EmitNetworkMessageEvents(InternalMessage):
"""Sent to the networking thread to tell it to emit events for list of
network messages.
Currently used after shares have rescanned to process any
QueueUpload messages that arrived while scanning.
"""
__slots__ = ("msgs",)
def __init__(self, msgs=None):
self.msgs = msgs
class DownloadFile(InternalMessage):
"""Sent to the networking thread to pass the file object to write."""
__slots__ = ("sock", "token", "file", "leftbytes", "speed")
def __init__(self, sock=None, token=None, file=None, leftbytes=None):
self.sock = sock
self.token = token
self.file = file
self.leftbytes = leftbytes
self.speed = 0
class UploadFile(InternalMessage):
__slots__ = ("sock", "token", "file", "size", "sentbytes", "offset", "speed")
def __init__(self, sock=None, token=None, file=None, size=None, sentbytes=0, offset=None):
self.sock = sock
self.token = token
self.file = file
self.size = size
self.sentbytes = sentbytes
self.offset = offset
self.speed = 0
class SetUploadLimit(InternalMessage):
"""Sent to the networking thread to indicate changes in bandwidth shaping rules."""
__slots__ = ("limit", "limitby")
def __init__(self, limit, limitby):
self.limit = limit
self.limitby = limitby
class SetDownloadLimit(InternalMessage):
"""Sent to the networking thread to indicate changes in bandwidth shaping rules."""
__slots__ = ("limit",)
def __init__(self, limit):
self.limit = limit
# Network Messages #
class SlskMessage:
"""This is a parent class for all protocol messages."""
__slots__ = ()
__excluded_attrs__ = {}
msg_type = None
@staticmethod
def pack_bytes(content):
return UINT32_PACK(len(content)) + content
@staticmethod
def pack_string(content, is_legacy=False):
if is_legacy:
# Legacy string
try:
encoded = content.encode("latin-1")
except UnicodeEncodeError:
encoded = content.encode("utf-8", "replace")
else:
encoded = content.encode("utf-8", "replace")
return UINT32_PACK(len(encoded)) + encoded
@staticmethod
def pack_bool(content):
return BOOL_PACK(content)
@staticmethod
def pack_uint8(content):
return UINT8_PACK(content)
@staticmethod
def pack_int32(content):
return INT32_PACK(content)
@staticmethod
def pack_uint32(content):
return UINT32_PACK(content)
@staticmethod
def pack_uint64(content):
return UINT64_PACK(content)
@staticmethod
def unpack_bytes(message, start=0):
length, = UINT32_UNPACK(message, start)
start += 4
end = start + length
content = message[start:end]
return end, content.tobytes()
@staticmethod
def unpack_string(message, start=0):
length, = UINT32_UNPACK(message, start)
start += 4
end = start + length
content = message[start:end].tobytes()
try:
string = content.decode("utf-8")
except UnicodeDecodeError:
# Legacy strings
string = content.decode("latin-1")
return end, string
@staticmethod
def unpack_bool(message, start=0):
return start + 1, bool(message[start])
@staticmethod
def unpack_ip(message, start=0):
end = start + 4
return end, inet_ntoa(message[start:end].tobytes()[::-1])
@staticmethod
def unpack_uint8(message, start=0):
return start + 1, message[start]
@staticmethod
def unpack_uint16(message, start=0):
result, = UINT16_UNPACK(message, start)
return start + 4, result
@staticmethod
def unpack_int32(message, start=0):
result, = INT32_UNPACK(message, start)
return start + 4, result
@staticmethod
def unpack_uint32(message, start=0):
result, = UINT32_UNPACK(message, start)
return start + 4, result
@staticmethod
def unpack_uint64(message, start=0):
result, = UINT64_UNPACK(message, start)
return start + 8, result
def __str__(self):
attrs = {s: getattr(self, s) for s in self.__slots__ if s not in self.__excluded_attrs__}
return f"<{self.msg_type} - {self.__class__.__name__}> {attrs}"
class FileListMessage(SlskMessage):
__slots__ = ()
VALID_FILE_ATTRIBUTES = {
FileAttribute.BITRATE,
FileAttribute.DURATION,
FileAttribute.VBR,
FileAttribute.SAMPLE_RATE,
FileAttribute.BIT_DEPTH
}
@classmethod
def pack_file_info(cls, fileinfo):
msg = bytearray()
virtual_file_path, size, quality, duration = fileinfo
bitrate = is_vbr = samplerate = bitdepth = None
if quality is not None:
bitrate, is_vbr, samplerate, bitdepth = quality
msg += cls.pack_uint8(1)
msg += cls.pack_string(virtual_file_path)
msg += cls.pack_uint64(size)
msg += cls.pack_uint32(0) # empty ext
num_attrs = 0
msg_attrs = bytearray()
is_lossless = bitdepth is not None
if is_lossless:
if duration is not None:
msg_attrs += cls.pack_uint32(1)
msg_attrs += cls.pack_uint32(duration)
num_attrs += 1
if samplerate is not None:
msg_attrs += cls.pack_uint32(4)
msg_attrs += cls.pack_uint32(samplerate)
num_attrs += 1
if bitdepth is not None:
msg_attrs += cls.pack_uint32(5)
msg_attrs += cls.pack_uint32(bitdepth)
num_attrs += 1
else:
if bitrate is not None:
msg_attrs += cls.pack_uint32(0)
msg_attrs += cls.pack_uint32(bitrate)
num_attrs += 1
if duration is not None:
msg_attrs += cls.pack_uint32(1)
msg_attrs += cls.pack_uint32(duration)
num_attrs += 1
if bitrate is not None:
msg_attrs += cls.pack_uint32(2)
msg_attrs += cls.pack_uint32(is_vbr)
num_attrs += 1
msg += cls.pack_uint32(num_attrs)
if msg_attrs:
msg += msg_attrs
return msg
@classmethod
def parse_file_size(cls, message, pos):
if message[pos + 7] == 255:
# Soulseek NS bug: >2 GiB files show up as ~16 EiB when unpacking the size
# as uint64 (8 bytes), due to the first 4 bytes containing the size, and the
# last 4 bytes containing garbage (a value of 4294967295 bytes, integer limit).
# Only unpack the first 4 bytes to work around this issue.
pos, size = cls.unpack_uint32(message, pos)
pos, _garbage = cls.unpack_uint32(message, pos)
else:
# Everything looks fine, parse size as usual
pos, size = cls.unpack_uint64(message, pos)
return pos, size
@classmethod
def unpack_file_attributes(cls, message, pos):
attrs = {}
valid_file_attributes = cls.VALID_FILE_ATTRIBUTES
pos, numattr = cls.unpack_uint32(message, pos)
for _ in range(numattr):
pos, attrnum = cls.unpack_uint32(message, pos)
pos, attr = cls.unpack_uint32(message, pos)
if attrnum in valid_file_attributes:
attrs[attrnum] = attr
return pos, attrs
@staticmethod
def parse_file_attributes(attributes):
if attributes is None:
attributes = {}
try:
bitrate = attributes.get(FileAttribute.BITRATE)
length = attributes.get(FileAttribute.DURATION)
vbr = attributes.get(FileAttribute.VBR)
sample_rate = attributes.get(FileAttribute.SAMPLE_RATE)
bit_depth = attributes.get(FileAttribute.BIT_DEPTH)
except AttributeError:
# Legacy attribute list format used for shares lists saved in Nicotine+ 3.2.2 and earlier
bitrate = length = vbr = sample_rate = bit_depth = None
if len(attributes) == 3:
attribute1, attribute2, attribute3 = attributes
if attribute3 in {0, 1}:
bitrate = attribute1
length = attribute2
vbr = attribute3
elif attribute3 > 1:
length = attribute1
sample_rate = attribute2
bit_depth = attribute3
elif len(attributes) == 2:
attribute1, attribute2 = attributes
if attribute2 in {0, 1}:
bitrate = attribute1
vbr = attribute2
elif attribute1 >= 8000 and attribute2 <= 64:
sample_rate = attribute1
bit_depth = attribute2
else:
bitrate = attribute1
length = attribute2
return bitrate, length, vbr, sample_rate, bit_depth
@classmethod
def parse_audio_quality_length(cls, filesize, attributes, always_show_bitrate=False):
bitrate, length, vbr, sample_rate, bit_depth = cls.parse_file_attributes(attributes)
if bitrate is None:
if sample_rate and bit_depth:
# Bitrate = sample rate (Hz) * word length (bits) * channel count
# Bitrate = 44100 * 16 * 2
bitrate = (sample_rate * bit_depth * 2) // 1000
else:
bitrate = -1
if length is None:
if bitrate > 0:
# Dividing the file size by the bitrate in Bytes should give us a good enough approximation
length = filesize // (bitrate * 125)
else:
length = -1
# Ignore invalid values
if bitrate <= 0 or bitrate > UINT32_LIMIT:
bitrate = 0
h_quality = ""
elif sample_rate and bit_depth:
h_quality = f"{sample_rate / 1000:.3g} kHz / {bit_depth} bit"
if always_show_bitrate:
h_quality += f" / {bitrate} kbps"
else:
h_quality = f"{bitrate} kbps"
if vbr == 1:
h_quality += " (vbr)"
if length < 0 or length > UINT32_LIMIT:
length = 0
h_length = ""
else:
h_length = human_length(length)
return h_quality, bitrate, h_length, length
class RecommendationsMessage(SlskMessage):
__slots__ = ()
@classmethod
def populate_recommendations(cls, recommendations, unrecommendations, message, pos=0):
pos, num = cls.unpack_uint32(message, pos)
for _ in range(num):
pos, key = cls.unpack_string(message, pos)
pos, rating = cls.unpack_int32(message, pos)
lst = recommendations if rating >= 0 else unrecommendations
item = (key, rating)
if item not in lst:
lst.append(item)
return pos
@classmethod
def parse_recommendations(cls, message, pos=0):
recommendations = []
unrecommendations = []
pos = cls.populate_recommendations(recommendations, unrecommendations, message, pos)
if message[pos:]:
pos = cls.populate_recommendations(recommendations, unrecommendations, message, pos)
return pos, recommendations, unrecommendations
class UserData:
"""When we join a room, the server sends us a bunch of these for each
user."""
__slots__ = ("username", "status", "avgspeed", "uploadnum", "unknown", "files", "dirs", "slotsfull", "country")
def __init__(self, username=None, status=None, avgspeed=None, uploadnum=None, unknown=None, files=None, dirs=None,
slotsfull=None, country=None):
self.username = username
self.status = status
self.avgspeed = avgspeed
self.uploadnum = uploadnum
self.unknown = unknown
self.files = files
self.dirs = dirs
self.slotsfull = slotsfull
self.country = country
class UsersMessage(SlskMessage):
__slots__ = ()
@classmethod
def parse_users(cls, message, pos=0):
pos, numusers = cls.unpack_uint32(message, pos)
users = []
for i in range(numusers):
users.append(UserData())
pos, users[i].username = cls.unpack_string(message, pos)
pos, statuslen = cls.unpack_uint32(message, pos)
for i in range(statuslen):
pos, users[i].status = cls.unpack_uint32(message, pos)
pos, statslen = cls.unpack_uint32(message, pos)
for i in range(statslen):
pos, users[i].avgspeed = cls.unpack_uint32(message, pos)
pos, users[i].uploadnum = cls.unpack_uint32(message, pos)
pos, users[i].unknown = cls.unpack_uint32(message, pos)
pos, users[i].files = cls.unpack_uint32(message, pos)
pos, users[i].dirs = cls.unpack_uint32(message, pos)
pos, slotslen = cls.unpack_uint32(message, pos)
for i in range(slotslen):
pos, users[i].slotsfull = cls.unpack_uint32(message, pos)
pos, countrylen = cls.unpack_uint32(message, pos)
for i in range(countrylen):
pos, users[i].country = cls.unpack_string(message, pos)
return pos, users
# Server Messages #
class ServerMessage(SlskMessage):
__slots__ = ()
msg_type = MessageType.SERVER
class Login(ServerMessage):
"""Server code 1.
We send this to the server right after the connection has been
established. Server responds with the greeting message.
"""
__slots__ = ("username", "passwd", "version", "minorversion", "success", "reason",
"banner", "ip_address", "local_address", "server_address", "is_supporter")
__excluded_attrs__ = {"passwd"}
def __init__(self, username=None, passwd=None, version=None, minorversion=None):
self.username = username
self.passwd = passwd
self.version = version
self.minorversion = minorversion
self.success = None
self.reason = None
self.banner = None
self.ip_address = None
self.local_address = None
self.server_address = None
self.is_supporter = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.username)
msg += self.pack_string(self.passwd)
msg += self.pack_uint32(self.version)
payload = self.username + self.passwd
md5hash = md5(payload.encode()).hexdigest()
msg += self.pack_string(md5hash)
msg += self.pack_uint32(self.minorversion)
return msg
def parse_network_message(self, message):
pos, self.success = self.unpack_bool(message)
if not self.success:
pos, self.reason = self.unpack_string(message, pos)
return
pos, self.banner = self.unpack_string(message, pos)
pos, self.ip_address = self.unpack_ip(message, pos)
pos, _checksum = self.unpack_string(message, pos) # MD5 hexdigest of the password you sent
pos, self.is_supporter = self.unpack_bool(message, pos)
class SetWaitPort(ServerMessage):
"""Server code 2.
We send this to the server to indicate the port number that we
listen on (2234 by default).
"""
__slots__ = ("port",)
def __init__(self, port=None):
self.port = port
def make_network_message(self):
return self.pack_uint32(self.port)
class GetPeerAddress(ServerMessage):
"""Server code 3.
We send this to the server to ask for a peer's address (IP address
and port), given the peer's username.
"""
__slots__ = ("user", "ip_address", "port", "unknown", "obfuscated_port")
def __init__(self, user=None):
self.user = user
self.ip_address = None
self.port = None
self.unknown = None
self.obfuscated_port = None
def make_network_message(self):
return self.pack_string(self.user)
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.ip_address = self.unpack_ip(message, pos)
pos, self.port = self.unpack_uint32(message, pos)
pos, self.unknown = self.unpack_uint32(message, pos)
pos, self.obfuscated_port = self.unpack_uint16(message, pos)
class WatchUser(ServerMessage):
"""Server code 5.
Used to be kept updated about a user's status. Whenever a user's status
changes, the server sends a GetUserStatus message.
Note that the server does not currently send stat updates (GetUserStats)
when watching a user, only the initial stats in the WatchUser response.
As a consequence, stats can be outdated.
"""
__slots__ = ("user", "userexists", "status", "avgspeed", "uploadnum", "unknown", "files", "dirs",
"country", "contains_stats")
def __init__(self, user=None):
self.user = user
self.userexists = None
self.status = None
self.avgspeed = None
self.uploadnum = None
self.unknown = None
self.files = None
self.dirs = None
self.country = None
self.contains_stats = False
def make_network_message(self):
return self.pack_string(self.user)
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.userexists = self.unpack_bool(message, pos)
if not message[pos:]:
# User does not exist
return
self.contains_stats = True
pos, self.status = self.unpack_uint32(message, pos)
pos, self.avgspeed = self.unpack_uint32(message, pos)
pos, self.uploadnum = self.unpack_uint32(message, pos)
pos, self.unknown = self.unpack_uint32(message, pos)
pos, self.files = self.unpack_uint32(message, pos)
pos, self.dirs = self.unpack_uint32(message, pos)
if not message[pos:]:
# User is offline
return
pos, self.country = self.unpack_string(message, pos)
class UnwatchUser(ServerMessage):
"""Server code 6.
Used when we no longer want to be kept updated about a user's status.
"""
__slots__ = ("user",)
def __init__(self, user=None):
self.user = user
def make_network_message(self):
return self.pack_string(self.user)
class GetUserStatus(ServerMessage):
"""Server code 7.
The server tells us if a user has gone away or has returned.
"""
__slots__ = ("user", "status", "privileged")
def __init__(self, user=None, status=None):
self.user = user
self.status = status
self.privileged = None
def make_network_message(self):
return self.pack_string(self.user)
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.status = self.unpack_uint32(message, pos)
pos, self.privileged = self.unpack_bool(message, pos)
class IgnoreUser(ServerMessage):
"""Server code 11.
We send this to the server to tell a user we have ignored them.
The server tells us a user has ignored us.
OBSOLETE, no longer used
"""
__slots__ = ("user",)
def __init__(self, user=None):
self.user = user
def make_network_message(self):
return self.pack_string(self.user)
def parse_network_message(self, message):
_pos, self.user = self.unpack_string(message)
class UnignoreUser(ServerMessage):
"""Server code 12.
We send this to the server to tell a user we are no longer ignoring them.
The server tells us a user is no longer ignoring us.
OBSOLETE, no longer used
"""
__slots__ = ("user",)
def __init__(self, user=None):
self.user = user
def make_network_message(self):
return self.pack_string(self.user)
def parse_network_message(self, message):
_pos, self.user = self.unpack_string(message)
class SayChatroom(ServerMessage):
"""Server code 13.
Either we want to say something in the chatroom, or someone else
did.
"""
__slots__ = ("room", "message", "user", "formatted_message", "message_type")
def __init__(self, room=None, message=None, user=None):
self.room = room
self.message = message
self.user = user
self.formatted_message = None
self.message_type = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.room)
msg += self.pack_string(self.message)
return msg
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.user = self.unpack_string(message, pos)
pos, self.message = self.unpack_string(message, pos)
class JoinRoom(ServerMessage):
"""Server code 14.
We send this message to the server when we want to join a room. If
the room doesn't exist, it is created.
Server responds with this message when we join a room. Contains
users list with data on everyone.
As long as we're in the room, the server will automatically send us
status/stat updates for room users, including ourselves, in the form
of GetUserStatus and GetUserStats messages.
Room names must meet certain requirements, otherwise the server will
send a MessageUser message containing an error message. Requirements
include:
- Non-empty string
- Only ASCII characters
- 24 characters or fewer
- No leading or trailing spaces
- No consecutive spaces
"""
__slots__ = ("room", "private", "owner", "users", "operators")
def __init__(self, room=None, private=False):
self.room = room
self.private = private
self.owner = None
self.users = []
self.operators = []
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.room)
msg += self.pack_uint32(1 if self.private else 0)
return msg
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.users = UsersMessage.parse_users(message, pos)
if message[pos:]:
self.private = True
pos, self.owner = self.unpack_string(message, pos)
if message[pos:] and self.private:
pos, numops = self.unpack_uint32(message, pos)
for _ in range(numops):
pos, operator = self.unpack_string(message, pos)
self.operators.append(operator)
class LeaveRoom(ServerMessage):
"""Server code 15.
We send this to the server when we want to leave a room.
"""
__slots__ = ("room",)
def __init__(self, room=None):
self.room = room
def make_network_message(self):
return self.pack_string(self.room)
def parse_network_message(self, message):
_pos, self.room = self.unpack_string(message)
class UserJoinedRoom(ServerMessage):
"""Server code 16.
The server tells us someone has just joined a room we're in.
"""
__slots__ = ("room", "userdata")
def __init__(self):
self.room = None
self.userdata = None
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
self.userdata = UserData()
pos, self.userdata.username = self.unpack_string(message, pos)
pos, self.userdata.status = self.unpack_uint32(message, pos)
pos, self.userdata.avgspeed = self.unpack_uint32(message, pos)
pos, self.userdata.uploadnum = self.unpack_uint32(message, pos)
pos, self.userdata.unknown = self.unpack_uint32(message, pos)
pos, self.userdata.files = self.unpack_uint32(message, pos)
pos, self.userdata.dirs = self.unpack_uint32(message, pos)
pos, self.userdata.slotsfull = self.unpack_uint32(message, pos)
pos, self.userdata.country = self.unpack_string(message, pos)
class UserLeftRoom(ServerMessage):
"""Server code 17.
The server tells us someone has just left a room we're in.
"""
__slots__ = ("room", "username")
def __init__(self):
self.room = None
self.username = None
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.username = self.unpack_string(message, pos)
class ConnectToPeer(ServerMessage):
"""Server code 18.
We send this to the server to attempt an indirect connection with a user.
The server forwards the message to the user, who in turn attempts to establish
a connection to our IP address and port from their end.
"""
__slots__ = ("token", "user", "conn_type", "ip_address", "port", "privileged", "unknown", "obfuscated_port")
def __init__(self, token=None, user=None, conn_type=None):
self.token = token
self.user = user
self.conn_type = conn_type
self.ip_address = None
self.port = None
self.privileged = None
self.unknown = None
self.obfuscated_port = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.user)
msg += self.pack_string(self.conn_type)
return msg
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.conn_type = self.unpack_string(message, pos)
pos, self.ip_address = self.unpack_ip(message, pos)
pos, self.port = self.unpack_uint32(message, pos)
pos, self.token = self.unpack_uint32(message, pos)
pos, self.privileged = self.unpack_bool(message, pos)
pos, self.unknown = self.unpack_uint32(message, pos)
pos, self.obfuscated_port = self.unpack_uint32(message, pos)
class MessageUser(ServerMessage):
"""Server code 22.
Chat phrase sent to someone or received by us in private.
"""
__slots__ = ("user", "message", "message_id", "timestamp", "is_new_message", "formatted_message",
"message_type")
def __init__(self, user=None, message=None):
self.user = user
self.message = message
self.message_id = None
self.timestamp = None
self.is_new_message = True
self.formatted_message = None
self.message_type = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.user)
msg += self.pack_string(self.message)
return msg
def parse_network_message(self, message):
pos, self.message_id = self.unpack_uint32(message)
pos, self.timestamp = self.unpack_uint32(message, pos)
pos, self.user = self.unpack_string(message, pos)
pos, self.message = self.unpack_string(message, pos)
pos, self.is_new_message = self.unpack_bool(message, pos)
class MessageAcked(ServerMessage):
"""Server code 23.
We send this to the server to confirm that we received a private
message. If we don't send it, the server will keep sending the chat
phrase to us.
"""
__slots__ = ("msgid",)
def __init__(self, msgid=None):
self.msgid = msgid
def make_network_message(self):
return self.pack_uint32(self.msgid)
class FileSearchRoom(ServerMessage):
"""Server code 25.
We send this to the server when we search for something in a room.
OBSOLETE, use RoomSearch server message
"""
__slots__ = ("token", "roomid", "searchterm")
def __init__(self, token=None, roomid=None, text=None):
self.token = token
self.roomid = roomid
self.searchterm = text
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_uint32(self.roomid)
msg += self.pack_string(self.searchterm)
return msg
class FileSearch(ServerMessage):
"""Server code 26.
We send this to the server when we search for something.
Alternatively, the server sends this message outside the distributed
network to tell us that someone is searching for something,
currently used for UserSearch and RoomSearch requests.
The token is a number generated by the client and is used to track
the search results.
"""
__slots__ = ("token", "searchterm", "search_username")
def __init__(self, token=None, text=None):
self.token = token
self.searchterm = text
self.search_username = None
if text:
self.searchterm = " ".join(x for x in text.split() if x != "-")
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.searchterm, is_legacy=True)
return msg
def parse_network_message(self, message):
pos, self.search_username = self.unpack_string(message)
pos, self.token = self.unpack_uint32(message, pos)
pos, self.searchterm = self.unpack_string(message, pos)
class SetStatus(ServerMessage):
"""Server code 28.
We send our new status to the server. Status is a way to define
whether we're available (online) or busy (away).
When changing our own status, the server sends us a GetUserStatus
message when enabling away status, but not when disabling it.
1 = Away 2 = Online
"""
__slots__ = ("status",)
def __init__(self, status=None):
self.status = status
def make_network_message(self):
return self.pack_int32(self.status)
class ServerPing(ServerMessage):
"""Server code 32.
We send this to the server at most once per minute to ensure the
connection stays alive.
The server used to send a response message in the past, but this is no
longer the case.
Nicotine+ uses TCP keepalive instead of sending this message.
"""
__slots__ = ()
def make_network_message(self):
return b""
def parse_network_message(self, message):
"""Obsolete."""
class SendConnectToken(ServerMessage):
"""Server code 33.
OBSOLETE, no longer used
"""
__slots__ = ("user", "token")
def __init__(self, user, token):
self.user = user
self.token = token
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.user)
msg += self.pack_uint32(self.token)
return msg
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.token = self.unpack_uint32(message, pos)
class SendDownloadSpeed(ServerMessage):
"""Server code 34.
We used to send this after a finished download to let the server
update the speed statistics for a user.
OBSOLETE, use SendUploadSpeed server message
"""
__slots__ = ("user", "speed")
def __init__(self, user=None, speed=None):
self.user = user
self.speed = speed
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.user)
msg += self.pack_uint32(self.speed)
return msg
class SharedFoldersFiles(ServerMessage):
"""Server code 35.
We send this to server to indicate the number of folder and files
that we share.
"""
__slots__ = ("folders", "files")
def __init__(self, folders=None, files=None):
self.folders = folders
self.files = files
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.folders)
msg += self.pack_uint32(self.files)
return msg
class GetUserStats(ServerMessage):
"""Server code 36.
The server sends this to indicate a change in a user's statistics,
if we've requested to watch the user in WatchUser previously. A
user's stats can also be requested by sending a GetUserStats message
to the server, but WatchUser should be used instead.
"""
__slots__ = ("user", "avgspeed", "uploadnum", "unknown", "files", "dirs")
def __init__(self, user=None, avgspeed=None, files=None, dirs=None):
self.user = user
self.avgspeed = avgspeed
self.files = files
self.dirs = dirs
self.uploadnum = None
self.unknown = None
def make_network_message(self):
return self.pack_string(self.user)
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.avgspeed = self.unpack_uint32(message, pos)
pos, self.uploadnum = self.unpack_uint32(message, pos)
pos, self.unknown = self.unpack_uint32(message, pos)
pos, self.files = self.unpack_uint32(message, pos)
pos, self.dirs = self.unpack_uint32(message, pos)
class QueuedDownloads(ServerMessage):
"""Server code 40.
The server sends this to indicate if someone has download slots
available or not.
OBSOLETE, no longer sent by the server
"""
__slots__ = ("user", "slotsfull")
def __init__(self):
self.user = None
self.slotsfull = None
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.slotsfull = self.unpack_uint32(message, pos)
class Relogged(ServerMessage):
"""Server code 41.
The server sends this if someone else logged in under our nickname,
and then disconnects us.
"""
__slots__ = ()
def parse_network_message(self, message):
# Empty message
pass
class UserSearch(ServerMessage):
"""Server code 42.
We send this to the server when we search a specific user's shares.
The token is a number generated by the client and is used to track
the search results.
In the past, the server sent us this message for UserSearch requests from
other users. Today, the server sends a FileSearch message instead.
"""
__slots__ = ("search_username", "token", "searchterm")
def __init__(self, search_username=None, token=None, text=None):
self.search_username = search_username
self.token = token
self.searchterm = text
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.search_username)
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.searchterm, is_legacy=True)
return msg
def parse_network_message(self, message):
"""Obsolete."""
pos, self.search_username = self.unpack_string(message)
pos, self.token = self.unpack_uint32(message, pos)
pos, self.searchterm = self.unpack_string(message, pos)
class SimilarRecommendations(ServerMessage):
"""Server code 50.
We send this to the server when we are adding a recommendation to our
"My recommendations" list, and want to receive a list of similar
recommendations.
The server sends a list of similar recommendations to the one we want to
add. Older versions of the official Soulseek client would display a dialog
containing such recommendations, asking us if we want to add our original
recommendation or one of the similar ones instead.
OBSOLETE
"""
__slots__ = ("recommendation", "similar_recommendations")
def __init__(self, recommendation=None):
self.recommendation = recommendation
self.similar_recommendations = []
def make_network_message(self):
return self.pack_string(self.recommendation)
def parse_network_message(self, message):
pos, self.recommendation = self.unpack_string(message)
pos, num = self.unpack_uint32(message)
for _ in range(num):
pos, similar_recommendation = self.unpack_string(message, pos)
self.similar_recommendations.append(similar_recommendation)
class AddThingILike(ServerMessage):
"""Server code 51.
We send this to the server when we add an item to our likes list.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("thing",)
def __init__(self, thing=None):
self.thing = thing
def make_network_message(self):
return self.pack_string(self.thing)
class RemoveThingILike(ServerMessage):
"""Server code 52.
We send this to the server when we remove an item from our likes
list.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("thing",)
def __init__(self, thing=None):
self.thing = thing
def make_network_message(self):
return self.pack_string(self.thing)
class Recommendations(ServerMessage):
"""Server code 54.
The server sends us a list of personal recommendations and a number
for each.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("recommendations", "unrecommendations")
def __init__(self):
self.recommendations = []
self.unrecommendations = []
def make_network_message(self):
return b""
def parse_network_message(self, message):
_pos, self.recommendations, self.unrecommendations = RecommendationsMessage.parse_recommendations(message)
class MyRecommendations(ServerMessage):
"""Server code 55.
We send this to the server to ask for our own list of added
likes/recommendations (called "My recommendations" in older versions
of the official Soulseek client).
The server sends us the list of recommendations it knows we have added.
For any recommendations present locally, but not on the server, the
official Soulseek client would send a AddThingILike message for each
missing item.
OBSOLETE
"""
__slots__ = ("my_recommendations",)
def __init__(self):
self.my_recommendations = []
def make_network_message(self):
return b""
def parse_network_message(self, message):
pos, num = self.unpack_uint32(message)
for _ in range(num):
pos, recommendation = self.unpack_string(message, pos)
self.my_recommendations.append(recommendation)
class GlobalRecommendations(ServerMessage):
"""Server code 56.
The server sends us a list of global recommendations and a number
for each.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("recommendations", "unrecommendations")
def __init__(self):
self.recommendations = []
self.unrecommendations = []
def make_network_message(self):
return b""
def parse_network_message(self, message):
_pos, self.recommendations, self.unrecommendations = RecommendationsMessage.parse_recommendations(message)
class UserInterests(ServerMessage):
"""Server code 57.
We ask the server for a user's liked and hated interests. The server
responds with a list of interests.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("user", "likes", "hates")
def __init__(self, user=None):
self.user = user
self.likes = []
self.hates = []
def make_network_message(self):
return self.pack_string(self.user)
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, likesnum = self.unpack_uint32(message, pos)
for _ in range(likesnum):
pos, key = self.unpack_string(message, pos)
self.likes.append(key)
pos, hatesnum = self.unpack_uint32(message, pos)
for _ in range(hatesnum):
pos, key = self.unpack_string(message, pos)
self.hates.append(key)
class AdminCommand(ServerMessage):
"""Server code 58.
We send this to the server to run an admin command (e.g. to ban or
silence a user) if we have admin status on the server.
OBSOLETE, no longer used since Soulseek stopped supporting third-
party servers in 2002
"""
__slots__ = ("command", "command_args")
def __init__(self, command=None, command_args=None):
self.command = command
self.command_args = command_args
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.command)
msg += self.pack_uint32(len(self.command_args))
for arg in self.command_args:
msg += self.pack_string(arg)
return msg
class PlaceInLineResponse(ServerMessage):
"""Server code 60.
The server sends this to indicate change in place in queue while
we're waiting for files from another peer.
OBSOLETE, use PlaceInQueueResponse peer message
"""
__slots__ = ("token", "user", "place")
def __init__(self, user=None, token=None, place=None):
self.token = token
self.user = user
self.place = place
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.user)
msg += self.pack_uint32(self.token)
msg += self.pack_uint32(self.place)
return msg
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.token = self.unpack_uint32(message, pos)
pos, self.place = self.unpack_uint32(message, pos)
class RoomAdded(ServerMessage):
"""Server code 62.
The server tells us a new room has been added.
OBSOLETE, no longer sent by the server
"""
__slots__ = ("room",)
def __init__(self):
self.room = None
def parse_network_message(self, message):
_pos, self.room = self.unpack_string(message)
class RoomRemoved(ServerMessage):
"""Server code 63.
The server tells us a room has been removed.
OBSOLETE, no longer sent by the server
"""
__slots__ = ("room",)
def __init__(self):
self.room = None
def parse_network_message(self, message):
_pos, self.room = self.unpack_string(message)
class RoomList(ServerMessage):
"""Server code 64.
The server tells us a list of rooms and the number of users in them.
When connecting to the server, the server only sends us rooms with
at least 5 users. A few select rooms are also excluded, such as
nicotine and The Lobby. Requesting the room list yields a response
containing the missing rooms.
"""
__slots__ = ("rooms", "ownedprivaterooms", "otherprivaterooms", "operatedprivaterooms")
def __init__(self):
self.rooms = []
self.ownedprivaterooms = []
self.otherprivaterooms = []
self.operatedprivaterooms = []
def make_network_message(self):
return b""
def parse_network_message(self, message):
pos, self.rooms = self.parse_rooms(message)
pos, self.ownedprivaterooms = self.parse_rooms(message, pos)
pos, self.otherprivaterooms = self.parse_rooms(message, pos)
pos, self.operatedprivaterooms = self.parse_rooms(message, pos, has_count=False)
def parse_rooms(self, message, pos=0, has_count=True):
pos, numrooms = self.unpack_uint32(message, pos)
rooms = []
for i in range(numrooms):
pos, room = self.unpack_string(message, pos)
if has_count:
rooms.append([room, None])
else:
rooms.append(room)
if not has_count:
return pos, rooms
pos, numusers = self.unpack_uint32(message, pos)
for i in range(numusers):
pos, usercount = self.unpack_uint32(message, pos)
rooms[i][1] = usercount
return pos, rooms
class ExactFileSearch(ServerMessage):
"""Server code 65.
We send this to search for an exact file name and folder, to find
other sources.
OBSOLETE, no results even with official client
"""
__slots__ = ("token", "file", "folder", "size", "checksum", "user", "unknown")
def __init__(self, token=None, file=None, folder=None, size=None, checksum=None, unknown=None):
self.token = token
self.file = file
self.folder = folder
self.size = size
self.checksum = checksum
self.unknown = unknown
self.user = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.file)
msg += self.pack_string(self.folder)
msg += self.pack_uint64(self.size)
msg += self.pack_uint32(self.checksum)
msg += self.pack_uint8(self.unknown)
return msg
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.token = self.unpack_uint32(message, pos)
pos, self.file = self.unpack_string(message, pos)
pos, self.folder = self.unpack_string(message, pos)
pos, self.size = self.unpack_uint64(message, pos)
pos, self.checksum = self.unpack_uint32(message, pos)
class AdminMessage(ServerMessage):
"""Server code 66.
A global message from the server admin has arrived.
"""
__slots__ = ("msg",)
def __init__(self):
self.msg = None
def parse_network_message(self, message):
_pos, self.msg = self.unpack_string(message)
class GlobalUserList(ServerMessage):
"""Server code 67.
We send this to get a global list of all users online.
OBSOLETE, no longer used
"""
__slots__ = ("users",)
def __init__(self):
self.users = None
def make_network_message(self):
return b""
def parse_network_message(self, message):
_pos, self.users = UsersMessage.parse_users(message)
class TunneledMessage(ServerMessage):
"""Server code 68.
Server message for tunneling a chat message.
OBSOLETE, no longer used
"""
__slots__ = ("user", "token", "code", "msg", "addr")
def __init__(self, user=None, token=None, code=None, msg=None):
self.user = user
self.token = token
self.code = code
self.msg = msg
self.addr = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.user)
msg += self.pack_uint32(self.token)
msg += self.pack_uint32(self.code)
msg += self.pack_string(self.msg)
return msg
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.code = self.unpack_uint32(message, pos)
pos, self.token = self.unpack_uint32(message, pos)
pos, ip_address = self.unpack_ip(message, pos)
pos, port = self.unpack_uint32(message, pos)
self.addr = (ip_address, port)
pos, self.msg = self.unpack_string(message, pos)
class PrivilegedUsers(ServerMessage):
"""Server code 69.
The server sends us a list of privileged users, a.k.a. users who
have donated.
"""
__slots__ = ("users",)
def __init__(self):
self.users = []
def parse_network_message(self, message):
pos, numusers = self.unpack_uint32(message)
for _ in range(numusers):
pos, user = self.unpack_string(message, pos)
self.users.append(user)
class HaveNoParent(ServerMessage):
"""Server code 71.
We inform the server if we have a distributed parent or not. If not,
the server eventually sends us a PossibleParents message with a list
of 10 possible parents to connect to.
"""
__slots__ = ("noparent",)
def __init__(self, noparent=None):
self.noparent = noparent
def make_network_message(self):
return self.pack_bool(self.noparent)
class SearchParent(ServerMessage):
"""Server code 73.
We send the IP address of our parent to the server.
DEPRECATED, sent by Soulseek NS but not SoulseekQt
"""
__slots__ = ("parentip",)
def __init__(self, parentip=None):
self.parentip = parentip
@staticmethod
def strunreverse(string):
strlist = string.split(".")
strlist.reverse()
return ".".join(strlist)
def make_network_message(self):
return self.pack_uint32(inet_aton(self.strunreverse(self.parentip)))
class ParentMinSpeed(ServerMessage):
"""Server code 83.
The server informs us about the minimum upload speed required to
become a parent in the distributed network.
"""
__slots__ = ("speed",)
def __init__(self):
self.speed = None
def parse_network_message(self, message):
_pos, self.speed = self.unpack_uint32(message)
class ParentSpeedRatio(ServerMessage):
"""Server code 84.
The server sends us a speed ratio determining the number of children
we can have in the distributed network. The maximum number of
children is our upload speed divided by the speed ratio.
"""
__slots__ = ("ratio",)
def __init__(self):
self.ratio = None
def parse_network_message(self, message):
_pos, self.ratio = self.unpack_uint32(message)
class ParentInactivityTimeout(ServerMessage):
"""Server code 86.
OBSOLETE, no longer sent by the server
"""
__slots__ = ("seconds",)
def __init__(self):
self.seconds = None
def parse_network_message(self, message):
_pos, self.seconds = self.unpack_uint32(message)
class SearchInactivityTimeout(ServerMessage):
"""Server code 87.
OBSOLETE, no longer sent by the server
"""
__slots__ = ("seconds",)
def __init__(self):
self.seconds = None
def parse_network_message(self, message):
_pos, self.seconds = self.unpack_uint32(message)
class MinParentsInCache(ServerMessage):
"""Server code 88.
OBSOLETE, no longer sent by the server
"""
__slots__ = ("num",)
def __init__(self):
self.num = None
def parse_network_message(self, message):
_pos, self.num = self.unpack_uint32(message)
class DistribPingInterval(ServerMessage):
"""Server code 90.
OBSOLETE, no longer sent by the server
"""
__slots__ = ("seconds",)
def __init__(self):
self.seconds = None
def parse_network_message(self, message):
_pos, self.seconds = self.unpack_uint32(message)
class AddToPrivileged(ServerMessage):
"""Server code 91.
The server sends us the username of a new privileged user, which we
add to our list of global privileged users.
OBSOLETE, no longer sent by the server
"""
__slots__ = ("user",)
def __init__(self):
self.user = None
def parse_network_message(self, message):
_pos, self.user = self.unpack_string(message)
class CheckPrivileges(ServerMessage):
"""Server code 92.
We ask the server how much time we have left of our privileges. The
server responds with the remaining time, in seconds.
"""
__slots__ = ("seconds",)
def __init__(self):
self.seconds = None
def make_network_message(self):
return b""
def parse_network_message(self, message):
_pos, self.seconds = self.unpack_uint32(message)
class EmbeddedMessage(ServerMessage):
"""Server code 93.
The server sends us an embedded distributed message. The only type
of distributed message sent at present is DistribSearch (distributed
code 3). If we receive such a message, we are a branch root in the
distributed network, and we distribute the embedded message (not the
unpacked distributed message) to our child peers.
"""
__slots__ = ("distrib_code", "distrib_message")
def __init__(self):
self.distrib_code = None
self.distrib_message = None
def parse_network_message(self, message):
pos, self.distrib_code = self.unpack_uint8(message)
self.distrib_message = message[pos:].tobytes()
class AcceptChildren(ServerMessage):
"""Server code 100.
We tell the server if we want to accept child nodes.
"""
__slots__ = ("enabled",)
def __init__(self, enabled=None):
self.enabled = enabled
def make_network_message(self):
return self.pack_bool(self.enabled)
class PossibleParents(ServerMessage):
"""Server code 102.
The server send us a list of 10 possible distributed parents to
connect to. This message is sent to us at regular intervals until we
tell the server we don't need more possible parents, through a
HaveNoParent message.
"""
__slots__ = ("list",)
def __init__(self):
self.list = {}
def parse_network_message(self, message):
pos, num = self.unpack_uint32(message)
for _ in range(num):
pos, username = self.unpack_string(message, pos)
pos, ip_address = self.unpack_ip(message, pos)
pos, port = self.unpack_uint32(message, pos)
self.list[username] = (ip_address, port)
class WishlistSearch(FileSearch):
"""Server code 103.
We send the server one of our wishlist search queries at each
interval.
"""
__slots__ = ()
class WishlistInterval(ServerMessage):
"""Server code 104.
The server tells us the wishlist search interval.
"""
__slots__ = ("seconds",)
def __init__(self):
self.seconds = None
def parse_network_message(self, message):
_pos, self.seconds = self.unpack_uint32(message)
class SimilarUsers(ServerMessage):
"""Server code 110.
The server sends us a list of similar users related to our
interests.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("users",)
def __init__(self):
self.users = {}
def make_network_message(self):
return b""
def parse_network_message(self, message):
pos, num = self.unpack_uint32(message)
for _ in range(num):
pos, user = self.unpack_string(message, pos)
pos, rating = self.unpack_uint32(message, pos)
self.users[user] = rating
class ItemRecommendations(ServerMessage):
"""Server code 111.
The server sends us a list of recommendations related to a specific
item, which is usually present in the like/dislike list or an
existing recommendation list.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("thing", "recommendations", "unrecommendations")
def __init__(self, thing=None):
self.thing = thing
self.recommendations = []
self.unrecommendations = []
def make_network_message(self):
return self.pack_string(self.thing)
def parse_network_message(self, message):
pos, self.thing = self.unpack_string(message)
pos, self.recommendations, self.unrecommendations = RecommendationsMessage.parse_recommendations(message, pos)
class ItemSimilarUsers(ServerMessage):
"""Server code 112.
The server sends us a list of similar users related to a specific
item, which is usually present in the like/dislike list or
recommendation list.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("thing", "users")
def __init__(self, thing=None):
self.thing = thing
self.users = []
def make_network_message(self):
return self.pack_string(self.thing)
def parse_network_message(self, message):
pos, self.thing = self.unpack_string(message)
pos, num = self.unpack_uint32(message, pos)
for _ in range(num):
pos, user = self.unpack_string(message, pos)
self.users.append(user)
class RoomTickerState(ServerMessage):
"""Server code 113.
The server returns a list of tickers in a chat room.
Tickers are customizable, user-specific messages that appear on chat
room walls.
"""
__slots__ = ("room", "user", "msgs")
def __init__(self):
self.room = None
self.user = None
self.msgs = []
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, num = self.unpack_uint32(message, pos)
for _ in range(num):
pos, user = self.unpack_string(message, pos)
pos, msg = self.unpack_string(message, pos)
self.msgs.append((user, msg))
class RoomTickerAdd(ServerMessage):
"""Server code 114.
The server sends us a new ticker that was added to a chat room.
Tickers are customizable, user-specific messages that appear on chat
room walls.
"""
__slots__ = ("room", "user", "msg")
def __init__(self):
self.room = None
self.user = None
self.msg = None
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.user = self.unpack_string(message, pos)
pos, self.msg = self.unpack_string(message, pos)
class RoomTickerRemove(ServerMessage):
"""Server code 115.
The server informs us that a ticker was removed from a chat room.
Tickers are customizable, user-specific messages that appear on chat
room walls.
"""
__slots__ = ("room", "user")
def __init__(self):
self.room = None
self.user = None
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.user = self.unpack_string(message, pos)
class RoomTickerSet(ServerMessage):
"""Server code 116.
We send this to the server when we change our own ticker in a chat
room. Sending an empty ticker string removes any existing ticker in
the room.
Tickers are customizable, user-specific messages that appear on chat
room walls.
"""
__slots__ = ("room", "msg")
def __init__(self, room=None, msg=""):
self.room = room
self.msg = msg
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.room)
msg += self.pack_string(self.msg)
return msg
class AddThingIHate(ServerMessage):
"""Server code 117.
We send this to the server when we add an item to our hate list.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("thing",)
def __init__(self, thing=None):
self.thing = thing
def make_network_message(self):
return self.pack_string(self.thing)
class RemoveThingIHate(ServerMessage):
"""Server code 118.
We send this to the server when we remove an item from our hate
list.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("thing",)
def __init__(self, thing=None):
self.thing = thing
def make_network_message(self):
return self.pack_string(self.thing)
class RoomSearch(ServerMessage):
"""Server code 120.
We send this to the server to search files shared by users who have
joined a specific chat room. The token is a number generated by the
client and is used to track the search results.
In the past, the server sent us this message for RoomSearch requests from
other users. Today, the server sends a FileSearch message instead.
"""
__slots__ = ("room", "token", "searchterm", "search_username")
def __init__(self, room=None, token=None, text=""):
self.room = room
self.token = token
self.searchterm = " ".join([x for x in text.split() if x != "-"])
self.search_username = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.room)
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.searchterm, is_legacy=True)
return msg
def parse_network_message(self, message):
"""Obsolete."""
pos, self.search_username = self.unpack_string(message)
pos, self.token = self.unpack_uint32(message, pos)
pos, self.searchterm = self.unpack_string(message, pos)
class SendUploadSpeed(ServerMessage):
"""Server code 121.
We send this after a finished upload to let the server update the
speed statistics for ourselves.
"""
__slots__ = ("speed",)
def __init__(self, speed=None):
self.speed = speed
def make_network_message(self):
return self.pack_uint32(self.speed)
class UserPrivileged(ServerMessage):
"""Server code 122.
We ask the server whether a user is privileged or not.
DEPRECATED, use WatchUser and GetUserStatus server messages
"""
__slots__ = ("user", "privileged")
def __init__(self, user=None):
self.user = user
self.privileged = None
def make_network_message(self):
return self.pack_string(self.user)
def parse_network_message(self, message):
pos, self.user = self.unpack_string(message)
pos, self.privileged = self.unpack_bool(message, pos)
class GivePrivileges(ServerMessage):
"""Server code 123.
We give (part of) our privileges, specified in days, to another user
on the network.
"""
__slots__ = ("user", "days")
def __init__(self, user=None, days=None):
self.user = user
self.days = days
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.user)
msg += self.pack_uint32(self.days)
return msg
class NotifyPrivileges(ServerMessage):
"""Server code 124.
DEPRECATED, sent by Soulseek NS but not SoulseekQt
"""
__slots__ = ("token", "user")
def __init__(self, token=None, user=None):
self.token = token
self.user = user
def parse_network_message(self, message):
pos, self.token = self.unpack_uint32(message)
pos, self.user = self.unpack_string(message, pos)
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.user)
return msg
class AckNotifyPrivileges(ServerMessage):
"""Server code 125.
DEPRECATED, no longer used
"""
__slots__ = ("token",)
def __init__(self, token=None):
self.token = token
def parse_network_message(self, message):
_pos, self.token = self.unpack_uint32(message)
def make_network_message(self):
return self.pack_uint32(self.token)
class BranchLevel(ServerMessage):
"""Server code 126.
We tell the server what our position is in our branch (xth
generation) on the distributed network.
"""
__slots__ = ("value",)
def __init__(self, value=None):
self.value = value
def make_network_message(self):
return self.pack_uint32(self.value)
class BranchRoot(ServerMessage):
"""Server code 127.
We tell the server the username of the root of the branch we’re in
on the distributed network.
"""
__slots__ = ("user",)
def __init__(self, user=None):
self.user = user
def make_network_message(self):
return self.pack_string(self.user)
class ChildDepth(ServerMessage):
"""Server code 129.
We tell the server the maximum number of generation of children we
have on the distributed network.
DEPRECATED, sent by Soulseek NS but not SoulseekQt
"""
__slots__ = ("value",)
def __init__(self, value=None):
self.value = value
def make_network_message(self):
return self.pack_uint32(self.value)
class ResetDistributed(ServerMessage):
"""Server code 130.
The server asks us to reset our distributed parent and children.
"""
__slots__ = ()
def parse_network_message(self, message):
# Empty message
pass
class PrivateRoomUsers(ServerMessage):
"""Server code 133.
The server sends us a list of members (excluding the owner) in a private
room we are in.
"""
__slots__ = ("room", "numusers", "users")
def __init__(self):
self.room = None
self.numusers = None
self.users = []
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.numusers = self.unpack_uint32(message, pos)
for _ in range(self.numusers):
pos, user = self.unpack_string(message, pos)
self.users.append(user)
class PrivateRoomAddUser(ServerMessage):
"""Server code 134.
We send this to the server to add a member to a private room, if we are
the owner or an operator.
The server tells us a member has been added to a private room we are in.
"""
__slots__ = ("room", "user")
def __init__(self, room=None, user=None):
self.room = room
self.user = user
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.room)
msg += self.pack_string(self.user)
return msg
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.user = self.unpack_string(message, pos)
class PrivateRoomRemoveUser(ServerMessage):
"""Server code 135.
We send this to the server to remove a member from a private room, if we
are the owner or an operator. Owners can remove operators and regular
members, operators can only remove regular members.
The server tells us a member has been removed from a private room we are in.
"""
__slots__ = ("room", "user")
def __init__(self, room=None, user=None):
self.room = room
self.user = user
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.room)
msg += self.pack_string(self.user)
return msg
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.user = self.unpack_string(message, pos)
class PrivateRoomCancelMembership(ServerMessage):
"""Server code 136.
We send this to the server to cancel our own membership of a private room.
"""
__slots__ = ("room",)
def __init__(self, room=None):
self.room = room
def make_network_message(self):
return self.pack_string(self.room)
class PrivateRoomDisown(ServerMessage):
"""Server code 137.
We send this to the server to stop owning a private room.
"""
__slots__ = ("room",)
def __init__(self, room=None):
self.room = room
def make_network_message(self):
return self.pack_string(self.room)
class PrivateRoomSomething(ServerMessage):
"""Server code 138.
OBSOLETE, no longer used
"""
__slots__ = ("room",)
def __init__(self, room=None):
self.room = room
def make_network_message(self):
return self.pack_string(self.room)
def parse_network_message(self, message):
_pos, self.room = self.unpack_string(message)
class PrivateRoomAdded(ServerMessage):
"""Server code 139.
The server tells us we were added to a private room.
"""
__slots__ = ("room",)
def __init__(self, room=None):
self.room = room
def parse_network_message(self, message):
_pos, self.room = self.unpack_string(message)
class PrivateRoomRemoved(ServerMessage):
"""Server code 140.
The server tells us we were removed from a private room.
"""
__slots__ = ("room",)
def __init__(self, room=None):
self.room = room
def parse_network_message(self, message):
_pos, self.room = self.unpack_string(message)
class PrivateRoomToggle(ServerMessage):
"""Server code 141.
We send this when we want to enable or disable invitations to
private rooms.
"""
__slots__ = ("enabled",)
def __init__(self, enabled=None):
self.enabled = enabled
def make_network_message(self):
return self.pack_bool(self.enabled)
def parse_network_message(self, message):
_pos, self.enabled = self.unpack_bool(message)
class ChangePassword(ServerMessage):
"""Server code 142.
We send this to the server to change our password. We receive a
response if our password changes.
"""
__slots__ = ("password",)
__excluded_attrs__ = {"password"}
def __init__(self, password=None):
self.password = password
def make_network_message(self):
return self.pack_string(self.password)
def parse_network_message(self, message):
_pos, self.password = self.unpack_string(message)
class PrivateRoomAddOperator(ServerMessage):
"""Server code 143.
We send this to the server to add private room operator abilities to
a member.
The server tells us a member received operator abilities in a private
room we are in.
"""
__slots__ = ("room", "user")
def __init__(self, room=None, user=None):
self.room = room
self.user = user
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.room)
msg += self.pack_string(self.user)
return msg
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.user = self.unpack_string(message, pos)
class PrivateRoomRemoveOperator(ServerMessage):
"""Server code 144.
We send this to the server to remove private room operator abilities
from a member.
The server tells us operator abilities were removed for a member in a
private room we are in.
"""
__slots__ = ("room", "user")
def __init__(self, room=None, user=None):
self.room = room
self.user = user
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.room)
msg += self.pack_string(self.user)
return msg
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.user = self.unpack_string(message, pos)
class PrivateRoomOperatorAdded(ServerMessage):
"""Server code 145.
The server tells us we were given operator abilities in a private room
we are in.
"""
__slots__ = ("room",)
def __init__(self, room=None):
self.room = room
def parse_network_message(self, message):
_pos, self.room = self.unpack_string(message)
class PrivateRoomOperatorRemoved(ServerMessage):
"""Server code 146.
The server tells us our operator abilities were removed in a private room
we are in.
"""
__slots__ = ("room",)
def __init__(self, room=None):
self.room = room
def make_network_message(self):
return self.pack_string(self.room)
def parse_network_message(self, message):
_pos, self.room = self.unpack_string(message)
class PrivateRoomOperators(ServerMessage):
"""Server code 148.
The server sends us a list of operators in a private room we are in.
"""
__slots__ = ("room", "number", "operators")
def __init__(self):
self.room = None
self.number = None
self.operators = []
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.number = self.unpack_uint32(message, pos)
for _ in range(self.number):
pos, user = self.unpack_string(message, pos)
self.operators.append(user)
class MessageUsers(ServerMessage):
"""Server code 149.
Sends a broadcast private message to the given list of online users.
"""
__slots__ = ("users", "msg")
def __init__(self, users=None, msg=None):
self.users = users
self.msg = msg
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(len(self.users))
for user in self.users:
msg += self.pack_string(user)
msg += self.pack_string(self.msg)
return msg
class JoinGlobalRoom(ServerMessage):
"""Server code 150.
We ask the server to send us messages from all public rooms, also
known as public room feed.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ()
def make_network_message(self):
return b""
class LeaveGlobalRoom(ServerMessage):
"""Server code 151.
We ask the server to stop sending us messages from all public rooms,
also known as public room feed.
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ()
def make_network_message(self):
return b""
class GlobalRoomMessage(ServerMessage):
"""Server code 152.
The server sends this when a new message has been written in the
public room feed (every single line written in every public room).
DEPRECATED, used in Soulseek NS but not SoulseekQt
"""
__slots__ = ("room", "user", "message", "formatted_message", "message_type")
def __init__(self):
self.room = None
self.user = None
self.message = None
self.formatted_message = None
self.message_type = None
def parse_network_message(self, message):
pos, self.room = self.unpack_string(message)
pos, self.user = self.unpack_string(message, pos)
pos, self.message = self.unpack_string(message, pos)
class RelatedSearch(ServerMessage):
"""Server code 153.
The server returns a list of related search terms for a search
query.
OBSOLETE, server sends empty list as of 2018
"""
__slots__ = ("query", "terms")
def __init__(self, query=None):
self.query = query
self.terms = []
def make_network_message(self):
return self.pack_string(self.query)
def parse_network_message(self, message):
pos, self.query = self.unpack_string(message)
pos, num = self.unpack_uint32(message, pos)
for _ in range(num):
pos, term = self.unpack_string(message, pos)
pos, score = self.unpack_uint32(message, pos)
self.terms.append((term, score))
class ExcludedSearchPhrases(ServerMessage):
"""Server code 160.
The server sends a list of phrases not allowed on the search network.
File paths containing such phrases should be excluded when responding
to search requests.
"""
__slots__ = ("phrases",)
def __init__(self):
self.phrases = []
def parse_network_message(self, message):
pos, num = self.unpack_uint32(message)
for _ in range(num):
pos, phrase = self.unpack_string(message, pos)
self.phrases.append(phrase)
class CantConnectToPeer(ServerMessage):
"""Server code 1001.
We send this when we are not able to respond to an indirect connection
request. We receive this if a peer was not able to respond to our
indirect connection request. The token is taken from the ConnectToPeer
message.
Do not rely on receiving this message from peers. Keep a local timeout
for indirect connections as well.
"""
__slots__ = ("token", "user")
def __init__(self, token=None, user=None):
self.token = token
self.user = user
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.user)
return msg
def parse_network_message(self, message):
_pos, self.token = self.unpack_uint32(message)
class CantCreateRoom(ServerMessage):
"""Server code 1003.
Server tells us a new room cannot be created. This message only
seems to be sent if we try to create a room with the same name as
an existing private room. In other cases, such as using a room name
with leading or trailing spaces, only a private message containing
an error message is sent.
"""
__slots__ = ("room",)
def __init__(self):
self.room = None
def parse_network_message(self, message):
_pos, self.room = self.unpack_string(message)
# Peer Init Messages #
class PeerInitMessage(SlskMessage):
__slots__ = ()
msg_type = MessageType.INIT
class PierceFireWall(PeerInitMessage):
"""Peer init code 0.
This message is sent in response to an indirect connection request
from another user. If the message goes through to the user, the
connection is ready. The token is taken from the ConnectToPeer
server message.
"""
__slots__ = ("sock", "token")
def __init__(self, sock=None, token=None):
self.sock = sock
self.token = token
def make_network_message(self):
return self.pack_uint32(self.token)
def parse_network_message(self, message):
if message:
# A token is not guaranteed to be sent (buggy client?)
_pos, self.token = self.unpack_uint32(message)
class PeerInit(PeerInitMessage):
"""Peer init code 1.
This message is sent to initiate a direct connection to another
peer. The token is apparently always 0 and ignored.
"""
__slots__ = ("sock", "init_user", "target_user", "conn_type", "outgoing_msgs", "token")
def __init__(self, sock=None, init_user=None, target_user=None, conn_type=None):
self.sock = sock
self.init_user = init_user # username of peer who initiated the message
self.target_user = target_user # username of peer we're connected to
self.conn_type = conn_type
self.outgoing_msgs = []
self.token = 0
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.init_user)
msg += self.pack_string(self.conn_type)
msg += self.pack_uint32(self.token)
return msg
def parse_network_message(self, message):
pos, self.init_user = self.unpack_string(message)
pos, self.conn_type = self.unpack_string(message, pos)
if self.target_user is None:
# The user we're connecting to initiated the connection. Set them as target user.
self.target_user = self.init_user
# Peer Messages #
class PeerMessage(SlskMessage):
__slots__ = ("username", "sock", "addr")
msg_type = MessageType.PEER
def __init__(self):
self.username = None
self.sock = None
self.addr = None
class SharedFileListRequest(PeerMessage):
"""Peer code 4.
We send this to a peer to ask for a list of shared files.
"""
__slots__ = ()
def make_network_message(self):
return b""
def parse_network_message(self, message):
# Empty message
pass
class SharedFileListResponse(PeerMessage):
"""Peer code 5.
A peer responds with a list of shared files when we've sent a
SharedFileListRequest.
"""
__slots__ = ("list", "unknown", "privatelist", "built", "permission_level",
"public_shares", "buddy_shares", "trusted_shares")
__excluded_attrs__ = {"list", "privatelist"}
def __init__(self, public_shares=None, buddy_shares=None, trusted_shares=None,
permission_level=None):
PeerMessage.__init__(self)
self.public_shares = public_shares
self.buddy_shares = buddy_shares
self.trusted_shares = trusted_shares
self.permission_level = permission_level
self.list = []
self.privatelist = []
self.unknown = 0
self.built = None
def _make_shares_list(self, share_groups):
try:
msg_list = bytearray()
num_folders = 0
for shares in share_groups:
num_folders += len(shares)
msg_list += self.pack_uint32(num_folders)
for shares in share_groups:
for key in shares:
msg_list += self.pack_string(key)
msg_list += shares[key]
except Exception as error:
from pynicotine.logfacility import log
msg_list = self.pack_uint32(0)
log.add(_("Unable to read shares database. Please rescan your shares. Error: %s"), error)
return msg_list
def make_network_message(self):
# Elaborate hack to save CPU
# Store packed message contents in self.built, and use instead of repacking it
if self.built is not None:
return self.built
from pynicotine.shares import PermissionLevel
msg = bytearray()
share_groups = []
private_share_groups = []
if self.permission_level and self.public_shares:
share_groups.append(self.public_shares)
if self.permission_level in {PermissionLevel.BUDDY, PermissionLevel.TRUSTED} and self.buddy_shares:
share_groups.append(self.buddy_shares)
if self.permission_level == PermissionLevel.TRUSTED and self.trusted_shares:
share_groups.append(self.trusted_shares)
msg += self._make_shares_list(share_groups)
# Unknown purpose, but official clients always send a value of 0
msg += self.pack_uint32(self.unknown)
for shares in (self.buddy_shares, self.trusted_shares):
if shares and shares not in share_groups:
private_share_groups.append(shares)
if private_share_groups:
msg += self._make_shares_list(share_groups=private_share_groups)
self.built = zlib.compress(msg)
return self.built
def parse_network_message(self, message):
self._parse_network_message(memoryview(zlib.decompress(message)))
def _parse_result_list(self, message, pos=0):
pos, ndir = self.unpack_uint32(message, pos)
ext = None
shares = []
for _ in range(ndir):
pos, directory = self.unpack_string(message, pos)
directory = directory.replace("/", "\\")
pos, nfiles = self.unpack_uint32(message, pos)
files = []
for _ in range(nfiles):
pos, code = self.unpack_uint8(message, pos)
pos, name = self.unpack_string(message, pos)
pos, size = FileListMessage.parse_file_size(message, pos)
pos, ext_len = self.unpack_uint32(message, pos) # Obsolete, ignore
pos, attrs = FileListMessage.unpack_file_attributes(message, pos + ext_len)
files.append((code, name, size, ext, attrs))
if nfiles > 1:
files.sort(key=itemgetter(1))
shares.append((directory, files))
if ndir > 1:
shares.sort(key=itemgetter(0))
return pos, shares
def _parse_network_message(self, message):
pos, self.list = self._parse_result_list(message)
if message[pos:]:
pos, self.unknown = self.unpack_uint32(message, pos)
if message[pos:]:
pos, self.privatelist = self._parse_result_list(message, pos)
class FileSearchRequest(PeerMessage):
"""Peer code 8.
We send this to the peer when we search for a file. Alternatively,
the peer sends this to tell us it is searching for a file.
OBSOLETE, use UserSearch server message
"""
__slots__ = ("token", "text", "searchterm")
def __init__(self, token=None, text=None):
PeerMessage.__init__(self)
self.token = token
self.text = text
self.searchterm = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.text)
return msg
def parse_network_message(self, message):
pos, self.token = self.unpack_uint32(message)
pos, self.searchterm = self.unpack_string(message, pos)
class FileSearchResponse(PeerMessage):
"""Peer code 9.
A peer sends this message when it has a file search match. The token
is taken from original FileSearch, UserSearch or RoomSearch server
message.
"""
__slots__ = ("search_username", "token", "list", "privatelist", "freeulslots",
"ulspeed", "inqueue", "unknown")
__excluded_attrs__ = {"list", "privatelist"}
def __init__(self, search_username=None, token=None, shares=None, freeulslots=None,
ulspeed=None, inqueue=None, private_shares=None):
PeerMessage.__init__(self)
self.search_username = search_username
self.token = token
self.list = shares
self.privatelist = private_shares
self.freeulslots = freeulslots
self.ulspeed = ulspeed
self.inqueue = inqueue
self.unknown = 0
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.search_username)
msg += self.pack_uint32(self.token)
msg += self.pack_uint32(len(self.list))
for fileinfo in self.list:
msg += FileListMessage.pack_file_info(fileinfo)
msg += self.pack_bool(self.freeulslots)
msg += self.pack_uint32(self.ulspeed)
msg += self.pack_uint32(self.inqueue)
msg += self.pack_uint32(self.unknown)
if self.privatelist:
msg += self.pack_uint32(len(self.privatelist))
for fileinfo in self.privatelist:
msg += FileListMessage.pack_file_info(fileinfo)
return zlib.compress(msg)
def parse_network_message(self, message):
decompressor = zlib.decompressobj()
_pos, username_len = self.unpack_uint32(decompressor.decompress(message, 4))
_pos, self.token = self.unpack_uint32(
decompressor.decompress(decompressor.unconsumed_tail, username_len + 4), username_len)
if self.token not in SEARCH_TOKENS_ALLOWED:
# Results are no longer accepted for this search token, stop parsing message
self.list = []
return
# Optimization: only decompress the rest of the message when needed
self._parse_remaining_network_message(
memoryview(decompressor.decompress(decompressor.unconsumed_tail))
)
def _parse_remaining_network_message(self, message):
pos, self.list = self._parse_result_list(message)
pos, self.freeulslots = self.unpack_bool(message, pos)
pos, self.ulspeed = self.unpack_uint32(message, pos)
pos, self.inqueue = self.unpack_uint32(message, pos)
if message[pos:]:
pos, self.unknown = self.unpack_uint32(message, pos)
if message[pos:]:
pos, self.privatelist = self._parse_result_list(message, pos)
def _parse_result_list(self, message, pos=0):
pos, nfiles = self.unpack_uint32(message, pos)
ext = None
results = []
for _ in range(nfiles):
pos, code = self.unpack_uint8(message, pos)
pos, name = self.unpack_string(message, pos)
pos, size = FileListMessage.parse_file_size(message, pos)
pos, ext_len = self.unpack_uint32(message, pos) # Obsolete, ignore
pos, attrs = FileListMessage.unpack_file_attributes(message, pos + ext_len)
results.append((code, name.replace("/", "\\"), size, ext, attrs))
if nfiles > 1:
results.sort(key=itemgetter(1))
return pos, results
class UserInfoRequest(PeerMessage):
"""Peer code 15.
We ask the other peer to send us their user information, picture and
all.
"""
__slots__ = ()
def make_network_message(self):
return b""
def parse_network_message(self, message):
# Empty message
pass
class UserInfoResponse(PeerMessage):
"""Peer code 16.
A peer responds with this after we've sent a UserInfoRequest.
"""
__slots__ = ("descr", "pic", "totalupl", "queuesize", "slotsavail", "uploadallowed", "has_pic")
__excluded_attrs__ = {"pic"}
def __init__(self, descr=None, pic=None, totalupl=None, queuesize=None,
slotsavail=None, uploadallowed=None):
PeerMessage.__init__(self)
self.descr = descr
self.pic = pic
self.totalupl = totalupl
self.queuesize = queuesize
self.slotsavail = slotsavail
self.uploadallowed = uploadallowed
self.has_pic = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.descr)
if self.pic is not None:
msg += self.pack_bool(True)
msg += self.pack_bytes(self.pic)
else:
msg += self.pack_bool(False)
msg += self.pack_uint32(self.totalupl)
msg += self.pack_uint32(self.queuesize)
msg += self.pack_bool(self.slotsavail)
msg += self.pack_uint32(self.uploadallowed)
return msg
def parse_network_message(self, message):
pos, self.descr = self.unpack_string(message)
pos, self.has_pic = self.unpack_bool(message, pos)
if self.has_pic:
pos, self.pic = self.unpack_bytes(message, pos)
pos, self.totalupl = self.unpack_uint32(message, pos)
pos, self.queuesize = self.unpack_uint32(message, pos)
pos, self.slotsavail = self.unpack_bool(message, pos)
# To prevent errors, ensure that >= 4 bytes are left. Museek+ incorrectly sends
# slotsavail as an integer, resulting in 3 bytes of garbage here.
if len(message[pos:]) >= 4:
pos, self.uploadallowed = self.unpack_uint32(message, pos)
class PMessageUser(PeerMessage):
"""Peer code 22.
Chat phrase sent to someone or received by us in private. This is a
Nicotine+ extension to the Soulseek protocol.
OBSOLETE
"""
__slots__ = ("message_username", "msg", "msgid", "timestamp")
def __init__(self, message_username=None, msg=None):
PeerMessage.__init__(self)
self.message_username = message_username
self.msg = msg
self.msgid = None
self.timestamp = None
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(0)
msg += self.pack_uint32(0)
msg += self.pack_string(self.message_username)
msg += self.pack_string(self.msg)
return msg
def parse_network_message(self, message):
pos, self.msgid = self.unpack_uint32(message)
pos, self.timestamp = self.unpack_uint32(message, pos)
pos, self.message_username = self.unpack_string(message, pos)
pos, self.msg = self.unpack_string(message, pos)
class FolderContentsRequest(PeerMessage):
"""Peer code 36.
We ask the peer to send us the contents of a single folder.
"""
__slots__ = ("dir", "token", "legacy_client")
def __init__(self, directory=None, token=None, legacy_client=False):
PeerMessage.__init__(self)
self.dir = directory
self.token = token
self.legacy_client = legacy_client
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.dir, is_legacy=self.legacy_client)
return msg
def parse_network_message(self, message):
pos, self.token = self.unpack_uint32(message)
pos, self.dir = self.unpack_string(message, pos)
class FolderContentsResponse(PeerMessage):
"""Peer code 37.
A peer responds with the contents of a particular folder (with all
subfolders) after we've sent a FolderContentsRequest.
"""
__slots__ = ("dir", "token", "list")
def __init__(self, directory=None, token=None, shares=None):
PeerMessage.__init__(self)
self.dir = directory
self.token = token
self.list = shares
def parse_network_message(self, message):
self._parse_network_message(memoryview(zlib.decompress(message)))
def _parse_network_message(self, message):
pos, self.token = self.unpack_uint32(message)
pos, self.dir = self.unpack_string(message, pos)
pos, ndir = self.unpack_uint32(message, pos)
folders = {}
for _ in range(ndir):
pos, directory = self.unpack_string(message, pos)
directory = directory.replace("/", "\\")
pos, nfiles = self.unpack_uint32(message, pos)
ext = None
folders[directory] = []
for _ in range(nfiles):
pos, code = self.unpack_uint8(message, pos)
pos, name = self.unpack_string(message, pos)
pos, size = self.unpack_uint64(message, pos)
pos, ext_len = self.unpack_uint32(message, pos) # Obsolete, ignore
pos, attrs = FileListMessage.unpack_file_attributes(message, pos + ext_len)
folders[directory].append((code, name, size, ext, attrs))
if nfiles > 1:
folders[directory].sort(key=itemgetter(1))
self.list = folders
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.dir)
if self.list is not None:
msg += self.pack_uint32(1)
msg += self.pack_string(self.dir)
# We already saved the folder contents as a bytearray when scanning our shares
msg += self.list
else:
# No folder contents
msg += self.pack_uint32(0)
return zlib.compress(msg)
class TransferRequest(PeerMessage):
"""Peer code 40.
This message is sent by a peer once they are ready to start
uploading a file. A TransferResponse message is expected from the
recipient, either allowing or rejecting the upload attempt.
This message was formerly used to send a download request (direction
0) as well, but Nicotine+ >= 3.0.3, Museek+ and the official clients
use the QueueUpload message for this purpose today.
"""
__slots__ = ("direction", "token", "file", "filesize")
def __init__(self, direction=None, token=None, file=None, filesize=None):
PeerMessage.__init__(self)
self.direction = direction
self.token = token
self.file = file # virtual file
self.filesize = filesize
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.direction)
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.file)
if self.direction == TransferDirection.UPLOAD:
msg += self.pack_uint64(self.filesize)
return msg
def parse_network_message(self, message):
pos, self.direction = self.unpack_uint32(message)
pos, self.token = self.unpack_uint32(message, pos)
pos, self.file = self.unpack_string(message, pos)
if self.direction == TransferDirection.UPLOAD:
pos, self.filesize = self.unpack_uint64(message, pos)
class TransferResponse(PeerMessage):
"""Peer code 41.
Response to TransferRequest - We (or the other peer) either agrees,
or tells the reason for rejecting the file transfer.
"""
__slots__ = ("allowed", "token", "reason", "filesize")
def __init__(self, allowed=None, reason=None, token=None, filesize=None):
PeerMessage.__init__(self)
self.allowed = allowed
self.token = token
self.reason = reason
self.filesize = filesize
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.token)
msg += self.pack_bool(self.allowed)
if self.reason is not None:
msg += self.pack_string(self.reason)
if self.filesize is not None:
msg += self.pack_uint64(self.filesize)
return msg
def parse_network_message(self, message):
pos, self.token = self.unpack_uint32(message)
pos, self.allowed = self.unpack_bool(message, pos)
if message[pos:]:
if self.allowed:
pos, self.filesize = self.unpack_uint64(message, pos)
else:
pos, self.reason = self.unpack_string(message, pos)
class PlaceholdUpload(PeerMessage):
"""Peer code 42.
OBSOLETE, no longer used
"""
__slots__ = ("file",)
def __init__(self, file=None):
PeerMessage.__init__(self)
self.file = file
def make_network_message(self):
return self.pack_string(self.file)
def parse_network_message(self, message):
_pos, self.file = self.unpack_string(message)
class QueueUpload(PeerMessage):
"""Peer code 43.
This message is used to tell a peer that an upload should be queued
on their end. Once the recipient is ready to transfer the requested
file, they will send a TransferRequest to us.
"""
__slots__ = ("file", "legacy_client")
def __init__(self, file=None, legacy_client=False):
PeerMessage.__init__(self)
self.file = file
self.legacy_client = legacy_client
def make_network_message(self):
return self.pack_string(self.file, is_legacy=self.legacy_client)
def parse_network_message(self, message):
_pos, self.file = self.unpack_string(message)
class PlaceInQueueResponse(PeerMessage):
"""Peer code 44.
The peer replies with the upload queue placement of the requested
file.
"""
__slots__ = ("filename", "place")
def __init__(self, filename=None, place=None):
PeerMessage.__init__(self)
self.filename = filename
self.place = place
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.filename)
msg += self.pack_uint32(self.place)
return msg
def parse_network_message(self, message):
pos, self.filename = self.unpack_string(message)
pos, self.place = self.unpack_uint32(message, pos)
class UploadFailed(PeerMessage):
"""Peer code 46.
This message is sent whenever a file connection of an active upload
closes. Soulseek NS clients can also send this message when a file
cannot be read. The recipient either re-queues the upload (download
on their end), or ignores the message if the transfer finished.
"""
__slots__ = ("file",)
def __init__(self, file=None):
PeerMessage.__init__(self)
self.file = file
def make_network_message(self):
return self.pack_string(self.file)
def parse_network_message(self, message):
_pos, self.file = self.unpack_string(message)
class UploadDenied(PeerMessage):
"""Peer code 50.
This message is sent to reject QueueUpload attempts and previously
queued files. The reason for rejection will appear in the transfer
list of the recipient.
"""
__slots__ = ("file", "reason")
def __init__(self, file=None, reason=None):
PeerMessage.__init__(self)
self.file = file
self.reason = reason
def make_network_message(self):
msg = bytearray()
msg += self.pack_string(self.file)
msg += self.pack_string(self.reason)
return msg
def parse_network_message(self, message):
pos, self.file = self.unpack_string(message)
pos, self.reason = self.unpack_string(message, pos)
class PlaceInQueueRequest(PeerMessage):
"""Peer code 51.
This message is sent when asking for the upload queue placement of a
file.
"""
__slots__ = ("file", "legacy_client")
def __init__(self, file=None, legacy_client=False):
PeerMessage.__init__(self)
self.file = file
self.legacy_client = legacy_client
def make_network_message(self):
return self.pack_string(self.file, is_legacy=self.legacy_client)
def parse_network_message(self, message):
_pos, self.file = self.unpack_string(message)
class UploadQueueNotification(PeerMessage):
"""Peer code 52.
This message is sent to inform a peer about an upload attempt
initiated by us.
DEPRECATED, sent by Soulseek NS but not SoulseekQt
"""
__slots__ = ()
def make_network_message(self):
return b""
def parse_network_message(self, _message):
return b""
class UnknownPeerMessage(PeerMessage):
"""Peer code 12547.
UNKNOWN
"""
__slots__ = ()
def parse_network_message(self, message):
# Empty message
pass
# File Messages #
class FileMessage(SlskMessage):
__slots__ = ("sock", "username")
msg_type = MessageType.FILE
def __init__(self, sock=None):
self.sock = sock
self.username = None
class FileTransferInit(FileMessage):
"""We send this to a peer via a 'F' connection to tell them that we want to
start uploading a file. The token is the same as the one previously included in the
TransferRequest peer message.
Note that slskd and Nicotine+ <= 3.0.2 use legacy download requests, and send this
message when initializing our file upload connection from their end.
"""
__slots__ = ("token", "is_outgoing")
def __init__(self, token=None, is_outgoing=False):
FileMessage.__init__(self)
self.token = token
self.is_outgoing = is_outgoing
def make_network_message(self):
return self.pack_uint32(self.token)
def parse_network_message(self, message):
_pos, self.token = self.unpack_uint32(message)
class FileOffset(FileMessage):
"""We send this to the uploading peer at the beginning of a 'F' connection,
to tell them how many bytes of the file we've previously downloaded. If nothing
was downloaded, the offset is 0.
Note that Soulseek NS fails to read the size of an incomplete download if more
than 2 GB of the file has been downloaded, and the download is resumed. In
consequence, the client sends an invalid file offset of -1.
"""
__slots__ = ("offset",)
def __init__(self, sock=None, offset=None):
FileMessage.__init__(self, sock=sock)
self.offset = offset
def make_network_message(self):
return self.pack_uint64(self.offset)
def parse_network_message(self, message):
_pos, self.offset = self.unpack_uint64(message)
# Distributed Messages #
class DistribMessage(SlskMessage):
__slots__ = ("sock", "username")
msg_type = MessageType.DISTRIBUTED
def __init__(self):
self.sock = None
self.username = None
class DistribPing(DistribMessage):
"""Distrib code 0.
We ping distributed children every 60 seconds.
DEPRECATED, sent by Soulseek NS but not SoulseekQt
"""
__slots__ = ()
def make_network_message(self):
return b""
def parse_network_message(self, message):
# Empty message
pass
class DistribSearch(DistribMessage):
"""Distrib code 3.
Search request that arrives through the distributed network. We
transmit the search request to our child peers.
"""
__slots__ = ("unknown", "search_username", "token", "searchterm")
def __init__(self, unknown=None, search_username=None, token=None, searchterm=None):
DistribMessage.__init__(self)
self.unknown = unknown
self.search_username = search_username
self.token = token
self.searchterm = searchterm
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint32(self.unknown)
msg += self.pack_string(self.search_username)
msg += self.pack_uint32(self.token)
msg += self.pack_string(self.searchterm)
return msg
def parse_network_message(self, message):
pos, self.unknown = self.unpack_uint32(message)
pos, self.search_username = self.unpack_string(message, pos)
pos, self.token = self.unpack_uint32(message, pos)
pos, self.searchterm = self.unpack_string(message, pos)
class DistribBranchLevel(DistribMessage):
"""Distrib code 4.
We tell our distributed children what our position is in our branch
(xth generation) on the distributed network.
If we receive a branch level of 0 from a parent, we should mark the
parent as our branch root, since they won't send a DistribBranchRoot
message in this case.
"""
__slots__ = ("level",)
def __init__(self, level=None):
DistribMessage.__init__(self)
self.level = level
def make_network_message(self):
return self.pack_int32(self.level)
def parse_network_message(self, message):
_pos, self.level = self.unpack_int32(message)
class DistribBranchRoot(DistribMessage):
"""Distrib code 5.
We tell our distributed children the username of the root of the
branch we’re in on the distributed network.
This message should not be sent when we're the branch root.
"""
__slots__ = ("root_username",)
def __init__(self, root_username=None):
DistribMessage.__init__(self)
self.root_username = root_username
def make_network_message(self):
return self.pack_string(self.root_username)
def parse_network_message(self, message):
_pos, self.root_username = self.unpack_string(message)
class DistribChildDepth(DistribMessage):
"""Distrib code 7.
We tell our distributed parent the maximum number of generation of
children we have on the distributed network.
DEPRECATED, sent by Soulseek NS but not SoulseekQt
"""
__slots__ = ("value",)
def __init__(self, value=None):
DistribMessage.__init__(self)
self.value = value
def make_network_message(self):
return self.pack_uint32(self.value)
def parse_network_message(self, message):
_pos, self.value = self.unpack_uint32(message)
class DistribEmbeddedMessage(DistribMessage):
"""Distrib code 93.
A branch root sends us an embedded distributed message. We unpack
the distributed message and distribute it to our child peers. The
only type of distributed message sent at present is DistribSearch
(distributed code 3).
"""
__slots__ = ("distrib_code", "distrib_message")
def __init__(self, distrib_code=None, distrib_message=None):
DistribMessage.__init__(self)
self.distrib_code = distrib_code
self.distrib_message = distrib_message
def make_network_message(self):
msg = bytearray()
msg += self.pack_uint8(self.distrib_code)
msg += self.distrib_message
return msg
def parse_network_message(self, message):
pos, self.distrib_code = self.unpack_uint8(message, 3)
self.distrib_message = message[pos:].tobytes()
# Message Events #
NETWORK_MESSAGE_EVENTS = {
AdminMessage: "admin-message",
ChangePassword: "change-password",
CheckPrivileges: "check-privileges",
ConnectToPeer: "connect-to-peer",
DistribSearch: "file-search-request-distributed",
ExcludedSearchPhrases: "excluded-search-phrases",
FileSearch: "file-search-request-server",
FileSearchResponse: "file-search-response",
FileTransferInit: "file-transfer-init",
FolderContentsRequest: "folder-contents-request",
FolderContentsResponse: "folder-contents-response",
GetPeerAddress: "peer-address",
GetUserStats: "user-stats",
GetUserStatus: "user-status",
GlobalRecommendations: "global-recommendations",
GlobalRoomMessage: "global-room-message",
ItemRecommendations: "item-recommendations",
ItemSimilarUsers: "item-similar-users",
JoinRoom: "join-room",
LeaveRoom: "leave-room",
Login: "server-login",
MessageUser: "message-user",
PlaceInQueueRequest: "place-in-queue-request",
PlaceInQueueResponse: "place-in-queue-response",
PrivateRoomAddOperator: "private-room-add-operator",
PrivateRoomAddUser: "private-room-add-user",
PrivateRoomAdded: "private-room-added",
PrivateRoomOperatorAdded: "private-room-operator-added",
PrivateRoomOperatorRemoved: "private-room-operator-removed",
PrivateRoomOperators: "private-room-operators",
PrivateRoomRemoveOperator: "private-room-remove-operator",
PrivateRoomRemoveUser: "private-room-remove-user",
PrivateRoomRemoved: "private-room-removed",
PrivateRoomToggle: "private-room-toggle",
PrivateRoomUsers: "private-room-users",
PrivilegedUsers: "privileged-users",
QueueUpload: "queue-upload",
Recommendations: "recommendations",
RoomList: "room-list",
RoomTickerAdd: "ticker-add",
RoomTickerRemove: "ticker-remove",
RoomTickerState: "ticker-state",
SayChatroom: "say-chat-room",
SharedFileListRequest: "shared-file-list-request",
SharedFileListResponse: "shared-file-list-response",
SimilarUsers: "similar-users",
TransferRequest: "transfer-request",
TransferResponse: "transfer-response",
UploadDenied: "upload-denied",
UploadFailed: "upload-failed",
UploadFile: "file-upload-progress",
UserInfoRequest: "user-info-request",
UserInfoResponse: "user-info-response",
UserInterests: "user-interests",
UserJoinedRoom: "user-joined-room",
UserLeftRoom: "user-left-room",
WatchUser: "watch-user",
WishlistInterval: "set-wishlist-interval"
}
# Message Codes #
SERVER_MESSAGE_CODES = {
Login: 1,
SetWaitPort: 2,
GetPeerAddress: 3,
WatchUser: 5,
UnwatchUser: 6,
GetUserStatus: 7,
IgnoreUser: 11,
UnignoreUser: 12,
SayChatroom: 13,
JoinRoom: 14,
LeaveRoom: 15,
UserJoinedRoom: 16,
UserLeftRoom: 17,
ConnectToPeer: 18,
MessageUser: 22,
MessageAcked: 23,
FileSearchRoom: 25, # Obsolete
FileSearch: 26,
SetStatus: 28,
ServerPing: 32,
SendConnectToken: 33, # Obsolete
SendDownloadSpeed: 34, # Obsolete
SharedFoldersFiles: 35,
GetUserStats: 36,
QueuedDownloads: 40, # Obsolete
Relogged: 41,
UserSearch: 42,
SimilarRecommendations: 50, # Obsolete
AddThingILike: 51, # Deprecated
RemoveThingILike: 52, # Deprecated
Recommendations: 54, # Deprecated
MyRecommendations: 55, # Obsolete
GlobalRecommendations: 56, # Deprecated
UserInterests: 57, # Deprecated
AdminCommand: 58, # Obsolete
PlaceInLineResponse: 60, # Obsolete
RoomAdded: 62, # Obsolete
RoomRemoved: 63, # Obsolete
RoomList: 64,
ExactFileSearch: 65, # Obsolete
AdminMessage: 66,
GlobalUserList: 67, # Obsolete
TunneledMessage: 68, # Obsolete
PrivilegedUsers: 69,
HaveNoParent: 71,
SearchParent: 73, # Deprecated
ParentMinSpeed: 83,
ParentSpeedRatio: 84,
ParentInactivityTimeout: 86, # Obsolete
SearchInactivityTimeout: 87, # Obsolete
MinParentsInCache: 88, # Obsolete
DistribPingInterval: 90, # Obsolete
AddToPrivileged: 91, # Obsolete
CheckPrivileges: 92,
EmbeddedMessage: 93,
AcceptChildren: 100,
PossibleParents: 102,
WishlistSearch: 103,
WishlistInterval: 104,
SimilarUsers: 110, # Deprecated
ItemRecommendations: 111, # Deprecated
ItemSimilarUsers: 112, # Deprecated
RoomTickerState: 113,
RoomTickerAdd: 114,
RoomTickerRemove: 115,
RoomTickerSet: 116,
AddThingIHate: 117, # Deprecated
RemoveThingIHate: 118, # Deprecated
RoomSearch: 120,
SendUploadSpeed: 121,
UserPrivileged: 122, # Deprecated
GivePrivileges: 123,
NotifyPrivileges: 124, # Deprecated
AckNotifyPrivileges: 125, # Deprecated
BranchLevel: 126,
BranchRoot: 127,
ChildDepth: 129, # Deprecated
ResetDistributed: 130,
PrivateRoomUsers: 133,
PrivateRoomAddUser: 134,
PrivateRoomRemoveUser: 135,
PrivateRoomCancelMembership: 136,
PrivateRoomDisown: 137,
PrivateRoomSomething: 138, # Obsolete
PrivateRoomAdded: 139,
PrivateRoomRemoved: 140,
PrivateRoomToggle: 141,
ChangePassword: 142,
PrivateRoomAddOperator: 143,
PrivateRoomRemoveOperator: 144,
PrivateRoomOperatorAdded: 145,
PrivateRoomOperatorRemoved: 146,
PrivateRoomOperators: 148,
MessageUsers: 149,
JoinGlobalRoom: 150, # Deprecated
LeaveGlobalRoom: 151, # Deprecated
GlobalRoomMessage: 152, # Deprecated
RelatedSearch: 153, # Obsolete
ExcludedSearchPhrases: 160,
CantConnectToPeer: 1001,
CantCreateRoom: 1003
}
PEER_INIT_MESSAGE_CODES = {
PierceFireWall: 0,
PeerInit: 1
}
PEER_MESSAGE_CODES = {
SharedFileListRequest: 4,
SharedFileListResponse: 5,
FileSearchRequest: 8, # Obsolete
FileSearchResponse: 9,
UserInfoRequest: 15,
UserInfoResponse: 16,
PMessageUser: 22, # Obsolete
FolderContentsRequest: 36,
FolderContentsResponse: 37,
TransferRequest: 40,
TransferResponse: 41,
PlaceholdUpload: 42, # Obsolete
QueueUpload: 43,
PlaceInQueueResponse: 44,
UploadFailed: 46,
UploadDenied: 50,
PlaceInQueueRequest: 51,
UploadQueueNotification: 52, # Deprecated
UnknownPeerMessage: 12547
}
DISTRIBUTED_MESSAGE_CODES = {
DistribPing: 0, # Deprecated
DistribSearch: 3,
DistribBranchLevel: 4,
DistribBranchRoot: 5,
DistribChildDepth: 7, # Deprecated
DistribEmbeddedMessage: 93
}
SERVER_MESSAGE_CLASSES = {v: k for k, v in SERVER_MESSAGE_CODES.items()}
PEER_INIT_MESSAGE_CLASSES = {v: k for k, v in PEER_INIT_MESSAGE_CODES.items()}
PEER_MESSAGE_CLASSES = {v: k for k, v in PEER_MESSAGE_CODES.items()}
DISTRIBUTED_MESSAGE_CLASSES = {v: k for k, v in DISTRIBUTED_MESSAGE_CODES.items()}
| 118,238 | Python | .py | 2,928 | 32.983265 | 118 | 0.648111 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,412 | pluginsystem.py | nicotine-plus_nicotine-plus/pynicotine/pluginsystem.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2016 Mutnick <muhing@yahoo.com>
# COPYRIGHT (C) 2008-2011 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2009 daelstorm <daelstorm@gmail.com>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import time
from ast import literal_eval
from collections import defaultdict
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.logfacility import log
from pynicotine.utils import encode_path
returncode = {
"break": 0, # don't give other plugins the event, do let n+ process it
"zap": 1, # don't give other plugins the event, don't let n+ process it
"pass": 2 # do give other plugins the event, do let n+ process it
} # returning nothing is the same as 'pass'
class BasePlugin:
# Attributes that can be modified, see examples in the pynicotine/plugins/ folder
__publiccommands__ = []
__privatecommands__ = []
commands = {}
settings = {}
metasettings = {}
# Attributes that are assigned when the plugin loads, do not modify these
internal_name = None # Technical plugin name based on plugin folder name
human_name = None # Friendly plugin name specified in the PLUGININFO file
path = None # Folder path where plugin files are stored
parent = None # Reference to PluginHandler
config = None # Reference to global Config handler
core = None # Reference to Core
def __init__(self):
# The plugin class is initializing, plugin settings are not available yet
pass
def init(self):
# Called after __init__() when plugin settings have loaded
pass
def loaded_notification(self):
# The plugin has finished loaded, commands are registered
pass
def disable(self):
# The plugin has started unloading
pass
def unloaded_notification(self):
# The plugin has finished unloading
pass
def shutdown_notification(self):
# Application is shutting down
pass
def public_room_message_notification(self, room, user, line):
# Override method in plugin
pass
def search_request_notification(self, searchterm, user, token):
# Override method in plugin
pass
def distrib_search_notification(self, searchterm, user, token):
# Override method in plugin
pass
def incoming_private_chat_event(self, user, line):
# Override method in plugin
pass
def incoming_private_chat_notification(self, user, line):
# Override method in plugin
pass
def incoming_public_chat_event(self, room, user, line):
# Override method in plugin
pass
def incoming_public_chat_notification(self, room, user, line):
# Override method in plugin
pass
def outgoing_private_chat_event(self, user, line):
# Override method in plugin
pass
def outgoing_private_chat_notification(self, user, line):
# Override method in plugin
pass
def outgoing_public_chat_event(self, room, line):
# Override method in plugin
pass
def outgoing_public_chat_notification(self, room, line):
# Override method in plugin
pass
def outgoing_global_search_event(self, text):
# Override method in plugin
pass
def outgoing_room_search_event(self, rooms, text):
# Override method in plugin
pass
def outgoing_buddy_search_event(self, text):
# Override method in plugin
pass
def outgoing_user_search_event(self, users, text):
# Override method in plugin
pass
def outgoing_wishlist_search_event(self, text):
# Override method in plugin
pass
def user_resolve_notification(self, user, ip_address, port, country):
# Override method in plugin
pass
def server_connect_notification(self):
# Override method in plugin
pass
def server_disconnect_notification(self, userchoice):
# Override method in plugin
pass
def join_chatroom_notification(self, room):
# Override method in plugin
pass
def leave_chatroom_notification(self, room):
# Override method in plugin
pass
def user_join_chatroom_notification(self, room, user):
# Override method in plugin
pass
def user_leave_chatroom_notification(self, room, user):
# Override method in plugin
pass
def user_stats_notification(self, user, stats):
# Override method in plugin
pass
def user_status_notification(self, user, status, privileged):
# Override method in plugin
pass
def upload_queued_notification(self, user, virtual_path, real_path):
# Override method in plugin
pass
def upload_started_notification(self, user, virtual_path, real_path):
# Override method in plugin
pass
def upload_finished_notification(self, user, virtual_path, real_path):
# Override method in plugin
pass
def download_started_notification(self, user, virtual_path, real_path):
# Override method in plugin
pass
def download_finished_notification(self, user, virtual_path, real_path):
# Override method in plugin
pass
# The following are functions to make your life easier,
# you shouldn't override them.
def log(self, msg, msg_args=None):
log.add(f"{self.human_name}: {msg}", msg_args)
def send_public(self, room, text):
"""Send chat message to a room, must already be joined."""
core.chatrooms.send_message(room, text)
def send_private(self, user, text, show_ui=True, switch_page=True):
"""Send user message in private.
show_ui controls if the UI opens a private chat view for the
user. switch_page controls whether the user's private chat view
should be opened.
"""
if show_ui:
core.privatechat.show_user(user, switch_page)
core.privatechat.send_message(user, text)
def echo_public(self, room, text, message_type="local"):
"""Display a raw message in chat rooms (not sent to others).
message_type changes the type (and color) of the message in the UI.
available message_type values: action, remote, local, hilite
"""
core.chatrooms.echo_message(room, text, message_type)
def echo_private(self, user, text, message_type="local"):
"""Display a raw message in private (not sent to others).
message_type changes the type (and color) of the message in the UI.
available message_type values: action, remote, local, hilite
"""
core.privatechat.show_user(user)
core.privatechat.echo_message(user, text, message_type)
def send_message(self, text):
"""Convenience function to send a message to the same user/room a
plugin command runs for."""
if self.parent.command_source is None:
# Function was not called from a command
return
command_interface, source = self.parent.command_source
if command_interface == "cli":
return
func = self.send_public if command_interface == "chatroom" else self.send_private
func(source, text)
def echo_message(self, text, message_type="local"):
"""Convenience function to display a raw message the same window a
plugin command runs from."""
if self.parent.command_source is None:
# Function was not called from a command
return
command_interface, source = self.parent.command_source
if command_interface == "cli":
print(text)
return
func = self.echo_public if command_interface == "chatroom" else self.echo_private
func(source, text, message_type)
def output(self, text):
self.echo_message(text, message_type="command")
class ResponseThrottle:
"""
ResponseThrottle - Mutnick 2016
See 'testreplier' plugin for example use
Purpose: Avoid flooding chat room with plugin responses
Some plugins respond based on user requests and we do not want
to respond too much and encounter a temporary server chat ban
Some of the throttle logic is guesswork as server code is closed source, but works adequately.
"""
def __init__(self, core, plugin_name, logging=False): # pylint: disable=redefined-outer-name
self.core = core
self.plugin_name = plugin_name
self.logging = logging
self.plugin_usage = {}
self.room = None
self.nick = None
self.request = None
def ok_to_respond(self, room, nick, request, seconds_limit_min=30):
self.room = room
self.nick = nick
self.request = request
willing_to_respond = True
current_time = time.monotonic()
if room not in self.plugin_usage:
self.plugin_usage[room] = {"last_time": 0, "last_request": "", "last_nick": ""}
last_time = self.plugin_usage[room]["last_time"]
last_nick = self.plugin_usage[room]["last_nick"]
last_request = self.plugin_usage[room]["last_request"]
try:
_ip_address, port = self.core.users.addresses[nick]
except Exception:
port = True
if self.core.network_filter.is_user_ignored(nick):
willing_to_respond, reason = False, "The nick is ignored"
elif self.core.network_filter.is_user_ip_ignored(nick):
willing_to_respond, reason = False, "The nick's Ip is ignored"
elif not port:
willing_to_respond, reason = False, "Request likely from simple PHP based griefer bot"
elif [nick, request] == [last_nick, last_request]:
if (current_time - last_time) < 12 * seconds_limit_min:
willing_to_respond, reason = False, "Too soon for same nick to request same resource in room"
elif request == last_request:
if (current_time - last_time) < 3 * seconds_limit_min:
willing_to_respond, reason = False, "Too soon for different nick to request same resource in room"
else:
recent_responses = 0
for responded_room, room_dict in self.plugin_usage.items():
if (current_time - room_dict["last_time"]) < seconds_limit_min:
recent_responses += 1
if responded_room == room:
willing_to_respond, reason = False, "Responded in specified room too recently"
break
if recent_responses > 3:
willing_to_respond, reason = False, "Responded in multiple rooms enough"
if self.logging and not willing_to_respond:
log.add_debug("%s plugin request rejected - room '%s', nick '%s' - %s",
(self.plugin_name, room, nick, reason))
return willing_to_respond
def responded(self):
self.plugin_usage[self.room] = {
"last_time": time.monotonic(), "last_request": self.request, "last_nick": self.nick}
class PluginHandler:
__slots__ = ("plugin_folders", "enabled_plugins", "command_source", "commands",
"user_plugin_folder")
def __init__(self):
self.plugin_folders = []
self.enabled_plugins = {}
self.command_source = None
self.commands = {
"chatroom": {},
"private_chat": {},
"cli": {}
}
# Load system-wide plugins
prefix = os.path.dirname(os.path.realpath(__file__))
self.plugin_folders.append(os.path.join(prefix, "plugins"))
# Load home folder plugins
self.user_plugin_folder = os.path.join(config.data_folder_path, "plugins")
self.plugin_folders.append(self.user_plugin_folder)
for event_name, callback in (
("cli-command", self._cli_command),
("start", self._start),
("quit", self._quit)
):
events.connect(event_name, callback)
def _start(self):
BasePlugin.parent = self
BasePlugin.config = config
BasePlugin.core = core
log.add(_("Loading plugin system"))
self.enable_plugin("core_commands")
if not config.sections["plugins"]["enable"]:
return
to_enable = config.sections["plugins"]["enabled"]
log.add_debug("Enabled plugin(s): %s", ', '.join(to_enable))
for plugin in to_enable:
self.enable_plugin(plugin)
def _quit(self):
# Notify plugins
self.shutdown_notification()
# Disable plugins
for plugin in self.list_installed_plugins():
self.disable_plugin(plugin, is_permanent=False)
def _cli_command(self, command, args):
self.trigger_cli_command_event(command, args)
def update_completions(self, plugin):
if not config.sections["words"]["commands"]:
return
if plugin.commands or plugin.__publiccommands__:
core.chatrooms.update_completions()
if plugin.commands or plugin.__privatecommands__:
core.privatechat.update_completions()
def get_plugin_path(self, plugin_name):
for folder_path in self.plugin_folders:
file_path = os.path.join(folder_path, plugin_name)
if os.path.isdir(encode_path(file_path)):
return file_path
return None
def _import_plugin_instance(self, plugin_name):
if (plugin_name == "now_playing_sender" and
(sys.platform in {"win32", "darwin"} or "SNAP_NAME" in os.environ)):
# MPRIS is not available on Windows and macOS
return None
plugin_path = self.get_plugin_path(plugin_name)
try:
# Import builtin plugin
from importlib import import_module
plugin = import_module(f"pynicotine.plugins.{plugin_name}")
except Exception:
# Import user plugin
if plugin_path is None:
log.add_debug("Failed to load plugin '%s', could not find it", plugin_name)
return None
# Add plugin folder to path in order to support relative imports
sys.path.append(plugin_path)
import importlib.util
spec = importlib.util.spec_from_file_location(plugin_name, os.path.join(plugin_path, "__init__.py"))
plugin = importlib.util.module_from_spec(spec)
spec.loader.exec_module(plugin)
# Set class attributes to make name available while initializing plugin
BasePlugin.internal_name = plugin_name
BasePlugin.human_name = self.get_plugin_info(plugin_name).get("Name", plugin_name)
BasePlugin.path = plugin_path
instance = plugin.Plugin()
instance.internal_name = BasePlugin.internal_name
instance.human_name = BasePlugin.human_name
instance.path = BasePlugin.path
# Reset class attributes
BasePlugin.internal_name = BasePlugin.human_name = BasePlugin.path = None
self.plugin_settings(plugin_name, instance)
if hasattr(plugin, "enable"):
instance.log("top-level enable() function is obsolete, please use BasePlugin.__init__() instead")
if hasattr(plugin, "disable"):
instance.log("top-level disable() function is obsolete, please use BasePlugin.disable() instead")
if hasattr(instance, "LoadNotification"):
instance.log("LoadNotification() is obsolete, please use init()")
return instance
def enable_plugin(self, plugin_name):
# Our config file doesn't play nicely with some characters
if "=" in plugin_name:
log.add(
_("Unable to load plugin %(name)s. Plugin folder name contains invalid characters: %(characters)s"), {
"name": plugin_name,
"characters": "="
})
return False
if plugin_name in self.enabled_plugins:
return False
try:
plugin = self._import_plugin_instance(plugin_name)
if plugin is None:
return False
plugin.init()
for command, data in plugin.commands.items():
if not data:
continue
disabled_interfaces = data.get("disable", [])
if "group" not in data:
# Group commands under human-friendly plugin name by default
data["group"] = plugin.human_name
for command_interface, command_list in self.commands.items():
if command_interface in disabled_interfaces:
continue
if command in command_list:
log.add(_("Conflicting %(interface)s command in plugin %(name)s: %(command)s"),
{"interface": command_interface, "name": plugin.human_name, "command": f"/{command}"})
continue
command_list[command] = data
# Legacy commands
for command_interface, attribute_name, plugin_commands in (
("chatroom", "__publiccommands__", plugin.__publiccommands__),
("private_chat", "__privatecommands__", plugin.__privatecommands__)
):
interface_commands = self.commands.get(command_interface)
for command, _func in plugin_commands:
if command not in interface_commands:
interface_commands[command] = None
plugin.log(f"/{command}: {attribute_name} is deprecated, please use the new "
f"command system. See pynicotine/plugins/ in the Git repository for examples.")
self.update_completions(plugin)
if plugin_name not in config.sections["plugins"]["enabled"]:
config.sections["plugins"]["enabled"].append(plugin_name)
self.enabled_plugins[plugin_name] = plugin
plugin.loaded_notification()
log.add(_("Loaded plugin %s"), plugin.human_name)
except Exception:
from traceback import format_exc
log.add(_("Unable to load plugin %(module)s\n%(exc_trace)s"),
{"module": plugin_name, "exc_trace": format_exc()})
return False
return True
def list_installed_plugins(self):
plugin_list = []
for folder_path in self.plugin_folders:
try:
for entry in os.scandir(encode_path(folder_path)):
file_path = entry.name.decode("utf-8", "replace")
if file_path == "core_commands":
continue
if (file_path == "now_playing_sender" and
(sys.platform in {"win32", "darwin"} or "SNAP_NAME" in os.environ)):
# MPRIS is not available on Windows and macOS
continue
if entry.is_dir() and file_path not in plugin_list:
plugin_list.append(file_path)
except OSError:
# Folder error, skip
continue
return plugin_list
def disable_plugin(self, plugin_name, is_permanent=True):
if plugin_name == "core_commands":
return False
if plugin_name not in self.enabled_plugins:
return False
plugin = self.enabled_plugins[plugin_name]
plugin_path = None
try:
plugin_path = str(plugin.path)
plugin.disable()
for command, data in plugin.commands.items():
for command_list in self.commands.values():
# Remove only if data matches command as defined in this plugin
if data and data == command_list.get(command):
del command_list[command]
# Legacy commands
for command_interface, plugin_commands in (
("chatroom", plugin.__publiccommands__),
("private_chat", plugin.__privatecommands__)
):
interface_commands = self.commands.get(command_interface)
for command, _func in plugin_commands:
if command in interface_commands and interface_commands.get(command) is None:
del interface_commands[command]
self.update_completions(plugin)
plugin.unloaded_notification()
log.add(_("Unloaded plugin %s"), plugin.human_name)
except Exception:
from traceback import format_exc
log.add(_("Unable to unload plugin %(module)s\n%(exc_trace)s"),
{"module": plugin_name, "exc_trace": format_exc()})
return False
finally:
if not plugin_path:
plugin_path = str(self.get_plugin_path(plugin_name))
# Remove references to relative modules
if plugin_path in sys.path:
sys.path.remove(plugin_path)
for name, module in sys.modules.copy().items():
try:
if module.__file__.startswith(plugin_path):
sys.modules.pop(name, None)
del module
except AttributeError:
# Builtin module
continue
if is_permanent and plugin_name in config.sections["plugins"]["enabled"]:
config.sections["plugins"]["enabled"].remove(plugin_name)
del self.enabled_plugins[plugin_name]
del plugin
return True
def toggle_plugin(self, plugin_name):
enabled = plugin_name in self.enabled_plugins
if enabled:
# Return False is plugin is unloaded
return not self.disable_plugin(plugin_name)
return self.enable_plugin(plugin_name)
def reload_plugin(self, plugin_name):
self.disable_plugin(plugin_name)
self.enable_plugin(plugin_name)
def get_plugin_settings(self, plugin_name):
if plugin_name in self.enabled_plugins:
plugin = self.enabled_plugins[plugin_name]
if plugin.metasettings:
return plugin.metasettings
return None
def get_plugin_info(self, plugin_name):
plugin_info = {}
plugin_path = self.get_plugin_path(plugin_name)
if plugin_path is None:
return plugin_info
info_path = os.path.join(plugin_path, "PLUGININFO")
with open(encode_path(info_path), encoding="utf-8") as file_handle:
for line in file_handle:
try:
key, _separator, value = line.partition("=")
key = key.strip()
value = value.strip()
# Translatable string
if value.startswith("_(") and value.endswith(")"):
plugin_info[key] = _(literal_eval(value[2:-1]))
continue
plugin_info[key] = literal_eval(value)
except Exception:
pass # this can happen on blank lines
return plugin_info
@staticmethod
def show_plugin_error(plugin_name, exc_type, exc_value, exc_traceback):
from traceback import format_tb
log.add(_("Plugin %(module)s failed with error %(errortype)s: %(error)s.\n"
"Trace: %(trace)s"), {
"module": plugin_name,
"errortype": exc_type,
"error": exc_value,
"trace": "".join(format_tb(exc_traceback))
})
def plugin_settings(self, plugin_name, plugin):
plugin_name = plugin_name.lower()
if not plugin.settings:
return
previous_settings = config.sections["plugins"].get(plugin_name, {})
for key in previous_settings:
if key not in plugin.settings:
log.add_debug("Stored setting '%s' is no longer present in the '%s' plugin",
(key, plugin_name))
continue
plugin.settings[key] = previous_settings[key]
# Persist plugin settings in the config
config.sections["plugins"][plugin_name] = plugin.settings
def get_command_list(self, command_interface):
"""Returns a list of every command and alias available.
Currently used for auto-completion in chats.
"""
commands = []
for command, data in self.commands.get(command_interface).items():
commands.append(f"/{command} ")
if not data:
continue
for alias in data.get("aliases", []):
commands.append(f"/{alias} ")
return commands
def get_command_groups_data(self, command_interface, search_query=None):
"""Returns the available command groups and data of commands in them.
Currently used for the /help command.
"""
command_groups = defaultdict(list)
for command, data in self.commands.get(command_interface).items():
aliases = []
parameters = []
description = _("No description")
group = _("Miscellaneous")
if data:
aliases = data.get("aliases", [])
parameters = data.get(f"parameters_{command_interface}", data.get("parameters", []))
description = data.get("description", description)
group = data.get("group", group)
if (search_query
and search_query not in group.lower()
and search_query not in command.lower()
and not any(search_query in alias for alias in aliases)
and not any(search_query in parameter for parameter in parameters)
and search_query not in description.lower()):
continue
command_groups[group].append((command, aliases, parameters, description))
return command_groups
def trigger_chatroom_command_event(self, room, command, args):
return self._trigger_command(command, args, room=room)
def trigger_private_chat_command_event(self, user, command, args):
return self._trigger_command(command, args, user=user)
def trigger_cli_command_event(self, command, args):
return self._trigger_command(command, args)
def _trigger_command(self, command, args, user=None, room=None):
plugin = None
command_found = False
is_successful = False
for module, plugin in self.enabled_plugins.items():
if plugin is None:
continue
if room is not None:
self.command_source = ("chatroom", room)
legacy_commands = plugin.__publiccommands__
elif user is not None:
self.command_source = ("private_chat", user)
legacy_commands = plugin.__privatecommands__
else:
self.command_source = ("cli", None)
legacy_commands = []
try:
for trigger, data in plugin.commands.items():
aliases = data.get("aliases", [])
if command != trigger and command not in aliases:
continue
command_interface = self.command_source[0]
disabled_interfaces = data.get("disable", [])
if command_interface in disabled_interfaces:
continue
command_found = True
rejection_message = None
parameters = data.get(f"parameters_{command_interface}", data.get("parameters", []))
args_split = args.split()
num_args = len(args_split)
num_required_args = 0
for i, parameter in enumerate(parameters):
if parameter.startswith("<"):
num_required_args += 1
if num_args < num_required_args:
rejection_message = _("Missing %s argument") % parameter
break
if num_args <= i or "|" not in parameter:
continue
choices = parameter[1:-1].split("|")
if args_split[i] not in choices:
rejection_message = _("Invalid argument, possible choices: %s") % " | ".join(choices)
break
if rejection_message:
plugin.output(rejection_message)
plugin.output(_("Usage: %(command)s %(parameters)s") % {
"command": f"/{command}",
"parameters": " ".join(parameters)
})
break
callback = data.get(f"callback_{command_interface}", data.get("callback"))
if room is not None:
is_successful = callback(args, room=room)
elif user is not None:
is_successful = callback(args, user=user)
else:
is_successful = callback(args)
if is_successful is None:
# Command didn't return anything, default to success
is_successful = True
if not command_found:
for trigger, func in legacy_commands:
if trigger == command:
func(self.command_source[1], args)
is_successful = True
command_found = True
break
except Exception:
self.show_plugin_error(module, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
plugin = None
break
if command_found:
plugin = None
break
if plugin:
plugin.output(_("Unknown command: %(command)s. Type %(help_command)s to list available commands.") % {
"command": f"/{command}",
"help_command": "/help"
})
self.command_source = None
return is_successful
def _trigger_event(self, function_name, args):
"""Triggers an event for the plugins.
Since events and notifications are precisely the same except for
how n+ responds to them, both can be triggered by this function.
"""
for module, plugin in self.enabled_plugins.items():
try:
return_value = getattr(plugin, function_name)(*args)
except Exception:
self.show_plugin_error(module, sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
continue
if return_value is None:
# Nothing changed, continue to the next plugin
continue
if isinstance(return_value, tuple):
# The original args were modified, update them
args = return_value
continue
if return_value == returncode["zap"]:
return None
if return_value == returncode["break"]:
return args
if return_value == returncode["pass"]:
continue
log.add_debug("Plugin %s returned something weird, '%s', ignoring", (module, return_value))
return args
def search_request_notification(self, searchterm, user, token):
self._trigger_event("search_request_notification", (searchterm, user, token))
def distrib_search_notification(self, searchterm, user, token):
self._trigger_event("distrib_search_notification", (searchterm, user, token))
def public_room_message_notification(self, room, user, line):
self._trigger_event("public_room_message_notification", (room, user, line))
def incoming_private_chat_event(self, user, line):
if user != core.users.login_username:
# dont trigger the scripts on our own talking - we've got "Outgoing" for that
return self._trigger_event("incoming_private_chat_event", (user, line))
return user, line
def incoming_private_chat_notification(self, user, line):
self._trigger_event("incoming_private_chat_notification", (user, line))
def incoming_public_chat_event(self, room, user, line):
return self._trigger_event("incoming_public_chat_event", (room, user, line))
def incoming_public_chat_notification(self, room, user, line):
self._trigger_event("incoming_public_chat_notification", (room, user, line))
def outgoing_private_chat_event(self, user, line):
if line is not None:
# if line is None nobody actually said anything
return self._trigger_event("outgoing_private_chat_event", (user, line))
return user, line
def outgoing_private_chat_notification(self, user, line):
self._trigger_event("outgoing_private_chat_notification", (user, line))
def outgoing_public_chat_event(self, room, line):
return self._trigger_event("outgoing_public_chat_event", (room, line))
def outgoing_public_chat_notification(self, room, line):
self._trigger_event("outgoing_public_chat_notification", (room, line))
def outgoing_global_search_event(self, text):
return self._trigger_event("outgoing_global_search_event", (text,))
def outgoing_room_search_event(self, rooms, text):
return self._trigger_event("outgoing_room_search_event", (rooms, text))
def outgoing_buddy_search_event(self, text):
return self._trigger_event("outgoing_buddy_search_event", (text,))
def outgoing_user_search_event(self, users, text):
return self._trigger_event("outgoing_user_search_event", (users, text))
def outgoing_wishlist_search_event(self, text):
return self._trigger_event("outgoing_wishlist_search_event", (text,))
def user_resolve_notification(self, user, ip_address, port, country=None):
"""Notification for user IP:Port resolving.
Note that country is only set when the user requested the
resolving
"""
self._trigger_event("user_resolve_notification", (user, ip_address, port, country))
def server_connect_notification(self):
self._trigger_event("server_connect_notification", (),)
def server_disconnect_notification(self, userchoice):
self._trigger_event("server_disconnect_notification", (userchoice, ))
def join_chatroom_notification(self, room):
self._trigger_event("join_chatroom_notification", (room,))
def leave_chatroom_notification(self, room):
self._trigger_event("leave_chatroom_notification", (room,))
def user_join_chatroom_notification(self, room, user):
self._trigger_event("user_join_chatroom_notification", (room, user,))
def user_leave_chatroom_notification(self, room, user):
self._trigger_event("user_leave_chatroom_notification", (room, user,))
def user_stats_notification(self, user, stats):
self._trigger_event("user_stats_notification", (user, stats))
def user_status_notification(self, user, status, privileged):
self._trigger_event("user_status_notification", (user, status, privileged))
def upload_queued_notification(self, user, virtual_path, real_path):
self._trigger_event("upload_queued_notification", (user, virtual_path, real_path))
def upload_started_notification(self, user, virtual_path, real_path):
self._trigger_event("upload_started_notification", (user, virtual_path, real_path))
def upload_finished_notification(self, user, virtual_path, real_path):
self._trigger_event("upload_finished_notification", (user, virtual_path, real_path))
def download_started_notification(self, user, virtual_path, real_path):
self._trigger_event("download_started_notification", (user, virtual_path, real_path))
def download_finished_notification(self, user, virtual_path, real_path):
self._trigger_event("download_finished_notification", (user, virtual_path, real_path))
def shutdown_notification(self):
self._trigger_event("shutdown_notification", (),)
| 37,668 | Python | .py | 771 | 37.016861 | 118 | 0.604978 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,413 | notifications.py | nicotine-plus_nicotine-plus/pynicotine/notifications.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from collections import deque
from threading import Thread
from pynicotine.config import config
from pynicotine.events import events
from pynicotine.logfacility import log
from pynicotine.utils import execute_command
class Notifications:
__slots__ = ("tts", "_tts_thread")
def __init__(self):
self.tts = deque()
self._tts_thread = None
events.connect("quit", self._quit)
def _quit(self):
self.tts.clear()
# Notification Messages #
def show_notification(self, message, title=None):
events.emit("show-notification", message, title=title)
def show_chatroom_notification(self, room, message, title=None, high_priority=False):
events.emit("show-chatroom-notification", room, message, title=title, high_priority=high_priority)
def show_download_notification(self, message, title=None, high_priority=False):
events.emit("show-download-notification", message, title=title, high_priority=high_priority)
def show_private_chat_notification(self, username, message, title=None):
events.emit("show-private-chat-notification", username, message, title=title)
def show_search_notification(self, search_token, message, title=None):
events.emit("show-search-notification", search_token, message, title=title)
# TTS #
def new_tts(self, message, args=None):
if not config.sections["ui"]["speechenabled"]:
return
if args:
for key, value in args.items():
args[key] = (value.replace("_", " ").replace("[", " ").replace("]", " ")
.replace("(", " ").replace(")", " "))
try:
message %= args
except Exception as error:
log.add(_("Text-to-speech for message failed: %s"), error)
return
self.tts.append(message)
if self._tts_thread and self._tts_thread.is_alive():
return
self._tts_thread = Thread(target=self.play_tts, name="TTS", daemon=True)
self._tts_thread.start()
def play_tts(self):
while self.tts:
try:
message = self.tts.popleft()
execute_command(config.sections["ui"]["speechcommand"], message, background=False, hidden=True)
except Exception as error:
log.add(_("Text-to-speech for message failed: %s"), error)
| 3,171 | Python | .py | 67 | 39.880597 | 111 | 0.666017 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,414 | userinfo.py | nicotine-plus_nicotine-plus/pynicotine/userinfo.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import time
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.logfacility import log
from pynicotine.shares import PermissionLevel
from pynicotine.slskmessages import CloseConnection
from pynicotine.slskmessages import UserInfoRequest
from pynicotine.slskmessages import UserInfoResponse
from pynicotine.slskmessages import UserInterests
from pynicotine.utils import encode_path
from pynicotine.utils import unescape
class UserInfo:
__slots__ = ("users", "requested_info_times")
def __init__(self):
self.users = set()
self.requested_info_times = {}
for event_name, callback in (
("quit", self._quit),
("server-login", self._server_login),
("server-disconnect", self._server_disconnect),
("user-info-progress", self._user_info_progress),
("user-info-request", self._user_info_request)
):
events.connect(event_name, callback)
def _quit(self):
self.remove_all_users()
def _server_login(self, msg):
if not msg.success:
return
for username in self.users:
core.users.watch_user(username, context="userinfo") # Get notified of user status
def _server_disconnect(self, _msg):
self.requested_info_times.clear()
def _get_user_info_response(self, requesting_username=None, requesting_ip_address=None):
if requesting_username is not None and requesting_ip_address is not None:
permission_level, reject_reason = core.shares.check_user_permission(
requesting_username, requesting_ip_address)
else:
permission_level = PermissionLevel.PUBLIC
reject_reason = None
if permission_level == PermissionLevel.BANNED:
# Hide most details from banned users
pic = None
descr = ""
totalupl = queuesize = uploadallowed = 0
slotsavail = False
if reject_reason:
descr = f"You are not allowed to download my shared files.\nReason: {reject_reason}"
else:
try:
with open(encode_path(os.path.expandvars(config.sections["userinfo"]["pic"])), "rb") as file_handle:
pic = file_handle.read()
except Exception:
pic = None
descr = unescape(config.sections["userinfo"]["descr"])
totalupl = core.uploads.get_total_uploads_allowed()
queuesize = core.uploads.get_upload_queue_size(requesting_username)
slotsavail = core.uploads.is_new_upload_accepted()
if config.sections["transfers"]["remotedownloads"]:
uploadallowed = config.sections["transfers"]["uploadallowed"]
else:
uploadallowed = 0
msg = UserInfoResponse(
descr=descr, pic=pic, totalupl=totalupl, queuesize=queuesize, slotsavail=slotsavail,
uploadallowed=uploadallowed
)
msg.username = core.users.login_username or config.sections["server"]["login"]
return msg
def show_user(self, username=None, refresh=False, switch_page=True):
local_username = core.users.login_username or config.sections["server"]["login"]
if not username:
username = local_username
if not username:
core.setup()
return
if username not in self.users:
self.users.add(username)
refresh = True
events.emit("user-info-show-user", user=username, refresh=refresh, switch_page=switch_page)
if not refresh:
return
if username == local_username:
msg = self._get_user_info_response()
events.emit("user-info-response", msg)
else:
# Request user status, speed and number of shared files
core.users.watch_user(username, context="userinfo")
# Request user description, picture and queue information
core.send_message_to_peer(username, UserInfoRequest())
# Request user interests
core.send_message_to_server(UserInterests(username))
def remove_user(self, username):
self.users.remove(username)
core.users.unwatch_user(username, context="userinfo")
events.emit("user-info-remove-user", username)
def remove_all_users(self):
for username in self.users.copy():
self.remove_user(username)
@staticmethod
def save_user_picture(file_path, picture_bytes):
try:
with open(encode_path(file_path), "wb") as file_handle:
file_handle.write(picture_bytes)
log.add(_("Picture saved to %s"), file_path)
except Exception as error:
log.add(_("Cannot save picture to %(filename)s: %(error)s"), {
"filename": file_path,
"error": error
})
def _user_info_progress(self, username, sock, _buffer_len, _msg_size_total):
if username not in self.users:
# We've removed the user. Close the connection to stop the user from
# sending their response and wasting bandwidth.
core.send_message_to_network_thread(CloseConnection(sock))
def _user_info_request(self, msg):
"""Peer code 15."""
username = msg.username
ip_address, _port = msg.addr
request_time = time.monotonic()
if username in self.requested_info_times and request_time < self.requested_info_times[username] + 0.4:
# Ignoring request, because it's less than half a second since the
# last one by this user
return
self.requested_info_times[username] = request_time
msg = self._get_user_info_response(username, ip_address)
log.add(_("User %(user)s is viewing your profile"), {"user": username})
core.send_message_to_peer(username, msg)
| 6,773 | Python | .py | 146 | 37.109589 | 116 | 0.650714 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,415 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/headless/__init__.py | # COPYRIGHT (C) 2022-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
def run():
"""Run application in headless (no GUI) mode."""
from pynicotine.headless.application import Application
return Application().run()
| 903 | Python | .py | 21 | 41.285714 | 71 | 0.76678 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,416 | application.py | nicotine-plus_nicotine-plus/pynicotine/headless/application.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import time
from pynicotine.cli import cli
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.logfacility import log
class Application:
def __init__(self):
sys.excepthook = self.on_critical_error
for log_level in ("download", "upload"):
log.add_log_level(log_level, is_permanent=False)
for event_name, callback in (
("confirm-quit", self.on_confirm_quit),
("invalid-password", self.on_invalid_password),
("invalid-username", self.on_invalid_password),
("setup", self.on_setup),
("shares-unavailable", self.on_shares_unavailable)
):
events.connect(event_name, callback)
def run(self):
core.start()
if config.sections["server"]["auto_connect_startup"]:
core.connect()
# Main loop, process events from threads 10 times per second
while events.process_thread_events():
time.sleep(0.1)
# Shut down with exit code 0 (success)
config.write_configuration()
return 0
def on_critical_error(self, _exc_type, exc_value, _exc_traceback):
sys.excepthook = None
core.quit()
events.emit("quit")
raise exc_value
def on_confirm_quit_response(self, user_input):
if user_input.lower().startswith("y"):
core.quit()
def on_confirm_quit(self):
responses = "[y/N] "
cli.prompt(_("Do you really want to exit? %s") % responses, callback=self.on_confirm_quit_response)
def on_invalid_password(self):
log.add(_("User %s already exists, and the password you entered is invalid."),
config.sections["server"]["login"])
log.add(_("Type %s to log in with another username or password."), "/connect")
config.sections["server"]["passw"] = ""
def on_setup_password_response(self, user_input):
config.sections["server"]["passw"] = user_input
config.write_configuration()
core.connect()
def on_setup_username_response(self, user_input):
if user_input:
config.sections["server"]["login"] = user_input
cli.prompt(_("Password: "), callback=self.on_setup_password_response, is_silent=True)
def on_setup(self):
log.add(_("To create a new Soulseek account, fill in your desired username and password. If you "
"already have an account, fill in your existing login details."))
cli.prompt(_("Username: "), callback=self.on_setup_username_response)
def on_shares_unavailable_response(self, user_input):
user_input = user_input.lower()
if not user_input or user_input.startswith("y"):
core.shares.rescan_shares()
elif user_input.startswith("f"):
core.shares.rescan_shares(force=True)
def on_shares_unavailable(self, shares):
responses = "[Y/n/force] "
message = _("The following shares are unavailable:") + "\n\n"
for virtual_name, folder_path in shares:
message += f'• "{virtual_name}" {folder_path}\n'
message += "\n" + _("Verify that external disks are mounted and folder permissions are correct.")
message += "\n" + _("Retry rescan? %s") % responses
cli.prompt(message, callback=self.on_shares_unavailable_response)
| 4,182 | Python | .py | 89 | 39.47191 | 107 | 0.660912 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,417 | test_i18n.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/test_i18n.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import subprocess
from unittest import TestCase
from pynicotine.i18n import BASE_PATH
class I18nTest(TestCase):
def test_po_files(self):
"""Verify that translation files don't contain errors."""
po_file_found = False
with os.scandir(os.path.join(BASE_PATH, "po")) as entries:
for entry in entries:
if not entry.is_file() or not entry.name.endswith(".po"):
continue
po_file_found = True
error_output = subprocess.check_output(
["msgfmt", "--check", entry.path, "-o", "/dev/null"], stderr=subprocess.STDOUT)
self.assertFalse(error_output)
self.assertTrue(po_file_found)
| 1,486 | Python | .py | 34 | 37.911765 | 99 | 0.693963 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,418 | test_version.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/test_version.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from unittest import TestCase
import pynicotine
from pynicotine.core import UpdateChecker
class VersionTest(TestCase):
def test_dev_version(self):
# Test a sample dev version to ensure it's older than the stable counterpart
sample_stable_version = UpdateChecker.create_integer_version("2.1.0")
sample_dev_version = UpdateChecker.create_integer_version("2.1.0.dev1")
self.assertGreater(sample_stable_version, sample_dev_version)
def test_update_check(self):
# Validate local version
local_version = UpdateChecker.create_integer_version(pynicotine.__version__)
self.assertIsInstance(local_version, int)
# Validate version of latest release
_h_latest_version, latest_version = UpdateChecker.retrieve_latest_version()
self.assertIsInstance(latest_version, int)
| 1,599 | Python | .py | 33 | 44.515152 | 84 | 0.757225 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,419 | test_shares.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/shares/test_shares.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
import struct
import wave
from unittest import TestCase
from pynicotine.config import config
from pynicotine.core import core
CURRENT_FOLDER_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_FOLDER_PATH = os.path.join(CURRENT_FOLDER_PATH, "temp_data")
SHARES_FOLDER_PATH = os.path.join(CURRENT_FOLDER_PATH, ".sharedfiles")
BUDDY_SHARES_FOLDER_PATH = os.path.join(CURRENT_FOLDER_PATH, ".sharedbuddyfiles")
TRUSTED_SHARES_FOLDER_PATH = os.path.join(CURRENT_FOLDER_PATH, ".sharedtrustedfiles")
INVALID_SHARES_FOLDER_PATH = os.path.join(CURRENT_FOLDER_PATH, ".sharedinvalidfiles")
AUDIO_FILES = (
(SHARES_FOLDER_PATH, "audiofile.wav", 50000),
(BUDDY_SHARES_FOLDER_PATH, "audiofile2.wav", 150000),
(TRUSTED_SHARES_FOLDER_PATH, "audiofile3.wav", 200000)
)
class SharesTest(TestCase):
def setUp(self):
config.set_data_folder(DATA_FOLDER_PATH)
config.set_config_file(os.path.join(DATA_FOLDER_PATH, "temp_config"))
core.init_components(enabled_components={"shares"})
# Prepare shares
config.sections["transfers"]["shared"] = [
("Shares", SHARES_FOLDER_PATH, "junk"), # Superfluous item in tuple
("invalid", os.path.join(SHARES_FOLDER_PATH, "folder2")) # Resharing subfolder from previous share
]
config.sections["transfers"]["buddyshared"] = [
("Secrets", BUDDY_SHARES_FOLDER_PATH),
("invalid2", os.path.join(BUDDY_SHARES_FOLDER_PATH, "buddies")), # Resharing subfolder from previous share
("invalid3", os.path.join(BUDDY_SHARES_FOLDER_PATH, "something2", "nothing2")), # File instead of folder
("Shares", INVALID_SHARES_FOLDER_PATH) # Duplicate virtual name
]
config.sections["transfers"]["trustedshared"] = [
("invalid4", SHARES_FOLDER_PATH), # Resharing public folder
("Trusted", TRUSTED_SHARES_FOLDER_PATH)
]
# Prepare audio files
for folder_path, basename, num_frames in AUDIO_FILES:
with wave.open(os.path.join(folder_path, basename), "wb") as audio_file:
# pylint: disable=no-member
audio_file.setnchannels(1)
audio_file.setsampwidth(2)
audio_file.setframerate(44100)
audio_file.writeframes(struct.pack("h", 0) * num_frames)
self.addCleanup(os.remove, os.path.join(folder_path, basename))
# Rescan shares
core.shares.rescan_shares(rebuild=True, use_thread=False)
core.shares.load_shares(core.shares.share_dbs, core.shares.share_db_paths)
def tearDown(self):
core.quit()
self.assertIsNone(core.shares)
@classmethod
def tearDownClass(cls):
shutil.rmtree(DATA_FOLDER_PATH)
def test_shares_scan(self):
"""Test a full shares scan."""
# Verify that modification times were saved
public_mtimes = list(core.shares.share_dbs["public_mtimes"])
buddy_mtimes = list(core.shares.share_dbs["buddy_mtimes"])
trusted_mtimes = list(core.shares.share_dbs["trusted_mtimes"])
self.assertIn(os.path.join(SHARES_FOLDER_PATH, "dummy_file"), public_mtimes)
self.assertIn(os.path.join(SHARES_FOLDER_PATH, "audiofile.wav"), public_mtimes)
self.assertIn(os.path.join(BUDDY_SHARES_FOLDER_PATH, "audiofile2.wav"), buddy_mtimes)
self.assertIn(os.path.join(BUDDY_SHARES_FOLDER_PATH, "something2", "nothing2"), buddy_mtimes)
self.assertIn(os.path.join(TRUSTED_SHARES_FOLDER_PATH, "audiofile3.wav"), trusted_mtimes)
self.assertIn(os.path.join(TRUSTED_SHARES_FOLDER_PATH, "folder", "folder2", "folder3", "folder4", "nothing"),
trusted_mtimes)
# Verify that shared files were added
public_files = core.shares.share_dbs["public_files"]
buddy_files = core.shares.share_dbs["buddy_files"]
trusted_files = core.shares.share_dbs["trusted_files"]
self.assertEqual(
["Shares\\dummy_file", 0, None, None],
public_files[os.path.join(SHARES_FOLDER_PATH, "dummy_file")]
)
self.assertEqual(
["Shares\\audiofile.wav", 100044, (706, 0, 44100, 16), 1],
public_files[os.path.join(SHARES_FOLDER_PATH, "audiofile.wav")]
)
self.assertEqual(
["Secrets\\audiofile2.wav", 300044, (706, 0, 44100, 16), 3],
buddy_files[os.path.join(BUDDY_SHARES_FOLDER_PATH, "audiofile2.wav")]
)
self.assertEqual(
["Secrets\\something2\\nothing2", 0, None, None],
buddy_files[os.path.join(BUDDY_SHARES_FOLDER_PATH, "something2", "nothing2")]
)
self.assertEqual(
["Trusted\\audiofile3.wav", 400044, (706, 0, 44100, 16), 4],
trusted_files[os.path.join(TRUSTED_SHARES_FOLDER_PATH, "audiofile3.wav")]
)
# Verify that expected folders are empty
self.assertEqual(core.shares.share_dbs["public_streams"]["Shares\\folder2"], b"\x00\x00\x00\x00")
self.assertEqual(core.shares.share_dbs["buddy_streams"]["Secrets\\folder3"], b"\x00\x00\x00\x00")
self.assertEqual(core.shares.share_dbs["trusted_streams"]["Trusted\\folder\\folder2"], b"\x00\x00\x00\x00")
# Verify that search index was updated
word_index = core.shares.share_dbs["words"]
audiofile_indexes = list(word_index["audiofile"])
audiofile2_indexes = list(word_index["audiofile2"])
audiofile3_indexes = list(word_index["audiofile3"])
wav_indexes = list(word_index["wav"])
self.assertEqual(set(word_index), {
"wav", "folder2", "nothing2", "trusted", "nothing", "folder3", "dummy",
"test", "file3", "folder", "file", "folder4", "secrets", "test2",
"something", "something2", "file2", "audiofile", "somefile",
"audiofile2", "txt", "folder1", "buddies", "audiofile3", "shares"
})
self.assertEqual(len(audiofile_indexes), 1)
self.assertEqual(len(audiofile2_indexes), 1)
self.assertEqual(len(audiofile3_indexes), 1)
self.assertEqual(len(wav_indexes), 3)
# File ID associated with word "wav" should return our audiofile files
self.assertIn(wav_indexes[0], audiofile_indexes)
self.assertIn(wav_indexes[1], audiofile2_indexes)
self.assertIn(wav_indexes[2], audiofile3_indexes)
self.assertEqual(
core.shares.share_dbs["public_files"][core.shares.file_path_index[wav_indexes[0]]][0],
"Shares\\audiofile.wav"
)
self.assertEqual(
core.shares.share_dbs["buddy_files"][core.shares.file_path_index[wav_indexes[1]]][0],
"Secrets\\audiofile2.wav"
)
self.assertEqual(
core.shares.share_dbs["trusted_files"][core.shares.file_path_index[wav_indexes[2]]][0],
"Trusted\\audiofile3.wav"
)
def test_hidden_file_folder_scan(self):
"""Test that hidden files and folders are excluded."""
# Check modification times
public_mtimes = list(core.shares.share_dbs["public_mtimes"])
buddy_mtimes = list(core.shares.share_dbs["buddy_mtimes"])
trusted_mtimes = list(core.shares.share_dbs["trusted_mtimes"])
self.assertNotIn(os.path.join(SHARES_FOLDER_PATH, ".abc", "nothing"), public_mtimes)
self.assertNotIn(os.path.join(SHARES_FOLDER_PATH, ".xyz", "nothing"), public_mtimes)
self.assertIn(os.path.join(SHARES_FOLDER_PATH, "folder1", "nothing"), public_mtimes)
self.assertIn(os.path.join(SHARES_FOLDER_PATH, "folder2", "test", "nothing"), public_mtimes)
self.assertNotIn(os.path.join(SHARES_FOLDER_PATH, "folder2", ".poof", "nothing"), public_mtimes)
self.assertIn(os.path.join(SHARES_FOLDER_PATH, "folder2", "test", "nothing"), public_mtimes)
self.assertIn(os.path.join(SHARES_FOLDER_PATH, "something", "nothing"), public_mtimes)
self.assertNotIn(os.path.join(BUDDY_SHARES_FOLDER_PATH, "folder3", ".poof2", "nothing2"), buddy_mtimes)
self.assertIn(os.path.join(BUDDY_SHARES_FOLDER_PATH, "folder3", "test2", "nothing2"), buddy_mtimes)
self.assertNotIn(os.path.join(INVALID_SHARES_FOLDER_PATH, "file.txt"), buddy_mtimes)
self.assertNotIn(os.path.join(TRUSTED_SHARES_FOLDER_PATH, ".hidden_folder", "nothing"), trusted_mtimes)
self.assertIn(os.path.join(TRUSTED_SHARES_FOLDER_PATH, "folder", "folder2", "folder3", "folder4", "nothing"),
trusted_mtimes)
# Check file data
public_files = core.shares.share_dbs["public_files"]
buddy_files = core.shares.share_dbs["buddy_files"]
trusted_files = core.shares.share_dbs["trusted_files"]
self.assertNotIn(os.path.join(SHARES_FOLDER_PATH, ".abc_file"), public_files)
self.assertNotIn(os.path.join(SHARES_FOLDER_PATH, ".hidden_file"), public_files)
self.assertNotIn(os.path.join(SHARES_FOLDER_PATH, ".xyz_file"), public_files)
self.assertIn(os.path.join(SHARES_FOLDER_PATH, "dummy_file"), public_files)
self.assertEqual(len(public_files), 5)
self.assertNotIn(os.path.join(BUDDY_SHARES_FOLDER_PATH, ".uvw_file"), buddy_files)
self.assertIn(os.path.join(BUDDY_SHARES_FOLDER_PATH, "dummy_file2"), buddy_files)
self.assertEqual(len(buddy_files), 6)
self.assertNotIn(os.path.join(TRUSTED_SHARES_FOLDER_PATH, ".hidden_folder", "nothing"), trusted_files)
self.assertIn(os.path.join(TRUSTED_SHARES_FOLDER_PATH, "dummy_file3"), trusted_files)
self.assertEqual(len(trusted_files), 3)
| 10,453 | Python | .py | 180 | 49.505556 | 119 | 0.661197 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,420 | test_config.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/config/test_config.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
from unittest import TestCase
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.utils import encode_path
CURRENT_FOLDER_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_FOLDER_PATH = os.path.join(CURRENT_FOLDER_PATH, "temp_data")
class ConfigTest(TestCase):
def setUp(self):
config.set_data_folder(DATA_FOLDER_PATH)
config.set_config_file(os.path.join(DATA_FOLDER_PATH, "temp_config"))
default_config_path = os.path.join(CURRENT_FOLDER_PATH, "config")
if not os.path.exists(DATA_FOLDER_PATH):
os.makedirs(DATA_FOLDER_PATH)
shutil.copy(default_config_path, config.config_file_path)
core.init_components(enabled_components={})
def tearDown(self):
core.quit()
self.assertTrue(config.sections)
@classmethod
def tearDownClass(cls):
shutil.rmtree(DATA_FOLDER_PATH)
def test_load_config(self):
"""Test loading a config file."""
self.assertEqual(config.defaults["server"]["login"], "")
self.assertEqual(config.defaults["server"]["passw"], "")
self.assertEqual(config.sections["server"]["login"], "user123")
self.assertEqual(config.sections["server"]["passw"], "pass123")
self.assertEqual(config.sections["server"]["autoreply"], "ääääääää")
def test_write_config(self):
"""Test writing to a config file."""
# Verify that changes are saved
config.sections["server"]["login"] = "newname"
config.write_configuration()
with open(encode_path(config.config_file_path), encoding="utf-8") as file_handle:
self.assertIn("newname", file_handle.read())
# Verify that the backup is valid
old_config = encode_path(f"{config.config_file_path}.old")
self.assertTrue(os.path.exists(old_config))
with open(old_config, encoding="utf-8") as file_handle:
self.assertIn("user123", file_handle.read())
# Reset
config.sections["server"]["login"] = "user123"
config.write_configuration()
| 2,873 | Python | .py | 62 | 40.403226 | 89 | 0.700467 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,421 | test_country.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/networkfilter/test_country.py | # COPYRIGHT (C) 2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
from unittest import TestCase
from pynicotine.config import config
from pynicotine.core import core
DATA_FOLDER_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp_data")
MAX_IPV4_RANGE = 4294967295
class CountryTest(TestCase):
# pylint: disable=protected-access
def setUp(self):
config.set_data_folder(DATA_FOLDER_PATH)
config.set_config_file(os.path.join(DATA_FOLDER_PATH, "temp_config"))
core.init_components(enabled_components={"network_filter"})
core.network_filter._populate_ip_country_data()
def tearDown(self):
core.quit()
self.assertIsNone(core.network_filter)
@classmethod
def tearDownClass(cls):
shutil.rmtree(DATA_FOLDER_PATH)
def test_ip_country_data_structure(self):
"""Verify that IP country data structure is valid."""
self.assertTrue(core.network_filter._ip_range_countries)
self.assertTrue(core.network_filter._ip_range_values)
self.assertEqual(len(core.network_filter._ip_range_countries), len(core.network_filter._ip_range_values))
self.assertTrue(all(isinstance(item, str) for item in core.network_filter._ip_range_countries))
self.assertTrue(all(len(item) == 2 or not item for item in core.network_filter._ip_range_countries))
self.assertTrue(all(isinstance(item, int) for item in core.network_filter._ip_range_values))
self.assertTrue(all(0 <= item <= MAX_IPV4_RANGE for item in core.network_filter._ip_range_values))
def test_read_ip_country(self):
"""Test reading country codes at IP range boundaries."""
for ip_address, country_code in (
("0.255.255.255", ""),
("1.0.0.0", "US"),
("1.0.0.255", "US"),
("1.0.1.0", "CN"),
("1.255.255.255", "KR"),
("2.0.0.0", "GB"),
("4.255.255.255", "US"),
("5.0.0.0", "SY"),
("9.255.255.255", "US"),
("10.0.0.0", ""),
("13.255.255.255", "US"),
("14.0.0.0", "CN")
):
self.assertEqual(core.network_filter.get_country_code(ip_address), country_code)
| 2,936 | Python | .py | 63 | 40.095238 | 113 | 0.667484 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,422 | test_get_upload_candidate.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/transfers/test_get_upload_candidate.py | # COPYRIGHT (C) 2022-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
from unittest import TestCase
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.transfers import Transfer
from pynicotine.slskmessages import increment_token
from pynicotine.slskmessages import initial_token
DATA_FOLDER_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp_data")
NUM_ALLOWED_NONE = 2
class GetUploadCandidateTest(TestCase):
# pylint: disable=protected-access
def setUp(self):
self.token = initial_token()
config.set_data_folder(DATA_FOLDER_PATH)
config.set_config_file(os.path.join(DATA_FOLDER_PATH, "temp_config"))
core.init_components(enabled_components={
"users", "pluginhandler", "shares", "statistics", "uploads", "buddies"}
)
core.start()
core.users.privileged = {"puser1", "puser2"}
core.uploads.transfers.clear()
def tearDown(self):
core.quit()
self.assertIsNone(core.users)
self.assertIsNone(core.pluginhandler)
self.assertIsNone(core.shares)
self.assertIsNone(core.statistics)
self.assertIsNone(core.uploads)
self.assertIsNone(core.buddies)
@classmethod
def tearDownClass(cls):
shutil.rmtree(DATA_FOLDER_PATH)
def add_transfers(self, users, is_active=False):
transfer_list = []
for username in users:
virtual_path = f"{username}/{len(core.uploads.transfers)}"
transfer = Transfer(username, virtual_path)
if is_active:
core.uploads._activate_transfer(transfer, self.token)
self.token = increment_token(self.token)
else:
core.uploads._enqueue_transfer(transfer)
transfer_list.append(transfer)
core.uploads._append_transfer(transfer)
core.uploads._update_transfer(transfer)
return transfer_list
def set_finished(self, transfer):
core.uploads._finish_transfer(transfer)
core.uploads._clear_transfer(transfer)
def consume_transfers(self, queued, in_progress, clear_first=False):
"""Call core.uploads.get_upload_candidate until no uploads are left.
Transfers should be added to core.uploads in the desired starting
states already.
One in progress upload will be removed each time get_upload_candidate
is called.
`queued` and `in_progress` should contain the transfers in those states.
`clear_first` indicates whether the upload candidate should be
generated after the in progress upload is marked finished or before.
All candidates received are returned in a list.
"""
candidates = []
none_count = 0 # prevent infinite loop in case of bug or bad test setup
while len(core.uploads.transfers) > 0 and none_count < NUM_ALLOWED_NONE:
# "finish" one in progress transfer, if any
if clear_first and in_progress:
self.set_finished(in_progress.pop(0))
candidate, _has_active_uploads = core.uploads._get_upload_candidate()
if not clear_first and in_progress:
self.set_finished(in_progress.pop(0))
if not candidate:
none_count += 1
candidates.append(None)
continue
none_count = 0
queued.remove(candidate)
core.uploads._dequeue_transfer(candidate)
candidates.append(candidate)
in_progress.append(candidate)
core.uploads._activate_transfer(candidate, self.token)
self.token = increment_token(self.token)
return candidates
def base_test(self, queued, in_progress, expected, round_robin=False, clear_first=False):
config.sections["transfers"]["fifoqueue"] = not round_robin
queued_transfers = self.add_transfers(queued)
in_progress_transfers = self.add_transfers(in_progress, is_active=True)
candidates = self.consume_transfers(queued_transfers, in_progress_transfers, clear_first=clear_first)
users = [transfer.username if transfer else None for transfer in candidates]
# `expected` should contain `None` in cases where there aren't
# expected to be any queued users without existing in progress uploads
self.assertEqual(users, expected)
def test_round_robin_basic(self):
self.base_test(
queued=[
"user1",
"user1",
"user2",
"user2",
"user3",
"user3"
],
in_progress=[],
expected=[
"user1",
"user2",
"user3",
"user1",
"user2",
"user3",
None
],
round_robin=True
)
def test_round_robin_no_contention(self):
self.base_test(
queued=[
"user1",
"user1",
"user2",
"user2",
"user3",
"user3"
],
in_progress=[],
expected=[
"user1",
"user2",
"user3",
"user1",
"user2",
"user3",
None
],
round_robin=True,
clear_first=True
)
def test_round_robin_one_user(self):
self.base_test(
queued=[
"user1",
"user1"
],
in_progress=[],
expected=[
"user1",
None,
"user1",
None
],
round_robin=True
)
def test_round_robin_returning_user(self):
self.base_test(
queued=[
"user1",
"user1",
"user2",
"user2",
"user2",
"user3",
"user3",
"user3",
"user1",
"user1"
],
in_progress=[],
expected=[
"user1",
"user2",
"user3",
"user1",
"user2",
"user3",
"user1",
"user2",
"user3",
"user1",
None
],
round_robin=True
)
def test_round_robin_in_progress(self):
self.base_test(
queued=[
"user1",
"user1",
"user2",
"user2"
],
in_progress=[
"user1"
],
expected=[
"user2",
"user1",
"user2",
"user1",
None
],
round_robin=True
)
def test_round_robin_privileged(self):
self.base_test(
queued=[
"user1",
"user2",
"puser1",
"puser1",
"puser2"
],
in_progress=[],
expected=[
"puser1",
"puser2",
"puser1",
"user1",
"user2",
None
],
round_robin=True
)
def test_fifo_basic(self):
self.base_test(
queued=[
"user1",
"user1",
"user2",
"user2",
"user3",
"user3"
],
in_progress=[],
expected=[
"user1",
"user2",
"user1",
"user2",
"user3",
None,
"user3",
None
]
)
def test_fifo_robin_no_contention(self):
self.base_test(
queued=[
"user1",
"user1",
"user2",
"user2",
"user3",
"user3"
],
in_progress=[],
expected=[
"user1",
"user1",
"user2",
"user2",
"user3",
"user3",
None
],
clear_first=True
)
def test_fifo_one_user(self):
self.base_test(
queued=[
"user1",
"user1"
],
in_progress=[],
expected=[
"user1",
None,
"user1",
None
]
)
def test_fifo_returning_user(self):
self.base_test(
queued=[
"user1",
"user1",
"user2",
"user2",
"user2",
"user3",
"user3",
"user3",
"user1",
"user1"
],
in_progress=[],
expected=[
"user1",
"user2",
"user1",
"user2",
"user3",
"user2",
"user3",
"user1",
"user3",
"user1",
None
]
)
def test_fifo_in_progress(self):
self.base_test(
queued=[
"user1",
"user1",
"user2",
"user2"
],
in_progress=[
"user1"
],
expected=[
"user2",
"user1",
"user2",
"user1",
None
]
)
def test_fifo_privileged(self):
self.base_test(
queued=[
"user1",
"user2",
"puser1",
"puser1",
"puser2"
],
in_progress=[],
expected=[
"puser1",
"puser2",
"puser1",
"user1",
"user2",
None
]
)
| 11,221 | Python | .py | 363 | 18.118457 | 109 | 0.468533 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,423 | test_downloads.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/transfers/test_downloads.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
from unittest import TestCase
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.downloads import RequestedFolder
from pynicotine.slskmessages import FileAttribute
from pynicotine.transfers import TransferStatus
from pynicotine.userbrowse import BrowsedUser
CURRENT_FOLDER_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_FOLDER_PATH = os.path.join(CURRENT_FOLDER_PATH, "temp_data")
TRANSFERS_BASENAME = "downloads.json"
TRANSFERS_FILE_PATH = os.path.join(CURRENT_FOLDER_PATH, TRANSFERS_BASENAME)
SAVED_TRANSFERS_FILE_PATH = os.path.join(DATA_FOLDER_PATH, TRANSFERS_BASENAME)
class DownloadsTest(TestCase):
# pylint: disable=protected-access
def setUp(self):
config.set_data_folder(DATA_FOLDER_PATH)
config.set_config_file(os.path.join(DATA_FOLDER_PATH, "temp_config"))
if not os.path.exists(DATA_FOLDER_PATH):
os.makedirs(DATA_FOLDER_PATH)
shutil.copy(TRANSFERS_FILE_PATH, os.path.join(DATA_FOLDER_PATH, TRANSFERS_BASENAME))
core.init_components(enabled_components={"users", "downloads", "userbrowse"})
config.sections["transfers"]["downloaddir"] = DATA_FOLDER_PATH
config.sections["transfers"]["incompletedir"] = DATA_FOLDER_PATH
core.start()
def tearDown(self):
core.quit()
self.assertIsNone(core.users)
self.assertIsNone(core.downloads)
self.assertIsNone(core.userbrowse)
self.assertIsNone(core.buddies)
@classmethod
def tearDownClass(cls):
shutil.rmtree(DATA_FOLDER_PATH)
def test_load_downloads(self):
"""Test loading a downloads.json file."""
transfers = list(core.downloads.transfers.values())
self.assertEqual(len(transfers), 17)
transfer = transfers[16]
self.assertEqual(transfer.username, "user17")
self.assertEqual(transfer.virtual_path, "Downloaded\\Song17.mp3")
self.assertEqual(transfer.status, TransferStatus.USER_LOGGED_OFF)
self.assertEqual(transfer.size, 0)
self.assertIsNone(transfer.current_byte_offset)
self.assertFalse(transfer.file_attributes)
transfer = transfers[0]
self.assertEqual(transfer.username, "user1")
self.assertEqual(transfer.virtual_path, "Downloaded\\Song1.mp3")
self.assertEqual(transfer.status, TransferStatus.PAUSED)
self.assertEqual(transfer.size, 10093741)
self.assertEqual(transfer.current_byte_offset, 5000)
self.assertEqual(transfer.file_attributes, {
FileAttribute.BITRATE: 320,
FileAttribute.DURATION: 252
})
# File attribute dictionary represented as string (downgrade from >=3.3.0 to earlier and upgrade again)
self.assertEqual(transfers[15].file_attributes, {
FileAttribute.BITRATE: 256,
FileAttribute.DURATION: 476
})
# Legacy bitrate/duration strings (Nicotine+ <3.3.0)
self.assertEqual(transfers[14].file_attributes, {
FileAttribute.BITRATE: 128,
FileAttribute.DURATION: 290
})
# Legacy bitrate/duration strings (vbr) (Nicotine+ <3.3.0)
self.assertEqual(transfers[13].file_attributes, {
FileAttribute.BITRATE: 238,
FileAttribute.VBR: 1,
FileAttribute.DURATION: 173
})
# Empty legacy bitrate/duration strings (Nicotine+ <3.3.0)
self.assertFalse(transfers[12].file_attributes)
def test_save_downloads(self):
"""Verify that the order of the download list at the end of the session
is identical to the one we loaded.
Ignore the last four transfers, since their missing properties
will be added at the end of the session.
"""
old_transfers = core.downloads._load_transfers_file(TRANSFERS_FILE_PATH)[:12]
core.downloads._save_transfers()
saved_transfers = core.downloads._load_transfers_file(SAVED_TRANSFERS_FILE_PATH)[:12]
self.assertEqual(old_transfers, saved_transfers)
def test_queue_download(self):
"""Verify that new downloads are prepended to the list."""
config.sections["transfers"]["usernamesubfolders"] = False
core.downloads.enqueue_download("newuser", "Hello\\Path\\File.mp3", "")
transfer = list(core.downloads.transfers.values())[-1]
self.assertEqual(transfer.username, "newuser")
self.assertEqual(transfer.virtual_path, "Hello\\Path\\File.mp3")
self.assertEqual(transfer.folder_path, config.data_folder_path)
def test_long_basename(self):
"""Verify that the basename in download paths doesn't exceed 255 bytes.
The basename can be shorter than 255 bytes when a truncated
multi-byte character is discarded.
"""
username = "abc"
finished_folder_path = os.path.join(os.sep, "path", "to", "somewhere", "downloads")
# Short file extension
virtual_path = ("Music\\Test\\片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片"
"片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片"
"片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片.mp3")
incomplete_file_path = core.downloads.get_incomplete_download_file_path(username, virtual_path)
incomplete_basename = os.path.basename(incomplete_file_path)
self.assertLess(
len(incomplete_basename.encode()),
core.downloads.get_basename_byte_limit(config.data_folder_path)
)
self.assertTrue(incomplete_basename.startswith("INCOMPLETE42d26e9276e024cdaeac645438912b88"))
self.assertTrue(incomplete_basename.endswith(".mp3"))
# Long file extension
virtual_path = ("Music\\Test\\abc123456.片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片"
"片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片"
"片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片")
incomplete_file_path = core.downloads.get_incomplete_download_file_path(username, virtual_path)
incomplete_basename = os.path.basename(incomplete_file_path)
self.assertLess(
len(incomplete_basename.encode()),
core.downloads.get_basename_byte_limit(config.data_folder_path)
)
self.assertTrue(incomplete_basename.startswith("INCOMPLETEf98e3f07a3fc60e114534045f26707d2."))
self.assertTrue(incomplete_basename.endswith("片"))
# Finished download
basename = ("片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片"
"片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片"
"片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片.mp3")
finished_basename = core.downloads.get_download_basename(basename, finished_folder_path)
self.assertLess(
len(finished_basename.encode()),
core.downloads.get_basename_byte_limit(config.data_folder_path)
)
self.assertTrue(finished_basename.startswith("片"))
self.assertTrue(finished_basename.endswith(".mp3"))
basename = ("abc123456.片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片"
"片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片"
"片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片片")
finished_basename = core.downloads.get_download_basename(basename, finished_folder_path)
self.assertLess(
len(finished_basename.encode()),
core.downloads.get_basename_byte_limit(config.data_folder_path)
)
self.assertTrue(finished_basename.startswith(".片"))
self.assertTrue(finished_basename.endswith("片"))
def test_download_folder_destination(self):
"""Verify that the correct download destination is used."""
username = "newuser"
folder_path = "Hello\\Path"
config.sections["transfers"]["usernamesubfolders"] = False
destination_default = core.downloads.get_folder_destination(username, folder_path)
core.downloads._requested_folders[username][folder_path] = RequestedFolder(
username=username, folder_path=folder_path, download_folder_path="test"
)
destination_custom = core.downloads.get_folder_destination(username, folder_path)
core.downloads._requested_folders.clear()
destination_custom_second = core.downloads.get_folder_destination(
username, folder_path, download_folder_path="test2")
config.sections["transfers"]["usernamesubfolders"] = True
destination_user = core.downloads.get_folder_destination(username, folder_path)
folder_path = "Hello"
destination_root = core.downloads.get_folder_destination(username, folder_path)
folder_path = "Hello\\Path\\Depth\\Test"
destination_depth = core.downloads.get_folder_destination(username, folder_path)
self.assertEqual(destination_default, os.path.join(config.data_folder_path, "Path"))
self.assertEqual(destination_custom, os.path.join("test", "Path"))
self.assertEqual(destination_custom_second, os.path.join("test2", "Path"))
self.assertEqual(destination_user, os.path.join(config.data_folder_path, "newuser", "Path"))
self.assertEqual(destination_root, os.path.join(config.data_folder_path, "newuser", "Hello"))
self.assertEqual(destination_depth, os.path.join(config.data_folder_path, "newuser", "Test"))
def test_download_subfolders(self):
"""Verify that subfolders are downloaded to the correct location."""
username = "random"
browsed_user = core.userbrowse.users[username] = BrowsedUser(username)
browsed_user.public_folders = dict([
("share", [
(1, "root1.mp3", 1000, "", {})
]),
("share\\Music", [
(1, "music1.mp3", 1000000, "", {}),
(1, "music2.mp3", 2000000, "", {})
]),
("share\\Soulseek", [
(1, "file1.mp3", 3000000, "", {}),
(1, "file2.mp3", 4000000, "", {})
]),
("share\\Soulseek\\folder1", [
(1, "file3.mp3", 5000000, "", {})
]),
("share\\Soulseek\\folder1\\sub1", [
(1, "file4.mp3", 6000000, "", {})
]),
("share\\Soulseek\\folder2", [
(1, "file5.mp3", 7000000, "", {})
]),
("share\\Soulseek\\folder2\\sub2", [
(1, "file6.mp3", 8000000, "", {})
]),
("share\\SoulseekSecond", [
(1, "file7.mp3", 9000000, "", {}),
(1, "file8.mp3", 10000000, "", {})
])
])
# Share root
target_folder_path = "share"
core.downloads.transfers.clear()
core.userbrowse.download_folder(username, target_folder_path, download_folder_path="test", recurse=True)
transfers = list(core.downloads.transfers.values())
self.assertEqual(len(transfers), 11)
self.assertEqual(transfers[10].folder_path, os.path.join("test", "share", "SoulseekSecond"))
self.assertEqual(transfers[9].folder_path, os.path.join("test", "share", "SoulseekSecond"))
self.assertEqual(transfers[8].folder_path, os.path.join("test", "share", "Soulseek", "folder2", "sub2"))
self.assertEqual(transfers[7].folder_path, os.path.join("test", "share", "Soulseek", "folder2"))
self.assertEqual(transfers[6].folder_path, os.path.join("test", "share", "Soulseek", "folder1", "sub1"))
self.assertEqual(transfers[5].folder_path, os.path.join("test", "share", "Soulseek", "folder1"))
self.assertEqual(transfers[4].folder_path, os.path.join("test", "share", "Soulseek"))
self.assertEqual(transfers[3].folder_path, os.path.join("test", "share", "Soulseek"))
self.assertEqual(transfers[2].folder_path, os.path.join("test", "share", "Music"))
self.assertEqual(transfers[1].folder_path, os.path.join("test", "share", "Music"))
self.assertEqual(transfers[0].folder_path, os.path.join("test", "share"))
# Share subfolder
target_folder_path = "share\\Soulseek"
core.downloads.transfers.clear()
core.userbrowse.download_folder(username, target_folder_path, download_folder_path="test2", recurse=True)
transfers = list(core.downloads.transfers.values())
self.assertEqual(len(transfers), 6)
self.assertEqual(transfers[5].folder_path, os.path.join("test2", "Soulseek", "folder2", "sub2"))
self.assertEqual(transfers[4].folder_path, os.path.join("test2", "Soulseek", "folder2"))
self.assertEqual(transfers[3].folder_path, os.path.join("test2", "Soulseek", "folder1", "sub1"))
self.assertEqual(transfers[2].folder_path, os.path.join("test2", "Soulseek", "folder1"))
self.assertEqual(transfers[1].folder_path, os.path.join("test2", "Soulseek"))
self.assertEqual(transfers[0].folder_path, os.path.join("test2", "Soulseek"))
def test_delete_stale_incomplete_downloads(self):
"""Verify that only files matching the pattern for incomplete downloads are deleted."""
file_names = (
("test_file.txt", True),
("test_file.mp3", True),
("INCOMPLETEsomefilename.mp3", True),
("INCOMPLETE435ed7e9f07f740abf511a62c00eef6e", True),
("INCOMPLETE435ed7e9f07f740abf511a62c00eef6efile.mp3", False)
)
for basename, _exists in file_names:
file_path = os.path.join(DATA_FOLDER_PATH, basename)
with open(file_path, "wb"):
pass
self.assertTrue(os.path.isfile(file_path))
core.downloads._delete_stale_incomplete_downloads()
for basename, exists in file_names:
self.assertEqual(os.path.isfile(os.path.join(DATA_FOLDER_PATH, basename)), exists)
| 15,821 | Python | .py | 265 | 45.860377 | 113 | 0.668385 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,424 | test_uploads.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/transfers/test_uploads.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
from unittest import TestCase
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.slskmessages import FileAttribute
from pynicotine.transfers import TransferStatus
CURRENT_FOLDER_PATH = os.path.dirname(os.path.realpath(__file__))
DATA_FOLDER_PATH = os.path.join(CURRENT_FOLDER_PATH, "temp_data")
TRANSFERS_BASENAME = "uploads.json"
TRANSFERS_FILE_PATH = os.path.join(CURRENT_FOLDER_PATH, TRANSFERS_BASENAME)
SAVED_TRANSFERS_FILE_PATH = os.path.join(DATA_FOLDER_PATH, TRANSFERS_BASENAME)
class UploadsTest(TestCase):
# pylint: disable=protected-access
def setUp(self):
config.set_data_folder(DATA_FOLDER_PATH)
config.set_config_file(os.path.join(DATA_FOLDER_PATH, "temp_config"))
if not os.path.exists(DATA_FOLDER_PATH):
os.makedirs(DATA_FOLDER_PATH)
shutil.copy(TRANSFERS_FILE_PATH, os.path.join(DATA_FOLDER_PATH, TRANSFERS_BASENAME))
core.init_components(enabled_components={"users", "shares", "uploads", "buddies"})
core.start()
def tearDown(self):
core.quit()
self.assertIsNone(core.users)
self.assertIsNone(core.shares)
self.assertIsNone(core.uploads)
self.assertIsNone(core.userbrowse)
self.assertIsNone(core.buddies)
@classmethod
def tearDownClass(cls):
shutil.rmtree(DATA_FOLDER_PATH)
def test_load_uploads(self):
"""Test loading a uploads.json file."""
transfers = list(core.uploads.transfers.values())
# Only finished uploads are loaded, other types should never be stored
self.assertEqual(len(transfers), 3)
transfer = transfers[2]
self.assertEqual(transfer.username, "user5")
self.assertEqual(transfer.virtual_path, "Junk\\Song5.mp3")
self.assertEqual(transfer.status, TransferStatus.FINISHED)
self.assertEqual(transfer.size, 11733776)
self.assertEqual(transfer.current_byte_offset, 11733776)
self.assertFalse(transfer.file_attributes)
transfer = transfers[0]
self.assertEqual(transfer.username, "user3")
self.assertEqual(transfer.virtual_path, "Junk\\Song3.flac")
self.assertEqual(transfer.status, TransferStatus.FINISHED)
self.assertEqual(transfer.size, 27231044)
self.assertEqual(transfer.current_byte_offset, 27231044)
self.assertEqual(transfer.file_attributes, {
FileAttribute.BITRATE: 792,
FileAttribute.DURATION: 268
})
def test_save_uploads(self):
"""Verify that the order of the upload list at the end of the session
is identical to the one we loaded.
Ignore the first two unfinished uploads, since only finished uploads are
saved to file.
"""
old_transfers = core.uploads._load_transfers_file(TRANSFERS_FILE_PATH)[2:]
core.uploads._save_transfers()
saved_transfers = core.uploads._load_transfers_file(SAVED_TRANSFERS_FILE_PATH)
self.assertEqual(old_transfers, saved_transfers)
def test_push_upload(self):
"""Verify that non-existent files are not added to the list."""
core.uploads.enqueue_upload("newuser2", "Hello\\Upload\\File.mp3")
core.uploads.enqueue_upload("newuser99", "Home\\None.mp3")
self.assertEqual(len(core.uploads.transfers.values()), 3)
| 4,135 | Python | .py | 86 | 41.755814 | 92 | 0.72008 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,425 | test_slskmessages.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/protocol/test_slskmessages.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from unittest import TestCase
from pynicotine.slskmessages import AckNotifyPrivileges
from pynicotine.slskmessages import ChangePassword
from pynicotine.slskmessages import FileSearch
from pynicotine.slskmessages import GetPeerAddress
from pynicotine.slskmessages import GetUserStatus
from pynicotine.slskmessages import JoinGlobalRoom
from pynicotine.slskmessages import JoinRoom
from pynicotine.slskmessages import LeaveGlobalRoom
from pynicotine.slskmessages import Login
from pynicotine.slskmessages import NotifyPrivileges
from pynicotine.slskmessages import PrivateRoomAddUser
from pynicotine.slskmessages import PrivateRoomCancelMembership
from pynicotine.slskmessages import PrivateRoomDisown
from pynicotine.slskmessages import PrivateRoomRemoveUser
from pynicotine.slskmessages import PrivateRoomSomething
from pynicotine.slskmessages import SayChatroom
from pynicotine.slskmessages import SetStatus
from pynicotine.slskmessages import SetWaitPort
from pynicotine.slskmessages import SlskMessage
from pynicotine.slskmessages import UnwatchUser
from pynicotine.slskmessages import WatchUser
class SlskMessageTest(TestCase):
def test_pack_objects(self):
# Arrange
obj = SlskMessage()
# Act
boolean_message = obj.pack_bool(123)
unsigned_int8_message = obj.pack_uint8(123)
unsigned_int32_message = obj.pack_uint32(123)
signed_int32_message = obj.pack_int32(123)
unsigned_int64_message = obj.pack_uint64(123)
bytes_message = obj.pack_bytes(b"testbytes")
str_message = obj.pack_string("teststring")
# Assert
self.assertEqual(b"\x01", boolean_message)
self.assertEqual(b"\x7B", unsigned_int8_message)
self.assertEqual(b"\x7B\x00\x00\x00", unsigned_int32_message)
self.assertEqual(b"\x7B\x00\x00\x00", signed_int32_message)
self.assertEqual(b"\x7B\x00\x00\x00\x00\x00\x00\x00", unsigned_int64_message)
self.assertEqual(b"\t\x00\x00\x00testbytes", bytes_message)
self.assertEqual(b"\n\x00\x00\x00teststring", str_message)
class LoginMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = Login(username="test", passwd="s33cr3t", version=157, minorversion=19)
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
bytearray(b"\x04\x00\x00\x00test\x07\x00\x00\x00s33cr3t\x9d\x00\x00\x00 "
b"\x00\x00\x00dbc93f24d8f3f109deed23c3e2f8b74c\x13\x00\x00\x00"),
message)
class ChangePasswordMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = ChangePassword(password="s33cr3t")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x07\x00\x00\x00s33cr3t",
message)
class SetWaitPortMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = SetWaitPort(port=1337)
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"9\x05\x00\x00",
message)
class GetPeerAddressMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = GetPeerAddress(user="user1")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00user1",
message)
class WatchUserMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = WatchUser(user="user2")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00user2",
message)
class UnwatchUserMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = UnwatchUser(user="user3")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00user3",
message)
class GetUserStatusMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = GetUserStatus(user="user4")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00user4",
message)
class FileSearchTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = FileSearch(token=524700074, text="70 gwen auto")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\xaaIF\x1f\x0c\x00\x00\x0070 gwen auto",
message)
class SetStatusMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = SetStatus(status=1)
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x01\x00\x00\x00",
message)
class NotifyPrivilegesMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = NotifyPrivileges(token=123456, user="user5")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"@\xe2\x01\x00\x05\x00\x00\x00user5",
message)
class AckNotifyPrivilegesMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = AckNotifyPrivileges(token=123456)
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"@\xe2\x01\x00",
message)
class JoinGlobalRoomMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = JoinGlobalRoom()
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"",
message)
class LeaveGlobalRoomMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = LeaveGlobalRoom()
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"",
message)
class GlobalRoomMessageMessageTest(TestCase):
...
class SayChatroomMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = SayChatroom(room="room1", message="Wassup?")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00room1\x07\x00\x00\x00Wassup?",
message)
class JoinRoomMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = JoinRoom(room="room2", private=False)
obj_private = JoinRoom(room="room2", private=True)
# Act
message = obj.make_network_message()
message_private = obj_private.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00room2\x00\x00\x00\x00",
message)
self.assertEqual(
b"\x05\x00\x00\x00room2\x01\x00\x00\x00",
message_private)
class PrivateRoomUsersMessageTest(TestCase):
...
class PrivateRoomOwnedMessageTest(TestCase):
...
class PrivateRoomAddUserMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = PrivateRoomAddUser(room="room3", user="admin")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00room3\x05\x00\x00\x00admin",
message)
class PrivateRoomCancelMembershipMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = PrivateRoomCancelMembership(room="room4")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00room4",
message)
class PrivateRoomDisownMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = PrivateRoomDisown(room="room5")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00room5",
message)
class PrivateRoomSomethingMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = PrivateRoomSomething(room="room6")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00room6",
message)
class PrivateRoomRemoveUserMessageTest(TestCase):
def test_make_network_message(self):
# Arrange
obj = PrivateRoomRemoveUser(room="room7", user="admin")
# Act
message = obj.make_network_message()
# Assert
self.assertEqual(
b"\x05\x00\x00\x00room7\x05\x00\x00\x00admin",
message)
def test_parse_network_message(self):
# Arrange
message = b"\x05\x00\x00\x00room7\x05\x00\x00\x00admin"
# Act
obj = PrivateRoomRemoveUser()
obj.parse_network_message(memoryview(message))
# Assert
self.assertEqual("room7", obj.room)
self.assertEqual("admin", obj.user)
| 10,086 | Python | .py | 280 | 28.114286 | 87 | 0.662229 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,426 | test_slskproto.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/protocol/test_slskproto.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2020 Lene Preuss <lene.preuss@gmail.com>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import pickle
import selectors
import shutil
import socket
import sys
from time import sleep
from unittest import TestCase
from unittest.mock import MagicMock
from unittest.mock import Mock
from unittest.mock import patch
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.slskmessages import ServerConnect, SetWaitPort
from pynicotine.utils import encode_path
DATA_FOLDER_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp_data")
SLSKPROTO_RUN_TIME = 1.5 # Time (in s) needed for SoulseekNetworkThread main loop to run at least once
class MockSocket(Mock):
def __init__(self):
super().__init__()
self.events = None
def set_data(self, datafile):
windows_line_ending = b"\r\n"
unix_line_ending = b"\n"
file_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), datafile)
with open(encode_path(file_path), "rb") as file_handle:
content = file_handle.read()
content = content.replace(windows_line_ending, unix_line_ending)
logs = pickle.loads(content, encoding="bytes")
self.events = {}
for mode in b"send", b"recv":
for time, event in logs[b"transactions"][mode].items():
self.events[time] = (mode.decode("latin1"), event)
@staticmethod
def send(data):
print(f"sending data {data}")
@staticmethod
def recv(bufsize):
print(f"recving {bufsize} data")
return b""
class SoulseekNetworkTest(TestCase):
def setUp(self):
# Windows doesn't accept mock_socket in select() calls
selectors.DefaultSelector = MagicMock()
config.set_data_folder(DATA_FOLDER_PATH)
config.set_config_file(os.path.join(DATA_FOLDER_PATH, "temp_config"))
core.init_components(enabled_components={"network_thread"})
config.sections["server"]["upnp"] = False
core.start()
events.emit("enable-message-queue")
# Slight delay to allow the network thread to fully start
sleep(SLSKPROTO_RUN_TIME / 2)
def tearDown(self):
core.quit()
sleep(SLSKPROTO_RUN_TIME / 2)
events.process_thread_events()
self.assertIsNone(core.portmapper)
self.assertIsNone(core._network_thread) # pylint: disable=protected-access
@classmethod
def tearDownClass(cls):
shutil.rmtree(DATA_FOLDER_PATH)
@patch("socket.socket")
def test_server_conn(self, _mock_socket):
core.send_message_to_network_thread(
ServerConnect(addr=("0.0.0.0", 0), login=("dummy", "dummy"), listen_port=65525)
)
sleep(SLSKPROTO_RUN_TIME)
# pylint: disable=no-member,protected-access
sock = core._network_thread._server_conn.sock
if hasattr(socket, "TCP_KEEPIDLE") or hasattr(socket, "TCP_KEEPALIVE"):
if sys.platform == "win32":
self.assertEqual(sock.setsockopt.call_count, 9)
elif hasattr(socket, "TCP_USER_TIMEOUT"):
self.assertEqual(sock.setsockopt.call_count, 11)
else:
self.assertEqual(sock.setsockopt.call_count, 10)
elif hasattr(socket, "SIO_KEEPALIVE_VALS"):
self.assertEqual(sock.ioctl.call_count, 1)
self.assertEqual(sock.setsockopt.call_count, 6)
self.assertEqual(sock.setblocking.call_count, 2)
self.assertEqual(sock.connect_ex.call_count, 1)
def test_login(self):
core.send_message_to_network_thread(
ServerConnect(addr=("0.0.0.0", 0), login=("dummy", "dummy"), listen_port=65525)
)
sleep(SLSKPROTO_RUN_TIME / 2)
core.send_message_to_server(SetWaitPort(1))
sleep(SLSKPROTO_RUN_TIME)
| 4,623 | Python | .py | 107 | 36.523364 | 103 | 0.68387 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,427 | test_search.py | nicotine-plus_nicotine-plus/pynicotine/tests/unit/search/test_search.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
from collections import UserDict
from unittest import TestCase
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.shares import PermissionLevel
from pynicotine.slskmessages import increment_token
DATA_FOLDER_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp_data")
SEARCH_TEXT = '70 - * Gwen "test" "" -mp3 "what\'s up" don\'t -nothanks a:::b;c+d +++---}[ *ello [[ @@ auto -No yes'
SEARCH_MODE = "global"
class SearchTest(TestCase):
# pylint: disable=protected-access
def setUp(self):
config.set_data_folder(DATA_FOLDER_PATH)
config.set_config_file(os.path.join(DATA_FOLDER_PATH, "temp_config"))
core.init_components(enabled_components={"pluginhandler", "search", "shares"})
def tearDown(self):
core.quit()
self.assertIsNone(core.pluginhandler)
self.assertIsNone(core.search)
self.assertIsNone(core.shares)
@classmethod
def tearDownClass(cls):
shutil.rmtree(DATA_FOLDER_PATH)
def test_do_search(self):
"""Test the do_search function, including the outgoing search term and
search history."""
old_token = core.search.token
core.search.do_search(SEARCH_TEXT, SEARCH_MODE)
search = core.search.searches[core.search.token]
self.assertEqual(core.search.token, old_token + 1)
self.assertEqual(search.term, SEARCH_TEXT)
self.assertEqual(
search.term_sanitized, '70 Gwen "test" -mp3 "what\'s up" don t -nothanks a b c d *ello auto -No yes'
)
self.assertEqual(
search.term_transmitted, '70 Gwen test -mp3 what s up don t -nothanks a b c d *ello auto -No yes'
)
self.assertEqual(config.sections["searches"]["history"][0], search.term_sanitized)
self.assertIn("ello", search.included_words)
self.assertIn("gwen", search.included_words)
self.assertIn("what's up", search.included_words)
self.assertIn("don", search.included_words)
self.assertIn("t", search.included_words)
self.assertIn("no", search.excluded_words)
self.assertIn("mp3", search.excluded_words)
def test_search_token_increment(self):
"""Test that search token increments work properly."""
old_token = core.search.token
core.search.token = increment_token(core.search.token)
self.assertEqual(old_token, core.search.token - 1)
def test_wishlist_add(self):
"""Test that items are added to the wishlist properly."""
old_token = core.search.token
# First item
core.search.add_wish(SEARCH_TEXT)
search = core.search.searches[core.search.token]
self.assertEqual(config.sections["server"]["autosearch"][0], SEARCH_TEXT)
self.assertEqual(core.search.token, old_token + 1)
self.assertEqual(core.search.token, core.search.token)
self.assertEqual(search.term, SEARCH_TEXT)
self.assertEqual(search.mode, "wishlist")
self.assertTrue(search.is_ignored)
# Second item
new_item = f"{SEARCH_TEXT}1"
core.search.add_wish(new_item)
search = core.search.searches[core.search.token]
self.assertEqual(config.sections["server"]["autosearch"][0], SEARCH_TEXT)
self.assertEqual(config.sections["server"]["autosearch"][1], new_item)
self.assertEqual(search.term, new_item)
self.assertEqual(search.mode, "wishlist")
self.assertTrue(search.is_ignored)
def test_create_search_result_list(self):
"""Test creating search result lists from the word index."""
max_results = 1500
word_index = {
"iso": [34, 35, 36, 37, 38],
"lts": [63, 68, 73],
"system": [37, 38],
"linux": [35, 36]
}
included_words = {"iso"}
excluded_words = {"linux", "game"}
partial_words = {"stem"}
results = core.search._create_search_result_list(
included_words, excluded_words, partial_words, max_results, word_index)
self.assertEqual(results, {37, 38})
included_words = {"lts", "iso"}
excluded_words = {"linux", "game", "music", "cd"}
partial_words = set()
results = core.search._create_search_result_list(
included_words, excluded_words, partial_words, max_results, word_index)
self.assertIsNone(results)
included_words = {"iso"}
excluded_words = {"system"}
partial_words = {"ibberish"}
results = core.search._create_search_result_list(
included_words, excluded_words, partial_words, max_results, word_index)
self.assertIsNone(results)
def test_exclude_server_phrases(self):
"""Verify that results containing excluded phrases are not included."""
core.search.excluded_phrases = ["linux distro", "netbsd"]
results = {0, 1, 2, 3, 4, 5}
public_share_db = core.shares.share_dbs["public_files"] = UserDict({
"real\\isos\\freebsd.iso": ["virtual\\isos\\freebsd.iso", 1000, None, None],
"real\\isos\\linux.iso": ["virtual\\isos\\linux.iso", 2000, None, None],
"real\\isos\\linux distro.iso": ["virtual\\isos\\linux distro.iso", 3000, None, None],
"real\\isos\\Linux Distro.iso": ["virtual\\isos\\Linux Distro.iso", 4000, None, None],
"real\\isos\\NetBSD.iso": ["virtual\\isos\\NetBSD.iso", 5000, None, None],
"real\\isos\\openbsd.iso": ["virtual\\isos\\openbsd.iso", 6000, None, None]
})
core.shares.share_dbs["buddy_files"] = core.shares.share_dbs["trusted_files"] = UserDict()
core.shares.file_path_index = list(public_share_db)
for share_db in core.shares.share_dbs.values():
share_db.close = lambda: None
num_results, fileinfos, private_fileinfos = core.search._create_file_info_list(
results, max_results=100, permission_level=PermissionLevel.PUBLIC
)
self.assertEqual(num_results, 3)
self.assertEqual(fileinfos, [
["virtual\\isos\\freebsd.iso", 1000, None, None],
["virtual\\isos\\linux.iso", 2000, None, None],
["virtual\\isos\\openbsd.iso", 6000, None, None]
])
self.assertEqual(private_fileinfos, [])
| 7,114 | Python | .py | 143 | 41.811189 | 116 | 0.656182 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,428 | test_startup.py | nicotine-plus_nicotine-plus/pynicotine/tests/integration/test_startup.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import shutil
import subprocess
import sys
from unittest import TestCase
DATA_FOLDER_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)), "temp_data")
CONFIG_FILE = os.path.join(DATA_FOLDER_PATH, "temp_config")
class StartupTest(TestCase):
@classmethod
def tearDownClass(cls):
shutil.rmtree(DATA_FOLDER_PATH)
def test_gui_startup(self):
"""Verify that regular GUI startup works."""
command = [sys.executable, "-m", "pynicotine", f"--config={CONFIG_FILE}", f"--user-data={DATA_FOLDER_PATH}",
"--ci-mode"]
broadway_display = ":1000"
broadway_process = None
is_success = False
if sys.platform not in {"darwin", "win32"}:
# Display server is required, use GDK's Broadway backend if available.
# If not available, leave it up to the user to run the tests with e.g. xvfb-run.
# pylint: disable=consider-using-with
try:
broadway_process = subprocess.Popen(["gtk4-broadwayd", broadway_display])
except Exception:
try:
broadway_process = subprocess.Popen(["broadwayd", broadway_display])
except Exception:
pass
if broadway_process is not None:
os.environ["GDK_BACKEND"] = "broadway"
os.environ["BROADWAY_DISPLAY"] = broadway_display
with subprocess.Popen(command) as process:
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
is_success = True
process.terminate()
if broadway_process is not None:
broadway_process.terminate()
broadway_process.wait()
self.assertTrue(is_success)
def test_cli_startup(self):
"""Verify that regular CLI startup works."""
command = [sys.executable, "-m", "pynicotine", f"--config={CONFIG_FILE}", f"--user-data={DATA_FOLDER_PATH}",
"--ci-mode", "--headless"]
is_success = False
with subprocess.Popen(command) as process:
try:
process.wait(timeout=5)
except subprocess.TimeoutExpired:
is_success = True
process.terminate()
self.assertTrue(is_success)
def test_cli(self):
"""Verify that CLI-exclusive functionality works."""
output = subprocess.check_output([sys.executable, "-m", "pynicotine", "--help"], timeout=3)
self.assertIn(b"--help", output)
# Check for " 0 folders found after rescan" in output. Text strings are translatable,
# so we can't match them directly.
output = subprocess.check_output(
[sys.executable, "-m", "pynicotine", f"--config={CONFIG_FILE}", f"--user-data={DATA_FOLDER_PATH}",
"--rescan"],
timeout=10
)
self.assertIn(b" 0 ", output)
output = subprocess.check_output([sys.executable, "-m", "pynicotine", "--version"], timeout=3)
self.assertIn(b"Nicotine+", output)
| 3,857 | Python | .py | 85 | 36.505882 | 116 | 0.632942 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,429 | tinytag.py | nicotine-plus_nicotine-plus/pynicotine/external/tinytag.py | # tinytag - an audio meta info reader
# Copyright (c) 2014-2023 Tom Wallroth
# Copyright (c) 2021-2023 Mat (mathiascode)
#
# Sources on GitHub:
# http://github.com/tinytag/tinytag/
# MIT License
# Copyright (c) 2014-2023 Tom Wallroth, Mat (mathiascode)
# Copyright (c) 2020-2023 Nicotine+ Contributors
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
from __future__ import division, print_function
from collections import OrderedDict, defaultdict
try:
from collections.abc import MutableMapping
except ImportError:
from collections import MutableMapping
from functools import reduce
from io import BytesIO
import base64
import codecs
import io
import json
import operator
import os
import re
import struct
import sys
DEBUG = os.environ.get('DEBUG', False) # some of the parsers can print debug info
class TinyTagException(LookupError): # inherit LookupError for backwards compat
pass
def _read(fh, nbytes): # helper function to check if we haven't reached EOF
b = fh.read(nbytes)
if len(b) < nbytes:
raise TinyTagException('Unexpected end of file')
return b
def stderr(*args):
sys.stderr.write('%s\n' % ' '.join(repr(arg) for arg in args))
sys.stderr.flush()
def _bytes_to_int_le(b):
fmt = {1: '<B', 2: '<H', 4: '<I', 8: '<Q'}.get(len(b))
return struct.unpack(fmt, b)[0] if fmt is not None else 0
def _bytes_to_int(b):
return reduce(lambda accu, elem: (accu << 8) + elem, b, 0)
class TinyTag(object):
SUPPORTED_FILE_EXTENSIONS = [
'.mp1', '.mp2', '.mp3',
'.oga', '.ogg', '.opus', '.spx',
'.wav', '.flac', '.wma',
'.m4b', '.m4a', '.m4r', '.m4v', '.mp4', '.aax', '.aaxc',
'.aiff', '.aifc', '.aif', '.afc'
]
_file_extension_mapping = None
_magic_bytes_mapping = None
def __init__(self, filehandler, filesize, ignore_errors=False):
# This is required for compatibility between python2 and python3
# in python2 there is a difference between `str` and `unicode`
# whereas in python3 everything every string is `unicode` by default and
# the type `unicode` is deprecated
if type(filehandler).__name__ in ('str', 'unicode'):
raise Exception('Use `TinyTag.get(filepath)` instead of `TinyTag(filepath)`')
self._filehandler = filehandler
self._filename = None # for debugging purposes
self._default_encoding = None # allow override for some file formats
self.filesize = filesize
self.album = None
self.albumartist = None
self.artist = None
self.audio_offset = None
self.bitrate = None
self.channels = None
self.comment = None
self.composer = None
self.disc = None
self.disc_total = None
self.duration = None
self.extra = defaultdict(lambda: None)
self.genre = None
self.samplerate = None
self.bitdepth = None
self.title = None
self.track = None
self.track_total = None
self.year = None
self.is_vbr = False # Nicotine+ extension
self._parse_tags = True
self._load_image = False
self._image_data = None
self._ignore_errors = ignore_errors
def as_dict(self):
return {k: v for k, v in self.__dict__.items() if not k.startswith('_')}
@classmethod
def is_supported(cls, filename):
return cls._get_parser_for_filename(filename) is not None
def get_image(self):
return self._image_data
@classmethod
def _get_parser_for_filename(cls, filename):
if cls._file_extension_mapping is None:
cls._file_extension_mapping = {
(b'.mp1', b'.mp2', b'.mp3'): ID3,
(b'.oga', b'.ogg', b'.opus', b'.spx'): Ogg,
(b'.wav',): Wave,
(b'.flac',): Flac,
(b'.wma',): Wma,
(b'.m4b', b'.m4a', b'.m4r', b'.m4v', b'.mp4', b'.aax', b'.aaxc'): MP4,
(b'.aiff', b'.aifc', b'.aif', b'.afc'): Aiff,
}
if not isinstance(filename, bytes): # convert filename to binary
try:
filename = filename.encode('ASCII', errors='ignore')
except AttributeError:
filename = bytes(filename) # pathlib
filename = filename.lower()
for ext, tagclass in cls._file_extension_mapping.items():
if filename.endswith(ext):
return tagclass
@classmethod
def _get_parser_for_file_handle(cls, fh):
# https://en.wikipedia.org/wiki/List_of_file_signatures
if cls._magic_bytes_mapping is None:
cls._magic_bytes_mapping = {
b'^ID3': ID3,
b'^\xff\xfb': ID3,
b'^OggS.........................FLAC': Ogg,
b'^OggS........................Opus': Ogg,
b'^OggS........................Speex': Ogg,
b'^OggS.........................vorbis': Ogg,
b'^RIFF....WAVE': Wave,
b'^fLaC': Flac,
b'^\x30\x26\xB2\x75\x8E\x66\xCF\x11\xA6\xD9\x00\xAA\x00\x62\xCE\x6C': Wma,
b'....ftypM4A': MP4, # https://www.file-recovery.com/m4a-signature-format.htm
b'....ftypaax': MP4, # Audible proprietary M4A container
b'....ftypaaxc': MP4, # Audible proprietary M4A container
b'\xff\xf1': MP4, # https://www.garykessler.net/library/file_sigs.html
b'^FORM....AIFF': Aiff,
b'^FORM....AIFC': Aiff,
}
header = fh.peek(max(len(sig) for sig in cls._magic_bytes_mapping))
for magic, parser in cls._magic_bytes_mapping.items():
if re.match(magic, header):
return parser
@classmethod
def get_parser_class(cls, filename=None, filehandle=None):
if cls != TinyTag: # if `get` is invoked on TinyTag, find parser by ext
return cls # otherwise use the class on which `get` was invoked
if filename:
parser_class = cls._get_parser_for_filename(filename)
if parser_class is not None:
return parser_class
# try determining the file type by magic byte header
if filehandle:
parser_class = cls._get_parser_for_file_handle(filehandle)
if parser_class is not None:
return parser_class
raise TinyTagException('No tag reader found to support filetype! ')
@classmethod
def get(cls, filename=None, tags=True, duration=True, image=False,
ignore_errors=False, encoding=None, file_obj=None):
should_open_file = (file_obj is None)
if should_open_file:
file_obj = io.open(filename, 'rb')
elif isinstance(file_obj, io.BytesIO):
file_obj = io.BufferedReader(file_obj) # buffered reader to support peeking
try:
file_obj.seek(0, os.SEEK_END)
filesize = file_obj.tell()
file_obj.seek(0)
if filesize <= 0:
return TinyTag(None, filesize)
parser_class = cls.get_parser_class(filename, file_obj)
tag = parser_class(file_obj, filesize, ignore_errors=ignore_errors)
tag._filename = filename
tag._default_encoding = encoding
tag.load(tags=tags, duration=duration, image=image)
tag.extra = dict(tag.extra) # turn default dict into dict so that it can throw KeyError
return tag
finally:
if should_open_file:
file_obj.close()
def __str__(self):
return json.dumps(OrderedDict(sorted(self.as_dict().items())))
def __repr__(self):
return str(self)
def load(self, tags, duration, image=False):
self._parse_tags = tags
self._parse_duration = duration
self._load_image = image
if tags:
self._parse_tag(self._filehandler)
if duration:
if tags: # rewind file if the tags were already parsed
self._filehandler.seek(0)
self._determine_duration(self._filehandler)
def _set_field(self, fieldname, value, overwrite=True):
"""convenience function to set fields of the tinytag by name"""
write_dest = self # write into the TinyTag by default
get_func = getattr
set_func = setattr
is_extra = fieldname.startswith('extra.') # but if it's marked as extra field
if is_extra:
fieldname = fieldname[6:]
write_dest = self.extra # write into the extra field instead
get_func = operator.getitem
set_func = operator.setitem
if get_func(write_dest, fieldname): # do not overwrite existing data
return
if DEBUG:
stderr('Setting field "%s" to "%s"' % (fieldname, value))
if fieldname == 'genre':
genre_id = 255
if value.isdigit(): # funky: id3v1 genre hidden in a id3v2 field
genre_id = int(value)
else: # funkier: the TCO may contain genres in parens, e.g. '(13)'
if value[:1] == '(' and value[-1:] == ')' and value[1:-1].isdigit():
genre_id = int(value[1:-1])
if 0 <= genre_id < len(ID3.ID3V1_GENRES):
value = ID3.ID3V1_GENRES[genre_id]
if fieldname in ("track", "disc", "track_total", "disc_total"):
# Converting to string for type consistency
value = str(value)
mapping = [(fieldname, value)]
if fieldname in ("track", "disc"):
if type(value).__name__ in ('str', 'unicode') and '/' in value:
value, total = value.split('/')[:2]
mapping = [(fieldname, str(value)), ("%s_total" % fieldname, str(total))]
for k, v in mapping:
if overwrite or not get_func(write_dest, k):
set_func(write_dest, k, v)
def _determine_duration(self, fh):
raise NotImplementedError()
def _parse_tag(self, fh):
raise NotImplementedError()
def update(self, other, all_fields=False):
# update the values of this tag with the values from another tag
if all_fields:
self.__dict__.update(other.__dict__)
return
for key in ['track', 'track_total', 'title', 'artist',
'album', 'albumartist', 'year', 'duration',
'genre', 'disc', 'disc_total', 'comment', 'composer',
'_image_data']:
if not getattr(self, key) and getattr(other, key):
setattr(self, key, getattr(other, key))
if other.extra:
self.extra.update(other.extra)
@staticmethod
def _unpad(s):
# strings in mp3 and asf *may* be terminated with a zero byte at the end
return s.strip('\x00')
class MP4(TinyTag):
# https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html
# https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap2/qtff2.html
class Parser:
# https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/Metadata/Metadata.html#//apple_ref/doc/uid/TP40000939-CH1-SW34
ATOM_DECODER_BY_TYPE = {
0: lambda x: x, # 'reserved',
1: lambda x: codecs.decode(x, 'utf-8', 'replace'), # UTF-8
2: lambda x: codecs.decode(x, 'utf-16', 'replace'), # UTF-16
3: lambda x: codecs.decode(x, 's/jis', 'replace'), # S/JIS
# 16: duration in millis
13: lambda x: x, # JPEG
14: lambda x: x, # PNG
21: lambda x: struct.unpack('>b', x)[0], # BE Signed int
22: lambda x: struct.unpack('>B', x)[0], # BE Unsigned int
23: lambda x: struct.unpack('>f', x)[0], # BE Float32
24: lambda x: struct.unpack('>d', x)[0], # BE Float64
# 27: lambda x: x, # BMP
# 28: lambda x: x, # QuickTime Metadata atom
65: lambda x: struct.unpack('b', x)[0], # 8-bit Signed int
66: lambda x: struct.unpack('>h', x)[0], # BE 16-bit Signed int
67: lambda x: struct.unpack('>i', x)[0], # BE 32-bit Signed int
74: lambda x: struct.unpack('>q', x)[0], # BE 64-bit Signed int
75: lambda x: struct.unpack('B', x)[0], # 8-bit Unsigned int
76: lambda x: struct.unpack('>H', x)[0], # BE 16-bit Unsigned int
77: lambda x: struct.unpack('>I', x)[0], # BE 32-bit Unsigned int
78: lambda x: struct.unpack('>Q', x)[0], # BE 64-bit Unsigned int
}
@classmethod
def make_data_atom_parser(cls, fieldname):
def parse_data_atom(data_atom):
data_type = struct.unpack('>I', data_atom[:4])[0]
conversion = cls.ATOM_DECODER_BY_TYPE.get(data_type)
if conversion is None:
stderr('Cannot convert data type: %s' % data_type)
return {} # don't know how to convert data atom
# skip header & null-bytes, convert rest
return {fieldname: conversion(data_atom[8:])}
return parse_data_atom
@classmethod
def make_number_parser(cls, fieldname1, fieldname2):
def _(data_atom):
number_data = data_atom[8:14]
numbers = struct.unpack('>HHH', number_data)
# for some reason the first number is always irrelevant.
return {fieldname1: numbers[1], fieldname2: numbers[2]}
return _
@classmethod
def parse_id3v1_genre(cls, data_atom):
# dunno why the genre is offset by -1 but that's how mutagen does it
idx = struct.unpack('>H', data_atom[8:])[0] - 1
if idx < len(ID3.ID3V1_GENRES):
return {'genre': ID3.ID3V1_GENRES[idx]}
return {'genre': None}
@classmethod
def read_extended_descriptor(cls, esds_atom):
for i in range(4):
if esds_atom.read(1) != b'\x80':
break
@classmethod
def parse_audio_sample_entry_mp4a(cls, data):
# this atom also contains the esds atom:
# https://ffmpeg.org/doxygen/0.6/mov_8c-source.html
# http://xhelmboyx.tripod.com/formats/mp4-layout.txt
# http://sasperger.tistory.com/103
datafh = BytesIO(data)
datafh.seek(16, os.SEEK_CUR) # jump over version and flags
channels = struct.unpack('>H', datafh.read(2))[0]
datafh.seek(2, os.SEEK_CUR) # jump over bit_depth
datafh.seek(2, os.SEEK_CUR) # jump over QT compr id & pkt size
sr = struct.unpack('>I', datafh.read(4))[0]
# ES Description Atom
esds_atom_size = struct.unpack('>I', data[28:32])[0]
esds_atom = BytesIO(data[36:36 + esds_atom_size])
esds_atom.seek(5, os.SEEK_CUR) # jump over version, flags and tag
# ES Descriptor
cls.read_extended_descriptor(esds_atom)
esds_atom.seek(4, os.SEEK_CUR) # jump over ES id, flags and tag
# Decoder Config Descriptor
cls.read_extended_descriptor(esds_atom)
esds_atom.seek(9, os.SEEK_CUR)
avg_br = struct.unpack('>I', esds_atom.read(4))[0] / 1000 # kbit/s
return {'channels': channels, 'samplerate': sr, 'bitrate': avg_br}
@classmethod
def parse_audio_sample_entry_alac(cls, data):
# https://github.com/macosforge/alac/blob/master/ALACMagicCookieDescription.txt
alac_atom_size = struct.unpack('>I', data[28:32])[0]
alac_atom = BytesIO(data[36:36 + alac_atom_size])
alac_atom.seek(9, os.SEEK_CUR)
bitdepth = struct.unpack('b', alac_atom.read(1))[0]
alac_atom.seek(3, os.SEEK_CUR)
channels = struct.unpack('b', alac_atom.read(1))[0]
alac_atom.seek(6, os.SEEK_CUR)
avg_br = struct.unpack('>I', alac_atom.read(4))[0] / 1000 # kbit/s
sr = struct.unpack('>I', alac_atom.read(4))[0]
return {'channels': channels, 'samplerate': sr, 'bitrate': avg_br, 'bitdepth': bitdepth}
@classmethod
def parse_mvhd(cls, data):
# http://stackoverflow.com/a/3639993/1191373
walker = BytesIO(data)
version = struct.unpack('b', walker.read(1))[0]
walker.seek(3, os.SEEK_CUR) # jump over flags
if version == 0: # uses 32 bit integers for timestamps
walker.seek(8, os.SEEK_CUR) # jump over create & mod times
time_scale = struct.unpack('>I', walker.read(4))[0]
duration = struct.unpack('>I', walker.read(4))[0]
else: # version == 1: # uses 64 bit integers for timestamps
walker.seek(16, os.SEEK_CUR) # jump over create & mod times
time_scale = struct.unpack('>I', walker.read(4))[0]
duration = struct.unpack('>q', walker.read(8))[0]
return {'duration': duration / time_scale}
@classmethod
def debug_atom(cls, data):
stderr(data) # use this function to inspect atoms in an atom tree
return {}
# The parser tree: Each key is an atom name which is traversed if existing.
# Leaves of the parser tree are callables which receive the atom data.
# callables return {fieldname: value} which is updates the TinyTag.
META_DATA_TREE = {b'moov': {b'udta': {b'meta': {b'ilst': {
# see: http://atomicparsley.sourceforge.net/mpeg-4files.html
# and: https://metacpan.org/dist/Image-ExifTool/source/lib/Image/ExifTool/QuickTime.pm#L3093
b'\xa9ART': {b'data': Parser.make_data_atom_parser('artist')},
b'\xa9alb': {b'data': Parser.make_data_atom_parser('album')},
b'\xa9cmt': {b'data': Parser.make_data_atom_parser('comment')},
# need test-data for this
# b'cpil': {b'data': Parser.make_data_atom_parser('extra.compilation')},
b'\xa9day': {b'data': Parser.make_data_atom_parser('year')},
b'\xa9des': {b'data': Parser.make_data_atom_parser('extra.description')},
b'\xa9gen': {b'data': Parser.make_data_atom_parser('genre')},
b'\xa9lyr': {b'data': Parser.make_data_atom_parser('extra.lyrics')},
b'\xa9mvn': {b'data': Parser.make_data_atom_parser('movement')},
b'\xa9nam': {b'data': Parser.make_data_atom_parser('title')},
b'\xa9wrt': {b'data': Parser.make_data_atom_parser('composer')},
b'aART': {b'data': Parser.make_data_atom_parser('albumartist')},
b'cprt': {b'data': Parser.make_data_atom_parser('extra.copyright')},
b'desc': {b'data': Parser.make_data_atom_parser('extra.description')},
b'disk': {b'data': Parser.make_number_parser('disc', 'disc_total')},
b'gnre': {b'data': Parser.parse_id3v1_genre},
b'trkn': {b'data': Parser.make_number_parser('track', 'track_total')},
# need test-data for this
# b'tmpo': {b'data': Parser.make_data_atom_parser('extra.bmp')},
}}}}}
# see: https://developer.apple.com/library/mac/documentation/QuickTime/QTFF/QTFFChap3/qtff3.html
AUDIO_DATA_TREE = {
b'moov': {
b'mvhd': Parser.parse_mvhd,
b'trak': {b'mdia': {b"minf": {b"stbl": {b"stsd": {
b'mp4a': Parser.parse_audio_sample_entry_mp4a,
b'alac': Parser.parse_audio_sample_entry_alac
}}}}}
}
}
IMAGE_DATA_TREE = {b'moov': {b'udta': {b'meta': {b'ilst': {
b'covr': {b'data': Parser.make_data_atom_parser('_image_data')},
}}}}}
VERSIONED_ATOMS = {b'meta', b'stsd'} # those have an extra 4 byte header
FLAGGED_ATOMS = {b'stsd'} # these also have an extra 4 byte header
def _determine_duration(self, fh):
self._traverse_atoms(fh, path=self.AUDIO_DATA_TREE)
def _parse_tag(self, fh):
self._traverse_atoms(fh, path=self.META_DATA_TREE)
if self._load_image: # A bit inefficient, we rewind the file
self._filehandler.seek(0) # to parse it again for the image
self._traverse_atoms(fh, path=self.IMAGE_DATA_TREE)
def _traverse_atoms(self, fh, path, stop_pos=None, curr_path=None):
header_size = 8
atom_header = fh.read(header_size)
while len(atom_header) == header_size:
atom_size = struct.unpack('>I', atom_header[:4])[0] - header_size
atom_type = atom_header[4:]
if curr_path is None: # keep track how we traversed in the tree
curr_path = [atom_type]
if atom_size <= 0: # empty atom, jump to next one
atom_header = fh.read(header_size)
continue
if DEBUG:
stderr('%s pos: %d atom: %s len: %d' %
(' ' * 4 * len(curr_path), fh.tell() - header_size, atom_type,
atom_size + header_size))
if atom_type in self.VERSIONED_ATOMS: # jump atom version for now
fh.seek(4, os.SEEK_CUR)
if atom_type in self.FLAGGED_ATOMS: # jump atom flags for now
fh.seek(4, os.SEEK_CUR)
sub_path = path.get(atom_type, None)
# if the path leaf is a dict, traverse deeper into the tree:
if issubclass(type(sub_path), MutableMapping):
atom_end_pos = fh.tell() + atom_size
self._traverse_atoms(fh, path=sub_path, stop_pos=atom_end_pos,
curr_path=curr_path + [atom_type])
# if the path-leaf is a callable, call it on the atom data
elif callable(sub_path):
for fieldname, value in sub_path(fh.read(atom_size)).items():
if DEBUG:
stderr(' ' * 4 * len(curr_path), 'FIELD: ', fieldname)
if fieldname:
self._set_field(fieldname, value)
# if no action was specified using dict or callable, jump over atom
else:
fh.seek(atom_size, os.SEEK_CUR)
# check if we have reached the end of this branch:
if stop_pos and fh.tell() >= stop_pos:
return # return to parent (next parent node in tree)
atom_header = fh.read(header_size) # read next atom
class ID3(TinyTag):
FRAME_ID_TO_FIELD = { # Mapping from Frame ID to a field of the TinyTag
'COMM': 'comment', 'COM': 'comment',
'TRCK': 'track', 'TRK': 'track',
'TYER': 'year', 'TYE': 'year', 'TDRC': 'year',
'TALB': 'album', 'TAL': 'album',
'TPE1': 'artist', 'TP1': 'artist',
'TIT2': 'title', 'TT2': 'title',
'TCON': 'genre', 'TCO': 'genre',
'TPOS': 'disc',
'TPE2': 'albumartist', 'TCOM': 'composer',
'WXXX': 'extra.url',
'TSRC': 'extra.isrc',
'TXXX': 'extra.text',
'TKEY': 'extra.initial_key',
'USLT': 'extra.lyrics',
'TCOP': 'extra.copyright', 'TCR': 'extra.copyright',
}
IMAGE_FRAME_IDS = {'APIC', 'PIC'}
PARSABLE_FRAME_IDS = set(FRAME_ID_TO_FIELD.keys()).union(IMAGE_FRAME_IDS)
_MAX_ESTIMATION_SEC = 30
_CBR_DETECTION_FRAME_COUNT = 5
_USE_XING_HEADER = True # much faster, but can be deactivated for testing
ID3V1_GENRES = [
'Blues', 'Classic Rock', 'Country', 'Dance', 'Disco',
'Funk', 'Grunge', 'Hip-Hop', 'Jazz', 'Metal', 'New Age', 'Oldies',
'Other', 'Pop', 'R&B', 'Rap', 'Reggae', 'Rock', 'Techno', 'Industrial',
'Alternative', 'Ska', 'Death Metal', 'Pranks', 'Soundtrack',
'Euro-Techno', 'Ambient', 'Trip-Hop', 'Vocal', 'Jazz+Funk', 'Fusion',
'Trance', 'Classical', 'Instrumental', 'Acid', 'House', 'Game',
'Sound Clip', 'Gospel', 'Noise', 'AlternRock', 'Bass', 'Soul', 'Punk',
'Space', 'Meditative', 'Instrumental Pop', 'Instrumental Rock',
'Ethnic', 'Gothic', 'Darkwave', 'Techno-Industrial', 'Electronic',
'Pop-Folk', 'Eurodance', 'Dream', 'Southern Rock', 'Comedy', 'Cult',
'Gangsta', 'Top 40', 'Christian Rap', 'Pop/Funk', 'Jungle',
'Native American', 'Cabaret', 'New Wave', 'Psychadelic', 'Rave',
'Showtunes', 'Trailer', 'Lo-Fi', 'Tribal', 'Acid Punk', 'Acid Jazz',
'Polka', 'Retro', 'Musical', 'Rock & Roll', 'Hard Rock',
# Wimamp Extended Genres
'Folk', 'Folk-Rock', 'National Folk', 'Swing', 'Fast Fusion', 'Bebob',
'Latin', 'Revival', 'Celtic', 'Bluegrass', 'Avantgarde', 'Gothic Rock',
'Progressive Rock', 'Psychedelic Rock', 'Symphonic Rock', 'Slow Rock',
'Big Band', 'Chorus', 'Easy Listening', 'Acoustic', 'Humour', 'Speech',
'Chanson', 'Opera', 'Chamber Music', 'Sonata', 'Symphony', 'Booty Bass',
'Primus', 'Porn Groove', 'Satire', 'Slow Jam', 'Club', 'Tango', 'Samba',
'Folklore', 'Ballad', 'Power Ballad', 'Rhythmic Soul', 'Freestyle',
'Duet', 'Punk Rock', 'Drum Solo', 'A capella', 'Euro-House',
'Dance Hall', 'Goa', 'Drum & Bass',
# according to https://de.wikipedia.org/wiki/Liste_der_ID3v1-Genres:
'Club-House', 'Hardcore Techno', 'Terror', 'Indie', 'BritPop',
'', # don't use ethnic slur ("Negerpunk", WTF!)
'Polsk Punk', 'Beat', 'Christian Gangsta Rap', 'Heavy Metal',
'Black Metal', 'Contemporary Christian', 'Christian Rock',
# WinAmp 1.91
'Merengue', 'Salsa', 'Thrash Metal', 'Anime', 'Jpop', 'Synthpop',
# WinAmp 5.6
'Abstract', 'Art Rock', 'Baroque', 'Bhangra', 'Big Beat', 'Breakbeat',
'Chillout', 'Downtempo', 'Dub', 'EBM', 'Eclectic', 'Electro',
'Electroclash', 'Emo', 'Experimental', 'Garage', 'Illbient',
'Industro-Goth', 'Jam Band', 'Krautrock', 'Leftfield', 'Lounge',
'Math Rock', 'New Romantic', 'Nu-Breakz', 'Post-Punk', 'Post-Rock',
'Psytrance', 'Shoegaze', 'Space Rock', 'Trop Rock', 'World Music',
'Neoclassical', 'Audiobook', 'Audio Theatre', 'Neue Deutsche Welle',
'Podcast', 'Indie Rock', 'G-Funk', 'Dubstep', 'Garage Rock', 'Psybient',
]
def __init__(self, filehandler, filesize, *args, **kwargs):
TinyTag.__init__(self, filehandler, filesize, *args, **kwargs)
# save position after the ID3 tag for duration measurement speedup
self._bytepos_after_id3v2 = None
@classmethod
def set_estimation_precision(cls, estimation_in_seconds):
cls._MAX_ESTIMATION_SEC = estimation_in_seconds
# see this page for the magic values used in mp3:
# http://www.mpgedit.org/mpgedit/mpeg_format/mpeghdr.htm
samplerates = [
[11025, 12000, 8000], # MPEG 2.5
[], # reserved
[22050, 24000, 16000], # MPEG 2
[44100, 48000, 32000], # MPEG 1
]
v1l1 = [0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448, 0]
v1l2 = [0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384, 0]
v1l3 = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 0]
v2l1 = [0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256, 0]
v2l2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160, 0]
v2l3 = v2l2
bitrate_by_version_by_layer = [
[None, v2l3, v2l2, v2l1], # MPEG Version 2.5 # note that the layers go
None, # reserved # from 3 to 1 by design.
[None, v2l3, v2l2, v2l1], # MPEG Version 2 # the first layer id is
[None, v1l3, v1l2, v1l1], # MPEG Version 1 # reserved
]
samples_per_frame = 1152 # the default frame size for mp3
channels_per_channel_mode = [
2, # 00 Stereo
2, # 01 Joint stereo (Stereo)
2, # 10 Dual channel (2 mono channels)
1, # 11 Single channel (Mono)
]
@staticmethod
def _parse_xing_header(fh):
# see: http://www.mp3-tech.org/programmer/sources/vbrheadersdk.zip
fh.seek(4, os.SEEK_CUR) # read over Xing header
header_flags = struct.unpack('>i', fh.read(4))[0]
frames = byte_count = toc = vbr_scale = None
if header_flags & 1: # FRAMES FLAG
frames = struct.unpack('>i', fh.read(4))[0]
if header_flags & 2: # BYTES FLAG
byte_count = struct.unpack('>i', fh.read(4))[0]
if header_flags & 4: # TOC FLAG
toc = [struct.unpack('>i', fh.read(4))[0] for _ in range(25)] # 100 bytes
if header_flags & 8: # VBR SCALE FLAG
vbr_scale = struct.unpack('>i', fh.read(4))[0]
return frames, byte_count, toc, vbr_scale
def _determine_duration(self, fh):
# if tag reading was disabled, find start position of audio data
if self._bytepos_after_id3v2 is None:
self._parse_id3v2_header(fh)
max_estimation_frames = (ID3._MAX_ESTIMATION_SEC * 44100) // ID3.samples_per_frame
frame_size_accu = 0
header_bytes = 4
frames = 0 # count frames for determining mp3 duration
bitrate_accu = 0 # add up bitrates to find average bitrate to detect
last_bitrates = [] # CBR mp3s (multiple frames with same bitrates)
# seek to first position after id3 tag (speedup for large header)
fh.seek(self._bytepos_after_id3v2)
while True:
# reading through garbage until 11 '1' sync-bits are found
b = fh.peek(4)
if len(b) < 4:
if frames:
self.bitrate = bitrate_accu / frames
break # EOF
sync, conf, bitrate_freq, rest = struct.unpack('BBBB', b[0:4])
br_id = (bitrate_freq >> 4) & 0x0F # biterate id
sr_id = (bitrate_freq >> 2) & 0x03 # sample rate id
padding = 1 if bitrate_freq & 0x02 > 0 else 0
mpeg_id = (conf >> 3) & 0x03
layer_id = (conf >> 1) & 0x03
channel_mode = (rest >> 6) & 0x03
# check for eleven 1s, validate bitrate and sample rate
if (not b[:2] > b'\xFF\xE0' or br_id > 14 or br_id == 0 or sr_id == 3
or layer_id == 0 or mpeg_id == 1): # noqa
idx = b.find(b'\xFF', 1) # invalid frame, find next sync header
if idx == -1:
idx = len(b) # not found: jump over the current peek buffer
fh.seek(max(idx, 1), os.SEEK_CUR)
continue
try:
self.channels = self.channels_per_channel_mode[channel_mode]
frame_bitrate = ID3.bitrate_by_version_by_layer[mpeg_id][layer_id][br_id]
self.samplerate = ID3.samplerates[mpeg_id][sr_id]
except (IndexError, TypeError):
raise TinyTagException('mp3 parsing failed')
# There might be a xing header in the first frame that contains
# all the info we need, otherwise parse multiple frames to find the
# accurate average bitrate
if frames == 0 and ID3._USE_XING_HEADER:
xing_header_offset = b.find(b'Xing')
if xing_header_offset != -1:
fh.seek(xing_header_offset, os.SEEK_CUR)
xframes, byte_count, toc, vbr_scale = ID3._parse_xing_header(fh)
if xframes and xframes != 0 and byte_count:
# MPEG-2 Audio Layer III uses 576 samples per frame
samples_per_frame = 576 if mpeg_id <= 2 else ID3.samples_per_frame
self.duration = xframes * samples_per_frame / float(self.samplerate)
# self.duration = (xframes * ID3.samples_per_frame / self.samplerate
# / self.channels) # noqa
self.bitrate = byte_count * 8 / self.duration / 1000
self.audio_offset = fh.tell()
self.is_vbr = True
return
continue
frames += 1 # it's most probably an mp3 frame
bitrate_accu += frame_bitrate
if frames == 1:
self.audio_offset = fh.tell()
if frames <= ID3._CBR_DETECTION_FRAME_COUNT:
last_bitrates.append(frame_bitrate)
fh.seek(4, os.SEEK_CUR) # jump over peeked bytes
frame_length = (144000 * frame_bitrate) // self.samplerate + padding
frame_size_accu += frame_length
# if bitrate does not change over time its probably CBR
is_cbr = (frames == ID3._CBR_DETECTION_FRAME_COUNT and len(set(last_bitrates)) == 1)
if frames == max_estimation_frames or is_cbr:
# try to estimate duration
fh.seek(-128, 2) # jump to last byte (leaving out id3v1 tag)
audio_stream_size = fh.tell() - self.audio_offset
est_frame_count = audio_stream_size / (frame_size_accu / frames)
samples = est_frame_count * ID3.samples_per_frame
self.duration = samples / self.samplerate
self.bitrate = bitrate_accu / frames
return
if frame_length > 1: # jump over current frame body
fh.seek(frame_length - header_bytes, os.SEEK_CUR)
if self.samplerate:
self.duration = frames * ID3.samples_per_frame / self.samplerate
def _parse_tag(self, fh):
self._parse_id3v2(fh)
attrs = ['track', 'track_total', 'title', 'artist', 'album', 'albumartist', 'year', 'genre']
has_all_tags = all(getattr(self, attr) for attr in attrs)
if not has_all_tags and self.filesize > 128:
fh.seek(-128, os.SEEK_END) # try parsing id3v1 in last 128 bytes
self._parse_id3v1(fh)
def _parse_id3v2_header(self, fh):
size, extended, major = 0, None, None
# for info on the specs, see: http://id3.org/Developer%20Information
header = struct.unpack('3sBBB4B', _read(fh, 10))
tag = codecs.decode(header[0], 'ISO-8859-1')
# check if there is an ID3v2 tag at the beginning of the file
if tag == 'ID3':
major, rev = header[1:3]
if DEBUG:
stderr('Found id3 v2.%s' % major)
# unsync = (header[3] & 0x80) > 0
extended = (header[3] & 0x40) > 0
# experimental = (header[3] & 0x20) > 0
# footer = (header[3] & 0x10) > 0
size = self._calc_size(header[4:8], 7)
self._bytepos_after_id3v2 = size
return size, extended, major
def _parse_id3v2(self, fh):
size, extended, major = self._parse_id3v2_header(fh)
if size:
end_pos = fh.tell() + size
parsed_size = 0
if extended: # just read over the extended header.
size_bytes = struct.unpack('4B', _read(fh, 6)[0:4])
extd_size = self._calc_size(size_bytes, 7)
fh.seek(extd_size - 6, os.SEEK_CUR) # jump over extended_header
while parsed_size < size:
frame_size = self._parse_frame(fh, id3version=major)
if frame_size == 0:
break
parsed_size += frame_size
fh.seek(end_pos, os.SEEK_SET)
def _parse_id3v1(self, fh):
if fh.read(3) == b'TAG': # check if this is an ID3 v1 tag
def asciidecode(x):
return self._unpad(codecs.decode(x, self._default_encoding or 'latin1'))
fields = fh.read(30 + 30 + 30 + 4 + 30 + 1)
self._set_field('title', asciidecode(fields[:30]), overwrite=False)
self._set_field('artist', asciidecode(fields[30:60]), overwrite=False)
self._set_field('album', asciidecode(fields[60:90]), overwrite=False)
self._set_field('year', asciidecode(fields[90:94]), overwrite=False)
comment = fields[94:124]
if b'\x00\x00' < comment[-2:] < b'\x01\x00':
self._set_field('track', str(ord(comment[-1:])), overwrite=False)
comment = comment[:-2]
self._set_field('comment', asciidecode(comment), overwrite=False)
genre_id = ord(fields[124:125])
if genre_id < len(ID3.ID3V1_GENRES):
self._set_field('genre', ID3.ID3V1_GENRES[genre_id], overwrite=False)
@staticmethod
def index_utf16(s, search):
for i in range(0, len(s), len(search)):
if s[i:i + len(search)] == search:
return i
return -1
def _parse_frame(self, fh, id3version=False):
# ID3v2.2 especially ugly. see: http://id3.org/id3v2-00
frame_header_size = 6 if id3version == 2 else 10
frame_size_bytes = 3 if id3version == 2 else 4
binformat = '3s3B' if id3version == 2 else '4s4B2B'
bits_per_byte = 7 if id3version == 4 else 8 # only id3v2.4 is synchsafe
frame_header_data = fh.read(frame_header_size)
if len(frame_header_data) != frame_header_size:
return 0
frame = struct.unpack(binformat, frame_header_data)
frame_id = self._decode_string(frame[0])
frame_size = self._calc_size(frame[1:1 + frame_size_bytes], bits_per_byte)
if DEBUG:
stderr('Found id3 Frame %s at %d-%d of %d' %
(frame_id, fh.tell(), fh.tell() + frame_size, self.filesize))
if frame_size > 0:
# flags = frame[1+frame_size_bytes:] # dont care about flags.
if frame_id not in ID3.PARSABLE_FRAME_IDS: # jump over unparsable frames
fh.seek(frame_size, os.SEEK_CUR)
return frame_size
content = fh.read(frame_size)
fieldname = ID3.FRAME_ID_TO_FIELD.get(frame_id)
if fieldname:
language = fieldname in ("comment", "extra.lyrics")
self._set_field(fieldname, self._decode_string(content, language))
elif frame_id in self.IMAGE_FRAME_IDS and self._load_image:
# See section 4.14: http://id3.org/id3v2.4.0-frames
encoding = content[0:1]
if frame_id == 'PIC': # ID3 v2.2:
desc_start_pos = 1 + 3 + 1 # skip encoding (1), imgformat (3), pictype(1)
else: # ID3 v2.3+
desc_start_pos = content.index(b'\x00', 1) + 1 + 1 # skip mimetype, pictype(1)
# latin1 and utf-8 are 1 byte
termination = b'\x00' if encoding in (b'\x00', b'\x03') else b'\x00\x00'
desc_length = ID3.index_utf16(content[desc_start_pos:], termination)
desc_end_pos = desc_start_pos + desc_length + len(termination)
self._image_data = content[desc_end_pos:]
return frame_size
return 0
def _decode_string(self, bytestr, language=False):
default_encoding = 'ISO-8859-1'
if self._default_encoding:
default_encoding = self._default_encoding
try: # it's not my fault, this is the spec.
first_byte = bytestr[:1]
if first_byte == b'\x00': # ISO-8859-1
bytestr = bytestr[1:]
encoding = default_encoding
elif first_byte == b'\x01': # UTF-16 with BOM
bytestr = bytestr[1:]
# remove language (but leave BOM)
if language:
if bytestr[3:5] in (b'\xfe\xff', b'\xff\xfe'):
bytestr = bytestr[3:]
if bytestr[:3].isalpha() and bytestr[3:4] == b'\x00':
bytestr = bytestr[4:] # remove language
if bytestr[:1] == b'\x00':
bytestr = bytestr[1:] # strip optional additional null byte
# read byte order mark to determine endianness
encoding = 'UTF-16be' if bytestr[0:2] == b'\xfe\xff' else 'UTF-16le'
# strip the bom if it exists
if bytestr[:2] in (b'\xfe\xff', b'\xff\xfe'):
bytestr = bytestr[2:] if len(bytestr) % 2 == 0 else bytestr[2:-1]
# remove ADDITIONAL EXTRA BOM :facepalm:
if bytestr[:4] == b'\x00\x00\xff\xfe':
bytestr = bytestr[4:]
elif first_byte == b'\x02': # UTF-16LE
# strip optional null byte, if byte count uneven
bytestr = bytestr[1:-1] if len(bytestr) % 2 == 0 else bytestr[1:]
encoding = 'UTF-16le'
elif first_byte == b'\x03': # UTF-8
bytestr = bytestr[1:]
encoding = 'UTF-8'
else:
bytestr = bytestr
encoding = default_encoding # wild guess
if language and bytestr[:3].isalpha() and bytestr[3:4] == b'\x00':
bytestr = bytestr[4:] # remove language
errors = 'ignore' if self._ignore_errors else 'strict'
return self._unpad(codecs.decode(bytestr, encoding, errors))
except UnicodeDecodeError:
raise TinyTagException('Error decoding ID3 Tag!')
def _calc_size(self, bytestr, bits_per_byte):
# length of some mp3 header fields is described by 7 or 8-bit-bytes
return reduce(lambda accu, elem: (accu << bits_per_byte) + elem, bytestr, 0)
class Ogg(TinyTag):
def __init__(self, filehandler, filesize, *args, **kwargs):
TinyTag.__init__(self, filehandler, filesize, *args, **kwargs)
self._tags_parsed = False
self._max_samplenum = 0 # maximum sample position ever read
def _determine_duration(self, fh):
max_page_size = 65536 # https://xiph.org/ogg/doc/libogg/ogg_page.html
if not self._tags_parsed:
self._parse_tag(fh) # determine sample rate
fh.seek(0) # and rewind to start
if self.duration is not None or not self.samplerate:
return # either ogg flac or invalid file
if self.filesize > max_page_size:
fh.seek(-max_page_size, 2) # go to last possible page position
while True:
b = fh.peek(4)
if len(b) == 0:
return # EOF
if b[:4] == b'OggS': # look for an ogg header
for _ in self._parse_pages(fh):
pass # parse all remaining pages
self.duration = self._max_samplenum / self.samplerate
else:
idx = b.find(b'OggS') # try to find header in peeked data
seekpos = idx if idx != -1 else len(b) - 3
fh.seek(max(seekpos, 1), os.SEEK_CUR)
def _parse_tag(self, fh):
page_start_pos = fh.tell() # set audio_offset later if its audio data
check_flac_second_packet = False
check_speex_second_packet = False
for packet in self._parse_pages(fh):
walker = BytesIO(packet)
if packet[0:7] == b"\x01vorbis":
if self._parse_duration:
(channels, self.samplerate, max_bitrate, bitrate,
min_bitrate) = struct.unpack("<B4i", packet[11:28])
if not self.audio_offset:
self.bitrate = bitrate / 1000
self.audio_offset = page_start_pos
elif packet[0:7] == b"\x03vorbis":
if self._parse_tags:
walker.seek(7, os.SEEK_CUR) # jump over header name
self._parse_vorbis_comment(walker)
elif packet[0:8] == b'OpusHead':
if self._parse_duration: # parse opus header
# https://www.videolan.org/developers/vlc/modules/codec/opus_header.c
# https://mf4.xiph.org/jenkins/view/opus/job/opusfile-unix/ws/doc/html/structOpusHead.html
walker.seek(8, os.SEEK_CUR) # jump over header name
(version, ch, _, sr, _, _) = struct.unpack("<BBHIHB", walker.read(11))
if (version & 0xF0) == 0: # only major version 0 supported
self.channels = ch
self.samplerate = 48000 # internally opus always uses 48khz
elif packet[0:8] == b'OpusTags':
if self._parse_tags: # parse opus metadata:
walker.seek(8, os.SEEK_CUR) # jump over header name
self._parse_vorbis_comment(walker)
elif packet[0:5] == b'\x7fFLAC':
# https://xiph.org/flac/ogg_mapping.html
walker.seek(9, os.SEEK_CUR) # jump over header name, version and number of headers
flactag = Flac(io.BufferedReader(walker), self.filesize)
flactag.load(tags=self._parse_tags, duration=self._parse_duration,
image=self._load_image)
self.update(flactag, all_fields=True)
check_flac_second_packet = True
elif check_flac_second_packet:
# second packet contains FLAC metadata block
if self._parse_tags:
meta_header = struct.unpack('B3B', walker.read(4))
block_type = meta_header[0] & 0x7f
if block_type == Flac.METADATA_VORBIS_COMMENT:
self._parse_vorbis_comment(walker)
check_flac_second_packet = False
elif packet[0:8] == b'Speex ':
# https://speex.org/docs/manual/speex-manual/node8.html
if self._parse_duration:
walker.seek(36, os.SEEK_CUR) # jump over header name and irrelevant fields
(self.samplerate, _, _, self.channels,
self.bitrate) = struct.unpack("<5i", walker.read(20))
check_speex_second_packet = True
elif check_speex_second_packet:
if self._parse_tags:
length = struct.unpack('I', walker.read(4))[0] # starts with a comment string
comment = codecs.decode(walker.read(length), 'UTF-8')
self._set_field('comment', comment)
self._parse_vorbis_comment(walker, contains_vendor=False) # other tags
check_speex_second_packet = False
else:
if DEBUG:
stderr('Unsupported Ogg page type: ', packet[:16])
break
page_start_pos = fh.tell()
self._tags_parsed = True
def _parse_vorbis_comment(self, fh, contains_vendor=True):
# for the spec, see: http://xiph.org/vorbis/doc/v-comment.html
# discnumber tag based on: https://en.wikipedia.org/wiki/Vorbis_comment
# https://sno.phy.queensu.ca/~phil/exiftool/TagNames/Vorbis.html
comment_type_to_attr_mapping = {
'album': 'album',
'albumartist': 'albumartist',
'title': 'title',
'artist': 'artist',
'author': 'artist',
'date': 'year',
'tracknumber': 'track',
'tracktotal': 'track_total',
'totaltracks': 'track_total',
'discnumber': 'disc',
'disctotal': 'disc_total',
'totaldiscs': 'disc_total',
'genre': 'genre',
'description': 'comment',
'comment': 'comment',
'composer': 'composer',
'copyright': 'extra.copyright',
'isrc': 'extra.isrc',
'lyrics': 'extra.lyrics',
}
if contains_vendor:
vendor_length = struct.unpack('I', fh.read(4))[0]
fh.seek(vendor_length, os.SEEK_CUR) # jump over vendor
elements = struct.unpack('I', fh.read(4))[0]
for i in range(elements):
length = struct.unpack('I', fh.read(4))[0]
try:
keyvalpair = codecs.decode(fh.read(length), 'UTF-8')
except UnicodeDecodeError:
continue
if '=' in keyvalpair:
key, value = keyvalpair.split('=', 1)
key_lowercase = key.lower()
if key_lowercase == "metadata_block_picture" and self._load_image:
if DEBUG:
stderr('Found Vorbis Image', key, value[:64])
self._image_data = Flac._parse_image(BytesIO(base64.b64decode(value)))
else:
if DEBUG:
stderr('Found Vorbis Comment', key, value[:64])
fieldname = comment_type_to_attr_mapping.get(key_lowercase)
if fieldname:
self._set_field(fieldname, value)
def _parse_pages(self, fh):
# for the spec, see: https://wiki.xiph.org/Ogg
previous_page = b'' # contains data from previous (continuing) pages
header_data = fh.read(27) # read ogg page header
while len(header_data) == 27:
header = struct.unpack('<4sBBqIIiB', header_data)
# https://xiph.org/ogg/doc/framing.html
oggs, version, flags, pos, serial, pageseq, crc, segments = header
self._max_samplenum = max(self._max_samplenum, pos)
if oggs != b'OggS' or version != 0:
raise TinyTagException('Not a valid ogg file!')
segsizes = struct.unpack('B' * segments, fh.read(segments))
total = 0
for segsize in segsizes: # read all segments
total += segsize
if total < 255: # less than 255 bytes means end of page
yield previous_page + fh.read(total)
previous_page = b''
total = 0
if total != 0:
if total % 255 == 0:
previous_page += fh.read(total)
else:
yield previous_page + fh.read(total)
previous_page = b''
header_data = fh.read(27)
class Wave(TinyTag):
# https://sno.phy.queensu.ca/~phil/exiftool/TagNames/RIFF.html
riff_mapping = {
b'INAM': 'title',
b'TITL': 'title',
b'IPRD': 'album',
b'IART': 'artist',
b'ICMT': 'comment',
b'ICRD': 'year',
b'IGNR': 'genre',
b'ISRC': 'extra.isrc',
b'ITRK': 'track',
b'TRCK': 'track',
b'PRT1': 'track',
b'PRT2': 'track_number',
b'YEAR': 'year',
# riff format is lacking the composer field.
}
def __init__(self, filehandler, filesize, *args, **kwargs):
TinyTag.__init__(self, filehandler, filesize, *args, **kwargs)
self._duration_parsed = False
def _determine_duration(self, fh):
# see: http://www-mmsp.ece.mcgill.ca/Documents/AudioFormats/WAVE/WAVE.html
# and: https://en.wikipedia.org/wiki/WAV
riff, size, fformat = struct.unpack('4sI4s', fh.read(12))
if riff != b'RIFF' or fformat != b'WAVE':
raise TinyTagException('not a wave file!')
self.bitdepth = 16 # assume 16bit depth (CD quality)
chunk_header = fh.read(8)
while len(chunk_header) == 8:
subchunkid, subchunksize = struct.unpack('4sI', chunk_header)
subchunksize += subchunksize % 2 # IFF chunks are padded to an even number of bytes
if subchunkid == b'fmt ':
_, self.channels, self.samplerate = struct.unpack('HHI', fh.read(8))
_, _, self.bitdepth = struct.unpack('<IHH', fh.read(8))
if self.bitdepth == 0:
# Certain codecs (e.g. GSM 6.10) give us a bit depth of zero.
# Avoid division by zero when calculating duration.
self.bitdepth = 1
self.bitrate = self.samplerate * self.channels * self.bitdepth / 1000
remaining_size = subchunksize - 16
if remaining_size > 0:
fh.seek(remaining_size, 1) # skip remaining data in chunk
elif subchunkid == b'data':
self.duration = subchunksize / self.channels / self.samplerate / (self.bitdepth / 8)
self.audio_offset = fh.tell() - 8 # rewind to data header
fh.seek(subchunksize, 1)
elif subchunkid == b'LIST' and self._parse_tags:
is_info = fh.read(4) # check INFO header
if is_info != b'INFO': # jump over non-INFO sections
fh.seek(subchunksize - 4, os.SEEK_CUR)
else:
sub_fh = BytesIO(fh.read(subchunksize - 4))
field = sub_fh.read(4)
while len(field) == 4:
data_length = struct.unpack('I', sub_fh.read(4))[0]
data_length += data_length % 2 # IFF chunks are padded to an even size
data = sub_fh.read(data_length).split(b'\x00', 1)[0] # strip zero-byte
fieldname = self.riff_mapping.get(field)
if fieldname:
self._set_field(fieldname, codecs.decode(data, 'utf-8'))
field = sub_fh.read(4)
elif subchunkid in (b'id3 ', b'ID3 ') and self._parse_tags:
id3 = ID3(fh, 0)
id3.load(tags=True, duration=False, image=self._load_image)
self.update(id3)
else: # some other chunk, just skip the data
fh.seek(subchunksize, 1)
chunk_header = fh.read(8)
self._duration_parsed = True
def _parse_tag(self, fh):
if not self._duration_parsed:
self._determine_duration(fh) # parse whole file to determine tags:(
class Flac(TinyTag):
METADATA_STREAMINFO = 0
METADATA_PADDING = 1
METADATA_APPLICATION = 2
METADATA_SEEKTABLE = 3
METADATA_VORBIS_COMMENT = 4
METADATA_CUESHEET = 5
METADATA_PICTURE = 6
def load(self, tags, duration, image=False):
self._parse_tags = tags
self._parse_duration = duration
self._load_image = image
header = self._filehandler.peek(4)
if header[:3] == b'ID3': # parse ID3 header if it exists
id3 = ID3(self._filehandler, 0)
id3._parse_id3v2(self._filehandler)
self.update(id3)
header = self._filehandler.peek(4) # after ID3 should be fLaC
if header[:4] != b'fLaC':
raise TinyTagException('Invalid flac header')
self._filehandler.seek(4, os.SEEK_CUR)
self._determine_duration(self._filehandler)
def _determine_duration(self, fh):
# for spec, see https://xiph.org/flac/ogg_mapping.html
header_data = fh.read(4)
while len(header_data) == 4:
meta_header = struct.unpack('B3B', header_data)
block_type = meta_header[0] & 0x7f
is_last_block = meta_header[0] & 0x80
size = _bytes_to_int(meta_header[1:4])
# http://xiph.org/flac/format.html#metadata_block_streaminfo
if block_type == Flac.METADATA_STREAMINFO and self._parse_duration:
stream_info_header = fh.read(size)
if len(stream_info_header) < 34: # invalid streaminfo
return
header = struct.unpack('HH3s3s8B16s', stream_info_header)
# From the xiph documentation:
# py | <bits>
# ----------------------------------------------
# H | <16> The minimum block size (in samples)
# H | <16> The maximum block size (in samples)
# 3s | <24> The minimum frame size (in bytes)
# 3s | <24> The maximum frame size (in bytes)
# 8B | <20> Sample rate in Hz.
# | <3> (number of channels)-1.
# | <5> (bits per sample)-1.
# | <36> Total samples in stream.
# 16s| <128> MD5 signature
# min_blk, max_blk, min_frm, max_frm = header[0:4]
# min_frm = _bytes_to_int(struct.unpack('3B', min_frm))
# max_frm = _bytes_to_int(struct.unpack('3B', max_frm))
# channels--. bits total samples
# |----- samplerate -----| |-||----| |---------~ ~----|
# 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
# #---4---# #---5---# #---6---# #---7---# #--8-~ ~-12-#
self.samplerate = _bytes_to_int(header[4:7]) >> 4
self.channels = ((header[6] >> 1) & 0x07) + 1
self.bitdepth = (((header[6] & 1) << 4) + ((header[7] & 0xF0) >> 4) + 1)
total_sample_bytes = [(header[7] & 0x0F)] + list(header[8:12])
total_samples = _bytes_to_int(total_sample_bytes)
self.duration = total_samples / self.samplerate
if self.duration > 0:
self.bitrate = self.filesize / self.duration * 8 / 1000
elif block_type == Flac.METADATA_VORBIS_COMMENT and self._parse_tags:
oggtag = Ogg(fh, 0)
oggtag._parse_vorbis_comment(fh)
self.update(oggtag)
elif block_type == Flac.METADATA_PICTURE and self._load_image:
self._image_data = self._parse_image(fh)
elif block_type >= 127:
return # invalid block type
else:
if DEBUG:
stderr('Unknown FLAC block type', block_type)
fh.seek(size, 1) # seek over this block
if is_last_block:
return
header_data = fh.read(4)
@staticmethod
def _parse_image(fh):
# https://xiph.org/flac/format.html#metadata_block_picture
pic_type, mime_len = struct.unpack('>2I', fh.read(8))
fh.read(mime_len)
description_len = struct.unpack('>I', fh.read(4))[0]
fh.read(description_len)
width, height, depth, colors, pic_len = struct.unpack('>5I', fh.read(20))
return fh.read(pic_len)
class Wma(TinyTag):
ASF_CONTENT_DESCRIPTION_OBJECT = b'3&\xb2u\x8ef\xcf\x11\xa6\xd9\x00\xaa\x00b\xcel'
ASF_EXTENDED_CONTENT_DESCRIPTION_OBJECT = (b'@\xa4\xd0\xd2\x07\xe3\xd2\x11\x97\xf0\x00'
b'\xa0\xc9^\xa8P')
STREAM_BITRATE_PROPERTIES_OBJECT = b'\xceu\xf8{\x8dF\xd1\x11\x8d\x82\x00`\x97\xc9\xa2\xb2'
ASF_FILE_PROPERTY_OBJECT = b'\xa1\xdc\xab\x8cG\xa9\xcf\x11\x8e\xe4\x00\xc0\x0c Se'
ASF_STREAM_PROPERTIES_OBJECT = b'\x91\x07\xdc\xb7\xb7\xa9\xcf\x11\x8e\xe6\x00\xc0\x0c Se'
STREAM_TYPE_ASF_AUDIO_MEDIA = b'@\x9ei\xf8M[\xcf\x11\xa8\xfd\x00\x80_\\D+'
# see:
# http://web.archive.org/web/20131203084402/http://msdn.microsoft.com/en-us/library/bb643323.aspx
# and (japanese, but none the less helpful)
# http://uguisu.skr.jp/Windows/format_asf.html
def __init__(self, filehandler, filesize, *args, **kwargs):
TinyTag.__init__(self, filehandler, filesize, *args, **kwargs)
self.__tag_parsed = False
def _determine_duration(self, fh):
if not self.__tag_parsed:
self._parse_tag(fh)
def read_blocks(self, fh, blocks):
# blocks are a list(tuple('fieldname', byte_count, cast_int), ...)
decoded = {}
for block in blocks:
val = fh.read(block[1])
if block[2]:
val = _bytes_to_int_le(val)
decoded[block[0]] = val
return decoded
def __bytes_to_guid(self, obj_id_bytes):
return '-'.join([
hex(_bytes_to_int_le(obj_id_bytes[:-12]))[2:].zfill(6),
hex(_bytes_to_int_le(obj_id_bytes[-12:-10]))[2:].zfill(4),
hex(_bytes_to_int_le(obj_id_bytes[-10:-8]))[2:].zfill(4),
hex(_bytes_to_int(obj_id_bytes[-8:-6]))[2:].zfill(4),
hex(_bytes_to_int(obj_id_bytes[-6:]))[2:].zfill(12),
])
def __decode_string(self, bytestring):
return self._unpad(codecs.decode(bytestring, 'utf-16'))
def __decode_ext_desc(self, value_type, value):
""" decode ASF_EXTENDED_CONTENT_DESCRIPTION_OBJECT values"""
if value_type == 0: # Unicode string
return self.__decode_string(value)
elif value_type == 1: # BYTE array
return value
elif 1 < value_type < 6: # DWORD / QWORD / WORD
return _bytes_to_int_le(value)
def _parse_tag(self, fh):
self.__tag_parsed = True
guid = fh.read(16) # 128 bit GUID
if guid != b'0&\xb2u\x8ef\xcf\x11\xa6\xd9\x00\xaa\x00b\xcel':
# not a valid ASF container! see: http://www.garykessler.net/library/file_sigs.html
return
struct.unpack('Q', fh.read(8))[0] # size
struct.unpack('I', fh.read(4))[0] # obj_count
if fh.read(2) != b'\x01\x02':
# http://web.archive.org/web/20131203084402/http://msdn.microsoft.com/en-us/library/bb643323.aspx#_Toc521913958
return # not a valid asf header!
while True:
object_id = fh.read(16)
object_size = _bytes_to_int_le(fh.read(8))
if object_size == 0 or object_size > self.filesize:
break # invalid object, stop parsing.
if object_id == Wma.ASF_CONTENT_DESCRIPTION_OBJECT and self._parse_tags:
len_blocks = self.read_blocks(fh, [
('title_length', 2, True),
('author_length', 2, True),
('copyright_length', 2, True),
('description_length', 2, True),
('rating_length', 2, True),
])
data_blocks = self.read_blocks(fh, [
('title', len_blocks['title_length'], False),
('artist', len_blocks['author_length'], False),
('', len_blocks['copyright_length'], True),
('comment', len_blocks['description_length'], False),
('', len_blocks['rating_length'], True),
])
for field_name, bytestring in data_blocks.items():
if field_name:
self._set_field(field_name, self.__decode_string(bytestring))
elif object_id == Wma.ASF_EXTENDED_CONTENT_DESCRIPTION_OBJECT and self._parse_tags:
mapping = {
'WM/TrackNumber': 'track',
'WM/PartOfSet': 'disc',
'WM/Year': 'year',
'WM/AlbumArtist': 'albumartist',
'WM/Genre': 'genre',
'WM/AlbumTitle': 'album',
'WM/Composer': 'composer',
}
# http://web.archive.org/web/20131203084402/http://msdn.microsoft.com/en-us/library/bb643323.aspx#_Toc509555195
descriptor_count = _bytes_to_int_le(fh.read(2))
for _ in range(descriptor_count):
name_len = _bytes_to_int_le(fh.read(2))
name = self.__decode_string(fh.read(name_len))
value_type = _bytes_to_int_le(fh.read(2))
value_len = _bytes_to_int_le(fh.read(2))
value = fh.read(value_len)
field_name = mapping.get(name)
if field_name:
field_value = self.__decode_ext_desc(value_type, value)
self._set_field(field_name, field_value)
elif object_id == Wma.ASF_FILE_PROPERTY_OBJECT:
blocks = self.read_blocks(fh, [
('file_id', 16, False),
('file_size', 8, False),
('creation_date', 8, True),
('data_packets_count', 8, True),
('play_duration', 8, True),
('send_duration', 8, True),
('preroll', 8, True),
('flags', 4, False),
('minimum_data_packet_size', 4, True),
('maximum_data_packet_size', 4, True),
('maximum_bitrate', 4, False),
])
# According to the specification, we need to subtract the preroll from play_duration
# to get the actual duration of the file
preroll = blocks.get('preroll') / 1000
self.duration = max(blocks.get('play_duration') / 10000000 - preroll, 0.0)
elif object_id == Wma.ASF_STREAM_PROPERTIES_OBJECT:
blocks = self.read_blocks(fh, [
('stream_type', 16, False),
('error_correction_type', 16, False),
('time_offset', 8, True),
('type_specific_data_length', 4, True),
('error_correction_data_length', 4, True),
('flags', 2, True),
('reserved', 4, False)
])
already_read = 0
if blocks['stream_type'] == Wma.STREAM_TYPE_ASF_AUDIO_MEDIA:
stream_info = self.read_blocks(fh, [
('codec_id_format_tag', 2, True),
('number_of_channels', 2, True),
('samples_per_second', 4, True),
('avg_bytes_per_second', 4, True),
('block_alignment', 2, True),
('bits_per_sample', 2, True),
])
self.samplerate = stream_info['samples_per_second']
self.bitrate = stream_info['avg_bytes_per_second'] * 8 / 1000
if stream_info['codec_id_format_tag'] == 355: # lossless
self.bitdepth = stream_info['bits_per_sample']
already_read = 16
fh.seek(blocks['type_specific_data_length'] - already_read, os.SEEK_CUR)
fh.seek(blocks['error_correction_data_length'], os.SEEK_CUR)
else:
fh.seek(object_size - 24, os.SEEK_CUR) # read over onknown object ids
class Aiff(TinyTag):
#
# AIFF is part of the IFF family of file formats.
#
# https://en.wikipedia.org/wiki/Audio_Interchange_File_Format#Data_format
# https://web.archive.org/web/20171118222232/http://www-mmsp.ece.mcgill.ca/documents/audioformats/aiff/aiff.html
# https://web.archive.org/web/20071219035740/http://www.cnpbagwell.com/aiff-c.txt
#
# A few things about the spec:
#
# * IFF strings are not supposed to be null terminated. They sometimes are.
# * Some tools might throw more metadata into the ANNO chunk but it is
# wildly unreliable to count on it. In fact, the official spec recommends against
# using it. That said... this code throws the ANNO field into comment and hopes
# for the best.
#
# The key thing here is that AIFF metadata is usually in a handful of fields
# and the rest is an ID3 or XMP field. XMP is too complicated and only Adobe-related
# products support it. The vast majority use ID3. As such, this code inherits from
# ID3 rather than TinyTag since it does everything that needs to be done here.
#
aiff_mapping = {
#
# "Name Chunk text contains the name of the sampled sound."
#
# "Author Chunk text contains one or more author names. An author in
# this case is the creator of a sampled sound."
#
# "Annotation Chunk text contains a comment. Use of this chunk is
# discouraged within FORM AIFC." Some tools: "hold my beer"
#
# "The Copyright Chunk contains a copyright notice for the sound. text
# contains a date followed by the copyright owner. The chunk ID '[c] '
# serves as the copyright character. " Some tools: "hold my beer"
#
b'NAME': 'title',
b'AUTH': 'artist',
b'ANNO': 'comment',
b'(c) ': 'extra.copyright',
}
def __init__(self, filehandler, filesize, *args, **kwargs):
TinyTag.__init__(self, filehandler, filesize, *args, **kwargs)
self._tags_parsed = False
def _parse_tag(self, fh):
chunk_id, size, form = struct.unpack('>4sI4s', fh.read(12))
if chunk_id != b'FORM' or form not in (b'AIFC', b'AIFF'):
raise TinyTagException('not an aiff file!')
chunk_header = fh.read(8)
while len(chunk_header) == 8:
sub_chunk_id, sub_chunk_size = struct.unpack('>4sI', chunk_header)
sub_chunk_size += sub_chunk_size % 2 # IFF chunks are padded to an even number of bytes
if sub_chunk_id in self.aiff_mapping and self._parse_tags:
value = self._unpad(fh.read(sub_chunk_size).decode('utf-8'))
self._set_field(self.aiff_mapping[sub_chunk_id], value)
elif sub_chunk_id == b'COMM':
self.channels, num_frames, self.bitdepth = struct.unpack('>hLh', fh.read(8))
try:
exponent, mantissa = struct.unpack('>HQ', fh.read(10)) # Extended precision
self.samplerate = int(mantissa * (2 ** (exponent - 0x3FFF - 63)))
self.duration = num_frames / self.samplerate
self.bitrate = self.samplerate * self.channels * self.bitdepth / 1000
except OverflowError:
self.samplerate = self.duration = self.bitrate = None # invalid sample rate
fh.seek(sub_chunk_size - 18, 1) # skip remaining data in chunk
elif sub_chunk_id in (b'id3 ', b'ID3 ') and self._parse_tags:
id3 = ID3(fh, 0)
id3.load(tags=True, duration=False, image=self._load_image)
self.update(id3)
elif sub_chunk_id == b'SSND':
self.audio_offset = fh.tell()
fh.seek(sub_chunk_size, 1)
else: # some other chunk, just skip the data
fh.seek(sub_chunk_size, 1)
chunk_header = fh.read(8)
self._tags_parsed = True
def _determine_duration(self, fh):
if not self._tags_parsed:
self._parse_tag(fh)
| 71,391 | Python | .py | 1,362 | 39.920705 | 141 | 0.55533 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,430 | mainwindow.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/mainwindow.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2016-2018 Mutnick <mutnick@techie.com>
# COPYRIGHT (C) 2008-2011 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2009 hedonist <ak@sensi.org>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import time
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
import pynicotine
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.buddies import Buddies
from pynicotine.gtkgui.chatrooms import ChatRooms
from pynicotine.gtkgui.downloads import Downloads
from pynicotine.gtkgui.interests import Interests
from pynicotine.gtkgui.privatechat import PrivateChats
from pynicotine.gtkgui.search import Searches
from pynicotine.gtkgui.uploads import Uploads
from pynicotine.gtkgui.userbrowse import UserBrowses
from pynicotine.gtkgui.userinfo import UserInfos
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.dialogs import MessageDialog
from pynicotine.gtkgui.widgets.iconnotebook import IconNotebook
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.textentry import TextSearchBar
from pynicotine.gtkgui.widgets.textview import TextView
from pynicotine.gtkgui.widgets.theme import USER_STATUS_ICON_NAMES
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.theme import remove_css_class
from pynicotine.gtkgui.widgets.theme import set_global_style
from pynicotine.gtkgui.widgets.theme import set_use_header_bar
from pynicotine.gtkgui.widgets.window import Window
from pynicotine.logfacility import log
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import open_folder_path
class MainWindow(Window):
def __init__(self, application):
self.application = application
self.current_page_id = ""
self.auto_away = False
self.away_timer_id = None
self.away_cooldown_time = 0
self.gesture_click = None
self.window_active_handler = None
self.window_visible_handler = None
# Load UI
(
self.add_buddy_entry,
self.buddy_list_container,
self.chatrooms_buddy_list_container,
self.chatrooms_container,
self.chatrooms_content,
self.chatrooms_end,
self.chatrooms_entry,
self.chatrooms_page,
self.chatrooms_paned,
self.chatrooms_title,
self.chatrooms_toolbar,
self.connections_label,
self.container,
self.content,
self.download_files_label,
self.download_status_button,
self.download_status_label,
self.download_users_button,
self.download_users_label,
self.downloads_content,
self.downloads_end,
self.downloads_expand_button,
self.downloads_expand_icon,
self.downloads_grouping_button,
self.downloads_page,
self.downloads_title,
self.downloads_toolbar,
self.header_bar,
self.header_end,
self.header_end_container,
self.header_menu,
self.header_title,
self.hide_window_button,
self.horizontal_paned,
self.interests_container,
self.interests_end,
self.interests_page,
self.interests_title,
self.interests_toolbar,
self.log_container,
self.log_search_bar,
self.log_view_container,
self.private_content,
self.private_end,
self.private_entry,
self.private_history_button,
self.private_history_label,
self.private_page,
self.private_title,
self.private_toolbar,
self.room_list_button,
self.room_list_label,
self.room_search_entry,
self.scan_progress_container,
self.scan_progress_spinner,
self.search_content,
self.search_end,
self.search_entry,
self.search_mode_button,
self.search_mode_label,
self.search_page,
self.search_title,
self.search_toolbar,
self.status_label,
self.upload_files_label,
self.upload_status_button,
self.upload_status_label,
self.upload_users_button,
self.upload_users_label,
self.uploads_content,
self.uploads_end,
self.uploads_expand_button,
self.uploads_expand_icon,
self.uploads_grouping_button,
self.uploads_page,
self.uploads_title,
self.uploads_toolbar,
self.user_search_entry,
self.user_status_button,
self.user_status_icon,
self.user_status_label,
self.userbrowse_content,
self.userbrowse_end,
self.userbrowse_entry,
self.userbrowse_page,
self.userbrowse_title,
self.userbrowse_toolbar,
self.userinfo_content,
self.userinfo_end,
self.userinfo_entry,
self.userinfo_page,
self.userinfo_title,
self.userinfo_toolbar,
self.userlist_content,
self.userlist_end,
self.userlist_page,
self.userlist_title,
self.userlist_toolbar,
self.vertical_paned
) = ui.load(scope=self, path="mainwindow.ui")
super().__init__(widget=Gtk.ApplicationWindow(child=self.container))
self.header_bar.pack_end(self.header_end)
if GTK_API_VERSION >= 4:
self.header_bar.set_show_title_buttons(True)
self.horizontal_paned.set_resize_start_child(True)
self.horizontal_paned.set_shrink_start_child(False)
self.horizontal_paned.set_resize_end_child(False)
self.chatrooms_paned.set_resize_end_child(False)
self.chatrooms_paned.set_shrink_start_child(False)
self.vertical_paned.set_resize_start_child(True)
self.vertical_paned.set_shrink_start_child(False)
self.vertical_paned.set_resize_end_child(False)
self.vertical_paned.set_shrink_end_child(False)
# Workaround for screen reader support in GTK <4.12
for label, button in (
(self.search_mode_label, self.search_mode_button),
(self.private_history_label, self.private_history_button),
(self.room_list_label, self.room_list_button),
(self.download_status_label, self.download_status_button),
(self.upload_status_label, self.upload_status_button)
):
inner_button = next(iter(button))
label.set_mnemonic_widget(inner_button)
else:
self.header_bar.set_has_subtitle(False)
self.header_bar.set_show_close_button(True)
self.horizontal_paned.child_set_property(self.vertical_paned, "resize", True)
self.horizontal_paned.child_set_property(self.vertical_paned, "shrink", False)
self.horizontal_paned.child_set_property(self.buddy_list_container, "resize", False)
self.chatrooms_paned.child_set_property(self.chatrooms_buddy_list_container, "resize", False)
self.chatrooms_paned.child_set_property(self.chatrooms_container, "shrink", False)
self.vertical_paned.child_set_property(self.content, "resize", True)
self.vertical_paned.child_set_property(self.content, "shrink", False)
self.vertical_paned.child_set_property(self.log_container, "resize", False)
self.vertical_paned.child_set_property(self.log_container, "shrink", False)
# Logging
self.log_view = TextView(
self.log_view_container, auto_scroll=not config.sections["logging"]["logcollapsed"],
parse_urls=False, editable=False, vertical_margin=5, pixels_below_lines=2
)
self.log_search_bar = TextSearchBar(
self.log_view.widget, self.log_search_bar, controller_widget=self.log_container,
placeholder_text=_("Search log…")
)
self.create_log_context_menu()
events.connect("log-message", self.log_callback)
# Events
for event_name, callback in (
("server-login", self.update_user_status),
("server-disconnect", self.update_user_status),
("set-connection-stats", self.set_connection_stats),
("shares-preparing", self.shares_preparing),
("shares-ready", self.shares_ready),
("shares-scanning", self.shares_scanning),
("user-status", self.user_status)
):
events.connect(event_name, callback)
# Main notebook
self.notebook = IconNotebook(
self,
parent=self.content,
switch_page_callback=self.on_switch_page,
reorder_page_callback=self.on_page_reordered
)
# Secondary notebooks
self.interests = Interests(self)
self.chatrooms = ChatRooms(self)
self.search = Searches(self)
self.downloads = Downloads(self)
self.uploads = Uploads(self)
self.buddies = Buddies(self)
self.privatechat = PrivateChats(self)
self.userinfo = UserInfos(self)
self.userbrowse = UserBrowses(self)
self.tabs = {
"chatrooms": self.chatrooms,
"downloads": self.downloads,
"interests": self.interests,
"private": self.privatechat,
"search": self.search,
"uploads": self.uploads,
"userbrowse": self.userbrowse,
"userinfo": self.userinfo,
"userlist": self.buddies
}
# Actions and menu
self.set_up_actions()
self.set_up_menu()
# Tab visibility/order
self.append_main_tabs()
self.set_tab_positions()
self.set_main_tabs_order()
self.set_main_tabs_visibility()
self.set_last_session_tab()
self.connect_tab_signals()
# Apply UI customizations
set_global_style()
# Show window
self.init_window()
# Initialize #
def init_window(self):
is_broadway_backend = (os.environ.get("GDK_BACKEND") == "broadway")
# Set main window title and icon
self.set_title(pynicotine.__application_name__)
self.widget.set_default_icon_name(pynicotine.__application_id__)
# Set main window size
self.widget.set_default_size(width=config.sections["ui"]["width"],
height=config.sections["ui"]["height"])
# Set main window position
if GTK_API_VERSION == 3:
x_pos = config.sections["ui"]["xposition"]
y_pos = config.sections["ui"]["yposition"]
if x_pos == -1 and y_pos == -1:
self.widget.set_position(Gtk.WindowPosition.CENTER)
else:
self.widget.move(x_pos, y_pos)
# Hide close button in Broadway backend
if is_broadway_backend:
self.widget.set_deletable(False)
# Maximize main window if necessary
if config.sections["ui"]["maximized"] or is_broadway_backend:
self.widget.maximize()
# Auto-away mode
if GTK_API_VERSION >= 4:
self.gesture_click = Gtk.GestureClick()
self.widget.add_controller(self.gesture_click)
key_controller = Gtk.EventControllerKey()
key_controller.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
key_controller.connect("key-released", self.on_cancel_auto_away)
self.widget.add_controller(key_controller)
else:
self.gesture_click = Gtk.GestureMultiPress(widget=self.widget)
self.widget.connect("key-release-event", self.on_cancel_auto_away)
self.gesture_click.set_button(0)
self.gesture_click.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
self.gesture_click.connect("pressed", self.on_cancel_auto_away)
# Clear notifications when main window is focused
self.window_active_handler = self.widget.connect("notify::is-active", self.on_window_active_changed)
self.window_visible_handler = self.widget.connect("notify::visible", self.on_window_visible_changed)
# System window close (X)
if GTK_API_VERSION >= 4:
self.widget.connect("close-request", self.on_close_window_request)
else:
self.widget.connect("delete-event", self.on_close_window_request)
self.application.add_window(self.widget)
def set_help_overlay(self, help_overlay):
self.widget.set_help_overlay(help_overlay)
# Window State #
def on_window_active_changed(self, *_args):
self.save_window_state()
if not self.is_active():
return
self.chatrooms.clear_notifications()
self.privatechat.clear_notifications()
self.on_cancel_auto_away()
self.set_urgency_hint(False)
def on_window_visible_changed(self, *_args):
self.application.tray_icon.update()
def update_title(self):
notification_text = ""
if not config.sections["notifications"]["notification_window_title"]:
# Reset Title
pass
elif self.privatechat.highlighted_users:
# Private Chats have a higher priority
user = self.privatechat.highlighted_users[-1]
notification_text = _("Private Message from %(user)s") % {"user": user}
self.set_urgency_hint(True)
elif self.chatrooms.highlighted_rooms:
# Allow for the possibility the username is not available
room, user = list(self.chatrooms.highlighted_rooms.items())[-1]
notification_text = _("Mentioned by %(user)s in Room %(room)s") % {"user": user, "room": room}
self.set_urgency_hint(True)
elif any(is_important for is_important in self.search.unread_pages.values()):
notification_text = _("Wishlist Results Found")
if not notification_text:
self.set_title(pynicotine.__application_name__)
return
self.set_title(f"{pynicotine.__application_name__} - {notification_text}")
def set_urgency_hint(self, enabled):
surface = self.get_surface()
is_active = self.is_active()
try:
surface.set_urgency_hint(enabled and not is_active)
except AttributeError:
# No support for urgency hints
pass
def save_window_state(self):
config.sections["ui"]["maximized"] = self.is_maximized()
if config.sections["ui"]["maximized"]:
return
width = self.get_width()
height = self.get_height()
if width <= 0 or height <= 0:
return
config.sections["ui"]["width"] = width
config.sections["ui"]["height"] = height
position = self.get_position()
if position is None:
return
x_pos, y_pos = position
config.sections["ui"]["xposition"] = x_pos
config.sections["ui"]["yposition"] = y_pos
# Actions #
def add_action(self, action):
self.widget.add_action(action)
def lookup_action(self, action_name):
return self.widget.lookup_action(action_name)
def set_up_actions(self):
# Main
if GTK_API_VERSION == 3:
action = Gio.SimpleAction(name="main-menu")
action.connect("activate", self.on_menu)
self.add_action(action)
action = Gio.SimpleAction(name="change-focus-view")
action.connect("activate", self.on_change_focus_view)
self.add_action(action)
action = Gio.SimpleAction(name="toggle-status")
action.connect("activate", self.on_toggle_status)
self.add_action(action)
# View
state = GLib.Variant.new_boolean(not config.sections["logging"]["logcollapsed"])
action = Gio.SimpleAction(name="show-log-pane", state=state)
action.connect("change-state", self.on_show_log_pane)
self.add_action(action)
# Search
state = GLib.Variant.new_string("global")
action = Gio.SimpleAction(name="search-mode", parameter_type=state.get_type(), state=state)
action.connect("change-state", self.search.on_search_mode)
self.add_action(action)
# Notebook Tabs
action = Gio.SimpleAction(name="reopen-closed-tab")
action.connect("activate", self.on_reopen_closed_tab)
self.add_action(action)
action = Gio.SimpleAction(name="close-tab")
action.connect("activate", self.on_close_tab)
self.add_action(action)
action = Gio.SimpleAction(name="cycle-tabs")
action.connect("activate", self.on_cycle_tabs)
self.add_action(action)
action = Gio.SimpleAction(name="cycle-tabs-reverse")
action.connect("activate", self.on_cycle_tabs, True)
self.add_action(action)
for num in range(1, 10):
action = Gio.SimpleAction(name=f"primary-tab-{num}")
action.connect("activate", self.on_change_primary_tab, num)
self.add_action(action)
# Primary Menus #
def set_up_menu(self):
menu = self.application.create_hamburger_menu()
self.header_menu.set_menu_model(menu.model)
if GTK_API_VERSION == 3:
return
# F10 shortcut to open menu
self.header_menu.set_primary(True)
# Ensure menu button always gets focus after closing menu
popover = self.header_menu.get_popover()
popover.connect("closed", lambda *_args: self.header_menu.grab_focus())
def on_menu(self, *_args):
self.header_menu.set_active(not self.header_menu.get_active())
# Headerbar/Toolbar #
def show_header_bar(self, page_id):
"""Set a headerbar for the main window (client side decorations
enabled)"""
if self.widget.get_titlebar() != self.header_bar:
self.widget.set_titlebar(self.header_bar)
self.widget.set_show_menubar(False)
if GTK_API_VERSION == 3:
self.lookup_action("main-menu").set_enabled(True)
# Avoid "Untitled window" in certain desktop environments
self.header_bar.set_title(self.widget.get_title())
title_widget = self.tabs[page_id].toolbar_start_content
title_widget.get_parent().remove(title_widget)
end_widget = self.tabs[page_id].toolbar_end_content
end_widget.get_parent().remove(end_widget)
for widget in end_widget:
# Themes decide if header bar buttons should be flat
if isinstance(widget, Gtk.Button):
remove_css_class(widget, "flat")
# Header bars never contain separators, hide them
elif isinstance(widget, Gtk.Separator):
widget.set_visible(False)
if GTK_API_VERSION >= 4:
self.header_title.append(title_widget)
self.header_end_container.append(end_widget)
else:
self.header_title.add(title_widget)
self.header_end_container.add(end_widget)
def hide_current_header_bar(self):
"""Hide the current CSD headerbar."""
if not self.current_page_id:
return
if self.header_bar.get_focus_child():
# Unfocus the header bar
self.notebook.grab_focus()
title_widget = self.tabs[self.current_page_id].toolbar_start_content
end_widget = self.tabs[self.current_page_id].toolbar_end_content
self.header_title.remove(title_widget)
self.header_end_container.remove(end_widget)
toolbar = self.tabs[self.current_page_id].toolbar
toolbar_content = next(iter(toolbar))
if GTK_API_VERSION >= 4:
toolbar_content.append(title_widget)
toolbar_content.append(end_widget)
else:
toolbar_content.add(title_widget)
toolbar_content.add(end_widget)
def show_toolbar(self, page_id):
"""Show the non-CSD toolbar."""
if not self.widget.get_show_menubar():
self.widget.set_show_menubar(True)
self.header_menu.get_popover().set_visible(False)
if GTK_API_VERSION == 3:
# Don't override builtin accelerator for menu bar
self.lookup_action("main-menu").set_enabled(False)
if self.widget.get_titlebar():
self.widget.unrealize()
self.widget.set_titlebar(None)
self.widget.map()
for widget in self.tabs[page_id].toolbar_end_content:
# Make secondary buttons at the end of the toolbar flat. Keep buttons
# next to text entries raised for more prominence.
if isinstance(widget, Gtk.Button):
add_css_class(widget, "flat")
elif isinstance(widget, Gtk.Separator):
widget.set_visible(True)
toolbar = self.tabs[page_id].toolbar
toolbar.set_visible(True)
def hide_current_toolbar(self):
"""Hide the current toolbar."""
if not self.current_page_id:
return
toolbar = self.tabs[self.current_page_id].toolbar
toolbar.set_visible(False)
def set_active_header_bar(self, page_id):
"""Switch out the active headerbar for another one.
This is used when changing the active notebook tab.
"""
if config.sections["ui"]["header_bar"]:
self.hide_current_header_bar()
self.show_header_bar(page_id)
else:
self.hide_current_toolbar()
self.show_toolbar(page_id)
self.current_page_id = config.sections["ui"]["last_tab_id"] = page_id
def _show_dialogs(self, dialogs):
for dialog in dialogs:
dialog.present()
def set_use_header_bar(self, enabled):
if enabled == (not self.widget.get_show_menubar()):
return
active_dialogs = Window.active_dialogs
# Hide active dialogs to prevent parenting issues
for dialog in reversed(active_dialogs):
dialog.hide()
# Toggle header bar
if enabled:
self.hide_current_toolbar()
self.show_header_bar(self.current_page_id)
else:
self.hide_current_header_bar()
self.show_toolbar(self.current_page_id)
set_use_header_bar(enabled)
config.sections["ui"]["header_bar"] = enabled
# Show active dialogs again after a slight delay
if active_dialogs:
GLib.idle_add(self._show_dialogs, active_dialogs)
def on_change_focus_view(self, *_args):
"""F6 - move focus between header bar/toolbar and main content."""
tab = self.tabs[self.current_page_id]
title_widget = tab.toolbar_start_content
# Find the correct widget to focus in the main view
if title_widget.get_focus_child():
if isinstance(tab, IconNotebook):
# Attempt to focus a widget in a secondary notebook
notebook = tab
secondary_page = notebook.get_current_page()
if secondary_page is not None:
# Found a focusable widget
secondary_page.focus_callback()
return
else:
# No notebook present, attempt to focus the main content widget
page_container = next(iter(tab.page))
content_widget = list(page_container)[-1]
if content_widget.child_focus(Gtk.DirectionType.TAB_FORWARD):
# Found a focusable widget
return
# Find the correct widget to focus in the header bar/toolbar
if tab.toolbar_default_widget is not None:
tab.toolbar_default_widget.grab_focus()
# Main Notebook #
def append_main_tabs(self):
for tab_id, tab_text, tab_icon_name in (
("search", _("Search Files"), "system-search-symbolic"),
("downloads", _("Downloads"), "folder-download-symbolic"),
("uploads", _("Uploads"), "emblem-shared-symbolic"),
("userbrowse", _("Browse Shares"), "folder-symbolic"),
("userinfo", _("User Profiles"), "avatar-default-symbolic"),
("private", _("Private Chat"), "mail-unread-symbolic"),
("userlist", _("Buddies"), "system-users-symbolic"),
("chatrooms", _("Chat Rooms"), "user-available-symbolic"),
("interests", _("Interests"), "face-smile-big-symbolic")
):
tab = self.tabs[tab_id]
self.notebook.append_page(tab.page, tab_text, focus_callback=tab.on_focus)
tab_label = self.notebook.get_tab_label(tab.page)
tab_label.set_start_icon_name(tab_icon_name)
self.notebook.set_tab_reorderable(tab.page, True)
self.set_tab_expand(tab.page)
def connect_tab_signals(self):
self.notebook.connect_signals()
self.chatrooms.connect_signals()
self.search.connect_signals()
self.privatechat.connect_signals()
self.userinfo.connect_signals()
self.userbrowse.connect_signals()
def on_switch_page(self, _notebook, page, _page_num):
self.set_active_header_bar(page.id)
def on_page_reordered(self, *_args):
page_ids = []
for i in range(self.notebook.get_n_pages()):
page = self.notebook.get_nth_page(i)
page_ids.append(page.id)
config.sections["ui"]["modes_order"] = page_ids
def on_reopen_closed_tab(self, *_args):
"""Ctrl+Shift+T - reopen recently closed tab."""
tab = self.tabs[self.current_page_id]
if not isinstance(tab, IconNotebook):
return False
notebook = tab
notebook.restore_removed_page()
return True
def on_close_tab(self, *_args):
"""Ctrl+W and Ctrl+F4 - close current secondary tab."""
tab = self.tabs[self.current_page_id]
if not isinstance(tab, IconNotebook):
return False
notebook = tab
secondary_page = notebook.get_current_page()
if secondary_page is None:
return False
tab_label = notebook.get_tab_label(secondary_page)
tab_label.close_callback()
return True
def on_cycle_tabs(self, _widget, _state, backwards=False):
"""Ctrl+Tab and Shift+Ctrl+Tab - cycle through secondary tabs."""
tab = self.tabs[self.current_page_id]
if not isinstance(tab, IconNotebook):
return False
notebook = tab
num_pages = notebook.get_n_pages()
current_page_num = notebook.get_current_page_num()
if backwards:
if current_page_num <= 0:
notebook.set_current_page_num(num_pages - 1)
else:
notebook.prev_page()
return True
if current_page_num == (num_pages - 1):
notebook.set_current_page_num(0)
else:
notebook.next_page()
return True
def on_change_primary_tab(self, _widget, _state, tab_num=1):
"""Alt+1-9 or Ctrl+1-9 - change main tab."""
visible_pages = []
for i in range(self.notebook.get_n_pages()):
page = self.notebook.get_nth_page(i)
if page.get_visible():
visible_pages.append(page)
if len(visible_pages) < tab_num:
return False
page_num = self.notebook.page_num(visible_pages[tab_num - 1])
self.notebook.set_current_page_num(page_num)
return True
def change_main_page(self, page):
self.show_tab(page)
self.notebook.set_current_page(page)
def show_tab(self, page):
config.sections["ui"]["modes_visible"][page.id] = True
page.set_visible(True)
self.content.set_visible(True)
def hide_tab(self, page):
config.sections["ui"]["modes_visible"][page.id] = False
page.set_visible(False)
if self.notebook.get_n_pages() <= 1:
self.content.set_visible(False)
def set_main_tabs_order(self):
for order, page_id in enumerate(config.sections["ui"]["modes_order"]):
tab = self.tabs.get(page_id)
if tab is not None:
self.notebook.reorder_child(tab.page, order)
def set_main_tabs_visibility(self):
visible_tab_found = False
buddies_tab_active = (config.sections["ui"]["buddylistinchatrooms"] == "tab")
for i in range(self.notebook.get_n_pages()):
page = self.notebook.get_nth_page(i)
if config.sections["ui"]["modes_visible"].get(page.id, True):
if page.id == "userlist" and not buddies_tab_active:
continue
visible_tab_found = True
self.show_tab(page)
continue
self.hide_tab(page)
if not visible_tab_found:
# Ensure at least one tab is visible
self.show_tab(self.search_page)
def set_last_session_tab(self):
if not config.sections["ui"]["tab_select_previous"]:
return
last_tab_id = config.sections["ui"]["last_tab_id"]
tab = self.tabs.get(last_tab_id)
if tab is None:
return
if tab.page.get_visible():
self.notebook.set_current_page(tab.page)
def set_tab_expand(self, page):
tab_position = config.sections["ui"]["tabmain"]
expand = tab_position in {"Top", "Bottom"}
self.notebook.set_tab_expand(page, expand)
def set_tab_positions(self):
default_pos = Gtk.PositionType.TOP
positions = {
"Top": Gtk.PositionType.TOP,
"Bottom": Gtk.PositionType.BOTTOM,
"Left": Gtk.PositionType.LEFT,
"Right": Gtk.PositionType.RIGHT
}
# Main notebook
main_position = positions.get(config.sections["ui"]["tabmain"], default_pos)
self.notebook.set_tab_pos(main_position)
# Ensure title/menubar borders are visible when needed
remove_css_class(self.widget, "menubar-border")
remove_css_class(self.widget, "titlebar-border")
if main_position != Gtk.PositionType.TOP:
if config.sections["ui"]["header_bar"]:
add_css_class(self.widget, "titlebar-border")
add_css_class(self.widget, "menubar-border")
# Other notebooks
self.chatrooms.set_tab_pos(positions.get(config.sections["ui"]["tabrooms"], default_pos))
self.privatechat.set_tab_pos(positions.get(config.sections["ui"]["tabprivate"], default_pos))
self.userinfo.set_tab_pos(positions.get(config.sections["ui"]["tabinfo"], default_pos))
self.userbrowse.set_tab_pos(positions.get(config.sections["ui"]["tabbrowse"], default_pos))
self.search.set_tab_pos(positions.get(config.sections["ui"]["tabsearch"], default_pos))
# Connection #
def update_user_status(self, *_args):
status = core.users.login_status
is_away = (status == UserStatus.AWAY)
# Away mode
if not is_away:
self.set_auto_away(False)
else:
self.remove_away_timer()
# Status bar
username = core.users.login_username
icon_name = USER_STATUS_ICON_NAMES[status]
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
if status == UserStatus.AWAY:
status_text = _("Away")
elif status == UserStatus.ONLINE:
status_text = _("Online")
else:
username = None
status_text = _("Offline")
if self.user_status_button.get_tooltip_text() != username:
# Hide widget to keep tooltips for other widgets visible
self.user_status_button.set_visible(False)
self.user_status_button.set_tooltip_text(username)
self.user_status_button.set_visible(True)
if self.user_status_label.get_text() != status_text:
self.user_status_icon.set_from_icon_name(icon_name, *icon_args)
self.user_status_label.set_text(status_text)
if self.user_status_button.get_active():
toggle_status_action = self.lookup_action("toggle-status")
toggle_status_action.set_enabled(False)
self.user_status_button.set_active(False)
toggle_status_action.set_enabled(True)
def user_status(self, msg):
if msg.user == core.users.login_username:
self.update_user_status()
# Search #
def on_search(self, *_args):
self.search.on_search()
def on_search_entry_changed(self, entry, *_args):
entry.props.secondary_icon_name = "edit-clear-symbolic" if entry.get_text() else None
def on_search_entry_icon_press(self, entry, icon_pos, *_args):
if icon_pos == Gtk.EntryIconPosition.SECONDARY:
entry.set_text("")
return
self.on_search()
# User Info #
def on_show_user_profile(self, *_args):
self.userinfo.on_show_user_profile()
# Shares #
def on_get_shares(self, *_args):
self.userbrowse.on_get_shares()
# Chat #
def on_get_private_chat(self, *_args):
self.privatechat.on_get_private_chat()
def on_create_room(self, *_args):
self.chatrooms.on_create_room()
# Away Mode #
def set_auto_away(self, active=True):
if active:
self.auto_away = True
self.away_timer_id = None
if core.users.login_status != UserStatus.AWAY:
core.users.set_away_mode(True)
return
if self.auto_away:
self.auto_away = False
if core.users.login_status == UserStatus.AWAY:
core.users.set_away_mode(False)
# Reset away timer
self.remove_away_timer()
self.create_away_timer()
def create_away_timer(self):
if core.users.login_status != UserStatus.ONLINE:
return
away_interval = config.sections["server"]["autoaway"]
if away_interval > 0:
self.away_timer_id = events.schedule(delay=(60 * away_interval), callback=self.set_auto_away)
def remove_away_timer(self):
events.cancel_scheduled(self.away_timer_id)
def on_cancel_auto_away(self, *_args):
current_time = time.monotonic()
if (current_time - self.away_cooldown_time) >= 5:
self.set_auto_away(False)
self.away_cooldown_time = current_time
# User Actions #
def on_add_buddy(self, *_args):
self.buddies.on_add_buddy()
# Log Pane #
def create_log_context_menu(self):
self.popup_menu_log_categories = PopupMenu(self.application)
self.popup_menu_log_categories.add_items(
("$" + _("Downloads"), "app.log-downloads"),
("$" + _("Uploads"), "app.log-uploads"),
("$" + _("Search"), "app.log-searches"),
("$" + _("Chat"), "app.log-chat"),
("", None),
("$" + _("[Debug] Connections"), "app.log-connections"),
("$" + _("[Debug] Messages"), "app.log-messages"),
("$" + _("[Debug] Transfers"), "app.log-transfers"),
("$" + _("[Debug] Miscellaneous"), "app.log-miscellaneous"),
)
self.popup_menu_log_view = PopupMenu(self.application, self.log_view.widget, self.on_popup_menu_log)
self.popup_menu_log_view.add_items(
("#" + _("_Find…"), self.on_find_log_window),
("", None),
("#" + _("_Copy"), self.log_view.on_copy_text),
("#" + _("Copy _All"), self.log_view.on_copy_all_text),
("", None),
("#" + _("View _Debug Logs"), self.on_view_debug_logs),
("#" + _("View _Transfer Logs"), self.on_view_transfer_logs),
("", None),
(">" + _("_Log Categories"), self.popup_menu_log_categories),
("", None),
("#" + _("Clear Log View"), self.on_clear_log_view)
)
def log_callback(self, timestamp_format, msg, title, level):
events.invoke_main_thread(self.update_log, timestamp_format, msg, title, level)
def update_log(self, timestamp_format, msg, title, level):
if title:
MessageDialog(parent=self, title=title, message=msg).present()
# Keep verbose debug messages out of statusbar to make it more useful
if level not in {"transfer", "connection", "message", "miscellaneous"}:
self.set_status_text(msg)
self.log_view.append_line(msg, timestamp_format=timestamp_format)
def on_popup_menu_log(self, menu, _textview):
menu.actions[_("_Copy")].set_enabled(self.log_view.get_has_selection())
def on_find_log_window(self, *_args):
self.log_search_bar.set_visible(True)
@staticmethod
def on_view_debug_logs(*_args):
open_folder_path(log.debug_folder_path, create_folder=True)
@staticmethod
def on_view_transfer_logs(*_args):
open_folder_path(log.transfer_folder_path, create_folder=True)
def on_clear_log_view(self, *_args):
self.log_view.on_clear_all_text()
self.set_status_text("")
def on_show_log_pane(self, action, state):
action.set_state(state)
visible = state.get_boolean()
self.log_view.auto_scroll = visible
if visible:
self.log_view.scroll_bottom()
config.sections["logging"]["logcollapsed"] = not visible
# Status Bar #
def set_status_text(self, msg):
# Hide widget to keep tooltips for other widgets visible
self.status_label.set_visible(False)
self.status_label.set_text(msg)
self.status_label.set_tooltip_text(msg)
self.status_label.set_visible(True)
def set_connection_stats(self, total_conns=0, **_kwargs):
total_conns_text = repr(total_conns)
if self.connections_label.get_text() != total_conns_text:
self.connections_label.set_text(total_conns_text)
def shares_preparing(self):
# Hide widget to keep tooltips for other widgets visible
self.scan_progress_container.set_visible(False)
self.scan_progress_container.set_tooltip_text(_("Preparing Shares"))
self.scan_progress_container.set_visible(True)
self.scan_progress_spinner.start()
def shares_scanning(self):
# Hide widget to keep tooltips for other widgets visible
self.scan_progress_container.set_visible(False)
self.scan_progress_container.set_tooltip_text(_("Scanning Shares"))
self.scan_progress_container.set_visible(True)
self.scan_progress_spinner.start()
def shares_ready(self, _successful):
self.scan_progress_container.set_visible(False)
self.scan_progress_spinner.stop()
def on_toggle_status(self, *_args):
if core.uploads.pending_shutdown:
core.uploads.cancel_shutdown()
else:
self.application.lookup_action("away").activate()
self.user_status_button.set_active(False)
# Exit #
def on_close_window_request(self, *_args):
if not config.sections["ui"]["exitdialog"]: # 'Quit Program'
core.quit()
elif config.sections["ui"]["exitdialog"] == 1: # 'Show Confirmation Dialog'
core.confirm_quit()
elif config.sections["ui"]["exitdialog"] >= 2: # 'Run in Background'
self.hide()
return True
def hide(self):
if not self.is_visible():
return
# Close any visible dialogs
for dialog in reversed(Window.active_dialogs):
dialog.close()
# Save config, in case application is killed later
config.write_configuration()
# Hide window
if sys.platform == "darwin":
# macOS-specific way to hide the application, to ensure it is restored when clicking the dock icon
self.hide_window_button.set_action_name("gtkinternal.hide")
self.hide_window_button.emit("clicked")
return
if sys.platform == "win32":
if GTK_API_VERSION >= 4:
self.widget.minimize()
else:
self.widget.iconify()
super().hide()
def destroy(self):
for tab in self.tabs.values():
tab.destroy()
self.notebook.destroy()
self.log_search_bar.destroy()
self.log_view.destroy()
self.popup_menu_log_view.destroy()
self.popup_menu_log_categories.destroy()
self.widget.disconnect(self.window_active_handler)
self.widget.disconnect(self.window_visible_handler)
super().destroy()
| 42,241 | Python | .py | 932 | 34.921674 | 110 | 0.620452 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,431 | interests.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/interests.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GLib
from gi.repository import GObject
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.popupmenu import UserPopupMenu
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.gtkgui.widgets.theme import USER_STATUS_ICON_NAMES
from pynicotine.gtkgui.widgets.theme import get_flag_icon_name
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import humanize
from pynicotine.utils import human_speed
class Interests:
def __init__(self, window):
(
self.add_dislike_entry,
self.add_like_entry,
self.container,
self.dislikes_list_container,
self.likes_list_container,
self.recommendations_button,
self.recommendations_label,
self.recommendations_list_container,
self.similar_users_label,
self.similar_users_list_container
) = ui.load(scope=self, path="interests.ui")
if GTK_API_VERSION >= 4:
window.interests_container.append(self.container)
else:
window.interests_container.add(self.container)
self.window = window
self.page = window.interests_page
self.page.id = "interests"
self.toolbar = window.interests_toolbar
self.toolbar_start_content = window.interests_title
self.toolbar_end_content = window.interests_end
self.toolbar_default_widget = None
self.popup_menus = []
self.populated_recommends = False
# Columns
self.likes_list_view = TreeView(
window, parent=self.likes_list_container,
delete_accelerator_callback=self.on_remove_thing_i_like,
columns={
"likes": {
"column_type": "text",
"title": _("Likes"),
"default_sort_type": "ascending"
}
}
)
self.dislikes_list_view = TreeView(
window, parent=self.dislikes_list_container,
delete_accelerator_callback=self.on_remove_thing_i_dislike,
columns={
"dislikes": {
"column_type": "text",
"title": _("Dislikes"),
"default_sort_type": "ascending"
}
}
)
self.recommendations_list_view = TreeView(
window, parent=self.recommendations_list_container,
activate_row_callback=self.on_r_row_activated,
columns={
# Visible columns
"rating": {
"column_type": "number",
"title": _("Rating"),
"width": 0,
"sort_column": "rating_data",
"default_sort_type": "descending"
},
"item": {
"column_type": "text",
"title": _("Item"),
"iterator_key": True
},
# Hidden data columns
"rating_data": {"data_type": GObject.TYPE_INT}
}
)
self.similar_users_list_view = TreeView(
window, parent=self.similar_users_list_container,
activate_row_callback=self.on_ru_row_activated,
columns={
# Visible columns
"status": {
"column_type": "icon",
"title": _("Status"),
"width": 25,
"hide_header": True
},
"country": {
"column_type": "icon",
"title": _("Country"),
"width": 30,
"hide_header": True
},
"user": {
"column_type": "text",
"title": _("User"),
"width": 120,
"expand_column": True,
"iterator_key": True
},
"speed": {
"column_type": "number",
"title": _("Speed"),
"width": 90,
"sort_column": "speed_data",
"expand_column": True
},
"files": {
"column_type": "number",
"title": _("Files"),
"sort_column": "files_data",
"expand_column": True
},
# Hidden data columns
"speed_data": {"data_type": GObject.TYPE_UINT},
"files_data": {"data_type": GObject.TYPE_UINT},
"rating_data": {
"data_type": GObject.TYPE_UINT,
"default_sort_type": "descending"
}
}
)
self.likes_list_view.freeze()
self.dislikes_list_view.freeze()
for item in config.sections["interests"]["likes"]:
if isinstance(item, str):
self.add_thing_i_like(item, select_row=False)
for item in config.sections["interests"]["dislikes"]:
if isinstance(item, str):
self.add_thing_i_hate(item, select_row=False)
self.likes_list_view.unfreeze()
self.dislikes_list_view.unfreeze()
# Popup menus
popup = PopupMenu(self.window.application, self.likes_list_view.widget)
popup.add_items(
("#" + _("_Recommendations for Item"), self.on_recommend_item, self.likes_list_view, "likes"),
("#" + _("_Search for Item"), self.on_recommend_search, self.likes_list_view, "likes"),
("", None),
("#" + _("Remove"), self.on_remove_thing_i_like)
)
self.popup_menus.append(popup)
popup = PopupMenu(self.window.application, self.dislikes_list_view.widget)
popup.add_items(
("#" + _("_Recommendations for Item"), self.on_recommend_item, self.dislikes_list_view, "dislikes"),
("#" + _("_Search for Item"), self.on_recommend_search, self.dislikes_list_view, "dislikes"),
("", None),
("#" + _("Remove"), self.on_remove_thing_i_dislike)
)
self.popup_menus.append(popup)
popup = PopupMenu(self.window.application, self.recommendations_list_view.widget, self.on_popup_r_menu)
popup.add_items(
("$" + _("I _Like This"), self.on_like_recommendation, self.recommendations_list_view, "item"),
("$" + _("I _Dislike This"), self.on_dislike_recommendation, self.recommendations_list_view, "item"),
("", None),
("#" + _("_Recommendations for Item"), self.on_recommend_item, self.recommendations_list_view, "item"),
("#" + _("_Search for Item"), self.on_recommend_search, self.recommendations_list_view, "item")
)
self.popup_menus.append(popup)
popup = UserPopupMenu(
self.window.application, parent=self.similar_users_list_view.widget, callback=self.on_popup_ru_menu,
tab_name="interests"
)
self.popup_menus.append(popup)
for event_name, callback in (
("add-dislike", self.add_thing_i_hate),
("add-interest", self.add_thing_i_like),
("global-recommendations", self.global_recommendations),
("item-recommendations", self.item_recommendations),
("item-similar-users", self.item_similar_users),
("recommendations", self.recommendations),
("remove-dislike", self.remove_thing_i_hate),
("remove-interest", self.remove_thing_i_like),
("server-login", self.server_login),
("server-disconnect", self.server_disconnect),
("similar-users", self.similar_users),
("user-country", self.user_country),
("user-stats", self.user_stats),
("user-status", self.user_status)
):
events.connect(event_name, callback)
def destroy(self):
for menu in self.popup_menus:
menu.destroy()
self.likes_list_view.destroy()
self.dislikes_list_view.destroy()
self.recommendations_list_view.destroy()
self.similar_users_list_view.destroy()
self.__dict__.clear()
def on_focus(self, *_args):
self.populate_recommendations()
self.recommendations_list_view.grab_focus()
return True
def server_login(self, msg):
if not msg.success:
return
self.recommendations_button.set_sensitive(True)
if self.window.current_page_id != self.window.interests_page.id:
# Only populate recommendations if the tab is open on login
return
self.populate_recommendations()
def server_disconnect(self, *_args):
self.recommendations_button.set_sensitive(False)
for iterator in self.similar_users_list_view.iterators.values():
self.similar_users_list_view.set_row_value(iterator, "status", USER_STATUS_ICON_NAMES[UserStatus.OFFLINE])
self.populated_recommends = False
def populate_recommendations(self):
"""Populates the lists of recommendations and similar users if
empty."""
if self.populated_recommends or core.users.login_status == UserStatus.OFFLINE:
return
self.show_recommendations()
def show_recommendations(self):
self.recommendations_label.set_label(_("Recommendations"))
self.similar_users_label.set_label(_("Similar Users"))
if not self.likes_list_view.iterators and not self.dislikes_list_view.iterators:
core.interests.request_global_recommendations()
else:
core.interests.request_recommendations()
core.interests.request_similar_users()
self.populated_recommends = True
def show_item_recommendations(self, list_view, column_id):
for iterator in list_view.get_selected_rows():
item = list_view.get_row_value(iterator, column_id)
core.interests.request_item_recommendations(item)
core.interests.request_item_similar_users(item)
self.populated_recommends = True
if self.window.current_page_id != self.window.interests_page.id:
self.window.change_main_page(self.window.interests_page)
return
def add_thing_i_like(self, item, select_row=True):
item = item.strip().lower()
if not item:
return
iterator = self.likes_list_view.iterators.get(item)
if iterator is None:
self.likes_list_view.add_row([item], select_row=select_row)
def add_thing_i_hate(self, item, select_row=True):
item = item.strip().lower()
if not item:
return
iterator = self.dislikes_list_view.iterators.get(item)
if iterator is None:
self.dislikes_list_view.add_row([item], select_row=select_row)
def remove_thing_i_like(self, item):
iterator = self.likes_list_view.iterators.get(item)
if iterator is not None:
self.likes_list_view.remove_row(iterator)
def remove_thing_i_hate(self, item):
iterator = self.dislikes_list_view.iterators.get(item)
if iterator is not None:
self.dislikes_list_view.remove_row(iterator)
def on_add_thing_i_like(self, *_args):
item = self.add_like_entry.get_text().strip()
if not item:
return
self.add_like_entry.set_text("")
core.interests.add_thing_i_like(item)
def on_add_thing_i_dislike(self, *_args):
item = self.add_dislike_entry.get_text().strip()
if not item:
return
self.add_dislike_entry.set_text("")
core.interests.add_thing_i_hate(item)
def on_remove_thing_i_like(self, *_args):
for iterator in self.likes_list_view.get_selected_rows():
item = self.likes_list_view.get_row_value(iterator, "likes")
core.interests.remove_thing_i_like(item)
return
def on_remove_thing_i_dislike(self, *_args):
for iterator in self.dislikes_list_view.get_selected_rows():
item = self.dislikes_list_view.get_row_value(iterator, "dislikes")
core.interests.remove_thing_i_hate(item)
return
def on_like_recommendation(self, action, state, list_view, column_id):
for iterator in list_view.get_selected_rows():
item = list_view.get_row_value(iterator, column_id)
if state.get_boolean():
core.interests.add_thing_i_like(item)
else:
core.interests.remove_thing_i_like(item)
action.set_state(state)
return
def on_dislike_recommendation(self, action, state, list_view, column_id):
for iterator in list_view.get_selected_rows():
item = list_view.get_row_value(iterator, column_id)
if state.get_boolean():
core.interests.add_thing_i_hate(item)
else:
core.interests.remove_thing_i_hate(item)
action.set_state(state)
return
def on_recommend_item(self, _action, _state, list_view, column_id):
self.show_item_recommendations(list_view, column_id)
def on_recommend_search(self, _action, _state, list_view, column_id):
for iterator in list_view.get_selected_rows():
item = list_view.get_row_value(iterator, column_id)
core.search.do_search(item, mode="global")
return
def on_refresh_recommendations(self, *_args):
self.show_recommendations()
def set_recommendations(self, recommendations, item=None):
if item:
self.recommendations_label.set_label(_("Recommendations (%s)") % item)
else:
self.recommendations_label.set_label(_("Recommendations"))
self.recommendations_list_view.clear()
self.recommendations_list_view.freeze()
for thing, rating in recommendations:
self.recommendations_list_view.add_row([humanize(rating), thing, rating], select_row=False)
self.recommendations_list_view.unfreeze()
def global_recommendations(self, msg):
self.set_recommendations(msg.recommendations + msg.unrecommendations)
def recommendations(self, msg):
self.set_recommendations(msg.recommendations + msg.unrecommendations)
def item_recommendations(self, msg):
self.set_recommendations(msg.recommendations + msg.unrecommendations, msg.thing)
def set_similar_users(self, users, item=None):
if item:
self.similar_users_label.set_label(_("Similar Users (%s)") % item)
else:
self.similar_users_label.set_label(_("Similar Users"))
self.similar_users_list_view.clear()
self.similar_users_list_view.freeze()
for index, (user, rating) in enumerate(reversed(list(users.items()))):
status = core.users.statuses.get(user, UserStatus.OFFLINE)
country_code = core.users.countries.get(user, "")
stats = core.users.watched.get(user)
rating = index + (1000 * rating) # Preserve default sort order
if stats is not None:
speed = stats.upload_speed or 0
files = stats.files
else:
speed = 0
files = None
h_files = humanize(files) if files is not None else ""
h_speed = human_speed(speed) if speed > 0 else ""
self.similar_users_list_view.add_row([
USER_STATUS_ICON_NAMES[status],
get_flag_icon_name(country_code),
user,
h_speed,
h_files,
speed,
files or 0,
rating
], select_row=False)
self.similar_users_list_view.unfreeze()
def similar_users(self, msg):
self.set_similar_users(msg.users)
def item_similar_users(self, msg):
rating = 0
self.set_similar_users({user: rating for user in msg.users}, msg.thing)
def user_country(self, user, country_code):
iterator = self.similar_users_list_view.iterators.get(user)
if iterator is None:
return
flag_icon_name = get_flag_icon_name(country_code)
if flag_icon_name and flag_icon_name != self.similar_users_list_view.get_row_value(iterator, "country"):
self.similar_users_list_view.set_row_value(iterator, "country", flag_icon_name)
def user_status(self, msg):
iterator = self.similar_users_list_view.iterators.get(msg.user)
if iterator is None:
return
status_icon_name = USER_STATUS_ICON_NAMES.get(msg.status)
if status_icon_name and status_icon_name != self.similar_users_list_view.get_row_value(iterator, "status"):
self.similar_users_list_view.set_row_value(iterator, "status", status_icon_name)
def user_stats(self, msg):
iterator = self.similar_users_list_view.iterators.get(msg.user)
if iterator is None:
return
speed = msg.avgspeed or 0
num_files = msg.files or 0
column_ids = []
column_values = []
if speed != self.similar_users_list_view.get_row_value(iterator, "speed_data"):
h_speed = human_speed(speed) if speed > 0 else ""
column_ids.extend(("speed", "speed_data"))
column_values.extend((h_speed, speed))
if num_files != self.similar_users_list_view.get_row_value(iterator, "files_data"):
h_num_files = humanize(num_files)
column_ids.extend(("files", "files_data"))
column_values.extend((h_num_files, num_files))
if column_ids:
self.similar_users_list_view.set_row_values(iterator, column_ids, column_values)
@staticmethod
def toggle_menu_items(menu, list_view, column_id):
for iterator in list_view.get_selected_rows():
item = list_view.get_row_value(iterator, column_id)
menu.actions[_("I _Like This")].set_state(
GLib.Variant.new_boolean(item in config.sections["interests"]["likes"])
)
menu.actions[_("I _Dislike This")].set_state(
GLib.Variant.new_boolean(item in config.sections["interests"]["dislikes"])
)
return
def on_popup_r_menu(self, menu, *_args):
self.toggle_menu_items(menu, self.recommendations_list_view, column_id="item")
def on_r_row_activated(self, *_args):
self.show_item_recommendations(self.recommendations_list_view, column_id="item")
def on_popup_ru_menu(self, menu, *_args):
for iterator in self.similar_users_list_view.get_selected_rows():
user = self.similar_users_list_view.get_row_value(iterator, "user")
menu.set_user(user)
menu.toggle_user_items()
return
def on_ru_row_activated(self, *_args):
for iterator in self.similar_users_list_view.get_selected_rows():
user = self.similar_users_list_view.get_row_value(iterator, "user")
core.userinfo.show_user(user)
return
| 20,458 | Python | .py | 439 | 35.056948 | 118 | 0.598752 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,432 | userbrowse.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/userbrowse.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2013 SeeSchloss <see@seos.fr>
# COPYRIGHT (C) 2009-2010 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Pango
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.dialogs.fileproperties import FileProperties
from pynicotine.gtkgui.widgets import clipboard
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.combobox import ComboBox
from pynicotine.gtkgui.widgets.dialogs import EntryDialog
from pynicotine.gtkgui.widgets.filechooser import FolderChooser
from pynicotine.gtkgui.widgets.iconnotebook import IconNotebook
from pynicotine.gtkgui.widgets.infobar import InfoBar
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.popupmenu import FilePopupMenu
from pynicotine.gtkgui.widgets.popupmenu import UserPopupMenu
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.theme import get_file_type_icon_name
from pynicotine.gtkgui.widgets.theme import remove_css_class
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.slskmessages import ConnectionType
from pynicotine.slskmessages import FileListMessage
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import human_size
from pynicotine.utils import humanize
from pynicotine.utils import open_file_path
from pynicotine.utils import open_folder_path
class UserBrowses(IconNotebook):
def __init__(self, window):
super().__init__(
window,
parent=window.userbrowse_content,
parent_page=window.userbrowse_page
)
self.page = window.userbrowse_page
self.page.id = "userbrowse"
self.toolbar = window.userbrowse_toolbar
self.toolbar_start_content = window.userbrowse_title
self.toolbar_end_content = window.userbrowse_end
self.toolbar_default_widget = window.userbrowse_entry
self.file_properties = None
self.userbrowse_combobox = ComboBox(
container=self.window.userbrowse_title, has_entry=True, has_entry_completion=True,
entry=self.window.userbrowse_entry, item_selected_callback=self.on_get_shares
)
# Events
for event_name, callback in (
("peer-connection-closed", self.peer_connection_error),
("peer-connection-error", self.peer_connection_error),
("quit", self.quit),
("server-disconnect", self.server_disconnect),
("shared-file-list-progress", self.shared_file_list_progress),
("shared-file-list-response", self.shared_file_list),
("user-browse-remove-user", self.remove_user),
("user-browse-show-user", self.show_user),
("user-status", self.user_status)
):
events.connect(event_name, callback)
def quit(self):
self.freeze()
def destroy(self):
self.userbrowse_combobox.destroy()
if self.file_properties is not None:
self.file_properties.destroy()
super().destroy()
def on_focus(self, *_args):
if self.window.current_page_id != self.window.userbrowse_page.id:
return True
if self.get_n_pages():
return True
if self.window.userbrowse_entry.is_sensitive():
self.window.userbrowse_entry.grab_focus()
return True
return False
def on_remove_all_pages(self, *_args):
core.userbrowse.remove_all_users()
def on_restore_removed_page(self, page_args):
username, = page_args
core.userbrowse.browse_user(username)
def on_get_shares(self, *_args):
entry_text = self.window.userbrowse_entry.get_text().strip()
if not entry_text:
return
self.window.userbrowse_entry.set_text("")
if entry_text.startswith("slsk://"):
core.userbrowse.open_soulseek_url(entry_text)
else:
core.userbrowse.browse_user(entry_text)
def show_user(self, user, path=None, switch_page=True):
page = self.pages.get(user)
if page is None:
self.pages[user] = page = UserBrowse(self, user)
self.append_page(page.container, user, focus_callback=page.on_focus,
close_callback=page.on_close, user=user)
page.set_label(self.get_tab_label_inner(page.container))
page.queued_path = path
page.browse_queued_path()
if switch_page:
self.set_current_page(page.container)
self.window.change_main_page(self.window.userbrowse_page)
def remove_user(self, user):
page = self.pages.get(user)
if page is None:
return
page.clear()
self.remove_page(page.container, page_args=(user,))
del self.pages[user]
page.destroy()
def peer_connection_error(self, username, conn_type, **_unused):
page = self.pages.get(username)
if page is None:
return
if conn_type == ConnectionType.PEER:
page.peer_connection_error()
def user_status(self, msg):
page = self.pages.get(msg.user)
if page is not None:
self.set_user_status(page.container, msg.user, msg.status)
def shared_file_list_progress(self, user, _sock, position, total):
page = self.pages.get(user)
if page is not None:
page.shared_file_list_progress(position, total)
def shared_file_list(self, msg):
page = self.pages.get(msg.username)
if page is not None:
page.shared_file_list(msg)
def server_disconnect(self, *_args):
for user, page in self.pages.items():
self.set_user_status(page.container, user, UserStatus.OFFLINE)
class UserBrowse:
def __init__(self, userbrowses, user):
(
self.container,
self.expand_button,
self.expand_icon,
self.file_list_container,
self.folder_tree_container,
self.info_bar_container,
self.num_folders_label,
self.path_bar,
self.path_bar_container,
self.progress_bar,
self.refresh_button,
self.retry_button,
self.save_button,
self.search_button,
self.search_entry,
self.search_entry_revealer,
self.share_size_label
) = ui.load(scope=self, path="userbrowse.ui")
self.userbrowses = userbrowses
self.window = userbrowses.window
self.user = user
self.indeterminate_progress = False
self.local_permission_level = None
self.queued_path = None
self.active_folder_path = None
self.selected_files = {}
self.search_folder_paths = []
self.query = None
self.search_position = 0
self.info_bar = InfoBar(parent=self.info_bar_container, button=self.retry_button)
self.path_bar_container.get_hadjustment().connect("changed", self.on_path_bar_scroll)
# Setup folder_tree_view
self.folder_tree_view = TreeView(
self.window, parent=self.folder_tree_container, has_tree=True,
multi_select=True, activate_row_callback=self.on_folder_row_activated,
select_row_callback=self.on_select_folder,
columns={
# Visible columns
"folder": {
"column_type": "text",
"title": _("Folder"),
"hide_header": True,
"tooltip_callback": self.on_folder_path_tooltip
},
# Hidden data columns
"folder_path_data": {"iterator_key": True}
}
)
# Popup Menu (folder_tree_view)
self.user_popup_menu = UserPopupMenu(
self.window.application, callback=self.on_tab_popup, username=user, tab_name="userbrowse"
)
self.user_popup_menu.add_items(
("", None),
("#" + _("_Save Shares List to Disk"), self.on_save),
("#" + _("Close All Tabs…"), self.on_close_all_tabs),
("#" + _("_Close Tab"), self.on_close)
)
self.folder_popup_menu = PopupMenu(self.window.application, self.folder_tree_view.widget,
self.on_folder_popup_menu)
if user == config.sections["server"]["login"]:
self.folder_popup_menu.add_items(
("#" + _("Upload Folder & Subfolders…"), self.on_upload_folder_recursive_to),
("", None),
("#" + _("Open in File _Manager"), self.on_file_manager),
("#" + _("F_ile Properties"), self.on_file_properties, True),
("", None),
("#" + _("Copy _Folder Path"), self.on_copy_folder_path),
("#" + _("Copy Folder U_RL"), self.on_copy_folder_url),
("", None),
(">" + _("User Actions"), self.user_popup_menu)
)
else:
self.folder_popup_menu.add_items(
("#" + _("_Download Folder & Subfolders"), self.on_download_folder_recursive),
("#" + _("Download Folder & Subfolders _To…"), self.on_download_folder_recursive_to),
("", None),
("#" + _("F_ile Properties"), self.on_file_properties, True),
("", None),
("#" + _("Copy _Folder Path"), self.on_copy_folder_path),
("#" + _("Copy Folder U_RL"), self.on_copy_folder_url),
("", None),
(">" + _("User Actions"), self.user_popup_menu)
)
# Setup file_list_view
self.file_list_view = TreeView(
self.window, parent=self.file_list_container, name="user_browse",
multi_select=True, activate_row_callback=self.on_file_row_activated,
columns={
# Visible columns
"file_type": {
"column_type": "icon",
"title": _("File Type"),
"width": 30,
"hide_header": True
},
"filename": {
"column_type": "text",
"title": _("File Name"),
"width": 150,
"expand_column": True,
"default_sort_type": "ascending",
"iterator_key": True
},
"size": {
"column_type": "number",
"title": _("Size"),
"width": 100,
"sort_column": "size_data"
},
"quality": {
"column_type": "number",
"title": _("Quality"),
"width": 150,
"sort_column": "bitrate_data"
},
"length": {
"column_type": "number",
"title": _("Duration"),
"width": 100,
"sort_column": "length_data"
},
# Hidden data columns
"size_data": {"data_type": GObject.TYPE_UINT64},
"bitrate_data": {"data_type": GObject.TYPE_UINT},
"length_data": {"data_type": GObject.TYPE_UINT},
"file_attributes_data": {"data_type": GObject.TYPE_PYOBJECT}
}
)
# Popup Menu (file_list_view)
self.file_popup_menu = FilePopupMenu(
self.window.application, parent=self.file_list_view.widget, callback=self.on_file_popup_menu
)
if user == config.sections["server"]["login"]:
self.file_popup_menu.add_items(
("#" + _("Up_load File(s)…"), self.on_upload_files_to),
("#" + _("Upload Folder…"), self.on_upload_folder_to),
("", None),
("#" + _("_Open File"), self.on_open_file),
("#" + _("Open in File _Manager"), self.on_file_manager),
("#" + _("F_ile Properties"), self.on_file_properties),
("", None),
("#" + _("Copy _File Path"), self.on_copy_file_path),
("#" + _("Copy _URL"), self.on_copy_url),
("", None),
(">" + _("User Actions"), self.user_popup_menu)
)
else:
self.file_popup_menu.add_items(
("#" + _("_Download File(s)"), self.on_download_files),
("#" + _("Download File(s) _To…"), self.on_download_files_to),
("", None),
("#" + _("_Download Folder"), self.on_download_folder),
("#" + _("Download Folder _To…"), self.on_download_folder_to),
("", None),
("#" + _("F_ile Properties"), self.on_file_properties),
("", None),
("#" + _("Copy _File Path"), self.on_copy_file_path),
("#" + _("Copy _URL"), self.on_copy_url),
("", None),
(">" + _("User Actions"), self.user_popup_menu)
)
# Key Bindings (folder_tree_view)
Accelerator("Right", self.folder_tree_view.widget, self.on_folder_expand_accelerator)
Accelerator("<Shift>Return", self.folder_tree_view.widget, self.on_folder_focus_filetree_accelerator)
Accelerator("<Primary>Return", self.folder_tree_view.widget, self.on_folder_transfer_to_accelerator)
Accelerator("<Shift><Primary>Return", self.folder_tree_view.widget, self.on_folder_transfer_accelerator)
Accelerator("<Primary><Alt>Return", self.folder_tree_view.widget, self.on_folder_open_manager_accelerator)
Accelerator("<Alt>Return", self.folder_tree_view.widget, self.on_file_properties_accelerator, True)
# Key Bindings (file_list_view)
for accelerator in ("BackSpace", "backslash"): # Navigate up, "\"
Accelerator(accelerator, self.file_list_view.widget, self.on_focus_folder_accelerator)
Accelerator("Left", self.file_list_view.widget, self.on_focus_folder_left_accelerator)
Accelerator("<Shift>Return", self.file_list_view.widget, self.on_file_transfer_multi_accelerator)
Accelerator("<Primary>Return", self.file_list_view.widget, self.on_file_transfer_to_accelerator)
Accelerator("<Shift><Primary>Return", self.file_list_view.widget, self.on_file_transfer_accelerator)
Accelerator("<Primary><Alt>Return", self.file_list_view.widget, self.on_file_open_manager_accelerator)
Accelerator("<Alt>Return", self.file_list_view.widget, self.on_file_properties_accelerator)
# Key Bindings (General)
for widget in (self.container, self.folder_tree_view.widget, self.file_list_view.widget):
Accelerator("<Primary>f", widget, self.on_search_accelerator) # Find focus
Accelerator("Escape", self.search_entry, self.on_search_escape_accelerator)
Accelerator("F3", self.container, self.on_search_next_accelerator)
Accelerator("<Shift>F3", self.container, self.on_search_previous_accelerator)
Accelerator("<Primary>g", self.container, self.on_search_next_accelerator) # Next search match
Accelerator("<Shift><Primary>g", self.container, self.on_search_previous_accelerator)
Accelerator("Up", self.search_entry, self.on_search_previous_accelerator)
Accelerator("Down", self.search_entry, self.on_search_next_accelerator)
Accelerator("<Primary>backslash", self.container, self.on_expand_accelerator) # expand / collapse all (button)
Accelerator("F5", self.container, self.on_refresh_accelerator)
Accelerator("<Primary>r", self.container, self.on_refresh_accelerator) # Refresh
Accelerator("<Primary>s", self.container, self.on_save_accelerator) # Save Shares List
self.popup_menus = (
self.folder_popup_menu, self.file_popup_menu, self.user_popup_menu
)
self.expand_button.set_active(config.sections["userbrowse"]["expand_folders"])
def clear(self):
self.clear_model()
def destroy(self):
for menu in self.popup_menus:
menu.destroy()
self.info_bar.destroy()
self.folder_tree_view.destroy()
self.file_list_view.destroy()
self.__dict__.clear()
self.indeterminate_progress = False # Stop progress bar timer
def set_label(self, label):
self.user_popup_menu.set_parent(label)
# Folder/File Views #
def clear_model(self):
self.search_position = 0
self.search_folder_paths.clear()
self.active_folder_path = None
self.populate_path_bar()
self.selected_files.clear()
self.folder_tree_view.clear()
self.file_list_view.clear()
def rebuild_model(self):
self.clear_model()
browsed_user = core.userbrowse.users[self.user]
if browsed_user.num_folders is None or browsed_user.shared_size is None:
return
# Generate the folder tree and select first folder
self.create_folder_tree(browsed_user.public_folders)
if browsed_user.private_folders:
self.create_folder_tree(browsed_user.private_folders, private=True)
self.num_folders_label.set_text(humanize(browsed_user.num_folders))
self.share_size_label.set_text(human_size(browsed_user.shared_size))
if self.expand_button.get_active():
self.folder_tree_view.expand_all_rows()
else:
self.folder_tree_view.expand_root_rows()
self.select_search_match_folder()
def create_folder_tree(self, folders, private=False):
if not folders:
return
iterators = self.folder_tree_view.iterators
add_row = self.folder_tree_view.add_row
query = self.query
private_template = _("[PRIVATE] %s")
for folder_path, files in reversed(list(folders.items())):
current_path = parent = None
root_processed = False
skip_folder = (query and query not in folder_path.lower())
if skip_folder:
for file_info in files:
if query in file_info[1].lower():
skip_folder = False
if skip_folder:
continue
for subfolder in folder_path.split("\\"):
if not root_processed:
current_path = subfolder
root_processed = True
else:
current_path += f"\\{subfolder}"
if current_path in iterators:
# Folder was already added to tree
parent = iterators[current_path]
continue
if not subfolder:
# Most likely a root folder
subfolder = "\\"
if private:
subfolder = private_template % subfolder
parent = add_row(
[subfolder, current_path], select_row=False, parent_iterator=parent
)
if query:
self.search_folder_paths.append(folder_path)
self.search_folder_paths.reverse()
def browse_queued_path(self):
if not self.queued_path:
return
# Reset search to show all folders
self.search_entry.set_text("")
self.search_button.set_active(False)
folder_path, _separator, basename = self.queued_path.rpartition("\\")
iterator = self.folder_tree_view.iterators.get(folder_path)
if not iterator:
return
self.queued_path = None
# Scroll to the requested folder
self.folder_tree_view.select_row(iterator)
iterator = self.file_list_view.iterators.get(basename)
if not iterator:
self.folder_tree_view.grab_focus()
return
# Scroll to the requested file
self.file_list_view.select_row(iterator)
self.file_list_view.grab_focus()
def shared_file_list(self, msg):
is_empty = (not msg.list and not msg.privatelist)
self.local_permission_level = msg.permission_level
self.rebuild_model()
self.info_bar.set_visible(False)
if is_empty:
self.info_bar.show_info_message(
_("User's list of shared files is empty. Either the user is not sharing anything, "
"or they are sharing files privately.")
)
self.retry_button.set_visible(False)
else:
self.browse_queued_path()
self.set_finished()
def peer_connection_error(self):
if self.refresh_button.get_sensitive():
return
self.info_bar.show_error_message(
_("Unable to request shared files from user. Either the user is offline, the listening ports "
"are closed on both sides, or there is a temporary connectivity issue.")
)
self.retry_button.set_visible(True)
self.set_finished()
def pulse_progress(self, repeat=True):
if not self.indeterminate_progress:
return False
self.progress_bar.pulse()
return repeat
def shared_file_list_progress(self, position, total):
self.indeterminate_progress = False
if total <= 0 or position <= 0:
fraction = 0.0
elif position < total:
fraction = float(position) / total
else:
fraction = 1.0
GLib.timeout_add(1000, self.set_finishing)
self.progress_bar.set_fraction(fraction)
def set_indeterminate_progress(self):
self.indeterminate_progress = True
self.progress_bar.get_parent().set_reveal_child(True)
self.progress_bar.pulse()
GLib.timeout_add(320, self.pulse_progress, False)
GLib.timeout_add(1000, self.pulse_progress)
self.info_bar.set_visible(False)
self.refresh_button.set_sensitive(False)
self.save_button.set_sensitive(False)
def set_finishing(self):
if hasattr(self, "refresh_button") and not self.refresh_button.get_sensitive():
self.set_indeterminate_progress()
return False
def set_finished(self):
self.indeterminate_progress = False
self.userbrowses.request_tab_changed(self.container)
self.progress_bar.set_fraction(1.0)
self.progress_bar.get_parent().set_reveal_child(False)
self.refresh_button.set_sensitive(True)
self.save_button.set_sensitive(not self.folder_tree_view.is_empty())
def populate_path_bar(self, folder_path=""):
for widget in list(self.path_bar):
self.path_bar.remove(widget)
if not folder_path:
return
folder_path_split = folder_path.split("\\")
for index, folder in enumerate(folder_path_split):
i_folder_path = "\\".join(folder_path_split[:index + 1])
if index:
label = Gtk.Label(label="\\", visible=True)
add_css_class(label, "dim-label")
add_css_class(label, "heading")
if GTK_API_VERSION >= 4:
self.path_bar.append(label) # pylint: disable=no-member
else:
self.path_bar.add(label) # pylint: disable=no-member
if len(folder) > 10:
width_chars = 10
ellipsize = Pango.EllipsizeMode.END
else:
width_chars = -1
ellipsize = Pango.EllipsizeMode.NONE
button_label = Gtk.Label(label=folder, ellipsize=ellipsize, width_chars=width_chars, visible=True)
if index == len(folder_path_split) - 1:
button = Gtk.MenuButton(visible=True)
button.set_menu_model(self.folder_popup_menu.model)
add_css_class(button_label, "heading")
if GTK_API_VERSION >= 4:
button.set_child(button_label) # pylint: disable=no-member
button.set_always_show_arrow(True) # pylint: disable=no-member
button.set_has_frame(False) # pylint: disable=no-member
button.set_create_popup_func(self.on_folder_popup_menu) # pylint: disable=no-member
inner_button = next(iter(button))
button_label.set_mnemonic_widget(inner_button)
else:
box = Gtk.Box(spacing=6, visible=True)
arrow_icon = Gtk.Image(icon_name="pan-down-symbolic", visible=True)
box.add(button_label) # pylint: disable=no-member
box.add(arrow_icon) # pylint: disable=no-member
button.add(box) # pylint: disable=no-member
button.connect("clicked", self.on_folder_popup_menu)
button_label.set_mnemonic_widget(button)
else:
button = Gtk.Button(child=button_label, visible=True)
button.connect("clicked", self.on_path_bar_clicked, i_folder_path)
add_css_class(button_label, "normal")
button_label.set_mnemonic_widget(button)
add_css_class(button, "flat")
remove_css_class(button, "text-button")
if GTK_API_VERSION >= 4:
self.path_bar.append(button) # pylint: disable=no-member
else:
self.path_bar.add(button) # pylint: disable=no-member
def set_active_folder(self, folder_path):
if self.active_folder_path == folder_path:
return
browsed_user = core.userbrowse.users.get(self.user)
if browsed_user is None:
# Redundant row selection event when closing tab, prevent crash
return
self.populate_path_bar(folder_path)
self.file_list_view.clear()
self.active_folder_path = folder_path
if not folder_path:
return
files = browsed_user.public_folders.get(folder_path)
if not files:
files = browsed_user.private_folders.get(folder_path)
if not files:
return
# Temporarily disable sorting for increased performance
self.file_list_view.freeze()
for _code, basename, size, _ext, file_attributes, *_unused in files:
h_size = human_size(size, config.sections["ui"]["file_size_unit"])
h_quality, bitrate, h_length, length = FileListMessage.parse_audio_quality_length(size, file_attributes)
self.file_list_view.add_row([
get_file_type_icon_name(basename),
basename,
h_size,
h_quality,
h_length,
size,
bitrate,
length,
file_attributes
], select_row=False)
self.file_list_view.unfreeze()
self.select_search_match_files()
def select_files(self):
self.selected_files.clear()
for iterator in self.file_list_view.get_selected_rows():
basename = self.file_list_view.get_row_value(iterator, "filename")
filesize = self.file_list_view.get_row_value(iterator, "size_data")
self.selected_files[basename] = filesize
def get_selected_folder_path(self):
for iterator in self.folder_tree_view.get_selected_rows():
folder_path = self.folder_tree_view.get_row_value(iterator, "folder_path_data")
return f'{folder_path or ""}\\'
return None
def get_selected_file_path(self):
selected_folder = self.get_selected_folder_path()
selected_file = next(iter(self.selected_files), "")
return f"{selected_folder}{selected_file}"
# Search #
def select_search_match_folder(self):
iterator = None
if self.search_folder_paths:
folder_path = self.search_folder_paths[self.search_position]
iterator = self.folder_tree_view.iterators[folder_path]
self.folder_tree_view.select_row(iterator)
def select_search_match_files(self):
if not self.query:
return
result_files = []
found_first_match = False
for filepath, iterator in self.file_list_view.iterators.items():
if self.query in filepath.lower():
result_files.append(iterator)
self.file_list_view.unselect_all_rows()
for iterator in result_files:
# Select each matching file in folder
self.file_list_view.select_row(iterator, should_scroll=(not found_first_match))
found_first_match = True
def find_search_matches(self, reverse=False):
query = self.search_entry.get_text().lower() or None
if self.query != query:
# New search query, rebuild result list
active_folder_path = self.active_folder_path
self.query = query
self.rebuild_model()
if not self.search_folder_paths:
iterator = self.folder_tree_view.iterators.get(active_folder_path)
if iterator:
self.folder_tree_view.select_row(iterator)
return False
elif query:
# Increment/decrement search position
self.search_position += -1 if reverse else 1
else:
return False
if self.search_position < 0:
self.search_position = len(self.search_folder_paths) - 1
elif self.search_position >= len(self.search_folder_paths):
self.search_position = 0
# Set active folder
self.select_search_match_folder()
# Get matching files in the current folder
self.select_search_match_files()
return True
# Callbacks (folder_tree_view) #
def on_select_folder(self, tree_view, iterator):
if iterator is None:
return
selected_iterators = tree_view.get_selected_rows()
folder_path = None
# Skip first folder
next(selected_iterators)
if next(selected_iterators, None):
# Multiple folders selected. Avoid any confusion by clearing the path bar and file list view.
folder_path = None
else:
folder_path = tree_view.get_row_value(iterator, "folder_path_data")
self.set_active_folder(folder_path)
def on_folder_path_tooltip(self, treeview, iterator):
return treeview.get_row_value(iterator, "folder_path_data")
def on_folder_popup_menu(self, *_args):
self.folder_popup_menu.update_model()
self.user_popup_menu.toggle_user_items()
def on_download_folder(self, *_args, download_folder_path=None, recurse=False):
prev_folder_path = None
for iterator in self.folder_tree_view.get_selected_rows():
folder_path = self.folder_tree_view.get_row_value(iterator, "folder_path_data")
if recurse and prev_folder_path and prev_folder_path in folder_path:
# Already recursing, avoid redundant request for subfolder
continue
core.userbrowse.download_folder(
self.user, folder_path, download_folder_path=download_folder_path, recurse=recurse)
prev_folder_path = folder_path
def on_download_folder_recursive(self, *_args):
self.on_download_folder(recurse=True)
def on_download_folder_to_selected(self, selected_download_folder_paths, recurse):
self.on_download_folder(
download_folder_path=next(iter(selected_download_folder_paths), None), recurse=recurse)
def on_download_folder_to(self, *_args, recurse=False):
if recurse:
str_title = _("Select Destination for Downloading Multiple Folders")
else:
str_title = _("Select Destination Folder")
FolderChooser(
parent=self.window,
title=str_title,
callback=self.on_download_folder_to_selected,
callback_data=recurse,
initial_folder=core.downloads.get_default_download_folder()
).present()
def on_download_folder_recursive_to(self, *_args):
self.on_download_folder_to(recurse=True)
def on_upload_folder_to_response(self, dialog, _response_id, recurse):
user = dialog.get_entry_value()
if not user:
return
prev_folder_path = None
sent_upload_notification = False
for iterator in self.folder_tree_view.get_selected_rows():
folder_path = self.folder_tree_view.get_row_value(iterator, "folder_path_data")
if recurse and prev_folder_path and prev_folder_path in folder_path:
# Already recursing, avoid redundant request for subfolder
continue
if not sent_upload_notification:
core.userbrowse.send_upload_attempt_notification(user)
sent_upload_notification = True
core.userbrowse.upload_folder(
user, folder_path, local_browsed_user=core.userbrowse.users[self.user], recurse=recurse)
prev_folder_path = folder_path
def on_upload_folder_to(self, *_args, recurse=False):
if recurse:
str_title = _("Upload Folder (with Subfolders) To User")
else:
str_title = _("Upload Folder To User")
EntryDialog(
parent=self.window,
title=str_title,
message=_("Enter the name of the user you want to upload to:"),
action_button_label=_("_Upload"),
callback=self.on_upload_folder_to_response,
callback_data=recurse,
droplist=sorted(core.buddies.users)
).present()
def on_upload_folder_recursive_to(self, *_args):
self.on_upload_folder_to(recurse=True)
def on_copy_folder_path(self, *_args):
folder_path = self.get_selected_folder_path()
clipboard.copy_text(folder_path)
def on_copy_folder_url(self, *_args):
folder_path = self.get_selected_folder_path()
folder_url = core.userbrowse.get_soulseek_url(self.user, folder_path)
clipboard.copy_text(folder_url)
# Key Bindings (folder_tree_view) #
def on_folder_row_activated(self, tree_view, iterator, _column_id):
if iterator is None:
return
# Keyboard accessibility support for <Return> key behaviour
if tree_view.is_row_expanded(iterator):
expandable = tree_view.collapse_row(iterator)
else:
expandable = tree_view.expand_row(iterator)
if not expandable and not self.file_list_view.is_empty():
# This is the deepest level, so move focus over to Files if there are any
self.file_list_view.grab_focus()
# Note: Other Folder actions are handled by Accelerator functions [Shift/Ctrl/Alt+Return]
# TODO: Mouse double-click actions will need keycode state & mods [Shift/Ctrl+DblClick]
def on_folder_expand_accelerator(self, *_args):
"""Right, Shift+Right (Gtk), "+" (Gtk) - expand row."""
iterator = self.folder_tree_view.get_focused_row()
if iterator is None:
return False
if not self.file_list_view.is_empty():
self.file_list_view.grab_focus()
return True
def on_folder_focus_filetree_accelerator(self, *_args):
"""Shift+Enter - focus selection over FileTree."""
if not self.file_list_view.is_empty():
self.file_list_view.grab_focus()
return True
iterator = self.folder_tree_view.get_focused_row()
if iterator is None:
return False
self.folder_tree_view.expand_row(iterator)
return True
def on_folder_transfer_to_accelerator(self, *_args):
"""Ctrl+Enter - Upload Folder To, Download Folder Into."""
if self.user == config.sections["server"]["login"]:
self.on_upload_folder_recursive_to()
else:
self.on_download_folder_recursive_to()
return True
def on_folder_transfer_accelerator(self, *_args):
"""Shift+Ctrl+Enter - Upload Folder Recursive To, Download Folder (without prompt)."""
if self.user == config.sections["server"]["login"]:
self.on_upload_folder_recursive_to()
else:
self.on_download_folder_recursive() # without prompt
return True
def on_folder_open_manager_accelerator(self, *_args):
"""Ctrl+Alt+Enter - Open folder in File Manager."""
if self.user != config.sections["server"]["login"]:
return False
self.on_file_manager()
return True
# Callbacks (file_list_view) #
def on_file_popup_menu(self, menu, _widget):
self.select_files()
menu.set_num_selected_files(len(self.selected_files))
self.user_popup_menu.toggle_user_items()
def on_download_files(self, *_args, download_folder_path=None):
folder_path = self.active_folder_path
browsed_user = core.userbrowse.users[self.user]
files = browsed_user.public_folders.get(folder_path)
if not files:
files = browsed_user.private_folders.get(folder_path)
if not files:
return
for file_data in files:
_code, basename, *_unused = file_data
# Find the wanted file
if basename not in self.selected_files:
continue
core.userbrowse.download_file(
self.user, folder_path, file_data, download_folder_path=download_folder_path)
def on_download_files_to_selected(self, selected_download_folder_paths, _data):
self.on_download_files(download_folder_path=next(iter(selected_download_folder_paths), None))
def on_download_files_to(self, *_args):
FolderChooser(
parent=self.window,
title=_("Select Destination Folder for Files"),
callback=self.on_download_files_to_selected,
initial_folder=core.downloads.get_default_download_folder()
).present()
def on_upload_files_to_response(self, dialog, _response_id, _data):
user = dialog.get_entry_value()
folder_path = self.active_folder_path
if not user or folder_path is None:
return
core.userbrowse.send_upload_attempt_notification(user)
for basename, size in self.selected_files.items():
core.userbrowse.upload_file(user, folder_path, (None, basename, size))
def on_upload_files_to(self, *_args):
EntryDialog(
parent=self.window,
title=_("Upload File(s) To User"),
message=_("Enter the name of the user you want to upload to:"),
action_button_label=_("_Upload"),
callback=self.on_upload_files_to_response,
droplist=sorted(core.buddies.users)
).present()
def on_open_file(self, *_args):
folder_path = core.shares.virtual2real(self.active_folder_path)
for basename in self.selected_files:
open_file_path(os.path.join(folder_path, basename))
def on_file_manager(self, *_args):
for iterator in self.folder_tree_view.get_selected_rows():
folder_path = self.folder_tree_view.get_row_value(iterator, "folder_path_data")
open_folder_path(core.shares.virtual2real(folder_path))
return
def on_file_properties(self, _action, _state, all_files=False):
data = []
selected_size = 0
selected_length = 0
watched_user = core.users.watched.get(self.user)
speed = 0
if watched_user is not None:
speed = watched_user.upload_speed or 0
if all_files:
prev_folder_path = None
for iterator in self.folder_tree_view.get_selected_rows():
selected_folder_path = self.folder_tree_view.get_row_value(iterator, "folder_path_data")
if prev_folder_path and prev_folder_path in selected_folder_path:
# Already recursing, avoid duplicates
continue
for folder_path, files in core.userbrowse.iter_matching_folders(
selected_folder_path, browsed_user=core.userbrowse.users[self.user], recurse=True
):
for file_data in files:
_code, basename, file_size, _ext, file_attributes, *_unused = file_data
_bitrate, length, *_unused = FileListMessage.parse_file_attributes(file_attributes)
file_path = "\\".join([folder_path, basename])
selected_size += file_size
if length:
selected_length += length
data.append({
"user": self.user,
"file_path": file_path,
"basename": basename,
"virtual_folder_path": folder_path,
"speed": speed,
"size": file_size,
"file_attributes": file_attributes
})
prev_folder_path = selected_folder_path
else:
selected_folder_path = self.active_folder_path
for iterator in self.file_list_view.get_selected_rows():
basename = self.file_list_view.get_row_value(iterator, "filename")
file_path = "\\".join([selected_folder_path, basename])
file_size = self.file_list_view.get_row_value(iterator, "size_data")
selected_size += file_size
selected_length += self.file_list_view.get_row_value(iterator, "length_data")
data.append({
"user": self.user,
"file_path": file_path,
"basename": basename,
"virtual_folder_path": selected_folder_path,
"speed": speed,
"size": file_size,
"file_attributes": self.file_list_view.get_row_value(iterator, "file_attributes_data"),
"country_code": core.users.countries.get(self.user)
})
if data:
if self.userbrowses.file_properties is None:
self.userbrowses.file_properties = FileProperties(self.window.application)
self.userbrowses.file_properties.update_properties(data, selected_size, selected_length)
self.userbrowses.file_properties.present()
def on_copy_file_path(self, *_args):
file_path = self.get_selected_file_path()
clipboard.copy_text(file_path)
def on_copy_url(self, *_args):
file_path = self.get_selected_file_path()
file_url = core.userbrowse.get_soulseek_url(self.user, file_path)
clipboard.copy_text(file_url)
# Key Bindings (file_list_view) #
def on_file_row_activated(self, _tree_view, _iterator, _column_id):
self.select_files()
if self.user == config.sections["server"]["login"]:
self.on_open_file()
else:
self.on_download_files()
def on_focus_folder_left_accelerator(self, *_args):
"""Left - focus back parent folder (left arrow)."""
column_id = self.file_list_view.get_focused_column()
if next(self.file_list_view.get_visible_columns(), None) != column_id:
return False # allow horizontal scrolling
self.folder_tree_view.grab_focus()
return True
def on_focus_folder_accelerator(self, *_args):
"""BackSpace, \backslash - focus selection back parent folder"""
self.folder_tree_view.grab_focus()
return True
def on_file_transfer_to_accelerator(self, *_args):
"""Ctrl+Enter - Upload File(s) To, Download File(s) Into."""
if self.file_list_view.is_empty(): # avoid navigation trap
self.folder_tree_view.grab_focus()
return True
self.select_files()
if self.user == config.sections["server"]["login"]:
if self.file_list_view.is_selection_empty():
self.on_upload_folder_to()
else:
self.on_upload_files_to()
return True
if self.file_list_view.is_selection_empty():
self.on_download_folder_to()
else:
self.on_download_files_to() # (with prompt, Single or Multi-selection)
return True
def on_file_transfer_accelerator(self, *_args):
"""Shift+Ctrl+Enter - Upload File(s) To, Download File(s) (without prompt)."""
if self.file_list_view.is_empty():
self.folder_tree_view.grab_focus() # avoid nav trap
return True
self.select_files()
if self.user == config.sections["server"]["login"]:
if self.file_list_view.is_selection_empty():
self.on_upload_folder_to()
else:
self.on_upload_files_to()
return True
if self.file_list_view.is_selection_empty():
self.on_download_folder() # (without prompt, No-selection=All)
else:
self.on_download_files() # (no prompt, Single or Multi-selection)
return True
def on_file_transfer_multi_accelerator(self, *_args):
"""Shift+Enter - Open File, Download Files (multiple)."""
if self.file_list_view.is_empty():
self.folder_tree_view.grab_focus() # avoid nav trap
return True
self.select_files() # support multi-select with Up/Dn keys
if self.user == config.sections["server"]["login"]:
self.on_open_file()
else:
self.on_download_files()
return True
def on_file_open_manager_accelerator(self, *_args):
"""Ctrl+Alt+Enter - Open in File Manager."""
if self.user == config.sections["server"]["login"]:
self.on_file_manager()
else: # [user is not self]
self.on_file_properties_accelerator() # same as Alt+Enter
return True
def on_file_properties_accelerator(self, *_args):
"""Alt+Enter - show file properties dialog."""
if self.file_list_view.is_empty():
self.folder_tree_view.grab_focus() # avoid nav trap
self.on_file_properties(*_args)
return True
# Callbacks (General) #
def on_show_progress_bar(self, progress_bar):
"""Enables indeterminate progress bar mode when tab is active."""
if not self.indeterminate_progress and progress_bar.get_fraction() <= 0.0:
self.set_indeterminate_progress()
if core.users.login_status == UserStatus.OFFLINE:
self.peer_connection_error()
def on_hide_progress_bar(self, progress_bar):
"""Disables indeterminate progress bar mode when switching to another tab."""
if self.indeterminate_progress:
self.indeterminate_progress = False
progress_bar.set_fraction(0.0)
def on_path_bar_clicked(self, _button, folder_path):
iterator = self.folder_tree_view.iterators.get(folder_path)
if iterator:
self.folder_tree_view.select_row(iterator)
self.folder_tree_view.grab_focus()
def on_path_bar_scroll(self, adjustment, *_args):
adjustment_end = (adjustment.get_upper() - adjustment.get_page_size())
if adjustment.get_value() < adjustment_end:
self.path_bar_container.emit("scroll-child", Gtk.ScrollType.END, True)
def on_expand(self, *_args):
active = self.expand_button.get_active()
if active:
icon_name = "view-restore-symbolic"
self.folder_tree_view.expand_all_rows()
else:
icon_name = "view-fullscreen-symbolic"
self.folder_tree_view.collapse_all_rows()
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.expand_icon.set_from_icon_name(icon_name, *icon_args)
config.sections["userbrowse"]["expand_folders"] = active
def on_tab_popup(self, *_args):
self.user_popup_menu.toggle_user_items()
def on_search_enabled(self, *_args):
self.search_button.set_active(self.search_entry_revealer.get_reveal_child())
def on_show_search(self, *_args):
active = self.search_button.get_active()
if active:
self.search_entry.grab_focus()
elif not self.file_list_view.is_selection_empty():
self.file_list_view.grab_focus()
else:
self.folder_tree_view.grab_focus()
self.search_entry_revealer.set_reveal_child(active)
def on_search(self, *_args):
self.find_search_matches()
def on_search_entry_changed(self, *_args):
if len(self.search_entry.get_text()) <= 0:
self.find_search_matches()
def on_save(self, *_args):
core.userbrowse.save_shares_list_to_disk(self.user)
def on_refresh(self, *_args):
if not self.refresh_button.get_sensitive():
# Refresh is already in progress
return
# Remember selection after refresh
self.select_files()
file_path = self.get_selected_file_path()
self.clear_model()
self.set_indeterminate_progress()
if self.local_permission_level:
core.userbrowse.browse_local_shares(
path=file_path, permission_level=self.local_permission_level, new_request=True)
else:
core.userbrowse.browse_user(self.user, path=file_path, new_request=True)
def on_focus(self):
if self.file_list_view.is_selection_empty():
self.folder_tree_view.grab_focus()
else:
self.file_list_view.grab_focus()
return True
def on_close(self, *_args):
core.userbrowse.remove_user(self.user)
def on_close_all_tabs(self, *_args):
self.userbrowses.remove_all_pages()
# Key Bindings (General) #
def on_expand_accelerator(self, *_args):
"""Ctrl+\backslash - Expand / Collapse All."""
self.expand_button.set_active(not self.expand_button.get_active())
return True
def on_save_accelerator(self, *_args):
"""Ctrl+S - Save Shares List."""
if not self.save_button.get_sensitive():
return False
self.on_save()
return True
def on_refresh_accelerator(self, *_args):
"""Ctrl+R or F5 - Refresh."""
self.on_refresh()
return True
def on_search_accelerator(self, *_args):
"""Ctrl+F - Find."""
if self.search_button.get_sensitive():
self.search_button.set_active(True)
self.search_entry.grab_focus()
return True
def on_search_next_accelerator(self, *_args):
"""Ctrl+G or F3 - Find Next."""
if not self.find_search_matches():
self.search_entry.grab_focus()
return True
def on_search_previous_accelerator(self, *_args):
"""Shift+Ctrl+G or Shift+F3 - Find Previous."""
if not self.find_search_matches(reverse=True):
self.search_entry.grab_focus()
return True
def on_search_escape_accelerator(self, *_args):
"""Escape - navigate out of search_entry."""
self.search_button.set_active(False)
return True
| 53,171 | Python | .py | 1,104 | 36.538043 | 119 | 0.601603 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,433 | search.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/search.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2018 Mutnick <mutnick@techie.com>
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2008-2011 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import operator
import re
from itertools import islice
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.dialogs.fileproperties import FileProperties
from pynicotine.gtkgui.widgets import clipboard
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.combobox import ComboBox
from pynicotine.gtkgui.widgets.filechooser import FolderChooser
from pynicotine.gtkgui.widgets.iconnotebook import IconNotebook
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.popupmenu import FilePopupMenu
from pynicotine.gtkgui.widgets.popupmenu import UserPopupMenu
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.theme import get_file_type_icon_name
from pynicotine.gtkgui.widgets.theme import get_flag_icon_name
from pynicotine.gtkgui.widgets.theme import remove_css_class
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.gtkgui.widgets.treeview import create_grouping_menu
from pynicotine.logfacility import log
from pynicotine.shares import FileTypes
from pynicotine.slskmessages import FileListMessage
from pynicotine.utils import factorize
from pynicotine.utils import humanize
from pynicotine.utils import human_size
from pynicotine.utils import human_speed
class SearchResultFile:
__slots__ = ("path", "attributes")
def __init__(self, path, attributes=None):
self.path = path
self.attributes = attributes
class Searches(IconNotebook):
def __init__(self, window):
super().__init__(
window,
parent=window.search_content,
parent_page=window.search_page,
switch_page_callback=self.on_switch_search_page
)
self.page = window.search_page
self.page.id = "search"
self.toolbar = window.search_toolbar
self.toolbar_start_content = window.search_title
self.toolbar_end_content = window.search_end
self.toolbar_default_widget = window.search_entry
self.modes = {
"global": _("_Global"),
"buddies": _("_Buddies"),
"rooms": _("_Rooms"),
"user": _("_User")
}
mode_menu = PopupMenu(window.application)
mode_menu.add_items(
("O" + self.modes["global"], "win.search-mode", "global"),
("O" + self.modes["buddies"], "win.search-mode", "buddies"),
("O" + self.modes["rooms"], "win.search-mode", "rooms"),
("O" + self.modes["user"], "win.search-mode", "user")
)
mode_menu.update_model()
window.search_mode_button.set_menu_model(mode_menu.model)
window.search_mode_label.set_label(self.modes["global"])
if GTK_API_VERSION >= 4:
inner_button = next(iter(window.search_mode_button))
add_css_class(inner_button, "arrow-button")
self.room_search_combobox = ComboBox(
container=self.window.search_title, has_entry=True, has_entry_completion=True,
entry=self.window.room_search_entry, visible=False
)
self.user_search_combobox = ComboBox(
container=self.window.search_title, has_entry=True, has_entry_completion=True,
entry=self.window.user_search_entry, visible=False
)
self.search_combobox = ComboBox(
container=self.window.search_title, has_entry=True, has_entry_completion=True,
entry=self.window.search_entry
)
self.file_properties = None
for event_name, callback in (
("add-search", self.add_search),
("add-wish", self.update_wish_button),
("file-search-response", self.file_search_response),
("quit", self.quit),
("remove-search", self.remove_search),
("remove-wish", self.update_wish_button),
("server-disconnect", self.server_disconnect),
("server-login", self.server_login),
("show-search", self.show_search)
):
events.connect(event_name, callback)
self.populate_search_history()
def quit(self):
self.freeze()
def destroy(self):
self.room_search_combobox.destroy()
self.user_search_combobox.destroy()
self.search_combobox.destroy()
if self.file_properties is not None:
self.file_properties.destroy()
super().destroy()
def on_focus(self, *_args):
if self.window.current_page_id != self.window.search_page.id:
return True
if self.window.search_entry.is_sensitive():
self.window.search_entry.grab_focus()
return True
return False
def on_restore_removed_page(self, page_args):
search_term, mode, room, users = page_args
core.search.do_search(search_term, mode, room=room, users=users)
def on_remove_all_pages(self, *_args):
core.search.remove_all_searches()
def on_switch_search_page(self, _notebook, page, _page_num):
if self.window.current_page_id != self.window.search_page.id:
return
for tab in self.pages.values():
if tab.container != page:
continue
self.window.update_title()
break
def on_search_mode(self, action, state):
action.set_state(state)
search_mode = state.get_string()
self.window.search_mode_label.set_label(self.modes[search_mode])
self.user_search_combobox.set_visible(search_mode == "user")
self.room_search_combobox.set_visible(search_mode == "rooms")
# Hide popover after click
self.window.search_mode_button.get_popover().set_visible(False)
def on_search(self):
text = self.window.search_entry.get_text().strip()
if not text:
return
mode = self.window.lookup_action("search-mode").get_state().get_string()
room = self.room_search_combobox.get_text()
user = self.user_search_combobox.get_text()
users = [user] if user else []
self.window.search_entry.set_text("")
core.search.do_search(text, mode, room=room, users=users)
def populate_search_history(self):
self.search_combobox.freeze()
if not config.sections["searches"]["enable_history"]:
self.search_combobox.clear()
else:
for term in islice(config.sections["searches"]["history"], core.search.SEARCH_HISTORY_LIMIT):
self.search_combobox.append(str(term))
self.search_combobox.unfreeze()
def add_search_history_item(self, term):
if not config.sections["searches"]["enable_history"]:
return
self.search_combobox.remove_id(term)
self.search_combobox.prepend(term)
while self.search_combobox.get_num_items() > core.search.SEARCH_HISTORY_LIMIT:
self.search_combobox.remove_pos(-1)
def create_page(self, token, text, mode=None, mode_label=None, room=None, users=None,
show_page=True):
page = self.pages.get(token)
if page is None:
self.pages[token] = page = Search(
self, text=text, token=token, mode=mode, mode_label=mode_label,
room=room, users=users, show_page=show_page)
else:
mode_label = page.mode_label
if not show_page:
return page
if mode_label is not None:
text = f"({mode_label}) {text}"
self.append_page(page.container, text, focus_callback=page.on_focus,
close_callback=page.on_close)
page.set_label(self.get_tab_label_inner(page.container))
return page
def add_search(self, token, search, switch_page=True):
mode = search.mode
mode_label = None
room = search.room
users = search.users
if mode == "rooms":
mode_label = room.strip()
elif mode == "user":
mode_label = ",".join(users)
elif mode == "buddies":
mode_label = _("Buddies")
self.create_page(token, search.term_sanitized, mode, mode_label, room=room, users=users)
if switch_page:
self.show_search(token)
self.add_search_history_item(search.term_sanitized)
def show_search(self, token):
page = self.pages.get(token)
if page is None:
return
self.set_current_page(page.container)
self.window.change_main_page(self.window.search_page)
def remove_search(self, token):
page = self.pages.get(token)
if page is None:
return
page.clear()
if page.show_page:
mode = page.mode
if mode == "wishlist":
# For simplicity's sake, turn wishlist tabs into regular ones when restored
mode = "global"
self.remove_page(page.container, page_args=(page.text, mode, page.room, page.searched_users))
del self.pages[token]
page.destroy()
def clear_search_history(self):
self.search_combobox.freeze()
self.window.search_entry.set_text("")
config.sections["searches"]["history"] = []
config.write_configuration()
self.search_combobox.clear()
self.search_combobox.unfreeze()
def add_filter_history_item(self, filter_id, value):
for page in self.pages.values():
page.add_filter_history_item(filter_id, value)
def clear_filter_history(self):
# Clear filter history in config
for filter_id in ("filterin", "filterout", "filtertype", "filtersize", "filterbr", "filterlength", "filtercc"):
config.sections["searches"][filter_id] = []
config.write_configuration()
# Update filters in search tabs
for page in self.pages.values():
page.filters_undo = page.FILTERS_EMPTY
page.populate_filter_history()
def file_search_response(self, msg):
page = self.pages.get(msg.token)
if page is None:
search_item = core.search.searches.get(msg.token)
if search_item is None:
return
search_term = search_item.term
mode = "wishlist"
mode_label = _("Wish")
page = self.create_page(msg.token, search_term, mode, mode_label, show_page=False)
# No more things to add because we've reached the result limit
if page.num_results_found >= page.max_limit:
core.search.remove_allowed_token(msg.token)
page.max_limited = True
page.update_result_counter()
return
page.file_search_response(msg)
def update_wish_button(self, wish):
for page in self.pages.values():
if page.text == wish:
page.update_wish_button()
def server_login(self, *_args):
self.window.search_title.set_sensitive(True)
self.on_focus()
def server_disconnect(self, *_args):
self.window.search_title.set_sensitive(False)
class Search:
FILTER_GENERIC_FILE_TYPES = (
("audio", FileTypes.AUDIO),
("executable", FileTypes.EXECUTABLE),
("image", FileTypes.IMAGE),
("video", FileTypes.VIDEO),
("document", FileTypes.DOCUMENT),
("text", FileTypes.TEXT),
("archive", FileTypes.ARCHIVE)
)
FILTER_PRESETS = {
"filterbr": ("!0", "128 <=192", ">192 <320", "=320", ">320"),
"filtersize": (">50MiB", ">20MiB <=50MiB", ">10MiB <=20MiB", ">5MiB <=10MiB", "<=5MiB"),
"filtertype": ("audio", "image", "video", "document", "text", "archive", "!executable", "audio image text"),
"filterlength": (">15:00", ">8:00 <=15:00", ">5:00 <=8:00", ">2:00 <=5:00", "<=2:00")
}
FILTER_SPLIT_DIGIT_PATTERN = re.compile(r"(?:[|&\s])+(?<![<>!=]\s)") # [pipe, ampersand, space]
FILTER_SPLIT_TEXT_PATTERN = re.compile(r"(?:[|&,;\s])+(?<!!\s)") # [pipe, ampersand, comma, semicolon, space]
FILTERS_EMPTY = {
"filterin": (None, ""),
"filterout": (None, ""),
"filtersize": (None, ""),
"filterbr": (None, ""),
"filterslot": (False, False),
"filtercc": (None, ""),
"filtertype": (None, ""),
"filterlength": (None, "")
}
def __init__(self, searches, text, token, mode, mode_label, room, users, show_page):
(
self.add_wish_button,
self.add_wish_icon,
self.add_wish_label,
self.clear_undo_filters_button,
self.clear_undo_filters_icon,
self.container,
self.expand_button,
self.expand_icon,
self.filter_bitrate_container,
self.filter_bitrate_entry,
self.filter_country_container,
self.filter_country_entry,
self.filter_exclude_container,
self.filter_exclude_entry,
self.filter_file_size_container,
self.filter_file_size_entry,
self.filter_file_type_container,
self.filter_file_type_entry,
self.filter_free_slot_button,
self.filter_include_container,
self.filter_include_entry,
self.filter_length_container,
self.filter_length_entry,
self.filters_button,
self.filters_container,
self.filters_label,
self.grouping_button,
self.results_button,
self.results_label,
self.tree_container
) = ui.load(scope=self, path="search.ui")
self.searches = searches
self.window = searches.window
self.text = text
self.token = token
self.mode = mode
self.mode_label = mode_label
self.room = room
self.searched_users = users
self.show_page = show_page
self.initialized = False
self.users = {}
self.folders = {}
self.all_data = []
self.grouping_mode = None
self.row_id = 0
self.filters = {}
self.filters_undo = self.FILTERS_EMPTY
self.populating_filters = False
self.refiltering = False
self.active_filter_count = 0
self.num_results_found = 0
self.num_results_visible = 0
self.max_limit = config.sections["searches"]["max_displayed_results"]
self.max_limited = False
# Use dict instead of list for faster membership checks
self.selected_users = {}
self.selected_results = {}
# Combo boxes
self.filter_include_combobox = ComboBox(
container=self.filter_include_container, has_entry=True,
entry=self.filter_include_entry, item_selected_callback=self.on_refilter)
self.filter_exclude_combobox = ComboBox(
container=self.filter_exclude_container, has_entry=True,
entry=self.filter_exclude_entry, item_selected_callback=self.on_refilter)
self.filter_file_type_combobox = ComboBox(
container=self.filter_file_type_container, has_entry=True,
entry=self.filter_file_type_entry, item_selected_callback=self.on_refilter)
self.filter_file_size_combobox = ComboBox(
container=self.filter_file_size_container, has_entry=True,
entry=self.filter_file_size_entry, item_selected_callback=self.on_refilter)
self.filter_bitrate_combobox = ComboBox(
container=self.filter_bitrate_container, has_entry=True,
entry=self.filter_bitrate_entry, item_selected_callback=self.on_refilter)
self.filter_length_combobox = ComboBox(
container=self.filter_length_container, has_entry=True,
entry=self.filter_length_entry, item_selected_callback=self.on_refilter)
self.filter_country_combobox = ComboBox(
container=self.filter_country_container, has_entry=True,
entry=self.filter_country_entry, item_selected_callback=self.on_refilter)
self.tree_view = TreeView(
self.window, parent=self.tree_container, name="file_search", persistent_sort=True,
multi_select=True, activate_row_callback=self.on_row_activated, focus_in_callback=self.on_refilter,
columns={
# Visible columns
"user": {
"column_type": "text",
"title": _("User"),
"width": 200,
"sensitive_column": "free_slot_data"
},
"country": {
"column_type": "icon",
"title": _("Country"),
"width": 30,
"hide_header": True
},
"speed": {
"column_type": "number",
"title": _("Speed"),
"width": 120,
"sort_column": "speed_data",
"sensitive_column": "free_slot_data"
},
"in_queue": {
"column_type": "number",
"title": _("In Queue"),
"width": 110,
"sort_column": "in_queue_data",
"sensitive_column": "free_slot_data"
},
"folder": {
"column_type": "text",
"title": _("Folder"),
"width": 200,
"expand_column": True,
"sensitive_column": "free_slot_data",
"tooltip_callback": self.on_file_path_tooltip
},
"file_type": {
"column_type": "icon",
"title": _("File Type"),
"width": 40,
"hide_header": True,
"sensitive_column": "free_slot_data"
},
"filename": {
"column_type": "text",
"title": _("Filename"),
"width": 200,
"expand_column": True,
"sensitive_column": "free_slot_data",
"tooltip_callback": self.on_file_path_tooltip
},
"size": {
"column_type": "number",
"title": _("Size"),
"width": 180,
"sort_column": "size_data",
"sensitive_column": "free_slot_data"
},
"quality": {
"column_type": "number",
"title": _("Quality"),
"width": 150,
"sort_column": "bitrate_data",
"sensitive_column": "free_slot_data"
},
"length": {
"column_type": "number",
"title": _("Duration"),
"width": 100,
"sort_column": "length_data",
"sensitive_column": "free_slot_data"
},
# Hidden data columns
"speed_data": {"data_type": GObject.TYPE_UINT},
"in_queue_data": {"data_type": GObject.TYPE_UINT},
"size_data": {"data_type": GObject.TYPE_UINT64},
"bitrate_data": {"data_type": GObject.TYPE_UINT},
"length_data": {"data_type": GObject.TYPE_UINT},
"free_slot_data": {"data_type": GObject.TYPE_BOOLEAN},
"file_data": {"data_type": GObject.TYPE_PYOBJECT},
"id_data": {
"data_type": GObject.TYPE_INT,
"default_sort_type": "ascending",
"iterator_key": True
}
}
)
# Popup menus
self.popup_menu_users = UserPopupMenu(self.window.application, tab_name="search")
self.popup_menu_copy = PopupMenu(self.window.application)
self.popup_menu_copy.add_items(
("#" + _("Copy _File Path"), self.on_copy_file_path),
("#" + _("Copy _URL"), self.on_copy_url),
("#" + _("Copy Folder U_RL"), self.on_copy_folder_url)
)
self.popup_menu = FilePopupMenu(
self.window.application, parent=self.tree_view.widget, callback=self.on_popup_menu
)
self.popup_menu.add_items(
("#" + _("_Download File(s)"), self.on_download_files),
("#" + _("Download File(s) _To…"), self.on_download_files_to),
("", None),
("#" + _("Download _Folder(s)"), self.on_download_folders),
("#" + _("Download F_older(s) To…"), self.on_download_folders_to),
("", None),
("#" + _("View User _Profile"), self.on_user_profile),
("#" + _("_Browse Folder"), self.on_browse_folder),
("#" + _("F_ile Properties"), self.on_file_properties),
("", None),
(">" + _("Copy"), self.popup_menu_copy),
(">" + _("User Actions"), self.popup_menu_users)
)
self.tab_menu = PopupMenu(self.window.application)
self.tab_menu.add_items(
("#" + _("Edit…"), self.on_edit_search),
("#" + _("Copy Search Term"), self.on_copy_search_term),
("", None),
("#" + _("Clear All Results"), self.on_clear),
("#" + _("Close All Tabs…"), self.on_close_all_tabs),
("#" + _("_Close Tab"), self.on_close)
)
self.popup_menus = (
self.popup_menu, self.popup_menu_users, self.popup_menu_copy, self.tab_menu
)
# Key bindings
for widget in (self.container, self.tree_view.widget):
Accelerator("<Primary>f", widget, self.on_show_filter_bar_accelerator)
Accelerator("Escape", self.filters_container, self.on_close_filter_bar_accelerator)
Accelerator("<Alt>Return", self.tree_view.widget, self.on_file_properties_accelerator)
# Grouping
menu = create_grouping_menu(self.window, config.sections["searches"]["group_searches"], self.on_group)
self.grouping_button.set_menu_model(menu)
self.expand_button.set_active(config.sections["searches"]["expand_searches"])
# Filter button widgets
self.filter_buttons = {
"filterslot": self.filter_free_slot_button
}
# Filter combobox widgets
self.filter_comboboxes = {
"filterin": self.filter_include_combobox,
"filterout": self.filter_exclude_combobox,
"filtersize": self.filter_file_size_combobox,
"filterbr": self.filter_bitrate_combobox,
"filtercc": self.filter_country_combobox,
"filtertype": self.filter_file_type_combobox,
"filterlength": self.filter_length_combobox
}
# Filter text entry widgets
for filter_id, combobox in self.filter_comboboxes.items():
combobox.entry.filter_id = filter_id
buffer = combobox.entry.get_buffer()
buffer.connect_after("deleted-text", self.on_filter_entry_deleted_text)
if GTK_API_VERSION == 3:
add_css_class(combobox.dropdown, "dropdown-scrollbar")
self.filters_button.set_active(config.sections["searches"]["filters_visible"])
self.populate_filter_history()
self.populate_default_filters()
# Wishlist
self.update_wish_button()
def clear(self):
self.clear_model(stored_results=True)
def destroy(self):
for menu in self.popup_menus:
menu.destroy()
for combobox in self.filter_comboboxes.values():
combobox.destroy()
self.tree_view.destroy()
self.window.update_title()
self.__dict__.clear()
def set_label(self, label):
self.tab_menu.set_parent(label)
def update_filter_widgets(self):
self.update_filter_counter(self.active_filter_count)
if self.filters_undo == self.FILTERS_EMPTY:
tooltip_text = _("Clear Filters")
icon_name = "edit-clear-symbolic"
else:
tooltip_text = _("Restore Filters")
icon_name = "edit-undo-symbolic"
if self.clear_undo_filters_icon.get_icon_name() == icon_name:
return
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.clear_undo_filters_button.set_tooltip_text(tooltip_text)
self.clear_undo_filters_icon.set_from_icon_name(icon_name, *icon_args)
def populate_filter_history(self):
for filter_id, widget in self.filter_comboboxes.items():
widget.freeze()
widget.clear()
presets = self.FILTER_PRESETS.get(filter_id)
filter_history = config.sections["searches"][filter_id]
if presets:
for index, value in enumerate(presets):
widget.append(value, item_id=f"preset_{index}")
if filter_history:
widget.append("") # Separator
for value in islice(filter_history, core.search.RESULT_FILTER_HISTORY_LIMIT):
widget.append(value)
widget.unfreeze()
def populate_default_filters(self):
if not config.sections["searches"]["enablefilters"]:
return
sfilter = config.sections["searches"]["defilter"]
num_filters = len(sfilter)
stored_filters = self.FILTERS_EMPTY.copy()
# Convert from list to dict
for i, filter_id in enumerate(stored_filters):
if i >= num_filters:
break
if filter_id in self.filter_buttons:
stored_filters[filter_id] = (False, bool(sfilter[i]))
elif filter_id in self.filter_comboboxes:
stored_filters[filter_id] = (None, str(sfilter[i]))
self.set_filters(stored_filters)
def set_filters(self, stored_filters):
"""Recall result filter values from a dict."""
self.populating_filters = True
for filter_id, button in self.filter_buttons.items():
_value, h_value = stored_filters.get(filter_id, (False, False))
button.set_active(h_value)
for filter_id, combobox in self.filter_comboboxes.items():
_value, h_value = stored_filters.get(filter_id, (None, ""))
combobox.set_text(h_value)
self.populating_filters = False
self.on_refilter()
def add_result_list(self, result_list, user, country_code, inqueue, ulspeed, h_speed,
h_queue, has_free_slots, private=False):
"""Adds a list of search results to the treeview.
Lists can either contain publicly or privately shared files.
"""
update_ui = False
search = core.search.searches[self.token]
row_id = 0
for _code, file_path, size, _ext, file_attributes, *_unused in result_list:
if self.num_results_found >= self.max_limit:
self.max_limited = True
break
file_path_lower = file_path.lower()
if any(word in file_path_lower for word in search.excluded_words):
# Filter out results with filtered words (e.g. nicotine -music)
log.add_debug(("Filtered out excluded search result %s from user %s for "
'search term "%s"'), (file_path, user, self.text))
continue
if not all(word in file_path_lower for word in search.included_words):
# Certain users may send us wrong results, filter out such ones
continue
self.num_results_found += 1
file_path_split = file_path.split("\\")
if config.sections["ui"]["reverse_file_paths"]:
# Reverse file path, file name is the first item. next() retrieves the name and removes
# it from the iterator.
file_path_split = reversed(file_path_split)
name = next(file_path_split)
else:
# Regular file path, file name is the last item. Retrieve it and remove it from the list.
name = file_path_split.pop()
# Join the resulting items into a folder path
folder_path = "\\".join(file_path_split)
h_size = human_size(size, config.sections["ui"]["file_size_unit"])
h_quality, bitrate, h_length, length = FileListMessage.parse_audio_quality_length(size, file_attributes)
if private:
name = _("[PRIVATE] %s") % name
is_result_visible = self.append(
[
user,
get_flag_icon_name(country_code),
h_speed,
h_queue,
folder_path,
get_file_type_icon_name(name),
name,
h_size,
h_quality,
h_length,
ulspeed,
inqueue,
size,
bitrate,
length,
has_free_slots,
SearchResultFile(file_path, file_attributes),
row_id
]
)
if is_result_visible:
update_ui = True
return update_ui
def file_search_response(self, msg):
user = msg.username
if user in self.users:
return
self.initialized = True
ip_address, _port = msg.addr
country_code = (
core.network_filter.get_country_code(ip_address)
or core.users.countries.get(user)
)
has_free_slots = msg.freeulslots
if has_free_slots:
inqueue = 0
h_queue = ""
else:
inqueue = msg.inqueue or 1 # Ensure value is always >= 1
h_queue = humanize(inqueue)
h_speed = ""
ulspeed = msg.ulspeed or 0
if ulspeed > 0:
h_speed = human_speed(ulspeed)
update_ui = self.add_result_list(msg.list, user, country_code, inqueue, ulspeed, h_speed,
h_queue, has_free_slots)
if msg.privatelist and config.sections["searches"]["private_search_results"]:
update_ui_private = self.add_result_list(
msg.privatelist, user, country_code, inqueue, ulspeed, h_speed, h_queue,
has_free_slots, private=True
)
if not update_ui and update_ui_private:
update_ui = True
if update_ui:
# If this search wasn't initiated by us (e.g. wishlist), and the results aren't spoofed, show tab
is_wish = (self.mode == "wishlist")
if not self.show_page:
self.searches.create_page(self.token, self.text)
self.show_page = True
tab_changed = self.searches.request_tab_changed(self.container, is_important=is_wish)
if tab_changed and is_wish:
self.window.update_title()
if config.sections["notifications"]["notification_popup_wish"]:
core.notifications.show_search_notification(
str(self.token), self.text,
title=_("Wishlist Results Found")
)
# Update number of results, even if they are all filtered
self.update_result_counter()
def append(self, row):
self.all_data.append(row)
if not self.check_filter(row):
return False
self.add_row_to_model(row)
return True
def add_row_to_model(self, row):
(user, flag, h_speed, h_queue, folder_path, _unused, _unused, _unused, _unused,
_unused, speed, queue, _unused, _unused, _unused, has_free_slots,
file_data, _unused) = row
expand_allowed = self.initialized
expand_user = False
expand_folder = False
parent_iterator = None
user_child_iterators = None
user_folder_child_iterators = None
if self.grouping_mode != "ungrouped":
# Group by folder or user
empty_int = 0
empty_str = ""
if user not in self.users:
iterator = self.tree_view.add_row(
[
user,
flag,
h_speed,
h_queue,
empty_str,
empty_str,
empty_str,
empty_str,
empty_str,
empty_str,
speed,
queue,
empty_int,
empty_int,
empty_int,
has_free_slots,
None,
self.row_id
], select_row=False
)
if expand_allowed:
expand_user = self.grouping_mode == "folder_grouping" or self.expand_button.get_active()
self.row_id += 1
self.users[user] = (iterator, [])
user_iterator, user_child_iterators = self.users[user]
if self.grouping_mode == "folder_grouping":
# Group by folder
user_folder_path = user + folder_path
if user_folder_path not in self.folders:
iterator = self.tree_view.add_row(
[
user,
flag,
h_speed,
h_queue,
folder_path,
empty_str,
empty_str,
empty_str,
empty_str,
empty_str,
speed,
queue,
empty_int,
empty_int,
empty_int,
has_free_slots,
SearchResultFile(file_data.path.rpartition("\\")[0]),
self.row_id
], select_row=False, parent_iterator=user_iterator
)
user_child_iterators.append(iterator)
expand_folder = expand_allowed and self.expand_button.get_active()
self.row_id += 1
self.folders[user_folder_path] = (iterator, [])
row = row[:]
row[4] = "" # Folder not visible for file row if "group by folder" is enabled
user_folder_iterator, user_folder_child_iterators = self.folders[user_folder_path]
parent_iterator = user_folder_iterator
else:
parent_iterator = user_iterator
else:
if user not in self.users:
self.users[user] = (None, [])
user_iterator, user_child_iterators = self.users[user]
row[17] = self.row_id
iterator = self.tree_view.add_row(row, select_row=False, parent_iterator=parent_iterator)
self.row_id += 1
if user_folder_child_iterators is not None:
user_folder_child_iterators.append(iterator)
else:
user_child_iterators.append(iterator)
if expand_user:
self.tree_view.expand_row(user_iterator)
if expand_folder:
self.tree_view.expand_row(user_folder_iterator)
self.num_results_visible += 1
return iterator
# Result Filters #
def add_filter_history_item(self, filter_id, value):
combobox = self.filter_comboboxes[filter_id]
position = len(self.FILTER_PRESETS.get(filter_id, ()))
combobox.freeze()
if position:
# Separator item
if position == combobox.get_num_items():
combobox.append("")
position += 1
num_items_limit = core.search.RESULT_FILTER_HISTORY_LIMIT + position
combobox.remove_id(value)
combobox.insert(position=position, item=value)
while combobox.get_num_items() > num_items_limit:
combobox.remove_pos(-1)
combobox.unfreeze()
def push_history(self, filter_id, value):
if not value:
return
history = config.sections["searches"].get(filter_id)
if history is None:
# Button filters do not store history
return
if history and history[0] == value:
# Most recent item selected, nothing to do
return
if value in history:
history.remove(value)
elif len(history) >= core.search.RESULT_FILTER_HISTORY_LIMIT:
del history[-1]
history.insert(0, value)
config.write_configuration()
# If called after selecting a filter history item from the dropdown, GTK 4 crashes
# when resetting the dropdown model (in freeze() and unfreeze()). Add a slight delay
# to allow the selected item signal to complete before we add an item.
GLib.idle_add(self.searches.add_filter_history_item, filter_id, value)
@staticmethod
def _split_operator(condition):
"""Returns (operation, digit)"""
operators = {
"<": operator.lt,
"<=": operator.le,
"==": operator.eq,
"!=": operator.ne,
">=": operator.ge,
">": operator.gt
}
if condition.startswith((">=", "<=", "==", "!=")):
return operators.get(condition[:2]), condition[2:]
if condition.startswith((">", "<")):
return operators.get(condition[:1]), condition[1:]
if condition.startswith(("=", "!")):
return operators.get(condition[:1] + "="), condition[1:]
return operator.ge, condition
def check_digit(self, result_filter, value, file_size=False):
"""Check if any conditions in result_filter match value."""
allowed = blocked = False
for condition in result_filter:
operation, digit = self._split_operator(condition)
if file_size:
digit, factor = factorize(digit)
if digit is None:
# Invalid Size unit
continue
# Exact match unlikely, approximate to within +/- 0.1 MiB (or 1 MiB if over 100 MiB)
adjust = factor / 8 if factor > 1024 and digit < 104857600 else factor # TODO: GiB
else:
adjust = 0
try:
# Bitrate in Kb/s or Duration in seconds
digit = int(digit)
except ValueError:
if ":" not in digit:
# Invalid syntax
continue
try:
# Duration: Convert string from HH:MM:SS or MM:SS into Seconds as integer
digit = sum(x * int(t) for x, t in zip([1, 60, 3600], reversed(digit.split(":"))))
except ValueError:
# Invalid Duration unit
continue
if (digit - adjust) <= value <= (digit + adjust):
if operation is operator.eq:
return True
if operation is operator.ne:
return False
if value and operation(value, digit) and not blocked:
allowed = True
continue
blocked = True
return False if blocked else allowed
@staticmethod
def check_country(result_filter, value):
allowed = False
for country_code in result_filter:
if country_code == value:
allowed = True
elif country_code.startswith("!") and country_code[1:] != value:
allowed = True
elif country_code.startswith("!") and country_code[1:] == value:
return False
return allowed
@staticmethod
def check_file_type(result_filter, value):
allowed = False
found_inclusive = False
for ext in result_filter:
exclude_ext = None
if ext.startswith("!"):
exclude_ext = ext[1:]
if not exclude_ext.startswith("."):
exclude_ext = "." + exclude_ext
elif not ext.startswith("."):
ext = "." + ext
if ext.startswith("!") and value.endswith(exclude_ext):
return False
if not ext.startswith("!"):
found_inclusive = True
if value.endswith(ext):
allowed = True
if not found_inclusive:
allowed = True
return allowed
def check_filter(self, row):
if self.active_filter_count <= 0:
return True
for filter_id, (filter_value, _h_filter_value) in self.filters.items():
if not filter_value:
continue
if filter_id == "filtertype" and not self.check_file_type(filter_value, row[16].path.lower()):
return False
if filter_id == "filtercc" and not self.check_country(filter_value, row[1][-2:].upper()):
return False
if filter_id == "filterin" and not filter_value.search(row[16].path) and not filter_value.fullmatch(row[0]):
return False
if filter_id == "filterout" and (filter_value.search(row[16].path) or filter_value.fullmatch(row[0])):
return False
if filter_id == "filterslot" and row[11] > 0:
return False
if filter_id == "filtersize" and not self.check_digit(filter_value, row[12], file_size=True):
return False
if filter_id == "filterbr" and not self.check_digit(filter_value, row[13]):
return False
if filter_id == "filterlength" and not self.check_digit(filter_value, row[14]):
return False
return True
def update_filter_counter(self, count):
if count > 0:
self.filters_label.set_label(_("_Result Filters [%d]") % count)
else:
self.filters_label.set_label(_("_Result Filters"))
self.filters_label.set_tooltip_text(_("%d active filter(s)") % count)
def clear_model(self, stored_results=False):
self.initialized = False
if stored_results:
self.all_data.clear()
self.num_results_found = 0
self.max_limited = False
self.max_limit = config.sections["searches"]["max_displayed_results"]
self.users.clear()
self.folders.clear()
self.tree_view.clear()
self.row_id = 0
self.num_results_visible = 0
def update_model(self):
self.tree_view.freeze()
for row in self.all_data:
if self.check_filter(row):
self.add_row_to_model(row)
# Update number of results
self.update_result_counter()
self.tree_view.unfreeze()
if self.grouping_mode != "ungrouped":
# Group by folder or user
if self.expand_button.get_active():
self.tree_view.expand_all_rows()
else:
self.tree_view.collapse_all_rows()
if self.grouping_mode == "folder_grouping":
self.tree_view.expand_root_rows()
self.initialized = True
def update_wish_button(self):
if self.mode not in {"global", "wishlist"}:
self.add_wish_button.set_visible(False)
return
if not core.search.is_wish(self.text):
icon_name = "list-add-symbolic"
label = _("Add Wi_sh")
else:
icon_name = "list-remove-symbolic"
label = _("Remove Wi_sh")
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.add_wish_icon.set_from_icon_name(icon_name, *icon_args)
self.add_wish_label.set_label(label)
def on_add_wish(self, *_args):
if core.search.is_wish(self.text):
core.search.remove_wish(self.text)
else:
core.search.add_wish(self.text)
def add_popup_menu_user(self, popup, user):
popup.add_items(
("", None),
("#" + _("Select User's Results"), self.on_select_user_results, user)
)
popup.update_model()
popup.toggle_user_items()
def populate_popup_menu_users(self):
self.popup_menu_users.clear()
if not self.selected_users:
return
# Multiple users, create submenus for some of them
if len(self.selected_users) > 1:
for user in islice(self.selected_users, 20):
popup = UserPopupMenu(self.window.application, username=user, tab_name="search")
self.add_popup_menu_user(popup, user)
self.popup_menu_users.add_items((">" + user, popup))
self.popup_menu_users.update_model()
return
# Single user, add items directly to "User Actions" submenu
user = next(iter(self.selected_users), None)
self.popup_menu_users.setup_user_menu(user)
self.add_popup_menu_user(self.popup_menu_users, user)
def on_close_filter_bar_accelerator(self, *_args):
"""Escape - hide filter bar."""
self.filters_button.set_active(False)
return True
def on_show_filter_bar_accelerator(self, *_args):
"""Ctrl+F - show filter bar."""
self.filters_button.set_active(True)
self.filter_include_combobox.grab_focus()
return True
def on_file_properties_accelerator(self, *_args):
"""Alt+Return - show file properties dialog."""
self.select_results()
self.on_file_properties()
return True
def on_select_user_results(self, _action, _parameter, selected_user):
if not self.selected_users:
return
_user_iterator, user_child_iterators = self.users[selected_user]
self.tree_view.unselect_all_rows()
for iterator in user_child_iterators:
if self.tree_view.get_row_value(iterator, "filename"):
self.tree_view.select_row(iterator, should_scroll=False)
continue
user_folder_path = selected_user + self.tree_view.get_row_value(iterator, "folder")
user_folder_data = self.folders.get(user_folder_path)
if not user_folder_data:
continue
_user_folder_iter, user_folder_child_iterators = user_folder_data
for i_iterator in user_folder_child_iterators:
self.tree_view.select_row(i_iterator, should_scroll=False)
def select_result(self, iterator):
user = self.tree_view.get_row_value(iterator, "user")
if user not in self.selected_users:
self.selected_users[user] = None
if self.tree_view.get_row_value(iterator, "filename"):
row_id = self.tree_view.get_row_value(iterator, "id_data")
if row_id not in self.selected_results:
self.selected_results[row_id] = iterator
return
self.select_child_results(iterator, user)
def select_child_results(self, iterator, user):
folder_path = self.tree_view.get_row_value(iterator, "folder")
if folder_path:
user_folder_path = user + folder_path
row_data = self.folders[user_folder_path]
else:
row_data = self.users[user]
_row_iter, child_transfers = row_data
for i_iterator in child_transfers:
self.select_result(i_iterator)
def select_results(self):
self.selected_results.clear()
self.selected_users.clear()
for iterator in self.tree_view.get_selected_rows():
self.select_result(iterator)
def update_result_counter(self):
if self.max_limited or self.num_results_found > self.num_results_visible:
# Append plus symbol "+" if Results are Filtered and/or reached 'Maximum per search'
str_plus = "+"
# Display total results on the tooltip, but only if we know the exact number of results
if self.max_limited:
total = f"> {self.max_limit}+"
else:
total = self.num_results_found
self.results_button.set_tooltip_text(_("Total: %s") % total)
else:
str_plus = ""
tooltip_text = _("Results")
if self.results_button.get_tooltip_text() != tooltip_text:
self.results_button.set_tooltip_text(tooltip_text)
self.results_label.set_text(humanize(self.num_results_visible) + str_plus)
def on_file_path_tooltip(self, treeview, iterator):
file_data = treeview.get_row_value(iterator, "file_data")
if not file_data:
return None
return file_data.path
def on_row_activated(self, treeview, iterator, _column):
self.select_results()
folder_path = treeview.get_row_value(iterator, "folder")
basename = treeview.get_row_value(iterator, "filename")
if not folder_path and not basename:
# Don't activate user rows
return
if not basename:
self.on_download_folders()
else:
self.on_download_files()
treeview.unselect_all_rows()
def on_popup_menu(self, menu, _widget):
self.select_results()
self.populate_popup_menu_users()
menu.set_num_selected_files(len(self.selected_results))
def on_browse_folder(self, *_args):
iterator = next(iter(self.selected_results.values()), None)
if iterator is None:
return
user = self.tree_view.get_row_value(iterator, "user")
path = self.tree_view.get_row_value(iterator, "file_data").path
core.userbrowse.browse_user(user, path=path)
def on_user_profile(self, *_args):
iterator = next(iter(self.selected_results.values()), None)
if iterator is None:
return
user = self.tree_view.get_row_value(iterator, "user")
core.userinfo.show_user(user)
def on_file_properties(self, *_args):
data = []
selected_size = 0
selected_length = 0
for iterator in self.selected_results.values():
file_data = self.tree_view.get_row_value(iterator, "file_data")
file_path = file_data.path
file_size = self.tree_view.get_row_value(iterator, "size_data")
selected_size += file_size
selected_length += self.tree_view.get_row_value(iterator, "length_data")
country_code = self.tree_view.get_row_value(iterator, "country")[-2:].upper()
folder_path, _separator, basename = file_path.rpartition("\\")
data.append({
"user": self.tree_view.get_row_value(iterator, "user"),
"file_path": file_path,
"basename": basename,
"virtual_folder_path": folder_path,
"size": file_size,
"speed": self.tree_view.get_row_value(iterator, "speed_data"),
"queue_position": self.tree_view.get_row_value(iterator, "in_queue_data"),
"file_attributes": file_data.attributes,
"country_code": country_code
})
if data:
if self.searches.file_properties is None:
self.searches.file_properties = FileProperties(self.window.application)
self.searches.file_properties.update_properties(data, selected_size, selected_length)
self.searches.file_properties.present()
def on_download_files(self, *_args, download_folder_path=None):
for iterator in self.selected_results.values():
user = self.tree_view.get_row_value(iterator, "user")
file_data = self.tree_view.get_row_value(iterator, "file_data")
file_path = file_data.path
size = self.tree_view.get_row_value(iterator, "size_data")
core.downloads.enqueue_download(
user, file_path, folder_path=download_folder_path, size=size,
file_attributes=file_data.attributes)
def on_download_files_to_selected(self, selected_folder_paths, _data):
self.on_download_files(download_folder_path=next(iter(selected_folder_paths), None))
def on_download_files_to(self, *_args):
FolderChooser(
parent=self.window,
title=_("Select Destination Folder for File(s)"),
callback=self.on_download_files_to_selected,
initial_folder=core.downloads.get_default_download_folder()
).present()
def on_download_folders(self, *_args, download_folder_path=None):
requested_folders = set()
for iterator in self.selected_results.values():
user = self.tree_view.get_row_value(iterator, "user")
folder_path = self.tree_view.get_row_value(iterator, "file_data").path.rpartition("\\")[0]
user_folder_key = user + folder_path
if user_folder_key in requested_folders:
# Ensure we don't send folder content requests for a folder more than once,
# e.g. when several selected results belong to the same folder
continue
visible_files = []
for row in self.all_data:
# Find the wanted folder
if folder_path != row[16].path.rpartition("\\")[0]:
continue
(_unused, _unused, _unused, _unused, _unused, _unused, _unused, _unused, _unused,
_unused, _unused, _unused, size, _unused, _unused, _unused, file_data,
_unused) = row
visible_files.append((file_data.path, size, file_data.attributes))
core.search.request_folder_download(
user, folder_path, visible_files, download_folder_path=download_folder_path
)
requested_folders.add(user_folder_key)
def on_download_folders_to_selected(self, selected_folder_paths, _data):
self.on_download_folders(download_folder_path=next(iter(selected_folder_paths), None))
def on_download_folders_to(self, *_args):
FolderChooser(
parent=self.window,
title=_("Select Destination Folder"),
callback=self.on_download_folders_to_selected,
initial_folder=core.downloads.get_default_download_folder()
).present()
def on_copy_file_path(self, *_args):
iterator = next(iter(self.selected_results.values()), None)
if iterator is None:
return
file_path = self.tree_view.get_row_value(iterator, "file_data").path
clipboard.copy_text(file_path)
def on_copy_url(self, *_args):
iterator = next(iter(self.selected_results.values()), None)
if iterator is None:
return
user = self.tree_view.get_row_value(iterator, "user")
file_path = self.tree_view.get_row_value(iterator, "file_data").path
url = core.userbrowse.get_soulseek_url(user, file_path)
clipboard.copy_text(url)
def on_copy_folder_url(self, *_args):
iterator = next(iter(self.selected_results.values()), None)
if iterator is None:
return
user = self.tree_view.get_row_value(iterator, "user")
file_path = self.tree_view.get_row_value(iterator, "file_data").path
folder_path, separator, _basename = file_path.rpartition("\\")
url = core.userbrowse.get_soulseek_url(user, folder_path + separator)
clipboard.copy_text(url)
def on_counter_button(self, *_args):
if self.num_results_found > self.num_results_visible:
self.on_clear_undo_filters()
else:
self.window.application.lookup_action("configure-searches").activate()
def on_group(self, action, state):
mode = state.get_string()
active = mode != "ungrouped"
popover = self.grouping_button.get_popover()
if popover is not None:
popover.set_visible(False)
config.sections["searches"]["group_searches"] = mode
self.tree_view.set_show_expanders(active)
self.expand_button.set_visible(active)
self.grouping_mode = mode
self.clear_model()
self.tree_view.has_tree = active
self.tree_view.create_model()
self.update_model()
action.set_state(state)
def on_toggle_expand_all(self, *_args):
active = self.expand_button.get_active()
if active:
icon_name = "view-restore-symbolic"
self.tree_view.expand_all_rows()
else:
icon_name = "view-fullscreen-symbolic"
self.tree_view.collapse_all_rows()
if self.grouping_mode == "folder_grouping":
self.tree_view.expand_root_rows()
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.expand_icon.set_from_icon_name(icon_name, *icon_args)
config.sections["searches"]["expand_searches"] = active
def on_toggle_filters(self, *_args):
visible = self.filters_button.get_active()
self.filters_container.set_reveal_child(visible)
config.sections["searches"]["filters_visible"] = visible
if visible:
self.filter_include_combobox.grab_focus()
return
self.tree_view.grab_focus()
def on_copy_search_term(self, *_args):
clipboard.copy_text(self.text)
def on_edit_search(self, *_args):
if self.mode == "wishlist":
self.window.application.lookup_action("wishlist").activate()
return
self.window.lookup_action("search-mode").change_state(GLib.Variant.new_string(self.mode))
if self.mode == "room":
self.window.room_search_entry.set_text(self.room)
elif self.mode == "user":
self.window.user_search_entry.set_text(self.searched_users[0])
self.window.search_entry.set_text(self.text)
self.window.search_entry.set_position(-1)
self.window.search_entry.grab_focus_without_selecting()
def on_refilter(self, *_args):
if self.populating_filters:
return
self.refiltering = True
filter_in = filter_out = filter_size = filter_bitrate = filter_country = filter_file_type = filter_length = None
filter_in_str = self.filter_include_combobox.get_text().strip()
filter_out_str = self.filter_exclude_combobox.get_text().strip()
filter_size_str = self.filter_file_size_combobox.get_text().strip()
filter_bitrate_str = self.filter_bitrate_combobox.get_text().strip()
filter_country_str = self.filter_country_combobox.get_text().strip()
filter_file_type_str = self.filter_file_type_combobox.get_text().strip()
filter_length_str = self.filter_length_combobox.get_text().strip()
filter_free_slot = self.filter_free_slot_button.get_active()
# Include/exclude text
error_entries = set()
if filter_in_str:
try:
filter_in = re.compile(filter_in_str, flags=re.IGNORECASE)
except re.error:
error_entries.add(self.filter_include_entry)
if filter_out_str:
try:
filter_out = re.compile(filter_out_str, flags=re.IGNORECASE)
except re.error:
error_entries.add(self.filter_exclude_entry)
for entry in (self.filter_include_entry, self.filter_exclude_entry):
# Set red background if invalid regex pattern is detected
css_class_function = add_css_class if entry in error_entries else remove_css_class
css_class_function(entry, "error")
# Split at | pipes ampersands & space(s) but don't split <>=! math operators spaced before digit condition
seperator_pattern = self.FILTER_SPLIT_DIGIT_PATTERN
if filter_size_str:
filter_size = seperator_pattern.split(filter_size_str)
if filter_bitrate_str:
filter_bitrate = seperator_pattern.split(filter_bitrate_str)
if filter_length_str:
filter_length = seperator_pattern.split(filter_length_str)
# Split at commas, in addition to | pipes ampersands & space(s) but don't split ! not operator before condition
seperator_pattern = self.FILTER_SPLIT_TEXT_PATTERN
if filter_country_str:
filter_country = seperator_pattern.split(filter_country_str.upper())
if filter_file_type_str:
filter_file_type = seperator_pattern.split(filter_file_type_str.lower())
# Replace generic file type filters with real file extensions
for filter_name, file_extensions in self.FILTER_GENERIC_FILE_TYPES:
excluded_filter_name = f"!{filter_name}"
if filter_name in filter_file_type:
filter_file_type.remove(filter_name)
filter_file_type += list(file_extensions)
elif excluded_filter_name in filter_file_type:
filter_file_type.remove(excluded_filter_name)
filter_file_type += ["!" + x for x in file_extensions]
filters = {
"filterin": (filter_in, filter_in_str),
"filterout": (filter_out, filter_out_str),
"filtersize": (filter_size, filter_size_str),
"filterbr": (filter_bitrate, filter_bitrate_str),
"filterslot": (filter_free_slot, filter_free_slot),
"filtercc": (filter_country, filter_country_str),
"filtertype": (filter_file_type, filter_file_type_str),
"filterlength": (filter_length, filter_length_str),
}
if self.filters == filters:
# Filters have not changed, no need to refilter
self.refiltering = False
return
if self.filters and filters == self.FILTERS_EMPTY:
# Filters cleared, enable Restore Filters
self.filters_undo = self.filters
else:
# Filters active, enable Clear Filters
self.filters_undo = self.FILTERS_EMPTY
self.active_filter_count = 0
# Add filters to history
for filter_id, (_value, h_value) in filters.items():
if not h_value:
continue
self.push_history(filter_id, h_value)
self.active_filter_count += 1
# Apply the new filters
self.filters = filters
self.update_filter_widgets()
self.clear_model()
self.update_model()
self.refiltering = False
def on_filter_entry_deleted_text(self, buffer, *_args):
if not self.refiltering and buffer.get_length() <= 0:
self.on_refilter()
def on_filter_entry_icon_press(self, entry, *_args):
entry_text = entry.get_text()
filter_id = entry.filter_id
_filter_value, h_filter_value = self.filters.get(filter_id)
if not entry_text:
# Recall last filter
history = config.sections["searches"].get(filter_id)
recall_text = history[0] if history else ""
entry.set_text(recall_text)
entry.set_position(-1)
entry.grab_focus_without_selecting()
elif entry_text == h_filter_value:
# Clear Filter
entry.set_text("")
return
# Activate new, edited or recalled filter
self.on_refilter()
def on_clear_undo_filters(self, *_args):
self.set_filters(self.filters_undo)
if not self.filters_button.get_active():
self.tree_view.grab_focus()
def on_clear(self, *_args):
self.clear_model(stored_results=True)
# Allow parsing search result messages again
core.search.add_allowed_token(self.token)
# Update number of results widget
self.update_result_counter()
def on_focus(self, *_args):
if not self.window.search_entry.get_text():
# Only focus treeview if we're not entering a new search term
self.tree_view.grab_focus()
return True
def on_close(self, *_args):
core.search.remove_search(self.token)
def on_close_all_tabs(self, *_args):
self.searches.remove_all_pages()
| 66,423 | Python | .py | 1,430 | 34.135664 | 120 | 0.579497 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,434 | buddies.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/buddies.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2018 Mutnick <mutnick@techie.com>
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2009 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import time
from gi.repository import GObject
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.dialogs import EntryDialog
from pynicotine.gtkgui.widgets.popupmenu import UserPopupMenu
from pynicotine.gtkgui.widgets.theme import USER_STATUS_ICON_NAMES
from pynicotine.gtkgui.widgets.theme import get_flag_icon_name
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import UINT64_LIMIT
from pynicotine.utils import humanize
from pynicotine.utils import human_speed
class Buddies:
def __init__(self, window):
(
self.container,
self.list_container,
self.side_toolbar
) = ui.load(scope=self, path="buddies.ui")
self.window = window
self.page = window.userlist_page
self.page.id = "userlist"
self.toolbar = window.userlist_toolbar
self.toolbar_start_content = window.userlist_title
self.toolbar_end_content = window.userlist_end
self.toolbar_default_widget = window.add_buddy_entry
# Columns
self.list_view = TreeView(
window, parent=self.list_container, name="buddy_list",
persistent_sort=True, activate_row_callback=self.on_row_activated,
delete_accelerator_callback=self.on_remove_buddy,
columns={
# Visible columns
"status": {
"column_type": "icon",
"title": _("Status"),
"width": 25,
"hide_header": True
},
"country": {
"column_type": "icon",
"title": _("Country"),
"width": 30,
"hide_header": True
},
"user": {
"column_type": "text",
"title": _("User"),
"width": 250,
"default_sort_type": "ascending",
"iterator_key": True
},
"speed": {
"column_type": "number",
"title": _("Speed"),
"width": 150,
"sort_column": "speed_data"
},
"files": {
"column_type": "number",
"title": _("Files"),
"width": 150,
"sort_column": "files_data"
},
"trusted": {
"column_type": "toggle",
"title": _("Trusted"),
"width": 0,
"toggle_callback": self.on_trusted
},
"notify": {
"column_type": "toggle",
"title": _("Notify"),
"width": 0,
"toggle_callback": self.on_notify
},
"privileged": {
"column_type": "toggle",
"title": _("Prioritized"),
"width": 0,
"toggle_callback": self.on_prioritized
},
"last_seen": {
"column_type": "text",
"title": _("Last Seen"),
"width": 160,
"sort_column": "last_seen_data"
},
"comments": {
"column_type": "text",
"title": _("Note"),
"width": 400
},
# Hidden data columns
"speed_data": {"data_type": GObject.TYPE_UINT},
"files_data": {"data_type": GObject.TYPE_UINT},
"last_seen_data": {"data_type": GObject.TYPE_UINT64}
}
)
# Popup menus
self.popup_menu = popup = UserPopupMenu(
window.application, parent=self.list_view.widget, callback=self.on_popup_menu,
tab_name="userlist"
)
popup.add_items(
("#" + _("Add User _Note…"), self.on_add_note),
("", None),
("#" + _("Remove"), self.on_remove_buddy)
)
# Events
for event_name, callback in (
("add-buddy", self.add_buddy),
("buddy-note", self.buddy_note),
("buddy-notify", self.buddy_notify),
("buddy-last-seen", self.buddy_last_seen),
("buddy-prioritized", self.buddy_prioritized),
("buddy-trusted", self.buddy_trusted),
("remove-buddy", self.remove_buddy),
("server-disconnect", self.server_disconnect),
("start", self.start),
("user-country", self.user_country),
("user-stats", self.user_stats),
("user-status", self.user_status)
):
events.connect(event_name, callback)
self.set_buddy_list_position()
def start(self):
comboboxes = (
self.window.search.user_search_combobox,
self.window.userbrowse.userbrowse_combobox,
self.window.userinfo.userinfo_combobox
)
for combobox in comboboxes:
combobox.freeze()
self.list_view.freeze()
for username, user_data in core.buddies.users.items():
self.add_buddy(username, user_data, select_row=False)
for combobox in comboboxes:
combobox.unfreeze()
self.list_view.unfreeze()
def destroy(self):
self.list_view.destroy()
self.popup_menu.destroy()
self.__dict__.clear()
def on_focus(self, *_args):
self.update_visible()
if self.container.get_parent().get_visible():
self.list_view.grab_focus()
return True
return False
def set_buddy_list_position(self):
parent_container = self.container.get_parent()
mode = config.sections["ui"]["buddylistinchatrooms"]
if mode not in {"tab", "chatrooms", "always"}:
mode = "tab"
if parent_container == self.window.buddy_list_container:
if mode == "always":
return
self.window.buddy_list_container.remove(self.container)
self.window.buddy_list_container.set_visible(False)
elif parent_container == self.window.chatrooms_buddy_list_container:
if mode == "chatrooms":
return
self.window.chatrooms_buddy_list_container.remove(self.container)
self.window.chatrooms_buddy_list_container.set_visible(False)
elif parent_container == self.window.userlist_content:
if mode == "tab":
return
self.window.userlist_content.remove(self.container)
if mode == "always":
if GTK_API_VERSION >= 4:
self.window.buddy_list_container.append(self.container)
else:
self.window.buddy_list_container.add(self.container)
self.side_toolbar.set_visible(True)
self.window.buddy_list_container.set_visible(True)
return
if mode == "chatrooms":
if GTK_API_VERSION >= 4:
self.window.chatrooms_buddy_list_container.append(self.container)
else:
self.window.chatrooms_buddy_list_container.add(self.container)
self.side_toolbar.set_visible(True)
self.window.chatrooms_buddy_list_container.set_visible(True)
return
if mode == "tab":
self.side_toolbar.set_visible(False)
if GTK_API_VERSION >= 4:
self.window.userlist_content.append(self.container)
else:
self.window.userlist_content.add(self.container)
def update_visible(self):
if config.sections["ui"]["buddylistinchatrooms"] in {"always", "chatrooms"}:
return
self.window.userlist_content.set_visible(bool(self.list_view.iterators))
def get_selected_username(self):
for iterator in self.list_view.get_selected_rows():
return self.list_view.get_row_value(iterator, "user")
return None
def on_row_activated(self, _list_view, _iterator, column_id):
user = self.get_selected_username()
if user is None:
return
if column_id == "comments":
self.on_add_note()
return
core.privatechat.show_user(user)
def on_popup_menu(self, menu, _widget):
username = self.get_selected_username()
menu.set_user(username)
menu.toggle_user_items()
def user_status(self, msg):
iterator = self.list_view.iterators.get(msg.user)
if iterator is None:
return
status = msg.status
status_icon_name = USER_STATUS_ICON_NAMES.get(status)
if status_icon_name and status_icon_name != self.list_view.get_row_value(iterator, "status"):
self.list_view.set_row_value(iterator, "status", status_icon_name)
def user_stats(self, msg):
iterator = self.list_view.iterators.get(msg.user)
if iterator is None:
return
speed = msg.avgspeed or 0
num_files = msg.files or 0
column_ids = []
column_values = []
if speed != self.list_view.get_row_value(iterator, "speed_data"):
h_speed = human_speed(speed) if speed > 0 else ""
column_ids.extend(("speed", "speed_data"))
column_values.extend((h_speed, speed))
if num_files != self.list_view.get_row_value(iterator, "files_data"):
h_num_files = humanize(num_files)
column_ids.extend(("files", "files_data"))
column_values.extend((h_num_files, num_files))
if column_ids:
self.list_view.set_row_values(iterator, column_ids, column_values)
def add_buddy(self, user, user_data, select_row=True):
status = user_data.status
country_code = user_data.country.replace("flag_", "")
stats = core.users.watched.get(user)
if stats is not None:
speed = stats.upload_speed or 0
files = stats.files
else:
speed = 0
files = None
h_speed = human_speed(speed) if speed > 0 else ""
h_files = humanize(files) if files is not None else ""
last_seen = UINT64_LIMIT
h_last_seen = ""
if user_data.last_seen:
try:
last_seen_time = time.strptime(user_data.last_seen, "%m/%d/%Y %H:%M:%S")
last_seen = time.mktime(last_seen_time)
h_last_seen = time.strftime("%x %X", last_seen_time)
except ValueError:
last_seen = 0
h_last_seen = _("Never seen")
self.list_view.add_row([
USER_STATUS_ICON_NAMES.get(status, ""),
get_flag_icon_name(country_code),
str(user),
h_speed,
h_files,
bool(user_data.is_trusted),
bool(user_data.notify_status),
bool(user_data.is_prioritized),
str(h_last_seen),
str(user_data.note),
speed,
files or 0,
last_seen
], select_row=select_row)
for combobox in (
self.window.search.user_search_combobox,
self.window.userbrowse.userbrowse_combobox,
self.window.userinfo.userinfo_combobox
):
combobox.append(str(user))
self.update_visible()
def remove_buddy(self, user):
iterator = self.list_view.iterators.get(user)
if iterator is None:
return
self.list_view.remove_row(iterator)
self.update_visible()
for combobox in (
self.window.search.user_search_combobox,
self.window.userbrowse.userbrowse_combobox,
self.window.userinfo.userinfo_combobox
):
combobox.remove_id(user)
def buddy_note(self, user, note):
iterator = self.list_view.iterators.get(user)
if iterator is not None:
self.list_view.set_row_value(iterator, "comments", note)
def buddy_trusted(self, user, trusted):
iterator = self.list_view.iterators.get(user)
if iterator is not None:
self.list_view.set_row_value(iterator, "trusted", trusted)
def buddy_notify(self, user, notify):
iterator = self.list_view.iterators.get(user)
if iterator is not None:
self.list_view.set_row_value(iterator, "notify", notify)
def buddy_prioritized(self, user, prioritized):
iterator = self.list_view.iterators.get(user)
if iterator is not None:
self.list_view.set_row_value(iterator, "privileged", prioritized)
def buddy_last_seen(self, user, online):
iterator = self.list_view.iterators.get(user)
if iterator is None:
return
last_seen = UINT64_LIMIT
h_last_seen = ""
if not online:
last_seen = time.time()
h_last_seen = time.strftime("%x %X", time.localtime(last_seen))
self.list_view.set_row_values(
iterator,
column_ids=["last_seen", "last_seen_data"],
values=[h_last_seen, last_seen]
)
def user_country(self, user, country_code):
iterator = self.list_view.iterators.get(user)
if iterator is None:
return
flag_icon_name = get_flag_icon_name(country_code)
if flag_icon_name and flag_icon_name != self.list_view.get_row_value(iterator, "country"):
self.list_view.set_row_value(iterator, "country", flag_icon_name)
def on_add_buddy(self, *_args):
username = self.window.add_buddy_entry.get_text().strip()
if not username:
return
self.window.add_buddy_entry.set_text("")
core.buddies.add_buddy(username)
self.list_view.grab_focus()
def on_remove_buddy(self, *_args):
core.buddies.remove_buddy(self.get_selected_username())
def on_trusted(self, list_view, iterator):
user = list_view.get_row_value(iterator, "user")
value = list_view.get_row_value(iterator, "trusted")
core.buddies.set_buddy_trusted(user, not value)
def on_notify(self, list_view, iterator):
user = list_view.get_row_value(iterator, "user")
value = list_view.get_row_value(iterator, "notify")
core.buddies.set_buddy_notify(user, not value)
def on_prioritized(self, list_view, iterator):
user = list_view.get_row_value(iterator, "user")
value = list_view.get_row_value(iterator, "privileged")
core.buddies.set_buddy_prioritized(user, not value)
def on_add_note_response(self, dialog, _response_id, user):
iterator = self.list_view.iterators.get(user)
if iterator is None:
return
note = dialog.get_entry_value()
if note is None:
return
core.buddies.set_buddy_note(user, note)
def on_add_note(self, *_args):
user = self.get_selected_username()
iterator = self.list_view.iterators.get(user)
if iterator is None:
return
note = self.list_view.get_row_value(iterator, "comments") or ""
EntryDialog(
parent=self.window,
title=_("Add User Note"),
message=_("Add a note about user %s:") % user,
action_button_label=_("_Add"),
callback=self.on_add_note_response,
callback_data=user,
default=note
).present()
def server_disconnect(self, *_args):
for iterator in self.list_view.iterators.values():
self.list_view.set_row_value(iterator, "status", USER_STATUS_ICON_NAMES[UserStatus.OFFLINE])
| 17,115 | Python | .py | 403 | 30.997519 | 104 | 0.577382 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,435 | uploads.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/uploads.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2018 Mutnick <mutnick@techie.com>
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2009-2011 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2009 hedonist <ak@sensi.org>
# COPYRIGHT (C) 2006-2008 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.popovers.uploadspeeds import UploadSpeeds
from pynicotine.gtkgui.transfers import Transfers
from pynicotine.gtkgui.widgets import clipboard
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
from pynicotine.transfers import TransferStatus
from pynicotine.utils import human_speed
from pynicotine.utils import open_file_path
from pynicotine.utils import open_folder_path
class Uploads(Transfers):
def __init__(self, window):
self.path_separator = "\\"
self.path_label = _("Folder")
self.retry_label = _("_Retry")
self.abort_label = _("_Abort")
self.transfer_page = self.page = window.uploads_page
self.page.id = "uploads"
self.toolbar = window.uploads_toolbar
self.toolbar_start_content = window.uploads_title
self.toolbar_end_content = window.uploads_end
self.toolbar_default_widget = window.upload_users_button
self.user_counter = window.upload_users_label
self.file_counter = window.upload_files_label
self.expand_button = window.uploads_expand_button
self.expand_icon = window.uploads_expand_icon
self.grouping_button = window.uploads_grouping_button
self.status_label = window.upload_status_label
super().__init__(window, transfer_type="upload")
if GTK_API_VERSION >= 4:
window.uploads_content.append(self.container)
else:
window.uploads_content.add(self.container)
self.popup_menu_clear.add_items(
("#" + _("Finished / Cancelled / Failed"), self.on_clear_finished_failed),
("#" + _("Finished / Cancelled"), self.on_clear_finished_cancelled),
("", None),
("#" + _("Finished"), self.on_clear_finished),
("#" + _("Cancelled"), self.on_clear_cancelled),
("#" + _("Failed"), self.on_clear_failed),
("#" + _("User Logged Off"), self.on_clear_logged_off),
("#" + _("Queued…"), self.on_try_clear_queued),
("", None),
("#" + _("Everything…"), self.on_try_clear_all),
)
self.popup_menu_clear.update_model()
for event_name, callback in (
("abort-upload", self.abort_transfer),
("abort-uploads", self.abort_transfers),
("clear-upload", self.clear_transfer),
("clear-uploads", self.clear_transfers),
("set-connection-stats", self.set_connection_stats),
("start", self.start),
("update-upload", self.update_model),
("update-upload-limits", self.update_limits),
("uploads-shutdown-request", self.shutdown_request),
("uploads-shutdown-cancel", self.shutdown_cancel)
):
events.connect(event_name, callback)
self.upload_speeds = UploadSpeeds(window)
def start(self):
self.init_transfers(core.uploads.transfers.values())
def destroy(self):
self.upload_speeds.destroy()
super().destroy()
def get_transfer_folder_path(self, transfer):
virtual_path = transfer.virtual_path
if virtual_path:
folder_path, _separator, _basename = virtual_path.rpartition("\\")
return folder_path
return transfer.folder_path
def retry_selected_transfers(self):
core.uploads.retry_uploads(self.selected_transfers)
def abort_selected_transfers(self):
core.uploads.abort_uploads(self.selected_transfers, denied_message="Cancelled")
def remove_selected_transfers(self):
core.uploads.clear_uploads(uploads=self.selected_transfers)
def set_connection_stats(self, upload_bandwidth=0, **_kwargs):
# Sync parent row updates with connection stats
self._update_pending_parent_rows()
upload_bandwidth = human_speed(upload_bandwidth)
upload_bandwidth_text = f"{upload_bandwidth} ( {len(core.uploads.active_users)} )"
if self.window.upload_status_label.get_text() == upload_bandwidth_text:
return
self.window.upload_status_label.set_text(upload_bandwidth_text)
self.window.application.tray_icon.set_upload_status(
_("Uploads: %(speed)s") % {"speed": upload_bandwidth})
def shutdown_request(self):
icon_name = "system-shutdown-symbolic"
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
toggle_status_action = self.window.lookup_action("toggle-status")
toggle_status_action.set_enabled(False)
self.window.user_status_button.set_active(True)
toggle_status_action.set_enabled(True)
self.window.user_status_icon.set_from_icon_name(icon_name, *icon_args)
self.window.user_status_label.set_text(_("Quitting..."))
def shutdown_cancel(self):
self.window.update_user_status()
def on_try_clear_queued(self, *_args):
OptionDialog(
parent=self.window,
title=_("Clear Queued Uploads"),
message=_("Do you really want to clear all queued uploads?"),
destructive_response_id="ok",
callback=self.on_clear_queued
).present()
def on_clear_all_response(self, *_args):
core.uploads.clear_uploads()
def on_try_clear_all(self, *_args):
OptionDialog(
parent=self.window,
title=_("Clear All Uploads"),
message=_("Do you really want to clear all uploads?"),
destructive_response_id="ok",
callback=self.on_clear_all_response
).present()
def on_copy_url(self, *_args):
transfer = next(iter(self.selected_transfers), None)
if transfer:
user = config.sections["server"]["login"]
url = core.userbrowse.get_soulseek_url(user, transfer.virtual_path)
clipboard.copy_text(url)
def on_copy_folder_url(self, *_args):
transfer = next(iter(self.selected_transfers), None)
if transfer:
user = config.sections["server"]["login"]
folder_path, separator, _basename = transfer.virtual_path.rpartition("\\")
url = core.userbrowse.get_soulseek_url(user, folder_path + separator)
clipboard.copy_text(url)
def on_open_file_manager(self, *_args):
transfer = next(iter(self.selected_transfers), None)
if transfer:
open_folder_path(transfer.folder_path)
def on_open_file(self, *_args):
for transfer in self.selected_transfers:
basename = transfer.virtual_path.rpartition("\\")[-1]
open_file_path(os.path.join(transfer.folder_path, basename))
def on_browse_folder(self, *_args):
transfer = next(iter(self.selected_transfers), None)
if not transfer:
return
user = config.sections["server"]["login"]
path = transfer.virtual_path
core.userbrowse.browse_user(user, path=path)
def on_abort_users(self, *_args):
self.select_transfers()
for transfer in self.transfer_list:
if transfer.username in self.selected_users and transfer not in self.selected_transfers:
self.selected_transfers[transfer] = None
self.abort_selected_transfers()
def on_ban_users(self, *_args):
self.select_transfers()
for username in self.selected_users:
core.network_filter.ban_user(username)
def on_clear_queued(self, *_args):
core.uploads.clear_uploads(statuses={TransferStatus.QUEUED})
def on_clear_finished(self, *_args):
core.uploads.clear_uploads(statuses={TransferStatus.FINISHED})
def on_clear_cancelled(self, *_args):
core.uploads.clear_uploads(statuses={TransferStatus.CANCELLED})
def on_clear_failed(self, *_args):
core.uploads.clear_uploads(statuses={TransferStatus.CONNECTION_TIMEOUT, TransferStatus.LOCAL_FILE_ERROR})
def on_clear_logged_off(self, *_args):
core.uploads.clear_uploads(statuses={TransferStatus.USER_LOGGED_OFF})
def on_clear_finished_cancelled(self, *_args):
core.uploads.clear_uploads(statuses={TransferStatus.CANCELLED, TransferStatus.FINISHED})
def on_clear_finished_failed(self, *_args):
core.uploads.clear_uploads(
statuses={TransferStatus.CANCELLED, TransferStatus.FINISHED, TransferStatus.CONNECTION_TIMEOUT,
TransferStatus.LOCAL_FILE_ERROR})
| 9,774 | Python | .py | 197 | 41.162437 | 113 | 0.667755 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,436 | privatechat.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/privatechat.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2008-2011 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2007 gallows <g4ll0ws@gmail.com>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GLib
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.popovers.chatcommandhelp import ChatCommandHelp
from pynicotine.gtkgui.popovers.chathistory import ChatHistory
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.iconnotebook import IconNotebook
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.popupmenu import UserPopupMenu
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
from pynicotine.gtkgui.widgets.textentry import ChatEntry
from pynicotine.gtkgui.widgets.textentry import TextSearchBar
from pynicotine.gtkgui.widgets.textview import ChatView
from pynicotine.logfacility import log
from pynicotine.slskmessages import UserStatus
class PrivateChats(IconNotebook):
def __init__(self, window):
super().__init__(
window,
parent=window.private_content,
parent_page=window.private_page,
switch_page_callback=self.on_switch_chat,
reorder_page_callback=self.on_reordered_page
)
self.page = window.private_page
self.page.id = "private"
self.toolbar = window.private_toolbar
self.toolbar_start_content = window.private_title
self.toolbar_end_content = window.private_end
self.toolbar_default_widget = window.private_entry
self.chat_entry = ChatEntry(
window.application, send_message_callback=core.privatechat.send_message,
command_callback=core.pluginhandler.trigger_private_chat_command_event,
enable_spell_check=config.sections["ui"]["spellcheck"]
)
self.history = ChatHistory(window)
self.command_help = None
self.highlighted_users = []
for event_name, callback in (
("clear-private-messages", self.clear_messages),
("echo-private-message", self.echo_private_message),
("message-user", self.message_user),
("private-chat-completions", self.update_completions),
("private-chat-show-user", self.show_user),
("private-chat-remove-user", self.remove_user),
("quit", self.quit),
("server-disconnect", self.server_disconnect),
("server-login", self.server_login),
("start", self.start),
("user-status", self.user_status)
):
events.connect(event_name, callback)
self.freeze()
def start(self):
self.unfreeze()
def quit(self):
self.freeze()
def destroy(self):
self.chat_entry.destroy()
self.history.destroy()
if self.command_help is not None:
self.command_help.destroy()
super().destroy()
def on_focus(self, *_args):
if self.window.current_page_id != self.window.private_page.id:
return True
if self.get_n_pages():
return True
if self.window.private_entry.is_sensitive():
self.window.private_entry.grab_focus()
return True
return False
def on_remove_all_pages(self, *_args):
core.privatechat.remove_all_users()
def on_restore_removed_page(self, page_args):
username, = page_args
core.privatechat.show_user(username)
def on_reordered_page(self, *_args):
tab_order = {}
for user, tab in self.pages.items():
tab_position = self.page_num(tab.container)
tab_order[tab_position] = user
config.sections["privatechat"]["users"] = [user for tab_index, user in sorted(tab_order.items())]
def on_switch_chat(self, _notebook, page, _page_num):
if self.window.current_page_id != self.window.private_page.id:
return
for user, tab in self.pages.items():
if tab.container != page:
continue
self.chat_entry.set_parent(user, tab.chat_entry_container, tab.chat_view)
tab.update_room_user_completions()
if self.command_help is None:
self.command_help = ChatCommandHelp(window=self.window, interface="private_chat")
self.command_help.set_menu_button(tab.help_button)
if not tab.loaded:
tab.load()
# Remove highlight if selected tab belongs to a user in the list of highlights
self.unhighlight_user(user)
break
def on_get_private_chat(self, *_args):
username = self.window.private_entry.get_text().strip()
if not username:
return
self.window.private_entry.set_text("")
core.privatechat.show_user(username)
def clear_messages(self, user):
page = self.pages.get(user)
if page is not None:
page.chat_view.clear()
def clear_notifications(self):
if self.window.current_page_id != self.window.private_page.id:
return
page = self.get_current_page()
for user, tab in self.pages.items():
if tab.container == page:
# Remove highlight
self.unhighlight_user(user)
break
def user_status(self, msg):
page = self.pages.get(msg.user)
if page is not None:
self.set_user_status(page.container, msg.user, msg.status)
page.chat_view.update_user_tag(msg.user)
if msg.user == core.users.login_username:
for page in self.pages.values():
# We've enabled/disabled away mode, update our username color in all chats
page.chat_view.update_user_tag(msg.user)
def show_user(self, user, switch_page=True, remembered=False):
if user not in self.pages:
self.pages[user] = page = PrivateChat(self, user)
tab_position = -1 if remembered else 0
self.insert_page(
page.container, user, focus_callback=page.on_focus, close_callback=page.on_close, user=user,
position=tab_position
)
page.set_label(self.get_tab_label_inner(page.container))
if switch_page:
self.set_current_page(self.pages[user].container)
self.window.change_main_page(self.window.private_page)
def remove_user(self, user):
page = self.pages.get(user)
if page is None:
return
if page.container == self.get_current_page():
self.chat_entry.set_parent(None)
if self.command_help is not None:
self.command_help.set_menu_button(None)
page.clear()
self.remove_page(page.container, page_args=(user,))
del self.pages[user]
page.destroy()
self.chat_entry.clear_unsent_message(user)
def highlight_user(self, user):
if not user or user in self.highlighted_users:
return
self.highlighted_users.append(user)
self.window.update_title()
self.window.application.tray_icon.update()
def unhighlight_user(self, user):
if user not in self.highlighted_users:
return
self.highlighted_users.remove(user)
self.window.update_title()
self.window.application.tray_icon.update()
def echo_private_message(self, user, text, message_type):
page = self.pages.get(user)
if page is not None:
page.echo_private_message(text, message_type)
def message_user(self, msg, **_unused):
page = self.pages.get(msg.user)
if page is not None:
page.message_user(msg)
def update_completions(self, completions):
page = self.get_current_page()
for tab in self.pages.values():
if tab.container == page:
tab.update_completions(completions)
break
def update_widgets(self):
self.chat_entry.set_spell_check_enabled(config.sections["ui"]["spellcheck"])
for tab in self.pages.values():
tab.toggle_chat_buttons()
tab.update_tags()
def server_login(self, msg):
if not msg.success:
return
page = self.get_current_page()
self.chat_entry.set_sensitive(True)
for tab in self.pages.values():
if tab.container == page:
tab.on_focus()
break
def server_disconnect(self, *_args):
self.chat_entry.set_sensitive(False)
for user, page in self.pages.items():
page.server_disconnect()
self.set_user_status(page.container, user, UserStatus.OFFLINE)
class PrivateChat:
def __init__(self, chats, user):
(
self.chat_entry_container,
self.chat_view_container,
self.container,
self.help_button,
self.log_toggle,
self.search_bar,
self.speech_toggle
) = ui.load(scope=self, path="privatechat.ui")
self.user = user
self.chats = chats
self.window = chats.window
self.loaded = False
self.offline_message = False
self.chat_view = ChatView(
self.chat_view_container, chat_entry=self.chats.chat_entry, editable=False,
horizontal_margin=10, vertical_margin=5, pixels_below_lines=2,
username_event=self.username_event
)
# Text Search
self.search_bar = TextSearchBar(
self.chat_view.widget, self.search_bar,
controller_widget=self.container, focus_widget=self.chats.chat_entry,
placeholder_text=_("Search chat log…")
)
self.log_toggle.set_active(user in config.sections["logging"]["private_chats"])
self.toggle_chat_buttons()
self.popup_menu_user_chat = UserPopupMenu(
self.window.application, parent=self.chat_view.widget, connect_events=False,
username=user, tab_name="privatechat"
)
self.popup_menu_user_tab = UserPopupMenu(
self.window.application, callback=self.on_popup_menu_user, username=user,
tab_name="privatechat"
)
for menu in (self.popup_menu_user_chat, self.popup_menu_user_tab):
menu.add_items(
("", None),
("#" + _("Close All Tabs…"), self.on_close_all_tabs),
("#" + _("_Close Tab"), self.on_close)
)
self.popup_menu = PopupMenu(self.window.application, self.chat_view.widget, self.on_popup_menu_chat)
self.popup_menu.add_items(
("#" + _("Find…"), self.on_find_chat_log),
("", None),
("#" + _("Copy"), self.chat_view.on_copy_text),
("#" + _("Copy Link"), self.chat_view.on_copy_link),
("#" + _("Copy All"), self.chat_view.on_copy_all_text),
("", None),
("#" + _("View Chat Log"), self.on_view_chat_log),
("#" + _("Delete Chat Log…"), self.on_delete_chat_log),
("", None),
("#" + _("Clear Message View"), self.chat_view.on_clear_all_text),
("", None),
(">" + _("User Actions"), self.popup_menu_user_tab),
)
self.popup_menus = (self.popup_menu, self.popup_menu_user_chat, self.popup_menu_user_tab)
self.prepend_old_messages()
def load(self):
GLib.idle_add(self.read_private_log_finished)
self.loaded = True
def read_private_log_finished(self):
if not hasattr(self, "chat_view"):
# Tab was closed
return
self.chat_view.scroll_bottom()
self.chat_view.auto_scroll = True
def prepend_old_messages(self):
log_lines = log.read_log(
folder_path=log.private_chat_folder_path,
basename=self.user,
num_lines=config.sections["logging"]["readprivatelines"]
)
self.chat_view.append_log_lines(log_lines, login_username=config.sections["server"]["login"])
def server_disconnect(self):
self.offline_message = False
self.chat_view.update_user_tags()
def clear(self):
self.chat_view.clear()
self.chats.unhighlight_user(self.user)
def destroy(self):
for menu in self.popup_menus:
menu.destroy()
self.chat_view.destroy()
self.search_bar.destroy()
self.__dict__.clear()
def set_label(self, label):
self.popup_menu_user_tab.set_parent(label)
def on_popup_menu_chat(self, menu, _widget):
self.popup_menu_user_tab.toggle_user_items()
menu.actions[_("Copy")].set_enabled(self.chat_view.get_has_selection())
menu.actions[_("Copy Link")].set_enabled(bool(self.chat_view.get_url_for_current_pos()))
def on_popup_menu_user(self, _menu, _widget):
self.popup_menu_user_tab.toggle_user_items()
def toggle_chat_buttons(self):
self.log_toggle.set_visible(not config.sections["logging"]["privatechat"])
self.speech_toggle.set_visible(config.sections["ui"]["speechenabled"])
def on_log_toggled(self, *_args):
if not self.log_toggle.get_active():
if self.user in config.sections["logging"]["private_chats"]:
config.sections["logging"]["private_chats"].remove(self.user)
return
if self.user not in config.sections["logging"]["private_chats"]:
config.sections["logging"]["private_chats"].append(self.user)
def on_find_chat_log(self, *_args):
self.search_bar.set_visible(True)
def on_view_chat_log(self, *_args):
log.open_log(log.private_chat_folder_path, self.user)
def on_delete_chat_log_response(self, *_args):
log.delete_log(log.private_chat_folder_path, self.user)
self.chats.history.remove_user(self.user)
self.chat_view.clear()
def on_delete_chat_log(self, *_args):
OptionDialog(
parent=self.window,
title=_("Delete Logged Messages?"),
message=_("Do you really want to permanently delete all logged messages for this user?"),
destructive_response_id="ok",
callback=self.on_delete_chat_log_response
).present()
def _show_notification(self, text, is_mentioned=False):
is_buddy = (self.user in core.buddies.users)
self.chats.request_tab_changed(self.container, is_important=is_buddy or is_mentioned)
if (self.chats.get_current_page() == self.container
and self.window.current_page_id == self.window.private_page.id and self.window.is_active()):
# Don't show notifications if the chat is open and the window is in use
return
# Update tray icon and show urgency hint
self.chats.highlight_user(self.user)
if config.sections["notifications"]["notification_popup_private_message"]:
core.notifications.show_private_chat_notification(
self.user, text,
title=_("Private Message from %(user)s") % {"user": self.user}
)
def message_user(self, msg):
is_outgoing_message = (msg.message_id is None)
is_new_message = msg.is_new_message
message_type = msg.message_type
username = msg.user
tag_username = (core.users.login_username if is_outgoing_message else username)
usertag = self.chat_view.get_user_tag(tag_username)
timestamp = msg.timestamp if not is_new_message else None
timestamp_format = config.sections["logging"]["private_timestamp"]
message = msg.message
formatted_message = msg.formatted_message
if not is_outgoing_message:
self._show_notification(message, is_mentioned=(message_type == "hilite"))
if self.speech_toggle.get_active():
core.notifications.new_tts(
config.sections["ui"]["speechprivate"], {"user": tag_username, "message": message}
)
if not is_outgoing_message and not is_new_message:
if not self.offline_message:
self.chat_view.append_line(
_("* Messages sent while you were offline"), message_type="hilite",
timestamp_format=timestamp_format
)
self.offline_message = True
else:
self.offline_message = False
self.chat_view.append_line(
formatted_message, message_type=message_type, timestamp=timestamp, timestamp_format=timestamp_format,
username=tag_username, usertag=usertag
)
self.chats.history.update_user(username, formatted_message)
def echo_private_message(self, text, message_type):
if message_type != "command":
timestamp_format = config.sections["logging"]["private_timestamp"]
else:
timestamp_format = None
self.chat_view.append_line(text, message_type=message_type, timestamp_format=timestamp_format)
def username_event(self, pos_x, pos_y, user):
self.popup_menu_user_chat.update_model()
self.popup_menu_user_chat.set_user(user)
self.popup_menu_user_chat.toggle_user_items()
self.popup_menu_user_chat.popup(pos_x, pos_y)
def update_tags(self):
self.chat_view.update_tags()
def on_focus(self, *_args):
if self.window.current_page_id == self.window.private_page.id:
widget = self.chats.chat_entry if self.chats.chat_entry.get_sensitive() else self.chat_view
widget.grab_focus()
return True
def on_close(self, *_args):
core.privatechat.remove_user(self.user)
def on_close_all_tabs(self, *_args):
self.chats.remove_all_pages()
def update_room_user_completions(self):
self.update_completions(core.privatechat.completions.copy())
def update_completions(self, completions):
# Tab-complete the recipient username
completions.add(self.user)
self.chats.chat_entry.set_completions(completions)
| 19,123 | Python | .py | 415 | 36.122892 | 113 | 0.632044 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,437 | downloads.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/downloads.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2016-2018 Mutnick <mutnick@techie.com>
# COPYRIGHT (C) 2013 eLvErDe <gandalf@le-vert.net>
# COPYRIGHT (C) 2008-2012 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2009 hedonist <ak@sensi.org>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.popovers.downloadspeeds import DownloadSpeeds
from pynicotine.gtkgui.transfers import Transfers
from pynicotine.gtkgui.widgets import clipboard
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
from pynicotine.transfers import TransferStatus
from pynicotine.utils import human_speed
from pynicotine.utils import open_file_path
from pynicotine.utils import open_folder_path
class Downloads(Transfers):
def __init__(self, window):
self.path_separator = os.sep
self.path_label = _("Path")
self.retry_label = _("_Resume")
self.abort_label = _("P_ause")
self.transfer_page = self.page = window.downloads_page
self.page.id = "downloads"
self.toolbar = window.downloads_toolbar
self.toolbar_start_content = window.downloads_title
self.toolbar_end_content = window.downloads_end
self.toolbar_default_widget = window.download_users_button
self.user_counter = window.download_users_label
self.file_counter = window.download_files_label
self.expand_button = window.downloads_expand_button
self.expand_icon = window.downloads_expand_icon
self.grouping_button = window.downloads_grouping_button
self.status_label = window.download_status_label
super().__init__(window, transfer_type="download")
if GTK_API_VERSION >= 4:
window.downloads_content.append(self.container)
else:
window.downloads_content.add(self.container)
self.popup_menu_clear.add_items(
("#" + _("Finished / Filtered"), self.on_clear_finished_filtered),
("", None),
("#" + _("Finished"), self.on_clear_finished),
("#" + _("Paused"), self.on_clear_paused),
("#" + _("Filtered"), self.on_clear_filtered),
("#" + _("Deleted"), self.on_clear_deleted),
("#" + _("Queued…"), self.on_try_clear_queued),
("", None),
("#" + _("Everything…"), self.on_try_clear_all),
)
self.popup_menu_clear.update_model()
for event_name, callback in (
("abort-download", self.abort_transfer),
("abort-downloads", self.abort_transfers),
("clear-download", self.clear_transfer),
("clear-downloads", self.clear_transfers),
("download-large-folder", self.download_large_folder),
("folder-download-finished", self.folder_download_finished),
("set-connection-stats", self.set_connection_stats),
("start", self.start),
("update-download", self.update_model),
("update-download-limits", self.update_limits)
):
events.connect(event_name, callback)
self.download_speeds = DownloadSpeeds(window)
def start(self):
self.init_transfers(core.downloads.transfers.values())
def destroy(self):
self.download_speeds.destroy()
super().destroy()
def get_transfer_folder_path(self, transfer):
return transfer.folder_path
def retry_selected_transfers(self):
core.downloads.retry_downloads(self.selected_transfers)
def abort_selected_transfers(self):
core.downloads.abort_downloads(self.selected_transfers)
def remove_selected_transfers(self):
core.downloads.clear_downloads(downloads=self.selected_transfers)
def set_connection_stats(self, download_bandwidth=0, **_kwargs):
# Sync parent row updates with connection stats
self._update_pending_parent_rows()
download_bandwidth = human_speed(download_bandwidth)
download_bandwidth_text = f"{download_bandwidth} ( {len(core.downloads.active_users)} )"
if self.window.download_status_label.get_text() == download_bandwidth_text:
return
self.window.download_status_label.set_text(download_bandwidth_text)
self.window.application.tray_icon.set_download_status(
_("Downloads: %(speed)s") % {"speed": download_bandwidth})
def on_try_clear_queued(self, *_args):
OptionDialog(
parent=self.window,
title=_("Clear Queued Downloads"),
message=_("Do you really want to clear all queued downloads?"),
destructive_response_id="ok",
callback=self.on_clear_queued
).present()
def on_clear_all_response(self, *_args):
core.downloads.clear_downloads()
def on_try_clear_all(self, *_args):
OptionDialog(
parent=self.window,
title=_("Clear All Downloads"),
message=_("Do you really want to clear all downloads?"),
destructive_response_id="ok",
callback=self.on_clear_all_response
).present()
def folder_download_response(self, _dialog, _response_id, data):
download_callback, callback_args = data
download_callback(*callback_args)
def folder_download_finished(self, _folder_path):
if self.window.current_page_id != self.transfer_page.id:
self.window.notebook.request_tab_changed(self.transfer_page, is_important=True)
def download_large_folder(self, username, folder, numfiles, download_callback, callback_args):
OptionDialog(
parent=self.window,
title=_("Download %(num)i files?") % {"num": numfiles},
message=_("Do you really want to download %(num)i files from %(user)s's folder %(folder)s?") % {
"num": numfiles, "user": username, "folder": folder},
buttons=[
("cancel", _("_Cancel")),
("download", _("_Download Folder"))
],
callback=self.folder_download_response,
callback_data=(download_callback, callback_args)
).present()
def on_copy_url(self, *_args):
transfer = next(iter(self.selected_transfers), None)
if transfer:
url = core.userbrowse.get_soulseek_url(transfer.username, transfer.virtual_path)
clipboard.copy_text(url)
def on_copy_folder_url(self, *_args):
transfer = next(iter(self.selected_transfers), None)
if transfer:
folder_path, separator, _basename = transfer.virtual_path.rpartition("\\")
url = core.userbrowse.get_soulseek_url(transfer.username, folder_path + separator)
clipboard.copy_text(url)
def on_open_file_manager(self, *_args):
folder_path = None
for transfer in self.selected_transfers:
file_path = core.downloads.get_current_download_file_path(transfer)
folder_path = os.path.dirname(file_path)
if transfer.status == TransferStatus.FINISHED:
# Prioritize finished downloads
break
open_folder_path(folder_path)
def on_open_file(self, *_args):
for transfer in self.selected_transfers:
file_path = core.downloads.get_current_download_file_path(transfer)
open_file_path(file_path)
def on_browse_folder(self, *_args):
transfer = next(iter(self.selected_transfers), None)
if not transfer:
return
user = transfer.username
path = transfer.virtual_path
core.userbrowse.browse_user(user, path=path)
def on_clear_queued(self, *_args):
core.downloads.clear_downloads(statuses={TransferStatus.QUEUED})
def on_clear_finished(self, *_args):
core.downloads.clear_downloads(statuses={TransferStatus.FINISHED})
def on_clear_paused(self, *_args):
core.downloads.clear_downloads(statuses={TransferStatus.PAUSED})
def on_clear_finished_filtered(self, *_args):
core.downloads.clear_downloads(statuses={TransferStatus.FINISHED, TransferStatus.FILTERED})
def on_clear_filtered(self, *_args):
core.downloads.clear_downloads(statuses={TransferStatus.FILTERED})
def on_clear_deleted(self, *_args):
core.downloads.clear_downloads(clear_deleted=True)
| 9,315 | Python | .py | 188 | 40.962766 | 108 | 0.665821 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,438 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/__init__.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
from pynicotine.logfacility import log
def get_default_gtk_version():
if sys.platform in {"darwin", "win32"}:
return "4"
try:
from gi.repository import GLib
from gi.repository import Gio
try:
dbus_proxy = Gio.DBusProxy.new_for_bus_sync(
bus_type=Gio.BusType.SESSION,
flags=Gio.DBusProxyFlags.NONE,
info=None,
name="org.a11y.Bus",
object_path="/org/a11y/bus",
interface_name="org.freedesktop.DBus.Properties"
)
# If screen reader is enabled, use GTK 3 until treeviews have been ported to
# Gtk.ColumnView. Gtk.TreeView doesn't support screen readers in GTK 4.
if dbus_proxy.Get("(ss)", "org.a11y.Status", "IsEnabled"):
log.add_debug("Screen reader enabled, using GTK 3 for improved accessibility")
return "3"
except GLib.Error:
# Service not available
pass
except ModuleNotFoundError:
pass
return "4"
def check_gtk_version(gtk_api_version):
is_gtk3_supported = sys.platform not in {"darwin", "win32"}
if gtk_api_version == "3" and not is_gtk3_supported:
log.add("WARNING: Using GTK 3, which might not work properly on Windows and macOS. "
"GTK 4 will be required in the future.")
# Require minor version of GTK
if gtk_api_version == "4":
pygobject_version = (3, 42, 1)
else:
gtk_api_version = "3"
pygobject_version = (3, 26, 1)
try:
import gi
gi.check_version(pygobject_version)
except (ImportError, ValueError):
if gtk_api_version == "4" and is_gtk3_supported:
return check_gtk_version(gtk_api_version="3")
return _("Cannot find %s, please install it.") % ("PyGObject >=" + ".".join(str(x) for x in pygobject_version))
try:
gi.require_version("Gtk", f"{gtk_api_version}.0")
except ValueError:
if gtk_api_version == "4" and is_gtk3_supported:
return check_gtk_version(gtk_api_version="3")
return _("Cannot find %s, please install it.") % f"GTK >={gtk_api_version}"
from gi.repository import Gtk
if sys.platform == "win32":
# Ensure all Windows-specific APIs are available
gi.require_version("GdkWin32", f"{gtk_api_version}.0")
from gi.repository import GdkWin32 # noqa: F401 # pylint:disable=no-name-in-module,unused-import
gtk_version = f"{Gtk.get_major_version()}.{Gtk.get_minor_version()}.{Gtk.get_micro_version()}"
log.add(_("Loading %(program)s %(version)s"), {"program": "GTK", "version": gtk_version})
return None
def run(hidden, ci_mode, multi_instance):
"""Run Nicotine+ GTK GUI."""
if getattr(sys, "frozen", False):
# Set up paths for frozen binaries (Windows and macOS)
executable_folder = os.path.dirname(sys.executable)
os.environ["GTK_EXE_PREFIX"] = executable_folder
os.environ["GTK_DATA_PREFIX"] = executable_folder
os.environ["GTK_PATH"] = executable_folder
os.environ["XDG_DATA_DIRS"] = os.path.join(executable_folder, "share")
os.environ["FONTCONFIG_FILE"] = os.path.join(executable_folder, "share", "fonts", "fonts.conf")
os.environ["FONTCONFIG_PATH"] = os.path.join(executable_folder, "share", "fonts")
os.environ["GDK_PIXBUF_MODULE_FILE"] = os.path.join(executable_folder, "lib", "pixbuf-loaders.cache")
os.environ["GI_TYPELIB_PATH"] = os.path.join(executable_folder, "lib", "typelibs")
os.environ["GSETTINGS_SCHEMA_DIR"] = os.path.join(executable_folder, "lib", "schemas")
if sys.platform == "win32":
# 'win32' PangoCairo backend on Windows is too slow, use 'fontconfig' instead
os.environ["PANGOCAIRO_BACKEND"] = "fontconfig"
# Disable client-side decorations when header bar is disabled
os.environ["GTK_CSD"] = "0"
# Use Cairo software rendering due to flickering issues in the GPU renderer (#2859).
# Reevaluate when the new GPU renderers are stable:
# https://blog.gtk.org/2024/01/28/new-renderers-for-gtk/
os.environ["GSK_RENDERER"] = "cairo"
elif sys.platform == "darwin":
# Older GL renderer is still faster on macOS for now
os.environ["GSK_RENDERER"] = "gl"
error = check_gtk_version(gtk_api_version=os.environ.get("NICOTINE_GTK_VERSION", get_default_gtk_version()))
if error:
log.add(error)
return 1
from gi.repository import Gdk
if not ci_mode and Gdk.Display.get_default() is None:
log.add(_("No graphical environment available, using headless (no GUI) mode"))
return None
from pynicotine.gtkgui.application import Application
return Application(hidden, ci_mode, multi_instance).run()
| 5,649 | Python | .py | 114 | 41.859649 | 119 | 0.657569 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,439 | chatrooms.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/chatrooms.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2016 Mutnick <muhing@yahoo.com>
# COPYRIGHT (C) 2008-2011 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2007 gallows <g4ll0ws@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Pango
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.popovers.chatcommandhelp import ChatCommandHelp
from pynicotine.gtkgui.popovers.roomlist import RoomList
from pynicotine.gtkgui.popovers.roomwall import RoomWall
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.iconnotebook import IconNotebook
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.popupmenu import UserPopupMenu
from pynicotine.gtkgui.widgets.textentry import ChatEntry
from pynicotine.gtkgui.widgets.textentry import TextSearchBar
from pynicotine.gtkgui.widgets.textview import ChatView
from pynicotine.gtkgui.widgets.textview import TextView
from pynicotine.gtkgui.widgets.theme import USER_STATUS_ICON_NAMES
from pynicotine.gtkgui.widgets.theme import get_flag_icon_name
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.logfacility import log
from pynicotine.slskmessages import UserData
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import humanize
from pynicotine.utils import human_speed
class ChatRooms(IconNotebook):
def __init__(self, window):
super().__init__(
window,
parent=window.chatrooms_content,
parent_page=window.chatrooms_page,
switch_page_callback=self.on_switch_chat,
reorder_page_callback=self.on_reordered_page
)
self.page = window.chatrooms_page
self.page.id = "chatrooms"
self.toolbar = window.chatrooms_toolbar
self.toolbar_start_content = window.chatrooms_title
self.toolbar_end_content = window.chatrooms_end
self.toolbar_default_widget = window.chatrooms_entry
self.chat_entry = ChatEntry(
self.window.application, send_message_callback=core.chatrooms.send_message,
command_callback=core.pluginhandler.trigger_chatroom_command_event,
enable_spell_check=config.sections["ui"]["spellcheck"]
)
self.room_list = RoomList(window)
self.command_help = None
self.room_wall = None
self.highlighted_rooms = {}
window.chatrooms_entry.set_max_length(core.chatrooms.ROOM_NAME_MAX_LENGTH)
if GTK_API_VERSION >= 4:
window.chatrooms_paned.set_resize_start_child(True)
else:
window.chatrooms_paned.child_set_property(window.chatrooms_container, "resize", True)
for event_name, callback in (
("clear-room-messages", self.clear_room_messages),
("echo-room-message", self.echo_room_message),
("global-room-message", self.global_room_message),
("join-room", self.join_room),
("leave-room", self.leave_room),
("private-room-add-operator", self.private_room_add_operator),
("private-room-add-user", self.private_room_add_user),
("private-room-remove-operator", self.private_room_remove_operator),
("private-room-remove-user", self.private_room_remove_user),
("quit", self.quit),
("remove-room", self.remove_room),
("room-completions", self.update_completions),
("say-chat-room", self.say_chat_room),
("server-disconnect", self.server_disconnect),
("server-login", self.server_login),
("show-room", self.show_room),
("start", self.start),
("user-country", self.user_country),
("user-joined-room", self.user_joined_room),
("user-left-room", self.user_left_room),
("user-stats", self.user_stats),
("user-status", self.user_status)
):
events.connect(event_name, callback)
self.freeze()
def start(self):
self.unfreeze()
def quit(self):
self.freeze()
def destroy(self):
self.chat_entry.destroy()
self.room_list.destroy()
if self.command_help is not None:
self.command_help.destroy()
if self.room_wall is not None:
self.room_wall.destroy()
super().destroy()
def on_focus(self, *_args):
if self.window.current_page_id != self.window.chatrooms_page.id:
return True
if self.get_n_pages():
return True
if self.window.chatrooms_entry.is_sensitive():
self.window.chatrooms_entry.grab_focus()
return True
return False
def on_remove_all_pages(self, *_args):
core.chatrooms.remove_all_rooms()
def on_restore_removed_page(self, page_args):
room, is_private = page_args
core.chatrooms.show_room(room, is_private=is_private)
def on_reordered_page(self, *_args):
room_tab_order = {}
# Find position of opened auto-joined rooms
for room, room_page in self.pages.items():
room_position = self.page_num(room_page.container)
room_tab_order[room_position] = room
config.sections["server"]["autojoin"] = [room for room_index, room in sorted(room_tab_order.items())]
def on_switch_chat(self, _notebook, page, _page_num):
if self.window.current_page_id != self.window.chatrooms_page.id:
return
for room, tab in self.pages.items():
if tab.container != page:
continue
joined_room = core.chatrooms.joined_rooms.get(room)
self.chat_entry.set_parent(room, tab.chat_entry_container, tab.chat_view)
self.chat_entry.set_sensitive(joined_room is not None and joined_room.users)
tab.update_room_user_completions()
if self.command_help is None:
self.command_help = ChatCommandHelp(window=self.window, interface="chatroom")
if self.room_wall is None:
self.room_wall = RoomWall(window=self.window)
self.command_help.set_menu_button(tab.help_button)
self.room_wall.set_menu_button(tab.room_wall_button)
self.room_wall.room = room
if not tab.loaded:
tab.load()
# Remove highlight
self.unhighlight_room(room)
break
def on_create_room_response(self, dialog, _response_id, room):
private = dialog.get_option_value()
core.chatrooms.show_room(room, private)
def on_create_room(self, *_args):
room = self.window.chatrooms_entry.get_text().strip()
if not room:
return
if room not in core.chatrooms.server_rooms and room not in core.chatrooms.private_rooms:
room = core.chatrooms.sanitize_room_name(room)
OptionDialog(
parent=self.window,
title=_("Create New Room?"),
message=_('Do you really want to create a new room "%s"?') % room,
option_label=_("Make room private"),
callback=self.on_create_room_response,
callback_data=room
).present()
else:
core.chatrooms.show_room(room)
self.window.chatrooms_entry.set_text("")
def clear_room_messages(self, room):
page = self.pages.get(room)
if page is not None:
page.chat_view.clear()
page.activity_view.clear()
def clear_notifications(self):
if self.window.current_page_id != self.window.chatrooms_page.id:
return
page = self.get_current_page()
for room, tab in self.pages.items():
if tab.container == page:
# Remove highlight
self.unhighlight_room(room)
break
def show_room(self, room, is_private=False, switch_page=True, remembered=False):
if room not in self.pages:
is_global = (room == core.chatrooms.GLOBAL_ROOM_NAME)
tab_position = 0 if is_global and not remembered else -1
self.pages[room] = tab = ChatRoom(self, room, is_private=is_private, is_global=is_global)
self.insert_page(
tab.container, room, focus_callback=tab.on_focus, close_callback=tab.on_leave_room,
position=tab_position
)
tab.set_label(self.get_tab_label_inner(tab.container))
if not is_global:
combobox = self.window.search.room_search_combobox
combobox.append(room)
if switch_page:
self.set_current_page(self.pages[room].container)
self.window.change_main_page(self.window.chatrooms_page)
def remove_room(self, room):
page = self.pages.get(room)
if page is None:
return
if page.container == self.get_current_page():
self.chat_entry.set_parent(None)
if self.command_help is not None:
self.command_help.set_menu_button(None)
if self.room_wall is not None:
self.room_wall.set_menu_button(None)
self.room_wall.room = None
page.clear()
self.remove_page(page.container, page_args=(room, page.is_private))
del self.pages[room]
page.destroy()
self.chat_entry.clear_unsent_message(room)
if room != core.chatrooms.GLOBAL_ROOM_NAME:
combobox = self.window.search.room_search_combobox
combobox.remove_id(room)
def highlight_room(self, room, user):
if not room or room in self.highlighted_rooms:
return
self.highlighted_rooms[room] = user
self.window.update_title()
self.window.application.tray_icon.update()
def unhighlight_room(self, room):
if room not in self.highlighted_rooms:
return
del self.highlighted_rooms[room]
self.window.update_title()
self.window.application.tray_icon.update()
def join_room(self, msg):
page = self.pages.get(msg.room)
if page is None:
return
page.join_room(msg)
if page.container == self.get_current_page():
self.chat_entry.set_sensitive(True)
page.on_focus()
def leave_room(self, msg):
page = self.pages.get(msg.room)
if page is not None:
page.leave_room()
def user_stats(self, msg):
for page in self.pages.values():
page.user_stats(msg)
def user_status(self, msg):
for page in self.pages.values():
page.user_status(msg)
def user_country(self, user, country):
for page in self.pages.values():
page.user_country(user, country)
def user_joined_room(self, msg):
page = self.pages.get(msg.room)
if page is not None:
page.user_joined_room(msg)
def user_left_room(self, msg):
page = self.pages.get(msg.room)
if page is not None:
page.user_left_room(msg)
def echo_room_message(self, room, text, message_type):
page = self.pages.get(room)
if page is not None:
page.echo_room_message(text, message_type)
def say_chat_room(self, msg):
page = self.pages.get(msg.room)
if page is not None:
page.say_chat_room(msg)
def global_room_message(self, msg):
page = self.pages.get(core.chatrooms.GLOBAL_ROOM_NAME)
if page is not None:
page.global_room_message(msg)
def private_room_add_operator(self, msg):
page = self.pages.get(msg.room)
if page is not None:
page.private_room_add_operator(msg)
def private_room_add_user(self, msg):
page = self.pages.get(msg.room)
if page is not None:
page.private_room_add_user(msg)
def private_room_remove_operator(self, msg):
page = self.pages.get(msg.room)
if page is not None:
page.private_room_remove_operator(msg)
def private_room_remove_user(self, msg):
page = self.pages.get(msg.room)
if page is not None:
page.private_room_remove_user(msg)
def update_completions(self, completions):
page = self.get_current_page()
for tab in self.pages.values():
if tab.container == page:
tab.update_completions(completions)
break
def update_widgets(self):
self.chat_entry.set_spell_check_enabled(config.sections["ui"]["spellcheck"])
for tab in self.pages.values():
tab.toggle_chat_buttons()
tab.update_tags()
def server_login(self, *_args):
self.window.chatrooms_title.set_sensitive(True)
def server_disconnect(self, *_args):
self.window.chatrooms_title.set_sensitive(False)
self.chat_entry.set_sensitive(False)
for page in self.pages.values():
page.server_disconnect()
class ChatRoom:
def __init__(self, chatrooms, room, is_private, is_global):
(
self.activity_container,
self.activity_search_bar,
self.activity_view_container,
self.chat_container,
self.chat_entry_container,
self.chat_entry_row,
self.chat_paned,
self.chat_search_bar,
self.chat_view_container,
self.container,
self.help_button,
self.log_toggle,
self.room_wall_button,
self.room_wall_label,
self.speech_toggle,
self.users_container,
self.users_label,
self.users_list_container
) = ui.load(scope=self, path="chatrooms.ui")
self.chatrooms = chatrooms
self.window = chatrooms.window
self.room = room
self.is_private = is_private
self.is_global = is_global
if GTK_API_VERSION >= 4:
self.chat_paned.set_shrink_end_child(False)
inner_button = next(iter(self.room_wall_button))
self.room_wall_button.set_has_frame(False)
self.room_wall_label.set_mnemonic_widget(inner_button)
else:
self.chat_paned.child_set_property(self.chat_container, "shrink", False)
self.loaded = False
self.activity_view = TextView(
self.activity_view_container, parse_urls=False, editable=False,
horizontal_margin=10, vertical_margin=5, pixels_below_lines=2
)
self.chat_view = ChatView(
self.chat_view_container, chat_entry=self.chatrooms.chat_entry, editable=False,
horizontal_margin=10, vertical_margin=5, pixels_below_lines=2,
status_users=core.chatrooms.joined_rooms[room].users,
username_event=self.username_event
)
# Event Text Search
self.activity_search_bar = TextSearchBar(
self.activity_view.widget, self.activity_search_bar,
placeholder_text=_("Search activity log…")
)
# Chat Text Search
self.chat_search_bar = TextSearchBar(
self.chat_view.widget, self.chat_search_bar,
controller_widget=self.chat_container, focus_widget=self.chatrooms.chat_entry,
placeholder_text=_("Search chat log…")
)
self.log_toggle.set_active(room in config.sections["logging"]["rooms"])
self.toggle_chat_buttons()
self.users_list_view = TreeView(
self.window, parent=self.users_list_container, name="chat_room", secondary_name=room,
persistent_sort=True, activate_row_callback=self.on_row_activated,
columns={
# Visible columns
"status": {
"column_type": "icon",
"title": _("Status"),
"width": 25,
"hide_header": True
},
"country": {
"column_type": "icon",
"title": _("Country"),
"width": 30,
"hide_header": True
},
"user": {
"column_type": "text",
"title": _("User"),
"width": 110,
"expand_column": True,
"iterator_key": True,
"default_sort_type": "ascending",
"text_underline_column": "username_underline_data",
"text_weight_column": "username_weight_data"
},
"speed": {
"column_type": "number",
"title": _("Speed"),
"width": 80,
"sort_column": "speed_data",
"expand_column": True
},
"files": {
"column_type": "number",
"title": _("Files"),
"sort_column": "files_data",
"expand_column": True
},
# Hidden data columns
"speed_data": {"data_type": GObject.TYPE_UINT},
"files_data": {"data_type": GObject.TYPE_UINT},
"username_weight_data": {"data_type": Pango.Weight},
"username_underline_data": {"data_type": Pango.Underline}
}
)
self.popup_menu_user_chat = UserPopupMenu(
self.window.application, parent=self.chat_view.widget, connect_events=False,
tab_name="chatrooms"
)
self.popup_menu_user_list = UserPopupMenu(
self.window.application, parent=self.users_list_view.widget,
callback=self.on_popup_menu_user, tab_name="chatrooms"
)
for menu in (self.popup_menu_user_chat, self.popup_menu_user_list):
menu.add_items(
("", None),
("#" + _("Sear_ch User's Files"), menu.on_search_user)
)
self.popup_menu_activity_view = PopupMenu(self.window.application, self.activity_view.widget,
self.on_popup_menu_log)
self.popup_menu_activity_view.add_items(
("#" + _("Find…"), self.on_find_activity_log),
("", None),
("#" + _("Copy"), self.activity_view.on_copy_text),
("#" + _("Copy All"), self.activity_view.on_copy_all_text),
("", None),
("#" + _("Clear Activity View"), self.activity_view.on_clear_all_text),
("", None),
("#" + _("_Leave Room"), self.on_leave_room)
)
self.popup_menu_chat_view = PopupMenu(self.window.application, self.chat_view.widget, self.on_popup_menu_chat)
self.popup_menu_chat_view.add_items(
("#" + _("Find…"), self.on_find_room_log),
("", None),
("#" + _("Copy"), self.chat_view.on_copy_text),
("#" + _("Copy Link"), self.chat_view.on_copy_link),
("#" + _("Copy All"), self.chat_view.on_copy_all_text),
("", None),
("#" + _("View Room Log"), self.on_view_room_log),
("#" + _("Delete Room Log…"), self.on_delete_room_log),
("", None),
("#" + _("Clear Message View"), self.chat_view.on_clear_all_text),
("#" + _("_Leave Room"), self.on_leave_room)
)
self.tab_menu = PopupMenu(self.window.application)
self.tab_menu.add_items(
("#" + _("_Leave Room"), self.on_leave_room)
)
self.popup_menus = (
self.popup_menu_user_chat, self.popup_menu_user_list,
self.popup_menu_activity_view, self.popup_menu_chat_view, self.tab_menu
)
self.setup_public_feed()
self.prepend_old_messages()
def load(self):
GLib.idle_add(self.read_room_logs_finished)
self.loaded = True
def clear(self):
self.activity_view.clear()
self.chat_view.clear()
self.users_list_view.clear()
def destroy(self):
for menu in self.popup_menus:
menu.destroy()
self.activity_view.destroy()
self.chat_view.destroy()
self.users_list_view.destroy()
self.__dict__.clear()
def set_label(self, label):
self.tab_menu.set_parent(label)
def setup_public_feed(self):
if not self.is_global:
return
for widget in (self.activity_container, self.users_container, self.chat_entry_container, self.help_button):
widget.set_visible(False)
self.speech_toggle.set_active(False) # Public feed is jibberish and too fast for TTS
self.chat_entry_row.set_halign(Gtk.Align.END)
def add_user_row(self, userdata):
username = userdata.username
status = userdata.status
status_icon_name = USER_STATUS_ICON_NAMES.get(status, "")
flag_icon_name = get_flag_icon_name(userdata.country)
speed = userdata.avgspeed or 0
files = userdata.files
h_speed = human_speed(speed) if speed > 0 else ""
h_files = humanize(files) if files is not None else ""
weight = Pango.Weight.NORMAL
underline = Pango.Underline.NONE
if self.room in core.chatrooms.private_rooms:
if username == core.chatrooms.private_rooms[self.room].owner:
weight = Pango.Weight.BOLD
underline = Pango.Underline.SINGLE
elif username in core.chatrooms.private_rooms[self.room].operators:
weight = Pango.Weight.BOLD
underline = Pango.Underline.NONE
self.users_list_view.add_row([
status_icon_name,
flag_icon_name,
username,
h_speed,
h_files,
speed,
files or 0,
weight,
underline
], select_row=False)
def read_room_logs_finished(self):
if not hasattr(self, "chat_view"):
# Tab was closed
return
self.activity_view.scroll_bottom()
self.chat_view.scroll_bottom()
self.activity_view.auto_scroll = self.chat_view.auto_scroll = True
def prepend_old_messages(self):
log_lines = log.read_log(
folder_path=log.room_folder_path,
basename=self.room,
num_lines=config.sections["logging"]["readroomlines"]
)
self.chat_view.append_log_lines(log_lines, login_username=config.sections["server"]["login"])
def populate_room_users(self, joined_users):
# Temporarily disable sorting for increased performance
self.users_list_view.freeze()
for userdata in joined_users:
username = userdata.username
iterator = self.users_list_view.iterators.get(username)
if iterator is not None:
self.users_list_view.remove_row(iterator)
self.add_user_row(userdata)
private_room = core.chatrooms.private_rooms.get(self.room)
# List private room members who are offline/not currently joined
if private_room is not None:
owner = private_room.owner
for username in private_room.members:
if username not in self.users_list_view.iterators:
self.add_user_row(UserData(username, status=UserStatus.OFFLINE))
if owner and owner not in self.users_list_view.iterators:
self.add_user_row(UserData(owner, status=UserStatus.OFFLINE))
self.users_list_view.unfreeze()
# Update user count
self.update_user_count()
# Update all username tags in chat log
self.chat_view.update_user_tags()
# Add room users to completion list
if self.chatrooms.get_current_page() == self.container:
self.update_room_user_completions()
def populate_user_menu(self, user, menu):
menu.set_user(user)
menu.toggle_user_items()
def on_find_activity_log(self, *_args):
self.activity_search_bar.set_visible(True)
def on_find_room_log(self, *_args):
self.chat_search_bar.set_visible(True)
def get_selected_username(self):
for iterator in self.users_list_view.get_selected_rows():
return self.users_list_view.get_row_value(iterator, "user")
return None
def on_row_activated(self, _list_view, _path, _column):
user = self.get_selected_username()
if user is not None:
core.userinfo.show_user(user)
def on_popup_menu_user(self, menu, _widget):
user = self.get_selected_username()
self.populate_user_menu(user, menu)
def on_popup_menu_log(self, menu, _textview):
menu.actions[_("Copy")].set_enabled(self.activity_view.get_has_selection())
def on_popup_menu_chat(self, menu, _textview):
menu.actions[_("Copy")].set_enabled(self.chat_view.get_has_selection())
menu.actions[_("Copy Link")].set_enabled(bool(self.chat_view.get_url_for_current_pos()))
def toggle_chat_buttons(self):
is_log_toggle_visible = not config.sections["logging"]["chatrooms"]
is_speech_toggle_visible = config.sections["ui"]["speechenabled"]
self.log_toggle.set_visible(is_log_toggle_visible)
self.speech_toggle.set_visible(is_speech_toggle_visible)
if self.is_global:
self.chat_entry_row.set_visible(is_log_toggle_visible or is_speech_toggle_visible)
def _show_notification(self, room, user, text, is_mentioned):
self.chatrooms.request_tab_changed(self.container, is_important=is_mentioned, is_quiet=self.is_global)
if self.is_global and room in core.chatrooms.joined_rooms:
# Don't show notifications about the Public feed that's duplicated in an open tab
return
if is_mentioned:
log.add(_("%(user)s mentioned you in room %(room)s") % {"user": user, "room": room})
if config.sections["notifications"]["notification_popup_chatroom_mention"]:
core.notifications.show_chatroom_notification(
room, text,
title=_("Mentioned by %(user)s in Room %(room)s") % {"user": user, "room": room},
high_priority=True
)
if (self.chatrooms.get_current_page() == self.container
and self.window.current_page_id == self.window.chatrooms_page.id and self.window.is_active()):
# Don't show notifications if the chat is open and the window is in use
return
if is_mentioned:
# We were mentioned, update tray icon and show urgency hint
self.chatrooms.highlight_room(room, user)
return
if not self.is_global and config.sections["notifications"]["notification_popup_chatroom"]:
# Don't show notifications for public feed room, they're too noisy
core.notifications.show_chatroom_notification(
room, text,
title=_("Message by %(user)s in Room %(room)s") % {"user": user, "room": room}
)
def say_chat_room(self, msg):
username = msg.user
room = msg.room
message = msg.message
formatted_message = msg.formatted_message
message_type = msg.message_type
usertag = self.chat_view.get_user_tag(username)
if message_type != "local":
if self.speech_toggle.get_active():
core.notifications.new_tts(
config.sections["ui"]["speechrooms"], {"room": room, "user": username, "message": message}
)
self._show_notification(
room, username, message, is_mentioned=(message_type == "hilite"))
self.chat_view.append_line(
formatted_message, message_type=message_type, username=username, usertag=usertag,
timestamp_format=config.sections["logging"]["rooms_timestamp"]
)
def global_room_message(self, msg):
self.say_chat_room(msg)
def echo_room_message(self, text, message_type):
if message_type != "command":
timestamp_format = config.sections["logging"]["rooms_timestamp"]
else:
timestamp_format = None
self.chat_view.append_line(text, message_type=message_type, timestamp_format=timestamp_format)
def user_joined_room(self, msg):
userdata = msg.userdata
username = userdata.username
iterator = self.users_list_view.iterators.get(username)
if iterator is not None:
if not self.is_private:
return
self.users_list_view.remove_row(iterator)
# Add to completion list, and completion drop-down
if self.chatrooms.get_current_page() == self.container:
self.chatrooms.chat_entry.add_completion(username)
if (username != core.users.login_username
and not core.network_filter.is_user_ignored(username)
and not core.network_filter.is_user_ip_ignored(username)):
self.activity_view.append_line(
_("%s joined the room") % username,
timestamp_format=config.sections["logging"]["rooms_timestamp"]
)
self.add_user_row(userdata)
self.chat_view.update_user_tag(username)
self.update_user_count()
def user_left_room(self, msg):
username = msg.username
iterator = self.users_list_view.iterators.get(username)
if iterator is None:
return
# Remove from completion list, and completion drop-down
if self.chatrooms.get_current_page() == self.container and username not in core.buddies.users:
self.chatrooms.chat_entry.remove_completion(username)
if not core.network_filter.is_user_ignored(username) and \
not core.network_filter.is_user_ip_ignored(username):
timestamp_format = config.sections["logging"]["rooms_timestamp"]
self.activity_view.append_line(_("%s left the room") % username, timestamp_format=timestamp_format)
if self.is_private:
status_icon_name = USER_STATUS_ICON_NAMES[UserStatus.OFFLINE]
empty_str = ""
empty_int = 0
self.users_list_view.set_row_values(
iterator,
column_ids=["status", "speed", "speed_data", "files", "files_data", "country"],
values=[status_icon_name, empty_str, empty_int, empty_str, empty_int, empty_str]
)
else:
self.users_list_view.remove_row(iterator)
self.chat_view.update_user_tag(username)
self.update_user_count()
def private_room_add_operator(self, msg):
iterator = self.users_list_view.iterators.get(msg.user)
if iterator is None:
return
self.users_list_view.set_row_values(
iterator,
column_ids=["username_weight_data", "username_underline_data"],
values=[Pango.Weight.BOLD, Pango.Underline.NONE]
)
def private_room_add_user(self, msg):
username = msg.user
iterator = self.users_list_view.iterators.get(username)
if iterator is not None:
return
self.add_user_row(UserData(username, status=UserStatus.OFFLINE))
self.chat_view.update_user_tag(username)
self.update_user_count()
def private_room_remove_operator(self, msg):
iterator = self.users_list_view.iterators.get(msg.user)
if iterator is None:
return
self.users_list_view.set_row_values(
iterator,
column_ids=["username_weight_data", "username_underline_data"],
values=[Pango.Weight.NORMAL, Pango.Underline.NONE]
)
def private_room_remove_user(self, msg):
username = msg.user
iterator = self.users_list_view.iterators.get(username)
if iterator is None:
return
self.users_list_view.remove_row(iterator)
self.chat_view.update_user_tag(username)
self.update_user_count()
def update_user_count(self):
user_count = len(self.users_list_view.iterators)
self.users_label.set_text(humanize(user_count))
def user_stats(self, msg):
user = msg.user
iterator = self.users_list_view.iterators.get(user)
if iterator is None:
return
if user not in core.chatrooms.joined_rooms[self.room].users:
# Private room member offline/not currently joined
return
speed = msg.avgspeed or 0
num_files = msg.files or 0
column_ids = []
column_values = []
if speed != self.users_list_view.get_row_value(iterator, "speed_data"):
h_speed = human_speed(speed) if speed > 0 else ""
column_ids.extend(("speed", "speed_data"))
column_values.extend((h_speed, speed))
if num_files != self.users_list_view.get_row_value(iterator, "files_data"):
h_num_files = humanize(num_files)
column_ids.extend(("files", "files_data"))
column_values.extend((h_num_files, num_files))
if column_ids:
self.users_list_view.set_row_values(iterator, column_ids, column_values)
def user_status(self, msg):
user = msg.user
iterator = self.users_list_view.iterators.get(user)
if iterator is None:
return
if user not in core.chatrooms.joined_rooms[self.room].users:
# Private room member offline/not currently joined
return
status = msg.status
status_icon_name = USER_STATUS_ICON_NAMES.get(status)
if not status_icon_name or status_icon_name == self.users_list_view.get_row_value(iterator, "status"):
return
if status == UserStatus.AWAY:
action = _("%s has gone away")
elif status == UserStatus.ONLINE:
action = _("%s has returned")
else:
# If we reach this point, the server did something wrong. The user should have
# left the room before an offline status is sent.
return
if not core.network_filter.is_user_ignored(user) and not core.network_filter.is_user_ip_ignored(user):
self.activity_view.append_line(
action % user, timestamp_format=config.sections["logging"]["rooms_timestamp"])
self.users_list_view.set_row_value(iterator, "status", status_icon_name)
self.chat_view.update_user_tag(user)
def user_country(self, user, country_code):
iterator = self.users_list_view.iterators.get(user)
if iterator is None:
return
if user not in core.chatrooms.joined_rooms[self.room].users:
# Private room member offline/not currently joined
return
flag_icon_name = get_flag_icon_name(country_code)
if flag_icon_name and flag_icon_name != self.users_list_view.get_row_value(iterator, "country"):
self.users_list_view.set_row_value(iterator, "country", flag_icon_name)
def username_event(self, pos_x, pos_y, user):
menu = self.popup_menu_user_chat
menu.update_model()
self.populate_user_menu(user, menu)
menu.popup(pos_x, pos_y)
def update_tags(self):
self.chat_view.update_tags()
def server_disconnect(self):
self.leave_room()
def join_room(self, msg):
self.is_private = msg.private
self.populate_room_users(msg.users)
self.activity_view.append_line(
_("%s joined the room") % core.users.login_username,
timestamp_format=config.sections["logging"]["rooms_timestamp"]
)
def leave_room(self):
self.users_list_view.clear()
self.update_user_count()
if self.chatrooms.get_current_page() == self.container:
self.update_room_user_completions()
self.chat_view.update_user_tags()
def on_focus(self, *_args):
if self.window.current_page_id == self.window.chatrooms_page.id:
widget = self.chatrooms.chat_entry if self.chatrooms.chat_entry.get_sensitive() else self.chat_view
widget.grab_focus()
return True
def on_leave_room(self, *_args):
core.chatrooms.remove_room(self.room)
def on_log_toggled(self, *_args):
if not self.log_toggle.get_active():
if self.room in config.sections["logging"]["rooms"]:
config.sections["logging"]["rooms"].remove(self.room)
return
if self.room not in config.sections["logging"]["rooms"]:
config.sections["logging"]["rooms"].append(self.room)
def on_view_room_log(self, *_args):
log.open_log(log.room_folder_path, self.room)
def on_delete_room_log_response(self, *_args):
log.delete_log(log.room_folder_path, self.room)
self.activity_view.clear()
self.chat_view.clear()
def on_delete_room_log(self, *_args):
OptionDialog(
parent=self.window,
title=_("Delete Logged Messages?"),
message=_("Do you really want to permanently delete all logged messages for this room?"),
destructive_response_id="ok",
callback=self.on_delete_room_log_response
).present()
def update_room_user_completions(self):
self.update_completions(core.chatrooms.completions.copy())
def update_completions(self, completions):
# We want to include users for this room only
if config.sections["words"]["roomusers"]:
room_users = core.chatrooms.joined_rooms[self.room].users
completions.update(room_users)
self.chatrooms.chat_entry.set_completions(completions)
| 39,143 | Python | .py | 844 | 35.466825 | 118 | 0.613931 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,440 | transfers.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/transfers.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2018 Mutnick <mutnick@techie.com>
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2008-2011 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2009 hedonist <ak@sensi.org>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from itertools import islice
from gi.repository import GObject
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.dialogs.fileproperties import FileProperties
from pynicotine.gtkgui.widgets import clipboard
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.popupmenu import FilePopupMenu
from pynicotine.gtkgui.widgets.popupmenu import UserPopupMenu
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.theme import get_file_type_icon_name
from pynicotine.gtkgui.widgets.theme import remove_css_class
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.gtkgui.widgets.treeview import create_grouping_menu
from pynicotine.slskmessages import FileListMessage
from pynicotine.slskmessages import TransferRejectReason
from pynicotine.transfers import Transfer
from pynicotine.transfers import TransferStatus
from pynicotine.utils import UINT64_LIMIT
from pynicotine.utils import human_length
from pynicotine.utils import human_size
from pynicotine.utils import human_speed
from pynicotine.utils import humanize
class Transfers:
STATUSES = {
TransferStatus.QUEUED: _("Queued"),
f"{TransferStatus.QUEUED} (prioritized)": _("Queued (prioritized)"),
f"{TransferStatus.QUEUED} (privileged)": _("Queued (privileged)"),
TransferStatus.GETTING_STATUS: _("Getting status"),
TransferStatus.TRANSFERRING: _("Transferring"),
TransferStatus.CONNECTION_CLOSED: _("Connection closed"),
TransferStatus.CONNECTION_TIMEOUT: _("Connection timeout"),
TransferStatus.USER_LOGGED_OFF: _("User logged off"),
TransferStatus.PAUSED: _("Paused"),
TransferStatus.CANCELLED: _("Cancelled"),
TransferStatus.FINISHED: _("Finished"),
TransferStatus.FILTERED: _("Filtered"),
TransferStatus.DOWNLOAD_FOLDER_ERROR: _("Download folder error"),
TransferStatus.LOCAL_FILE_ERROR: _("Local file error"),
TransferRejectReason.BANNED: _("Banned"),
TransferRejectReason.FILE_NOT_SHARED: _("File not shared"),
TransferRejectReason.PENDING_SHUTDOWN: _("Pending shutdown"),
TransferRejectReason.FILE_READ_ERROR: _("File read error")
}
STATUS_PRIORITIES = {
TransferStatus.FILTERED: 0,
TransferStatus.FINISHED: 1,
TransferStatus.PAUSED: 2,
TransferStatus.CANCELLED: 3,
TransferStatus.QUEUED: 4,
f"{TransferStatus.QUEUED} (prioritized)": 4,
f"{TransferStatus.QUEUED} (privileged)": 4,
TransferStatus.USER_LOGGED_OFF: 5,
TransferStatus.CONNECTION_CLOSED: 6,
TransferStatus.CONNECTION_TIMEOUT: 7,
TransferRejectReason.FILE_NOT_SHARED: 8,
TransferRejectReason.PENDING_SHUTDOWN: 9,
TransferRejectReason.FILE_READ_ERROR: 10,
TransferStatus.LOCAL_FILE_ERROR: 11,
TransferStatus.DOWNLOAD_FOLDER_ERROR: 12,
TransferRejectReason.BANNED: 13,
TransferStatus.GETTING_STATUS: 9998,
TransferStatus.TRANSFERRING: 9999
}
PENDING_ITERATOR_REBUILD = 0
PENDING_ITERATOR_ADD = 1
PENDING_ITERATORS = {PENDING_ITERATOR_REBUILD, PENDING_ITERATOR_ADD}
UNKNOWN_STATUS_PRIORITY = 1000
path_separator = path_label = retry_label = abort_label = None
transfer_page = user_counter = file_counter = expand_button = expand_icon = grouping_button = status_label = None
def __init__(self, window, transfer_type):
(
self.clear_all_button,
self.clear_all_label,
self.container,
self.tree_container
) = ui.load(scope=self, path=f"{transfer_type}s.ui")
self.window = window
self.type = transfer_type
if GTK_API_VERSION >= 4:
inner_button = next(iter(self.clear_all_button))
self.clear_all_button.set_has_frame(False)
self.clear_all_label.set_mnemonic_widget(inner_button)
self.transfer_list = {}
self.users = {}
self.paths = {}
self.pending_folder_rows = set()
self.pending_user_rows = set()
self.grouping_mode = None
self.row_id = 0
self.file_properties = None
self.initialized = False
# Use dict instead of list for faster membership checks
self.selected_users = {}
self.selected_transfers = {}
self.tree_view = TreeView(
window, parent=self.tree_container, name=transfer_type,
multi_select=True, persistent_sort=True, activate_row_callback=self.on_row_activated,
delete_accelerator_callback=self.on_remove_transfers_accelerator,
columns={
# Visible columns
"user": {
"column_type": "text",
"title": _("User"),
"width": 200,
"sensitive_column": "is_sensitive_data"
},
"path": {
"column_type": "text",
"title": self.path_label,
"width": 200,
"expand_column": True,
"tooltip_callback": self.on_file_path_tooltip,
"sensitive_column": "is_sensitive_data"
},
"file_type": {
"column_type": "icon",
"title": _("File Type"),
"width": 40,
"hide_header": True,
"sensitive_column": "is_sensitive_data"
},
"filename": {
"column_type": "text",
"title": _("Filename"),
"width": 200,
"expand_column": True,
"tooltip_callback": self.on_file_path_tooltip,
"sensitive_column": "is_sensitive_data"
},
"status": {
"column_type": "text",
"title": _("Status"),
"width": 140,
"sensitive_column": "is_sensitive_data"
},
"queue_position": {
"column_type": "number",
"title": _("Queue"),
"width": 90,
"sort_column": "queue_position_data"
},
"percent": {
"column_type": "progress",
"title": _("Percent"),
"width": 90,
"sensitive_column": "is_sensitive_data"
},
"size": {
"column_type": "number",
"title": _("Size"),
"width": 180,
"sort_column": "size_data",
"sensitive_column": "is_sensitive_data"
},
"speed": {
"column_type": "number",
"title": _("Speed"),
"width": 100,
"sort_column": "speed_data",
"sensitive_column": "is_sensitive_data"
},
"time_elapsed": {
"column_type": "number",
"title": _("Time Elapsed"),
"width": 140,
"sort_column": "time_elapsed_data",
"sensitive_column": "is_sensitive_data"
},
"time_left": {
"column_type": "number",
"title": _("Time Left"),
"width": 140,
"sort_column": "time_left_data",
"sensitive_column": "is_sensitive_data"
},
# Hidden data columns
"size_data": {"data_type": GObject.TYPE_UINT64},
"current_bytes_data": {"data_type": GObject.TYPE_UINT64},
"speed_data": {"data_type": GObject.TYPE_UINT64},
"queue_position_data": {"data_type": GObject.TYPE_UINT},
"time_elapsed_data": {"data_type": GObject.TYPE_INT},
"time_left_data": {"data_type": GObject.TYPE_UINT64},
"is_sensitive_data": {"data_type": GObject.TYPE_BOOLEAN},
"transfer_data": {"data_type": GObject.TYPE_PYOBJECT},
"id_data": {
"data_type": GObject.TYPE_INT,
"default_sort_type": "ascending",
"iterator_key": True
}
}
)
Accelerator("t", self.tree_view.widget, self.on_abort_transfers_accelerator)
Accelerator("r", self.tree_view.widget, self.on_retry_transfers_accelerator)
Accelerator("<Alt>Return", self.tree_view.widget, self.on_file_properties_accelerator)
menu = create_grouping_menu(
window, config.sections["transfers"][f"group{transfer_type}s"], self.on_toggle_tree)
self.grouping_button.set_menu_model(menu)
if GTK_API_VERSION >= 4:
inner_button = next(iter(self.grouping_button))
add_css_class(widget=inner_button, css_class="image-button")
self.expand_button.connect("toggled", self.on_expand_tree)
self.expand_button.set_active(config.sections["transfers"][f"{transfer_type}sexpanded"])
self.popup_menu_users = UserPopupMenu(window.application, tab_name="transfers")
self.popup_menu_clear = PopupMenu(window.application)
self.clear_all_button.set_menu_model(self.popup_menu_clear.model)
self.popup_menu_copy = PopupMenu(window.application)
self.popup_menu_copy.add_items(
("#" + _("Copy _File Path"), self.on_copy_file_path),
("#" + _("Copy _URL"), self.on_copy_url),
("#" + _("Copy Folder U_RL"), self.on_copy_folder_url)
)
self.popup_menu = FilePopupMenu(
window.application, parent=self.tree_view.widget, callback=self.on_popup_menu
)
self.popup_menu.add_items(
("#" + _("_Open File"), self.on_open_file),
("#" + _("Open in File _Manager"), self.on_open_file_manager),
("#" + _("F_ile Properties"), self.on_file_properties),
("", None),
("#" + self.retry_label, self.on_retry_transfer),
("#" + self.abort_label, self.on_abort_transfer),
("#" + _("Remove"), self.on_remove_transfer),
("", None),
("#" + _("View User _Profile"), self.on_user_profile),
("#" + _("_Browse Folder"), self.on_browse_folder),
("#" + _("_Search"), self.on_file_search),
("", None),
(">" + _("Copy"), self.popup_menu_copy),
(">" + _("Clear All"), self.popup_menu_clear),
(">" + _("User Actions"), self.popup_menu_users)
)
def destroy(self):
self.clear_model()
self.tree_view.destroy()
self.popup_menu.destroy()
self.popup_menu_users.destroy()
self.popup_menu_clear.destroy()
self.popup_menu_copy.destroy()
self.__dict__.clear()
def on_focus(self, *_args):
self.update_model()
self.window.notebook.remove_tab_changed(self.transfer_page)
if self.container.get_parent().get_visible():
self.tree_view.grab_focus()
return True
return False
def init_transfers(self, transfer_list):
self.transfer_list = transfer_list
for transfer in transfer_list:
# Tab highlights are only used when transfers are appended, but we
# won't create a transfer row until the tab is active. To prevent
# spurious highlights when a previously added transfer changes, but
# the tab wasn't activated yet (iterator is None), mark the iterator
# as pending.
transfer.iterator = self.PENDING_ITERATOR_REBUILD
self.container.get_parent().set_visible(bool(transfer_list))
def select_transfers(self):
self.selected_transfers.clear()
self.selected_users.clear()
for iterator in self.tree_view.get_selected_rows():
transfer = self.tree_view.get_row_value(iterator, "transfer_data")
self.select_transfer(transfer, select_user=True)
def select_child_transfers(self, transfer):
if transfer.virtual_path is not None:
return
# Dummy Transfer object for user/folder rows
user = transfer.username
folder_path = self.get_transfer_folder_path(transfer)
if folder_path is not None:
user_folder_path = user + folder_path
row_data = self.paths[user_folder_path]
else:
row_data = self.users[user]
_row_iter, child_transfers = row_data
for i_transfer in child_transfers:
self.select_transfer(i_transfer)
def select_transfer(self, transfer, select_user=False):
if transfer.virtual_path is not None and transfer not in self.selected_transfers:
self.selected_transfers[transfer] = None
if select_user and transfer.username not in self.selected_users:
self.selected_users[transfer.username] = None
self.select_child_transfers(transfer)
def on_file_search(self, *_args):
transfer = next(iter(self.selected_transfers), None)
if not transfer:
return
_folder_path, _separator, basename = transfer.virtual_path.rpartition("\\")
self.window.search_entry.set_text(basename)
self.window.change_main_page(self.window.search_page)
def translate_status(self, status):
translated_status = self.STATUSES.get(status)
if translated_status:
return translated_status
return status
def update_limits(self):
"""Underline status bar bandwidth labels when alternative speed limits
are active."""
if config.sections["transfers"][f"use_{self.type}_speed_limit"] == "alternative":
add_css_class(self.status_label, "underline")
return
remove_css_class(self.status_label, "underline")
def update_num_users_files(self):
self.user_counter.set_text(humanize(len(self.users)))
self.file_counter.set_text(humanize(len(self.transfer_list)))
def update_model(self, transfer=None, update_parent=True):
if self.window.current_page_id != self.transfer_page.id:
if transfer is not None and transfer.iterator is None:
self.window.notebook.request_tab_changed(self.transfer_page)
transfer.iterator = self.PENDING_ITERATOR_ADD
# No need to do unnecessary work if transfers are not visible
return
has_disabled_sorting = False
has_selected_parent = False
update_counters = False
use_reverse_file_path = config.sections["ui"]["reverse_file_paths"]
if transfer is not None:
update_counters = self.update_specific(transfer, use_reverse_file_path=use_reverse_file_path)
elif self.transfer_list:
for transfer_i in self.transfer_list:
select_parent = (not has_selected_parent and transfer_i.iterator == self.PENDING_ITERATOR_ADD)
row_added = self.update_specific(transfer_i, select_parent, use_reverse_file_path)
if select_parent:
has_selected_parent = True
if not row_added:
continue
update_counters = True
if not has_disabled_sorting:
# Optimization: disable sorting while adding rows
self.tree_view.freeze()
has_disabled_sorting = True
if update_parent:
self.update_parent_rows(transfer)
if update_counters:
self.update_num_users_files()
if has_disabled_sorting:
self.tree_view.unfreeze()
if not self.initialized:
self.on_expand_tree()
self.initialized = True
self.tree_view.redraw()
def _update_pending_parent_rows(self):
for user_folder_path in self.pending_folder_rows:
if user_folder_path not in self.paths:
continue
user_folder_path_iter, user_folder_path_child_transfers = self.paths[user_folder_path]
self.update_parent_row(
user_folder_path_iter, user_folder_path_child_transfers, user_folder_path=user_folder_path)
for username in self.pending_user_rows:
if username not in self.users:
continue
user_iter, user_child_transfers = self.users[username]
self.update_parent_row(user_iter, user_child_transfers, username=username)
self.pending_folder_rows.clear()
self.pending_user_rows.clear()
def update_parent_rows(self, transfer=None):
if self.grouping_mode == "ungrouped":
return
if transfer is not None:
username = transfer.username
if self.paths:
user_folder_path = username + self.get_transfer_folder_path(transfer)
self.pending_folder_rows.add(user_folder_path)
self.pending_user_rows.add(username)
return
if self.paths:
for user_folder_path, (user_folder_path_iter, child_transfers) in self.paths.copy().items():
self.update_parent_row(user_folder_path_iter, child_transfers, user_folder_path=user_folder_path)
for username, (user_iter, child_transfers) in self.users.copy().items():
self.update_parent_row(user_iter, child_transfers, username=username)
@staticmethod
def get_hqueue_position(queue_position):
return str(queue_position) if queue_position > 0 else ""
@staticmethod
def get_hsize(current_byte_offset, size):
if current_byte_offset >= size:
return human_size(size)
return f"{human_size(current_byte_offset)} / {human_size(size)}"
@staticmethod
def get_hspeed(speed):
return human_speed(speed) if speed > 0 else ""
@staticmethod
def get_helapsed(elapsed):
return human_length(elapsed) if elapsed > 0 else ""
@staticmethod
def get_hleft(left):
return human_length(left) if left >= 1 else ""
@staticmethod
def get_percent(current_byte_offset, size):
if current_byte_offset > size or size <= 0:
return 100
# Multiply first to avoid decimals
return (100 * current_byte_offset) // size
def update_parent_row(self, iterator, child_transfers, username=None, user_folder_path=None):
speed = 0.0
total_size = current_byte_offset = 0
elapsed = 0
parent_status = TransferStatus.FINISHED
if not child_transfers:
# Remove parent row if no children are present anymore
if user_folder_path:
transfer = self.tree_view.get_row_value(iterator, "transfer_data")
_user_iter, user_child_transfers = self.users[transfer.username]
user_child_transfers.remove(transfer)
del self.paths[user_folder_path]
else:
del self.users[username]
self.tree_view.remove_row(iterator)
if not self.tree_view.iterators:
# Show tab description
self.container.get_parent().set_visible(False)
self.update_num_users_files()
return
for transfer in child_transfers:
status = transfer.status
if status == TransferStatus.TRANSFERRING:
# "Transferring" status always has the highest priority
parent_status = status
speed += transfer.speed
elif parent_status in self.STATUS_PRIORITIES:
parent_status_priority = self.STATUS_PRIORITIES[parent_status]
status_priority = self.STATUS_PRIORITIES.get(status, self.UNKNOWN_STATUS_PRIORITY)
if status_priority > parent_status_priority:
parent_status = status
if status == TransferStatus.FILTERED and transfer.virtual_path:
# We don't want to count filtered files when calculating the progress
continue
elapsed += transfer.time_elapsed
total_size += transfer.size
current_byte_offset += transfer.current_byte_offset or 0
transfer = self.tree_view.get_row_value(iterator, "transfer_data")
if total_size > UINT64_LIMIT: # pylint: disable=consider-using-min-builtin
total_size = UINT64_LIMIT
if current_byte_offset > UINT64_LIMIT: # pylint: disable=consider-using-min-builtin
current_byte_offset = UINT64_LIMIT
should_update_size = False
column_ids = []
column_values = []
if transfer.status != parent_status:
column_ids.append("status")
column_values.append(self.translate_status(parent_status))
if parent_status == TransferStatus.USER_LOGGED_OFF:
column_ids.append("is_sensitive_data")
column_values.append(False)
elif transfer.status == TransferStatus.USER_LOGGED_OFF:
column_ids.append("is_sensitive_data")
column_values.append(True)
transfer.status = parent_status
if transfer.speed != speed:
column_ids.extend(("speed", "speed_data"))
column_values.extend((self.get_hspeed(speed), speed))
transfer.speed = speed
if transfer.time_elapsed != elapsed:
left = (total_size - current_byte_offset) / speed if speed and total_size > current_byte_offset else 0
column_ids.extend(("time_elapsed", "time_left", "time_elapsed_data", "time_left_data"))
column_values.extend((self.get_helapsed(elapsed), self.get_hleft(left), elapsed, left))
transfer.time_elapsed = elapsed
if transfer.current_byte_offset != current_byte_offset:
column_ids.append("current_bytes_data")
column_values.append(current_byte_offset)
transfer.current_byte_offset = current_byte_offset
should_update_size = True
if transfer.size != total_size:
column_ids.append("size_data")
column_values.append(total_size)
transfer.size = total_size
should_update_size = True
if should_update_size:
column_ids.extend(("percent", "size"))
column_values.extend((
self.get_percent(current_byte_offset, total_size),
self.get_hsize(current_byte_offset, total_size)
))
if column_ids:
self.tree_view.set_row_values(iterator, column_ids, column_values)
def update_specific(self, transfer, select_parent=False, use_reverse_file_path=True):
current_byte_offset = transfer.current_byte_offset or 0
queue_position = transfer.queue_position
status = transfer.status or ""
if transfer.modifier and status == TransferStatus.QUEUED:
# Priority status
status += f" ({transfer.modifier})"
translated_status = self.translate_status(status)
size = transfer.size
speed = transfer.speed
elapsed = transfer.time_elapsed
left = transfer.time_left
iterator = transfer.iterator
# Modify old transfer
if iterator and iterator not in self.PENDING_ITERATORS:
should_update_size = False
old_translated_status = self.tree_view.get_row_value(iterator, "status")
column_ids = []
column_values = []
if old_translated_status != translated_status:
column_ids.append("status")
column_values.append(translated_status)
if transfer.status == TransferStatus.USER_LOGGED_OFF:
column_ids.append("is_sensitive_data")
column_values.append(False)
elif old_translated_status == _("User logged off"):
column_ids.append("is_sensitive_data")
column_values.append(True)
if self.tree_view.get_row_value(iterator, "speed_data") != speed:
column_ids.extend(("speed", "speed_data"))
column_values.extend((self.get_hspeed(speed), speed))
if self.tree_view.get_row_value(iterator, "time_elapsed_data") != elapsed:
column_ids.extend(("time_elapsed", "time_left", "time_elapsed_data", "time_left_data"))
column_values.extend((self.get_helapsed(elapsed), self.get_hleft(left), elapsed, left))
if self.tree_view.get_row_value(iterator, "current_bytes_data") != current_byte_offset:
column_ids.append("current_bytes_data")
column_values.append(current_byte_offset)
should_update_size = True
if self.tree_view.get_row_value(iterator, "size_data") != size:
column_ids.append("size_data")
column_values.append(size)
should_update_size = True
if self.tree_view.get_row_value(iterator, "queue_position_data") != queue_position:
column_ids.extend(("queue_position", "queue_position_data"))
column_values.extend((self.get_hqueue_position(queue_position), queue_position))
if should_update_size:
column_ids.extend(("percent", "size"))
column_values.extend((
self.get_percent(current_byte_offset, size),
self.get_hsize(current_byte_offset, size)
))
if column_ids:
self.tree_view.set_row_values(iterator, column_ids, column_values)
return False
expand_allowed = self.initialized
expand_user = False
expand_folder = False
user_iterator = None
user_folder_path_iterator = None
parent_iterator = None
select_iterator = None
user = transfer.username
folder_path, _separator, basename = transfer.virtual_path.rpartition("\\")
original_folder_path = folder_path = self.get_transfer_folder_path(transfer)
is_sensitive = (status != TransferStatus.USER_LOGGED_OFF)
if use_reverse_file_path:
parts = folder_path.split(self.path_separator)
parts.reverse()
folder_path = self.path_separator.join(parts)
if not self.tree_view.iterators:
# Hide tab description
self.container.get_parent().set_visible(True)
if self.grouping_mode != "ungrouped":
# Group by folder or user
empty_int = 0
empty_str = ""
if user not in self.users:
# Create parent if it doesn't exist
iterator = self.tree_view.add_row(
[
user,
empty_str,
empty_str,
empty_str,
translated_status,
empty_str,
empty_int,
empty_str,
empty_str,
empty_str,
empty_str,
empty_int,
empty_int,
empty_int,
empty_int,
empty_int,
empty_int,
is_sensitive,
Transfer(user, status=status), # Dummy Transfer object
self.row_id
], select_row=False
)
if expand_allowed:
expand_user = self.grouping_mode == "folder_grouping" or self.expand_button.get_active()
self.row_id += 1
self.users[user] = (iterator, [])
user_iterator, user_child_transfers = self.users[user]
parent_iterator = user_iterator
if select_parent:
select_iterator = parent_iterator
if self.grouping_mode == "folder_grouping":
# Group by folder
# Make sure we don't add files to the wrong user in the TreeView
user_folder_path = user + original_folder_path
if user_folder_path not in self.paths:
path_transfer = Transfer( # Dummy Transfer object
user, folder_path=original_folder_path, status=status
)
iterator = self.tree_view.add_row(
[
user,
folder_path,
empty_str,
empty_str,
translated_status,
empty_str,
empty_int,
empty_str,
empty_str,
empty_str,
empty_str,
empty_int,
empty_int,
empty_int,
empty_int,
empty_int,
empty_int,
is_sensitive,
path_transfer,
self.row_id
], select_row=False, parent_iterator=user_iterator
)
user_child_transfers.append(path_transfer)
expand_folder = expand_allowed and self.expand_button.get_active()
self.row_id += 1
self.paths[user_folder_path] = (iterator, [])
user_folder_path_iterator, user_folder_path_child_transfers = self.paths[user_folder_path]
parent_iterator = user_folder_path_iterator
user_folder_path_child_transfers.append(transfer)
if select_parent and (expand_user or self.tree_view.is_row_expanded(user_iterator)):
select_iterator = parent_iterator
# Group by folder, path not visible in file rows
folder_path = ""
else:
user_child_transfers.append(transfer)
else:
# No grouping
if user not in self.users:
self.users[user] = (None, [])
user_iterator, user_child_transfers = self.users[user]
user_child_transfers.append(transfer)
# Add a new transfer
transfer.iterator = self.tree_view.add_row([
user,
folder_path,
get_file_type_icon_name(basename),
basename,
translated_status,
self.get_hqueue_position(queue_position),
self.get_percent(current_byte_offset, size),
self.get_hsize(current_byte_offset, size),
self.get_hspeed(speed),
self.get_helapsed(elapsed),
self.get_hleft(left),
size,
current_byte_offset,
speed,
queue_position,
elapsed,
left,
is_sensitive,
transfer,
self.row_id
], select_row=False, parent_iterator=parent_iterator)
self.row_id += 1
if expand_user and user_iterator is not None:
self.tree_view.expand_row(user_iterator)
if expand_folder and user_folder_path_iterator is not None:
self.tree_view.expand_row(user_folder_path_iterator)
if select_iterator and (not self.tree_view.is_row_selected(select_iterator)
or self.tree_view.get_num_selected_rows() != 1):
# Select parent row of newly added transfer, and scroll to it.
# Unselect any other rows to prevent accidental actions on previously
# selected transfers.
self.tree_view.unselect_all_rows()
self.tree_view.select_row(select_iterator, expand_rows=False)
return True
def clear_model(self):
self.initialized = False
self.users.clear()
self.paths.clear()
self.pending_folder_rows.clear()
self.pending_user_rows.clear()
self.selected_transfers.clear()
self.selected_users.clear()
self.tree_view.clear()
self.row_id = 0
for transfer in self.transfer_list:
transfer.iterator = self.PENDING_ITERATOR_REBUILD
def get_transfer_folder_path(self, _transfer):
# Implemented in subclasses
raise NotImplementedError
def retry_selected_transfers(self):
# Implemented in subclasses
raise NotImplementedError
def abort_selected_transfers(self):
# Implemented in subclasses
raise NotImplementedError
def remove_selected_transfers(self):
# Implemented in subclasses
raise NotImplementedError
def abort_transfer(self, transfer, status_message=None, update_parent=True):
if status_message is not None and status_message != TransferStatus.QUEUED:
self.update_model(transfer, update_parent=update_parent)
def abort_transfers(self, _transfers, _status_message=None):
self.update_parent_rows()
def clear_transfer(self, transfer, update_parent=True):
iterator = transfer.iterator
transfer.iterator = None
if not iterator or iterator in self.PENDING_ITERATORS:
return
user = transfer.username
if self.grouping_mode == "folder_grouping":
user_folder_path = user + self.get_transfer_folder_path(transfer)
_user_folder_path_iter, user_folder_path_child_transfers = self.paths[user_folder_path]
user_folder_path_child_transfers.remove(transfer)
else:
_user_iter, user_child_transfers = self.users[user]
user_child_transfers.remove(transfer)
if self.grouping_mode == "ungrouped" and not user_child_transfers:
del self.users[user]
self.tree_view.remove_row(iterator)
if update_parent:
self.update_parent_rows(transfer)
self.update_num_users_files()
if not self.tree_view.iterators:
# Show tab description
self.container.get_parent().set_visible(False)
def clear_transfers(self, *_args):
self.update_parent_rows()
def add_popup_menu_user(self, popup, user):
popup.add_items(
("", None),
("#" + _("Select User's Transfers"), self.on_select_user_transfers, user)
)
popup.update_model()
popup.toggle_user_items()
def populate_popup_menu_users(self):
self.popup_menu_users.clear()
if not self.selected_users:
return
# Multiple users, create submenus for some of them
if len(self.selected_users) > 1:
for user in islice(self.selected_users, 20):
popup = UserPopupMenu(self.window.application, username=user, tab_name="transfers")
self.add_popup_menu_user(popup, user)
self.popup_menu_users.add_items((">" + user, popup))
self.popup_menu_users.update_model()
return
# Single user, add items directly to "User Actions" submenu
user = next(iter(self.selected_users), None)
self.popup_menu_users.setup_user_menu(user)
self.add_popup_menu_user(self.popup_menu_users, user)
def on_expand_tree(self, *_args):
if not self.expand_button.get_visible():
return
expanded = self.expand_button.get_active()
if expanded:
icon_name = "view-restore-symbolic"
self.tree_view.expand_all_rows()
else:
icon_name = "view-fullscreen-symbolic"
self.tree_view.collapse_all_rows()
if self.grouping_mode == "folder_grouping":
self.tree_view.expand_root_rows()
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.expand_icon.set_from_icon_name(icon_name, *icon_args)
config.sections["transfers"][f"{self.type}sexpanded"] = expanded
config.write_configuration()
def on_toggle_tree(self, action, state):
mode = state.get_string()
active = mode != "ungrouped"
popover = self.grouping_button.get_popover()
if popover is not None:
popover.set_visible(False)
if GTK_API_VERSION >= 4:
# Ensure buttons are flat in libadwaita
css_class_function = add_css_class if active else remove_css_class
css_class_function(widget=self.grouping_button.get_parent(), css_class="linked")
config.sections["transfers"][f"group{self.type}s"] = mode
self.tree_view.set_show_expanders(active)
self.expand_button.set_visible(active)
self.grouping_mode = mode
self.clear_model()
self.tree_view.has_tree = active
self.tree_view.create_model()
if self.transfer_list:
self.update_model()
action.set_state(state)
def on_popup_menu(self, menu, _widget):
self.select_transfers()
menu.set_num_selected_files(len(self.selected_transfers))
self.populate_popup_menu_users()
def on_file_path_tooltip(self, treeview, iterator):
transfer = treeview.get_row_value(iterator, "transfer_data")
return transfer.virtual_path or self.get_transfer_folder_path(transfer)
def on_row_activated(self, _treeview, iterator, _column_id):
if self.tree_view.collapse_row(iterator):
return
if self.tree_view.expand_row(iterator):
return
self.select_transfers()
action = config.sections["transfers"][f"{self.type}_doubleclick"]
if action == 1: # Open File
self.on_open_file()
elif action == 2: # Open in File Manager
self.on_open_file_manager()
elif action == 3: # Search
self.on_file_search()
elif action == 4: # Pause / Abort
self.abort_selected_transfers()
elif action == 5: # Remove
self.remove_selected_transfers()
elif action == 6: # Resume / Retry
self.retry_selected_transfers()
elif action == 7: # Browse Folder
self.on_browse_folder()
def on_select_user_transfers(self, _action, _parameter, selected_user):
if not self.selected_users:
return
_user_iterator, user_child_transfers = self.users[selected_user]
self.tree_view.unselect_all_rows()
for transfer in user_child_transfers:
iterator = transfer.iterator
if iterator:
self.tree_view.select_row(iterator, should_scroll=False)
continue
# Dummy Transfer object for folder rows
user_folder_path = transfer.username + self.get_transfer_folder_path(transfer)
user_folder_path_data = self.paths.get(user_folder_path)
if not user_folder_path_data:
continue
_user_folder_path_iter, user_folder_path_child_transfers = user_folder_path_data
for i_transfer in user_folder_path_child_transfers:
self.tree_view.select_row(i_transfer.iterator, should_scroll=False)
def on_abort_transfers_accelerator(self, *_args):
"""T - abort transfer."""
self.select_transfers()
self.abort_selected_transfers()
return True
def on_retry_transfers_accelerator(self, *_args):
"""R - retry transfers."""
self.select_transfers()
self.retry_selected_transfers()
return True
def on_remove_transfers_accelerator(self, *_args):
"""Delete - remove transfers."""
self.select_transfers()
self.remove_selected_transfers()
return True
def on_file_properties_accelerator(self, *_args):
"""Alt+Return - show file properties dialog."""
self.select_transfers()
self.on_file_properties()
return True
def on_user_profile(self, *_args):
username = next(iter(self.selected_users), None)
if username:
core.userinfo.show_user(username)
def on_file_properties(self, *_args):
data = []
selected_size = 0
selected_length = 0
for transfer in self.selected_transfers:
username = transfer.username
watched_user = core.users.watched.get(username)
speed = 0
file_path = transfer.virtual_path
file_size = transfer.size
file_attributes = transfer.file_attributes
_bitrate, length, *_unused = FileListMessage.parse_file_attributes(file_attributes)
selected_size += file_size
if length:
selected_length += length
folder_path, _separator, basename = file_path.rpartition("\\")
if watched_user is not None:
speed = watched_user.upload_speed or 0
data.append({
"user": transfer.username,
"file_path": file_path,
"basename": basename,
"virtual_folder_path": folder_path,
"real_folder_path": transfer.folder_path,
"queue_position": transfer.queue_position,
"speed": speed,
"size": file_size,
"file_attributes": file_attributes,
"country_code": core.users.countries.get(username)
})
if data:
if self.file_properties is None:
self.file_properties = FileProperties(self.window.application)
self.file_properties.update_properties(data, selected_size, selected_length)
self.file_properties.present()
def on_copy_url(self, *_args):
# Implemented in subclasses
raise NotImplementedError
def on_copy_folder_url(self, *_args):
# Implemented in subclasses
raise NotImplementedError
def on_copy_file_path(self, *_args):
transfer = next(iter(self.selected_transfers), None)
if transfer:
clipboard.copy_text(transfer.virtual_path)
def on_open_file(self, *_args):
# Implemented in subclasses
raise NotImplementedError
def on_open_file_manager(self, *_args):
# Implemented in subclasses
raise NotImplementedError
def on_browse_folder(self, *_args):
# Implemented in subclasses
raise NotImplementedError
def on_retry_transfer(self, *_args):
self.select_transfers()
self.retry_selected_transfers()
def on_abort_transfer(self, *_args):
self.select_transfers()
self.abort_selected_transfers()
def on_remove_transfer(self, *_args):
self.select_transfers()
self.remove_selected_transfers()
| 44,706 | Python | .py | 944 | 34.802966 | 117 | 0.592004 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,441 | application.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/application.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
import threading
import time
import gi
from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
import pynicotine
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.logfacility import log
from pynicotine.shares import PermissionLevel
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import open_uri
GTK_API_VERSION = Gtk.get_major_version()
GTK_MINOR_VERSION = Gtk.get_minor_version()
GTK_MICRO_VERSION = Gtk.get_micro_version()
GTK_GUI_FOLDER_PATH = os.path.normpath(os.path.dirname(os.path.realpath(__file__)))
LIBADWAITA_API_VERSION = 0
if GTK_API_VERSION >= 4:
try:
if "NICOTINE_LIBADWAITA" not in os.environ:
os.environ["NICOTINE_LIBADWAITA"] = str(int(
sys.platform in {"win32", "darwin"} or "gnome" in os.environ.get("XDG_CURRENT_DESKTOP", "").lower()
))
if os.environ.get("NICOTINE_LIBADWAITA") == "1":
gi.require_version("Adw", "1")
from gi.repository import Adw # pylint: disable=ungrouped-imports
LIBADWAITA_API_VERSION = Adw.MAJOR_VERSION
except (ImportError, ValueError):
pass
class Application:
def __init__(self, start_hidden, ci_mode, multi_instance):
self._instance = Gtk.Application(application_id=pynicotine.__application_id__)
GLib.set_application_name(pynicotine.__application_name__)
GLib.set_prgname(pynicotine.__application_id__)
if multi_instance:
self._instance.set_flags(Gio.ApplicationFlags.NON_UNIQUE)
self.start_hidden = start_hidden
self.ci_mode = ci_mode
self.window = None
self.about = None
self.fast_configure = None
self.preferences = None
self.file_properties = None
self.shortcuts = None
self.statistics = None
self.wishlist = None
self.tray_icon = None
self.spell_checker = None
# Show errors in the GUI from here on
sys.excepthook = self.on_critical_error
self._instance.connect("activate", self.on_activate)
self._instance.connect("shutdown", self.on_shutdown)
for event_name, callback in (
("confirm-quit", self.on_confirm_quit),
("invalid-password", self.on_invalid_password),
("invalid-username", self.on_invalid_password),
("quit", self._instance.quit),
("server-login", self._update_user_status),
("server-disconnect", self._update_user_status),
("setup", self.on_fast_configure),
("shares-unavailable", self.on_shares_unavailable),
("show-notification", self._show_notification),
("show-chatroom-notification", self._show_chatroom_notification),
("show-download-notification", self._show_download_notification),
("show-private-chat-notification", self._show_private_chat_notification),
("show-search-notification", self._show_search_notification),
("user-status", self.on_user_status)
):
events.connect(event_name, callback)
def run(self):
return self._instance.run()
def add_action(self, action):
self._instance.add_action(action)
def lookup_action(self, action_name):
return self._instance.lookup_action(action_name)
def remove_action(self, action):
self._instance.remove_action(action)
def add_window(self, window):
self._instance.add_window(window)
def _set_up_actions(self):
# Regular actions
for action_name, callback, parameter_type, is_enabled in (
# General
("disabled", None, None, False),
("connect", self.on_connect, None, True),
("disconnect", self.on_disconnect, None, False),
("soulseek-privileges", self.on_soulseek_privileges, None, False),
("away", self.on_away, None, True),
("away-accel", self.on_away_accelerator, None, False),
("message-downloading-users", self.on_message_downloading_users, None, False),
("message-buddies", self.on_message_buddies, None, False),
("wishlist", self.on_wishlist, None, True),
("confirm-quit", self.on_confirm_quit_request, None, True),
("force-quit", self.on_force_quit_request, None, True),
("quit", self.on_quit_request, None, True),
# Shares
("rescan-shares", self.on_rescan_shares, None, True),
("browse-public-shares", self.on_browse_public_shares, None, True),
("browse-buddy-shares", self.on_browse_buddy_shares, None, True),
("browse-trusted-shares", self.on_browse_trusted_shares, None, True),
("load-shares-from-disk", self.on_load_shares_from_disk, None, True),
# Configuration
("preferences", self.on_preferences, None, True),
("configure-shares", self.on_configure_shares, None, True),
("configure-downloads", self.on_configure_downloads, None, True),
("configure-uploads", self.on_configure_uploads, None, True),
("configure-chats", self.on_configure_chats, None, True),
("configure-searches", self.on_configure_searches, None, True),
("configure-ignored-users", self.on_configure_ignored_users, None, True),
("configure-account", self.on_configure_account, None, True),
("configure-user-profile", self.on_configure_user_profile, None, True),
("personal-profile", self.on_personal_profile, None, True),
# Notifications
("chatroom-notification-activated", self.on_chatroom_notification_activated, "s", True),
("download-notification-activated", self.on_downloads, None, True),
("private-chat-notification-activated", self.on_private_chat_notification_activated, "s", True),
("search-notification-activated", self.on_search_notification_activated, "s", True),
# Help
("keyboard-shortcuts", self.on_keyboard_shortcuts, None, True),
("setup-assistant", self.on_fast_configure, None, True),
("transfer-statistics", self.on_transfer_statistics, None, True),
("report-bug", self.on_report_bug, None, True),
("improve-translations", self.on_improve_translations, None, True),
("about", self.on_about, None, True)
):
if parameter_type:
parameter_type = GLib.VariantType(parameter_type)
action = Gio.SimpleAction(name=action_name, parameter_type=parameter_type, enabled=is_enabled)
if callback:
action.connect("activate", callback)
self.add_action(action)
self.lookup_action("away-accel").cooldown_time = 0 # needed to prevent server ban
# Stateful actions
enabled_logs = config.sections["logging"]["debugmodes"]
for action_name, callback, state in (
# Logging
("log-downloads", self.on_debug_downloads, ("download" in enabled_logs)),
("log-uploads", self.on_debug_uploads, ("upload" in enabled_logs)),
("log-searches", self.on_debug_searches, ("search" in enabled_logs)),
("log-chat", self.on_debug_chat, ("chat" in enabled_logs)),
("log-connections", self.on_debug_connections, ("connection" in enabled_logs)),
("log-messages", self.on_debug_messages, ("message" in enabled_logs)),
("log-transfers", self.on_debug_transfers, ("transfer" in enabled_logs)),
("log-miscellaneous", self.on_debug_miscellaneous, ("miscellaneous" in enabled_logs))
):
action = Gio.SimpleAction(name=action_name, state=GLib.Variant.new_boolean(state))
action.connect("change-state", callback)
self.add_action(action)
def _set_accels_for_action(self, action, accels):
if GTK_API_VERSION >= 4 and sys.platform == "darwin":
# Use Command key instead of Ctrl in accelerators on macOS
for i, accelerator in enumerate(accels):
accels[i] = accelerator.replace("<Primary>", "<Meta>")
self._instance.set_accels_for_action(action, accels)
def _set_up_action_accels(self):
for action_name, accelerators in (
# Global accelerators
("app.connect", ["<Shift><Primary>c"]),
("app.disconnect", ["<Shift><Primary>d"]),
("app.away-accel", ["<Shift><Primary>a"]),
("app.wishlist", ["<Shift><Primary>w"]),
("app.confirm-quit", ["<Primary>q"]),
("app.force-quit", ["<Primary><Alt>q"]),
("app.quit", ["<Primary>q"]), # Only used to show accelerator in menus
("app.rescan-shares", ["<Shift><Primary>r"]),
("app.keyboard-shortcuts", ["<Primary>question", "F1"]),
("app.preferences", ["<Primary>comma", "<Primary>p"]),
# Window accelerators
("win.main-menu", ["F10"]),
("win.context-menu", ["<Shift>F10"]),
("win.change-focus-view", ["F6"]),
("win.show-log-pane", ["<Primary>l"]),
("win.reopen-closed-tab", ["<Primary><Shift>t"]),
("win.close-tab", ["<Primary>F4", "<Primary>w"]),
("win.cycle-tabs", ["<Control>Tab"]),
("win.cycle-tabs-reverse", ["<Control><Shift>Tab"]),
# Other accelerators (logic defined elsewhere, actions only used for shortcuts dialog)
("accel.cut-clipboard", ["<Primary>x"]),
("accel.copy-clipboard", ["<Primary>c"]),
("accel.paste-clipboard", ["<Primary>v"]),
("accel.insert-emoji", ["<Control>period"]),
("accel.select-all", ["<Primary>a"]),
("accel.find", ["<Primary>f"]),
("accel.find-next-match", ["<Primary>g"]),
("accel.find-previous-match", ["<Shift><Primary>g"]),
("accel.refresh", ["<Primary>r", "F5"]),
("accel.remove", ["Delete"]),
("accel.toggle-row-expand", ["<Primary>backslash"]),
("accel.save", ["<Primary>s"]),
("accel.download-to", ["<Primary>Return"]),
("accel.file-properties", ["<Alt>Return"]),
("accel.back", ["BackSpace"]),
("accel.retry-transfer", ["r"]),
("accel.abort-transfer", ["t"])
):
self._set_accels_for_action(action_name, accelerators)
numpad_accels = []
for num in range(1, 10):
numpad_accels.append(f"<Alt>KP_{num}")
self._set_accels_for_action(f"win.primary-tab-{num}", [f"<Primary>{num}", f"<Alt>{num}"])
# Disable Alt+1-9 accelerators for numpad keys to avoid conflict with Alt codes
self._set_accels_for_action("app.disabled", numpad_accels)
if GTK_API_VERSION == 3 or sys.platform != "darwin":
return
# Add some missing macOS shortcuts here until they are fixed upstream
for widget in (Gtk.Text, Gtk.TextView):
for accelerator, step, count, extend in (
("<Meta>Left|<Meta>KP_Left", Gtk.MovementStep.DISPLAY_LINE_ENDS, -1, False),
("<Shift><Meta>Left|<Shift><Meta>KP_Left", Gtk.MovementStep.DISPLAY_LINE_ENDS, -1, True),
("<Meta>Right|<Meta>KP_Right", Gtk.MovementStep.DISPLAY_LINE_ENDS, 1, False),
("<Shift><Meta>Right|<Shift><Meta>KP_Right", Gtk.MovementStep.DISPLAY_LINE_ENDS, 1, True),
("<Alt>Left|<Alt>KP_Left", Gtk.MovementStep.WORDS, -1, False),
("<Alt>Right|<Alt>KP_Right", Gtk.MovementStep.WORDS, 1, False)
):
widget.add_shortcut(
Gtk.Shortcut(
trigger=Gtk.ShortcutTrigger.parse_string(accelerator),
action=Gtk.SignalAction(signal_name="move-cursor"),
arguments=GLib.Variant.new_tuple(
GLib.Variant.new_int32(step),
GLib.Variant.new_int32(count),
GLib.Variant.new_boolean(extend)
)
)
)
def _update_user_status(self, *_args):
status = core.users.login_status
is_online = (status != UserStatus.OFFLINE)
self.lookup_action("connect").set_enabled(not is_online)
for action_name in ("disconnect", "soulseek-privileges", "away-accel",
"message-downloading-users", "message-buddies"):
self.lookup_action(action_name).set_enabled(is_online)
self.tray_icon.update()
# Primary Menus #
@staticmethod
def _add_connection_section(menu):
menu.add_items(
("=" + _("_Connect"), "app.connect"),
("=" + _("_Disconnect"), "app.disconnect"),
("#" + _("Soulseek _Privileges"), "app.soulseek-privileges"),
("", None)
)
@staticmethod
def _add_preferences_item(menu):
menu.add_items(("^" + _("_Preferences"), "app.preferences"))
def _add_quit_item(self, menu):
menu.add_items(
("", None),
("^" + _("_Quit"), "app.quit")
)
def _create_file_menu(self):
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
menu = PopupMenu(self)
self._add_connection_section(menu)
self._add_preferences_item(menu)
self._add_quit_item(menu)
return menu
def _add_browse_shares_section(self, menu):
menu.add_items(
("#" + _("Browse _Public Shares"), "app.browse-public-shares"),
("#" + _("Browse _Buddy Shares"), "app.browse-buddy-shares"),
("#" + _("Browse _Trusted Shares"), "app.browse-trusted-shares")
)
def _create_shares_menu(self):
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
menu = PopupMenu(self)
menu.add_items(
("#" + _("_Rescan Shares"), "app.rescan-shares"),
("#" + _("Configure _Shares"), "app.configure-shares"),
("", None)
)
self._add_browse_shares_section(menu)
return menu
def _create_browse_shares_menu(self):
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
menu = PopupMenu(self)
self._add_browse_shares_section(menu)
return menu
def _create_help_menu(self):
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
menu = PopupMenu(self)
menu.add_items(
("#" + _("_Keyboard Shortcuts"), "app.keyboard-shortcuts"),
("#" + _("_Setup Assistant"), "app.setup-assistant"),
("#" + _("_Transfer Statistics"), "app.transfer-statistics"),
("", None),
("#" + _("Report a _Bug"), "app.report-bug"),
("#" + _("Improve T_ranslations"), "app.improve-translations"),
("", None),
("^" + _("_About Nicotine+"), "app.about")
)
return menu
def _set_up_menubar(self):
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
menu = PopupMenu(self)
menu.add_items(
(">" + _("_File"), self._create_file_menu()),
(">" + _("_Shares"), self._create_shares_menu()),
(">" + _("_Help"), self._create_help_menu())
)
menu.update_model()
self._instance.set_menubar(menu.model)
def create_hamburger_menu(self):
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
menu = PopupMenu(self)
self._add_connection_section(menu)
menu.add_items(
("#" + _("_Rescan Shares"), "app.rescan-shares"),
(">" + _("_Browse Shares"), self._create_browse_shares_menu()),
("#" + _("Configure _Shares"), "app.configure-shares"),
("", None),
(">" + _("_Help"), self._create_help_menu())
)
self._add_preferences_item(menu)
self._add_quit_item(menu)
menu.update_model()
return menu
# Notifications #
def _show_notification(self, message, title=None, action=None, action_target=None, high_priority=False):
if title is None:
title = pynicotine.__application_name__
title = title.strip()
message = message.strip()
try:
if sys.platform == "win32":
self.tray_icon.show_notification(
title=title, message=message, action=action, action_target=action_target,
high_priority=high_priority
)
return
priority = Gio.NotificationPriority.HIGH if high_priority else Gio.NotificationPriority.NORMAL
notification = Gio.Notification.new(title)
notification.set_body(message)
notification.set_priority(priority)
# Fix notification icon in Snap package
snap_name = os.environ.get("SNAP_NAME")
if snap_name:
notification.set_icon(Gio.ThemedIcon(name=f"snap.{snap_name}.{pynicotine.__application_id__}"))
# Unity doesn't support default click actions, and replaces the notification with a dialog.
# Disable actions to prevent this from happening.
if action and os.environ.get("XDG_CURRENT_DESKTOP", "").lower() != "unity":
if action_target:
notification.set_default_action_and_target(action, GLib.Variant.new_string(action_target))
else:
notification.set_default_action(action)
self._instance.send_notification(id=None, notification=notification)
if config.sections["notifications"]["notification_popup_sound"]:
Gdk.Display.get_default().beep()
except Exception as error:
log.add(_("Unable to show notification: %s"), error)
def _show_chatroom_notification(self, room, message, title=None, high_priority=False):
self._show_notification(
message, title, action="app.chatroom-notification-activated", action_target=room,
high_priority=high_priority
)
if high_priority:
self.window.set_urgency_hint(True)
def _show_download_notification(self, message, title=None, high_priority=False):
self._show_notification(
message, title, action="app.download-notification-activated",
high_priority=high_priority
)
def _show_private_chat_notification(self, user, message, title=None):
self._show_notification(
message, title, action="app.private-chat-notification-activated", action_target=user,
high_priority=True
)
self.window.set_urgency_hint(True)
def _show_search_notification(self, search_token, message, title=None):
self._show_notification(
message, title, action="app.search-notification-activated", action_target=search_token,
high_priority=True
)
# Core Events #
def on_confirm_quit_response(self, dialog, response_id, _data):
should_finish_uploads = dialog.get_option_value()
if response_id == "quit":
if should_finish_uploads:
core.uploads.request_shutdown()
else:
core.quit()
elif response_id == "run_background":
self.window.hide()
def on_confirm_quit(self):
has_active_uploads = core.uploads.has_active_uploads()
if not self.window.is_visible():
# Never show confirmation dialog when main window is hidden
core.quit()
return
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
if has_active_uploads:
message = _("You are still uploading files. Do you really want to exit?")
option_label = _("Wait for uploads to finish")
else:
message = _("Do you really want to exit?")
option_label = None
buttons = [
("cancel", _("_No")),
("quit", _("_Quit")),
("run_background", _("_Run in Background"))
]
OptionDialog(
parent=self.window,
title=_("Quit Nicotine+"),
message=message,
buttons=buttons,
option_label=option_label,
callback=self.on_confirm_quit_response
).present()
def on_shares_unavailable_response(self, _dialog, response_id, _data):
core.shares.rescan_shares(force=(response_id == "force_rescan"))
def on_shares_unavailable(self, shares):
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
shares_list_message = ""
for virtual_name, folder_path in shares:
shares_list_message += f'• "{virtual_name}" {folder_path}\n'
OptionDialog(
parent=self.window,
title=_("Shares Not Available"),
message=_("Verify that external disks are mounted and folder permissions are correct."),
long_message=shares_list_message,
buttons=[
("cancel", _("_Cancel")),
("ok", _("_Retry")),
("force_rescan", _("_Force Rescan"))
],
destructive_response_id="force_rescan",
callback=self.on_shares_unavailable_response
).present()
def on_invalid_password(self):
self.on_fast_configure(invalid_password=True)
def on_user_status(self, msg):
if msg.user == core.users.login_username:
self._update_user_status()
# Actions #
def on_connect(self, *_args):
if core.users.login_status == UserStatus.OFFLINE:
core.connect()
def on_disconnect(self, *_args):
if core.users.login_status != UserStatus.OFFLINE:
core.disconnect()
def on_soulseek_privileges(self, *_args):
core.users.request_check_privileges(should_open_url=True)
def on_preferences(self, *_args, page_id="network"):
if self.preferences is None:
from pynicotine.gtkgui.dialogs.preferences import Preferences
self.preferences = Preferences(self)
self.preferences.set_settings()
self.preferences.set_active_page(page_id)
self.preferences.present()
def on_set_debug_level(self, action, state, level):
if state.get_boolean():
log.add_log_level(level)
else:
log.remove_log_level(level)
action.set_state(state)
def on_debug_downloads(self, action, state):
self.on_set_debug_level(action, state, "download")
def on_debug_uploads(self, action, state):
self.on_set_debug_level(action, state, "upload")
def on_debug_searches(self, action, state):
self.on_set_debug_level(action, state, "search")
def on_debug_chat(self, action, state):
self.on_set_debug_level(action, state, "chat")
def on_debug_connections(self, action, state):
self.on_set_debug_level(action, state, "connection")
def on_debug_messages(self, action, state):
self.on_set_debug_level(action, state, "message")
def on_debug_transfers(self, action, state):
self.on_set_debug_level(action, state, "transfer")
def on_debug_miscellaneous(self, action, state):
self.on_set_debug_level(action, state, "miscellaneous")
def on_fast_configure(self, *_args, invalid_password=False):
if self.fast_configure is None:
from pynicotine.gtkgui.dialogs.fastconfigure import FastConfigure
self.fast_configure = FastConfigure(self)
if invalid_password and self.fast_configure.is_visible():
self.fast_configure.hide()
self.fast_configure.invalid_password = invalid_password
self.fast_configure.present()
def on_keyboard_shortcuts(self, *_args):
if self.shortcuts is None:
from pynicotine.gtkgui.dialogs.shortcuts import Shortcuts
self.shortcuts = Shortcuts(self)
self.shortcuts.present()
def on_transfer_statistics(self, *_args):
if self.statistics is None:
from pynicotine.gtkgui.dialogs.statistics import Statistics
self.statistics = Statistics(self)
self.statistics.present()
@staticmethod
def on_report_bug(*_args):
open_uri(pynicotine.__issue_tracker_url__)
@staticmethod
def on_improve_translations(*_args):
open_uri(pynicotine.__translations_url__)
def on_wishlist(self, *_args):
if self.wishlist is None:
from pynicotine.gtkgui.dialogs.wishlist import WishList
self.wishlist = WishList(self)
self.wishlist.present()
def on_about(self, *_args):
if self.about is None:
from pynicotine.gtkgui.dialogs.about import About
self.about = About(self)
self.about.present()
def on_chatroom_notification_activated(self, _action, room_variant):
room = room_variant.get_string()
core.chatrooms.show_room(room)
self.window.present()
def on_private_chat_notification_activated(self, _action, user_variant):
user = user_variant.get_string()
core.privatechat.show_user(user)
self.window.present()
def on_search_notification_activated(self, _action, search_token_variant):
search_token = int(search_token_variant.get_string())
core.search.show_search(search_token)
self.window.present()
def on_downloads(self, *_args):
self.window.change_main_page(self.window.downloads_page)
self.window.present()
def on_uploads(self, *_args):
self.window.change_main_page(self.window.uploads_page)
self.window.present()
def on_private_chat(self, *_args):
self.window.change_main_page(self.window.private_page)
self.window.present()
def on_chat_rooms(self, *_args):
self.window.change_main_page(self.window.chatrooms_page)
self.window.present()
def on_searches(self, *_args):
self.window.change_main_page(self.window.search_page)
self.window.present()
def on_message_users_response(self, dialog, _response_id, target):
message = dialog.get_entry_value()
if message:
core.privatechat.send_message_users(target, message)
def on_message_downloading_users(self, *_args):
from pynicotine.gtkgui.widgets.dialogs import EntryDialog
EntryDialog(
parent=self.window,
title=_("Message Downloading Users"),
message=_("Send private message to all users who are downloading from you:"),
action_button_label=_("_Send Message"),
callback=self.on_message_users_response,
callback_data="downloading",
show_emoji_icon=True
).present()
def on_message_buddies(self, *_args):
from pynicotine.gtkgui.widgets.dialogs import EntryDialog
EntryDialog(
parent=self.window,
title=_("Message Buddies"),
message=_("Send private message to all online buddies:"),
action_button_label=_("_Send Message"),
callback=self.on_message_users_response,
callback_data="buddies",
show_emoji_icon=True
).present()
def on_rescan_shares(self, *_args):
core.shares.rescan_shares()
def on_browse_public_shares(self, *_args):
core.userbrowse.browse_local_shares(permission_level=PermissionLevel.PUBLIC, new_request=True)
def on_browse_buddy_shares(self, *_args):
core.userbrowse.browse_local_shares(permission_level=PermissionLevel.BUDDY, new_request=True)
def on_browse_trusted_shares(self, *_args):
core.userbrowse.browse_local_shares(permission_level=PermissionLevel.TRUSTED, new_request=True)
def on_load_shares_from_disk_selected(self, selected_file_paths, _data):
for file_path in selected_file_paths:
core.userbrowse.load_shares_list_from_disk(file_path)
def on_load_shares_from_disk(self, *_args):
from pynicotine.gtkgui.widgets.filechooser import FileChooser
FileChooser(
parent=self.window,
title=_("Select a Saved Shares List File"),
callback=self.on_load_shares_from_disk_selected,
initial_folder=core.userbrowse.create_user_shares_folder(),
select_multiple=True
).present()
def on_personal_profile(self, *_args):
core.userinfo.show_user()
def on_configure_shares(self, *_args):
self.on_preferences(page_id="shares")
def on_configure_searches(self, *_args):
self.on_preferences(page_id="searches")
def on_configure_chats(self, *_args):
self.on_preferences(page_id="chats")
def on_configure_downloads(self, *_args):
self.on_preferences(page_id="downloads")
def on_configure_uploads(self, *_args):
self.on_preferences(page_id="uploads")
def on_configure_ignored_users(self, *_args):
self.on_preferences(page_id="ignored-users")
def on_configure_account(self, *_args):
self.on_preferences(page_id="network")
def on_configure_user_profile(self, *_args):
self.on_preferences(page_id="user-profile")
def on_window_hide_unhide(self, *_args):
if self.window.is_visible():
self.window.hide()
return
self.window.present()
def on_away_accelerator(self, action, *_args):
"""Ctrl+H: Away/Online toggle."""
current_time = time.monotonic()
if (current_time - action.cooldown_time) >= 1:
# Prevent rapid key-repeat toggling to avoid server ban
self.on_away()
action.cooldown_time = current_time
def on_away(self, *_args):
"""Away/Online status button."""
if core.users.login_status == UserStatus.OFFLINE:
core.connect()
return
core.users.set_away_mode(core.users.login_status != UserStatus.AWAY, save_state=True)
# Running #
def _raise_exception(self, exc_value):
raise exc_value
def _show_critical_error_dialog_response(self, _dialog, response_id, data):
loop, error = data
if response_id == "copy_report_bug":
from pynicotine.gtkgui.widgets import clipboard
clipboard.copy_text(error)
open_uri(pynicotine.__issue_tracker_url__)
self._show_critical_error_dialog(error, loop)
return
loop.quit()
def _show_critical_error_dialog(self, error, loop):
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
OptionDialog(
parent=self.window,
title=_("Critical Error"),
message=_("Nicotine+ has encountered a critical error and needs to exit. "
"Please copy the following message and include it in a bug report:"),
long_message=error,
buttons=[
("quit", _("_Quit Nicotine+")),
("copy_report_bug", _("_Copy & Report Bug"))
],
callback=self._show_critical_error_dialog_response,
callback_data=(loop, error)
).present()
def _on_critical_error(self, exc_type, exc_value, exc_traceback):
if self.ci_mode:
core.quit()
self._raise_exception(exc_value)
return
from traceback import format_tb
# Check if exception occurred in a plugin
if core.pluginhandler is not None:
traceback = exc_traceback
while traceback.tb_next:
file_path = traceback.tb_frame.f_code.co_filename
for plugin_name in core.pluginhandler.enabled_plugins:
plugin_path = core.pluginhandler.get_plugin_path(plugin_name)
if file_path.startswith(plugin_path):
core.pluginhandler.show_plugin_error(
plugin_name, exc_type, exc_value, exc_traceback)
return
traceback = traceback.tb_next
# Show critical error dialog
loop = GLib.MainLoop()
gtk_version = f"{Gtk.get_major_version()}.{Gtk.get_minor_version()}.{Gtk.get_micro_version()}"
error = (f"Nicotine+ Version: {pynicotine.__version__}\nGTK Version: {gtk_version}\n"
f"Python Version: {sys.version.split()[0]} ({sys.platform})\n\n"
f"Type: {exc_type}\nValue: {exc_value}\nTraceback: {''.join(format_tb(exc_traceback))}")
self._show_critical_error_dialog(error, loop)
# Keep dialog open if error occurs on startup
loop.run()
# Dialog was closed, quit
sys.excepthook = None
core.quit()
# Process 'quit' event after slight delay in case thread event loop is stuck
GLib.idle_add(lambda: events.process_thread_events() == -1)
# Log exception in terminal
self._raise_exception(exc_value)
def on_critical_error(self, _exc_type, exc_value, _exc_traceback):
if threading.current_thread() is threading.main_thread():
self._on_critical_error(_exc_type, exc_value, _exc_traceback)
return
# Raise exception in the main thread
GLib.idle_add(self._raise_exception, exc_value)
def on_process_thread_events(self):
return events.process_thread_events()
def on_activate(self, *_args):
if self.window:
# Show the window of the running application instance
self.window.present()
return
from pynicotine.gtkgui.mainwindow import MainWindow
from pynicotine.gtkgui.widgets.theme import load_icons
from pynicotine.gtkgui.widgets.trayicon import TrayIcon
# Process thread events 10 times per second.
# High priority to ensure there are no delays.
GLib.timeout_add(100, self.on_process_thread_events, priority=GLib.PRIORITY_HIGH_IDLE)
load_icons()
self._set_up_actions()
self._set_up_action_accels()
self._set_up_menubar()
self.tray_icon = TrayIcon(self)
self.window = MainWindow(self)
core.start()
if config.sections["server"]["auto_connect_startup"]:
core.connect()
# Check command line option and config option
start_hidden = (self.start_hidden or (self.tray_icon.available
and config.sections["ui"]["trayicon"]
and config.sections["ui"]["startup_hidden"]))
if not start_hidden:
self.window.present()
def on_confirm_quit_request(self, *_args):
core.confirm_quit()
def on_force_quit_request(self, *_args):
core.quit()
def on_quit_request(self, *_args):
if not core.uploads.has_active_uploads():
core.quit()
return
core.confirm_quit()
def on_shutdown(self, *_args):
if self.about is not None:
self.about.destroy()
if self.fast_configure is not None:
self.fast_configure.destroy()
if self.preferences is not None:
self.preferences.destroy()
if self.file_properties is not None:
self.file_properties.destroy()
if self.shortcuts is not None:
self.shortcuts.destroy()
if self.statistics is not None:
self.statistics.destroy()
if self.wishlist is not None:
self.wishlist.destroy()
if self.spell_checker is not None:
self.spell_checker.destroy()
if self.window is not None:
self.window.destroy()
if self.tray_icon is not None:
self.tray_icon.destroy()
self.__dict__.clear()
| 36,962 | Python | .py | 763 | 37.710354 | 115 | 0.611345 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,442 | userinfo.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/userinfo.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2008-2010 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import time
from gi.repository import Gdk
from gi.repository import GdkPixbuf
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.application import GTK_MINOR_VERSION
from pynicotine.gtkgui.widgets import clipboard
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.combobox import ComboBox
from pynicotine.gtkgui.widgets.dialogs import EntryDialog
from pynicotine.gtkgui.widgets.filechooser import FileChooserSave
from pynicotine.gtkgui.widgets.iconnotebook import IconNotebook
from pynicotine.gtkgui.widgets.infobar import InfoBar
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.popupmenu import UserPopupMenu
from pynicotine.gtkgui.widgets.textview import TextView
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.theme import get_flag_icon_name
from pynicotine.gtkgui.widgets.theme import remove_css_class
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.logfacility import log
from pynicotine.slskmessages import ConnectionType
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import humanize
from pynicotine.utils import human_speed
class UserInfos(IconNotebook):
def __init__(self, window):
super().__init__(
window,
parent=window.userinfo_content,
parent_page=window.userinfo_page
)
self.page = window.userinfo_page
self.page.id = "userinfo"
self.toolbar = window.userinfo_toolbar
self.toolbar_start_content = window.userinfo_title
self.toolbar_end_content = window.userinfo_end
self.toolbar_default_widget = window.userinfo_entry
self.userinfo_combobox = ComboBox(
container=self.window.userinfo_title, has_entry=True, has_entry_completion=True,
entry=self.window.userinfo_entry, item_selected_callback=self.on_show_user_profile
)
# Events
for event_name, callback in (
("add-buddy", self.add_remove_buddy),
("ban-user", self.ban_unban_user),
("check-privileges", self.check_privileges),
("ignore-user", self.ignore_unignore_user),
("peer-connection-closed", self.peer_connection_error),
("peer-connection-error", self.peer_connection_error),
("quit", self.quit),
("remove-buddy", self.add_remove_buddy),
("server-disconnect", self.server_disconnect),
("server-login", self.server_login),
("unban-user", self.ban_unban_user),
("unignore-user", self.ignore_unignore_user),
("user-country", self.user_country),
("user-info-progress", self.user_info_progress),
("user-info-remove-user", self.remove_user),
("user-info-response", self.user_info_response),
("user-info-show-user", self.show_user),
("user-interests", self.user_interests),
("user-stats", self.user_stats),
("user-status", self.user_status)
):
events.connect(event_name, callback)
def quit(self):
self.freeze()
def destroy(self):
self.userinfo_combobox.destroy()
super().destroy()
def on_focus(self, *_args):
if self.window.current_page_id != self.window.userinfo_page.id:
return True
if self.get_n_pages():
return True
if self.window.userinfo_entry.is_sensitive():
self.window.userinfo_entry.grab_focus()
return True
return False
def on_remove_all_pages(self, *_args):
core.userinfo.remove_all_users()
def on_restore_removed_page(self, page_args):
username, = page_args
core.userinfo.show_user(username)
def on_show_user_profile(self, *_args):
username = self.window.userinfo_entry.get_text().strip()
if not username:
return
self.window.userinfo_entry.set_text("")
core.userinfo.show_user(username)
def show_user(self, user, switch_page=True, **_unused):
page = self.pages.get(user)
if page is None:
self.pages[user] = page = UserInfo(self, user)
self.append_page(page.container, user, focus_callback=page.on_focus,
close_callback=page.on_close, user=user)
page.set_label(self.get_tab_label_inner(page.container))
if switch_page:
self.set_current_page(page.container)
self.window.change_main_page(self.window.userinfo_page)
def remove_user(self, user):
page = self.pages.get(user)
if page is None:
return
page.clear()
self.remove_page(page.container, page_args=(user,))
del self.pages[user]
page.destroy()
def check_privileges(self, _msg):
for page in self.pages.values():
page.update_privileges_button_state()
def ban_unban_user(self, user):
page = self.pages.get(user)
if page is not None:
page.update_ban_button_state()
def ignore_unignore_user(self, user):
page = self.pages.get(user)
if page is not None:
page.update_ignore_button_state()
def add_remove_buddy(self, user, *_args):
page = self.pages.get(user)
if page is not None:
page.update_buddy_button_state()
def peer_connection_error(self, username, conn_type, **_unused):
page = self.pages.get(username)
if page is None:
return
if conn_type == ConnectionType.PEER:
page.peer_connection_error()
def user_stats(self, msg):
page = self.pages.get(msg.user)
if page is not None:
page.user_stats(msg)
def user_status(self, msg):
page = self.pages.get(msg.user)
if page is not None:
self.set_user_status(page.container, msg.user, msg.status)
def user_country(self, user, country_code):
page = self.pages.get(user)
if page is not None:
page.user_country(country_code)
def user_interests(self, msg):
page = self.pages.get(msg.user)
if page is not None:
page.user_interests(msg)
def user_info_progress(self, user, _sock, position, total):
page = self.pages.get(user)
if page is not None:
page.user_info_progress(position, total)
def user_info_response(self, msg):
page = self.pages.get(msg.username)
if page is not None:
page.user_info_response(msg)
def server_login(self, *_args):
for page in self.pages.values():
page.update_ip_address_button_state()
def server_disconnect(self, *_args):
for user, page in self.pages.items():
self.set_user_status(page.container, user, UserStatus.OFFLINE)
page.update_ip_address_button_state()
class UserInfo:
def __init__(self, userinfos, user):
(
self.add_remove_buddy_label,
self.ban_unban_user_button,
self.ban_unban_user_label,
self.container,
self.country_icon,
self.country_label,
self.description_view_container,
self.dislikes_list_container,
self.edit_interests_button,
self.edit_profile_button,
self.free_upload_slots_label,
self.gift_privileges_button,
self.ignore_unignore_user_button,
self.ignore_unignore_user_label,
self.info_bar_container,
self.interests_container,
self.likes_list_container,
self.picture_view,
self.progress_bar,
self.queued_uploads_label,
self.refresh_button,
self.retry_button,
self.shared_files_label,
self.shared_folders_label,
self.show_ip_address_button,
self.upload_slots_label,
self.upload_speed_label,
self.user_info_container,
self.user_label
) = ui.load(scope=self, path="userinfo.ui")
self.userinfos = userinfos
self.window = userinfos.window
self.info_bar = InfoBar(parent=self.info_bar_container, button=self.retry_button)
self.description_view = TextView(self.description_view_container, editable=False, vertical_margin=5)
self.user_label.set_text(user)
if GTK_API_VERSION >= 4:
self.country_icon.set_pixel_size(21)
self.picture = Gtk.Picture(can_shrink=True, focusable=True, hexpand=True, vexpand=True)
self.picture_view.append(self.picture) # pylint: disable=no-member
if (GTK_API_VERSION, GTK_MINOR_VERSION) >= (4, 8):
self.picture.set_content_fit(Gtk.ContentFit.CONTAIN)
else:
self.picture.set_keep_aspect_ratio(True)
else:
# Setting a pixel size of 21 results in a misaligned country flag
self.country_icon.set_pixel_size(0)
self.picture = Gtk.EventBox(can_focus=True, hexpand=True, vexpand=True, visible=True)
self.picture.connect("draw", self.on_draw_picture)
self.picture_view.add(self.picture) # pylint: disable=no-member
self.user = user
self.picture_data = None
self.picture_surface = None
self.indeterminate_progress = False
# Set up likes list
self.likes_list_view = TreeView(
self.window, parent=self.likes_list_container,
activate_row_callback=self.on_likes_row_activated,
columns={
"likes": {
"column_type": "text",
"title": _("Likes"),
"default_sort_type": "ascending"
}
}
)
# Set up dislikes list
self.dislikes_list_view = TreeView(
self.window, parent=self.dislikes_list_container,
activate_row_callback=self.on_dislikes_row_activated,
columns={
"dislikes": {
"column_type": "text",
"title": _("Dislikes"),
"default_sort_type": "ascending"
}
}
)
# Popup menus
self.user_popup_menu = UserPopupMenu(
self.window.application, callback=self.on_tab_popup, username=user, tab_name="userinfo"
)
self.user_popup_menu.add_items(
("", None),
("#" + _("Close All Tabs…"), self.on_close_all_tabs),
("#" + _("_Close Tab"), self.on_close)
)
def get_interest_items(list_view, column_id):
return (
("$" + _("I _Like This"), self.window.interests.on_like_recommendation, list_view, column_id),
("$" + _("I _Dislike This"), self.window.interests.on_dislike_recommendation, list_view, column_id),
("", None),
("#" + _("_Recommendations for Item"), self.window.interests.on_recommend_item, list_view, column_id),
("#" + _("_Search for Item"), self.window.interests.on_recommend_search, list_view, column_id)
)
self.likes_popup_menu = PopupMenu(self.window.application, self.likes_list_view.widget,
self.on_popup_likes_menu)
self.likes_popup_menu.add_items(*get_interest_items(self.likes_list_view, "likes"))
self.dislikes_popup_menu = PopupMenu(self.window.application, self.dislikes_list_view.widget,
self.on_popup_dislikes_menu)
self.dislikes_popup_menu.add_items(*get_interest_items(self.dislikes_list_view, "dislikes"))
self.picture_popup_menu = PopupMenu(self.window.application, self.picture)
self.picture_popup_menu.add_items(
("#" + _("Copy Picture"), self.on_copy_picture),
("#" + _("Save Picture"), self.on_save_picture),
("", None),
("#" + _("Remove"), self.on_hide_picture)
)
self.popup_menus = (
self.user_popup_menu, self.likes_popup_menu, self.dislikes_popup_menu,
self.picture_popup_menu
)
self.remove_picture()
self.populate_stats()
self.update_button_states()
def clear(self):
self.description_view.clear()
self.likes_list_view.clear()
self.dislikes_list_view.clear()
self.remove_picture()
def destroy(self):
for menu in self.popup_menus:
menu.destroy()
self.info_bar.destroy()
self.description_view.destroy()
self.likes_list_view.destroy()
self.dislikes_list_view.destroy()
self.__dict__.clear()
self.indeterminate_progress = False # Stop progress bar timer
def set_label(self, label):
self.user_popup_menu.set_parent(label)
# General #
def populate_stats(self):
country_code = core.users.countries.get(self.user)
stats = core.users.watched.get(self.user)
if stats is not None:
speed = stats.upload_speed or 0
files = stats.files
folders = stats.folders
else:
speed = 0
files = folders = None
if speed > 0:
self.upload_speed_label.set_text(human_speed(speed))
if files is not None:
self.shared_files_label.set_text(humanize(files))
if folders is not None:
self.shared_folders_label.set_text(humanize(folders))
if country_code:
self.user_country(country_code)
def remove_picture(self):
if GTK_API_VERSION >= 4:
# Empty paintable to prevent container width from shrinking
self.picture.set_paintable(Gdk.Paintable.new_empty(intrinsic_width=1, intrinsic_height=1))
self.picture_data = None
self.picture_surface = None
self.hide_picture()
def load_picture(self, data):
if not data:
self.remove_picture()
return
try:
if GTK_API_VERSION >= 4:
self.picture_data = Gdk.Texture.new_from_bytes(GLib.Bytes(data))
self.picture.set_paintable(self.picture_data)
else:
data_stream = Gio.MemoryInputStream.new_from_bytes(GLib.Bytes(data))
self.picture_data = GdkPixbuf.Pixbuf.new_from_stream(data_stream, cancellable=None)
self.picture_surface = Gdk.cairo_surface_create_from_pixbuf(self.picture_data, scale=1, for_window=None)
except Exception as error:
log.add(_("Failed to load picture for user %(user)s: %(error)s"), {
"user": self.user,
"error": error
})
self.remove_picture()
return
self.show_picture()
def show_picture(self):
if GTK_API_VERSION == 3:
self.user_info_container.set_hexpand(False)
self.interests_container.set_hexpand(False)
self.picture_view.set_visible(True)
self.picture_view.set_hexpand(True)
add_css_class(self.interests_container, "border-end")
def hide_picture(self):
if GTK_API_VERSION == 3:
self.user_info_container.set_hexpand(True)
self.interests_container.set_hexpand(True)
self.picture_view.set_visible(False)
self.picture_view.set_hexpand(False)
remove_css_class(self.interests_container, "border-end")
def peer_connection_error(self):
if self.refresh_button.get_sensitive():
return
self.info_bar.show_error_message(
_("Unable to request information from user. Either you both have a closed listening "
"port, the user is offline, or there's a temporary connectivity issue.")
)
self.set_finished()
def pulse_progress(self, repeat=True):
if not self.indeterminate_progress:
return False
self.progress_bar.pulse()
return repeat
def user_info_progress(self, position, total):
self.indeterminate_progress = False
if total <= 0 or position <= 0:
fraction = 0.0
elif position < total:
fraction = float(position) / total
else:
fraction = 1.0
self.progress_bar.set_fraction(fraction)
def set_indeterminate_progress(self):
self.indeterminate_progress = True
self.progress_bar.get_parent().set_reveal_child(True)
self.progress_bar.pulse()
GLib.timeout_add(320, self.pulse_progress, False)
GLib.timeout_add(1000, self.pulse_progress)
self.info_bar.set_visible(False)
self.refresh_button.set_sensitive(False)
def set_finished(self):
self.indeterminate_progress = False
self.userinfos.request_tab_changed(self.container)
self.progress_bar.set_fraction(1.0)
self.progress_bar.get_parent().set_reveal_child(False)
self.refresh_button.set_sensitive(True)
# Button States #
def update_local_buttons_state(self):
local_username = core.users.login_username or config.sections["server"]["login"]
for widget in (self.edit_interests_button, self.edit_profile_button):
widget.set_visible(self.user == local_username)
for widget in (self.ban_unban_user_button, self.ignore_unignore_user_button):
widget.set_visible(self.user != local_username)
def update_buddy_button_state(self):
label = _("Remove _Buddy") if self.user in core.buddies.users else _("Add _Buddy")
self.add_remove_buddy_label.set_text_with_mnemonic(label)
def update_ban_button_state(self):
label = _("Unban User") if core.network_filter.is_user_banned(self.user) else _("Ban User")
self.ban_unban_user_label.set_text(label)
def update_ignore_button_state(self):
label = _("Unignore User") if core.network_filter.is_user_ignored(self.user) else _("Ignore User")
self.ignore_unignore_user_label.set_text(label)
def update_privileges_button_state(self):
self.gift_privileges_button.set_sensitive(bool(core.users.privileges_left))
def update_ip_address_button_state(self):
self.show_ip_address_button.set_sensitive(core.users.login_status != UserStatus.OFFLINE)
def update_button_states(self):
self.update_local_buttons_state()
self.update_buddy_button_state()
self.update_ban_button_state()
self.update_ignore_button_state()
self.update_privileges_button_state()
self.update_ip_address_button_state()
# Network Messages #
def user_info_response(self, msg):
if msg is None:
return
if msg.descr is not None:
self.description_view.clear()
self.description_view.append_line(msg.descr)
self.free_upload_slots_label.set_text(_("Yes") if msg.slotsavail else _("No"))
self.upload_slots_label.set_text(humanize(msg.totalupl))
self.queued_uploads_label.set_text(humanize(msg.queuesize))
self.upload_slots_label.get_parent().set_visible(not msg.slotsavail)
self.queued_uploads_label.get_parent().set_visible(not msg.slotsavail)
self.picture_data = None
self.load_picture(msg.pic)
self.info_bar.set_visible(False)
self.set_finished()
def user_stats(self, msg):
speed = msg.avgspeed or 0
num_files = msg.files or 0
num_folders = msg.dirs or 0
h_speed = human_speed(speed) if speed > 0 else _("Unknown")
h_num_files = humanize(num_files)
h_num_folders = humanize(num_folders)
if self.upload_speed_label.get_text() != h_speed:
self.upload_speed_label.set_text(h_speed)
if self.shared_files_label.get_text() != h_num_files:
self.shared_files_label.set_text(h_num_files)
if self.shared_folders_label.get_text() != h_num_folders:
self.shared_folders_label.set_text(h_num_folders)
def user_country(self, country_code):
if not country_code:
return
country_name = core.network_filter.COUNTRIES.get(country_code, _("Unknown"))
country_text = f"{country_name} ({country_code})"
self.country_label.set_text(country_text)
icon_name = get_flag_icon_name(country_code)
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.country_icon.set_from_icon_name(icon_name, *icon_args)
self.country_icon.set_visible(bool(icon_name))
def user_interests(self, msg):
self.likes_list_view.clear()
self.likes_list_view.freeze()
self.dislikes_list_view.clear()
self.dislikes_list_view.freeze()
for like in msg.likes:
self.likes_list_view.add_row([like], select_row=False)
for hate in msg.hates:
self.dislikes_list_view.add_row([hate], select_row=False)
self.likes_list_view.unfreeze()
self.dislikes_list_view.unfreeze()
# Callbacks #
def on_show_progress_bar(self, progress_bar):
"""Enables indeterminate progress bar mode when tab is active."""
if not self.indeterminate_progress and progress_bar.get_fraction() <= 0.0:
self.set_indeterminate_progress()
if core.users.login_status == UserStatus.OFFLINE:
self.peer_connection_error()
def on_hide_progress_bar(self, progress_bar):
"""Disables indeterminate progress bar mode when switching to another tab."""
if self.indeterminate_progress:
self.indeterminate_progress = False
progress_bar.set_fraction(0.0)
def on_draw_picture(self, area, context):
"""Draws a centered picture that fills the drawing area."""
area_width = area.get_allocated_width()
area_height = area.get_allocated_height()
picture_width = self.picture_surface.get_width()
picture_height = self.picture_surface.get_height()
scale_factor = min(area_width / picture_width, area_height / picture_height)
translate_x = (area_width - (picture_width * scale_factor)) / 2
translate_y = (area_height - (picture_height * scale_factor)) / 2
context.translate(translate_x, translate_y)
context.scale(scale_factor, scale_factor)
context.set_source_surface(self.picture_surface, 0, 0)
context.paint()
def on_tab_popup(self, *_args):
self.user_popup_menu.toggle_user_items()
def on_popup_likes_menu(self, menu, *_args):
self.window.interests.toggle_menu_items(menu, self.likes_list_view, column_id="likes")
def on_popup_dislikes_menu(self, menu, *_args):
self.window.interests.toggle_menu_items(menu, self.dislikes_list_view, column_id="dislikes")
def on_edit_profile(self, *_args):
self.window.application.on_preferences(page_id="user-profile")
def on_edit_interests(self, *_args):
self.window.change_main_page(self.window.interests_page)
def on_likes_row_activated(self, *_args):
self.window.interests.show_item_recommendations(self.likes_list_view, column_id="likes")
def on_dislikes_row_activated(self, *_args):
self.window.interests.show_item_recommendations(self.dislikes_list_view, column_id="dislikes")
def on_send_message(self, *_args):
core.privatechat.show_user(self.user)
def on_show_ip_address(self, *_args):
core.users.request_ip_address(self.user, notify=True)
def on_browse_user(self, *_args):
core.userbrowse.browse_user(self.user)
def on_add_remove_buddy(self, *_args):
if self.user in core.buddies.users:
core.buddies.remove_buddy(self.user)
return
core.buddies.add_buddy(self.user)
def on_ban_unban_user(self, *_args):
if core.network_filter.is_user_banned(self.user):
core.network_filter.unban_user(self.user)
return
core.network_filter.ban_user(self.user)
def on_ignore_unignore_user(self, *_args):
if core.network_filter.is_user_ignored(self.user):
core.network_filter.unignore_user(self.user)
return
core.network_filter.ignore_user(self.user)
def on_give_privileges_response(self, dialog, _response_id, _data):
days = dialog.get_entry_value()
if not days:
return
try:
days = int(days)
except ValueError:
self.on_give_privileges(error=_("Please enter number of days."))
return
core.users.request_give_privileges(self.user, days)
def on_give_privileges(self, *_args, error=None):
core.users.request_check_privileges()
if core.users.privileges_left is None:
days = _("Unknown")
else:
days = core.users.privileges_left // 60 // 60 // 24
message = (_("Gift days of your Soulseek privileges to user %(user)s (%(days_left)s):") %
{"user": self.user, "days_left": _("%(days)s days left") % {"days": days}})
if error:
message += "\n\n" + error
EntryDialog(
parent=self.window,
title=_("Gift Privileges"),
message=message,
action_button_label=_("_Give Privileges"),
callback=self.on_give_privileges_response
).present()
def on_copy_picture(self, *_args):
if self.picture_data is None:
return
clipboard.copy_image(self.picture_data)
def on_save_picture_response(self, selected, *_args):
file_path = next(iter(selected), None)
if not file_path:
return
if GTK_API_VERSION >= 4:
picture_bytes = self.picture_data.save_to_png_bytes().get_data()
else:
_success, picture_bytes = self.picture_data.save_to_bufferv(
type="png", option_keys=[], option_values=[])
core.userinfo.save_user_picture(file_path, picture_bytes)
def on_save_picture(self, *_args):
if self.picture_data is None:
return
current_date_time = time.strftime("%Y-%m-%d_%H-%M-%S")
FileChooserSave(
parent=self.window,
callback=self.on_save_picture_response,
initial_folder=core.downloads.get_default_download_folder(),
initial_file=f"{self.user}_{current_date_time}.png"
).present()
def on_hide_picture(self, *_args):
self.hide_picture()
def on_refresh(self, *_args):
self.set_indeterminate_progress()
core.userinfo.show_user(self.user, refresh=True)
def on_focus(self, *_args):
self.userinfos.grab_focus()
return True
def on_close(self, *_args):
core.userinfo.remove_user(self.user)
def on_close_all_tabs(self, *_args):
self.userinfos.remove_all_pages()
| 28,373 | Python | .py | 616 | 36.137987 | 120 | 0.633639 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,443 | media-floppy-symbolic.svg | nicotine-plus_nicotine-plus/pynicotine/gtkgui/icons/hicolor/scalable/devices/media-floppy-symbolic.svg | <?xml version="1.0" encoding="UTF-8"?>
<svg height="16px" viewBox="0 0 16 16" width="16px" xmlns="http://www.w3.org/2000/svg">
<path d="m 3.96875 1 s -2.96875 0 -2.96875 2.96875 v 8.03125 s 0 0.5 0.3125 0.71875 l 1.6875 1.6875 v -10.40625 c 0 -1 1 -1 1 -1 h 8 s 1 0 1 1 v 8 c 0 1 -1 1 -1 1 h -1 v 2 h 1 s 3 0 3 -2.96875 v -8.0625 s 0 -2.96875 -2.96875 -2.96875 z m 1.03125 8 c -0.554688 0 -1 0.445312 -1 1 v 4 c 0 0.554688 0.445312 1 1 1 h 4 c 0.554688 0 1 -0.445312 1 -1 v -4 c 0 -0.554688 -0.445312 -1 -1 -1 z m 0 1 h 2 v 4 h -2 z m 0 0" fill="#222222"/>
</svg>
| 568 | Python | .py | 4 | 140 | 433 | 0.602837 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,444 | nplus-flag-py.svg | nicotine-plus_nicotine-plus/pynicotine/gtkgui/icons/hicolor/scalable/intl/nplus-flag-py.svg | <svg xmlns="http://www.w3.org/2000/svg" width="21" height="15"><defs><linearGradient id="a" x1="50%" x2="50%" y1="0%" y2="100%"><stop offset="0%" stop-color="#FFF"/><stop offset="100%" stop-color="#F0F0F0"/></linearGradient><linearGradient id="b" x1="50%" x2="50%" y1="0%" y2="100%"><stop offset="0%" stop-color="#E33F39"/><stop offset="100%" stop-color="#D32E28"/></linearGradient><linearGradient id="c" x1="50%" x2="50%" y1="0%" y2="100%"><stop offset="0%" stop-color="#124BBA"/><stop offset="100%" stop-color="#073DA6"/></linearGradient></defs><g fill="none" fill-rule="evenodd"><path fill="url(#a)" d="M0 0h21v15H0z"/><path fill="url(#b)" d="M0 0h21v5H0z"/><path fill="url(#c)" d="M0 10h21v5H0z"/><path fill="url(#a)" d="M0 5h21v5H0z"/><path fill="#398153" fill-rule="nonzero" d="M10.5 9a1.5 1.5 0 1 0 0-3 1.5 1.5 0 0 0 0 3Zm0 .5a2 2 0 1 1 0-4 2 2 0 0 1 0 4Z"/><circle cx="10.5" cy="7.5" r="1" fill="#E5CF58"/></g></svg> | 924 | Python | .py | 1 | 924 | 924 | 0.624459 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,445 | combobox.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/combobox.py | # COPYRIGHT (C) 2023-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Pango
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.textentry import CompletionEntry
from pynicotine.gtkgui.widgets.theme import add_css_class
class ComboBox:
def __init__(self, container, label=None, has_entry=False, has_entry_completion=False,
entry=None, visible=True, items=None, item_selected_callback=None):
self.widget = None
self.dropdown = None
self.entry = entry
self.item_selected_callback = item_selected_callback
self._ids = {}
self._positions = {}
self._model = None
self._button = None
self._popover = None
self._entry_completion = None
self._is_popup_visible = False
self._create_combobox(container, label, has_entry, has_entry_completion)
if items:
self.freeze()
for provided_item in items:
if isinstance(provided_item, str):
item = provided_item
item_id = None
else:
item, item_id = provided_item
self.append(item, item_id)
self.unfreeze()
self.set_visible(visible)
def destroy(self):
self.__dict__.clear()
def _create_combobox_gtk4(self, container, label, has_entry):
self._model = Gtk.StringList()
self.dropdown = self._button = Gtk.DropDown(
model=self._model, valign=Gtk.Align.CENTER, visible=True
)
list_factory = self.dropdown.get_factory()
button_factory = None
if not has_entry:
button_factory = Gtk.SignalListItemFactory()
button_factory.connect("setup", self._on_button_factory_setup)
button_factory.connect("bind", self._on_button_factory_bind)
self.dropdown.set_factory(button_factory)
self.dropdown.set_list_factory(list_factory)
self._popover = list(self.dropdown)[-1]
self._popover.connect("notify::visible", self._on_dropdown_visible)
try:
scrollable = list(self._popover.get_child())[-1]
list_view = scrollable.get_child()
list_view.connect("activate", self._on_item_selected)
except AttributeError:
pass
if not has_entry:
self.widget = self.dropdown
if label:
label.set_mnemonic_widget(self.widget)
container.append(self.widget)
return
list_factory = Gtk.SignalListItemFactory()
list_factory.connect("setup", self._on_entry_list_factory_setup)
list_factory.connect("bind", self._on_entry_list_factory_bind)
self.dropdown.set_list_factory(list_factory)
self.widget = Gtk.Box(valign=Gtk.Align.CENTER, visible=True)
self._popover.connect("map", self._on_dropdown_map)
if self.entry is None:
self.entry = Gtk.Entry(hexpand=True, width_chars=8, visible=True)
if label:
label.set_mnemonic_widget(self.entry)
self._button.set_sensitive(False)
self.widget.append(self.entry)
self.widget.append(self.dropdown)
add_css_class(self.widget, "linked")
add_css_class(self.dropdown, "entry")
container.append(self.widget)
def _create_combobox_gtk3(self, container, label, has_entry, has_entry_completion):
self.dropdown = self.widget = Gtk.ComboBoxText(has_entry=has_entry, valign=Gtk.Align.CENTER, visible=True)
self._model = self.dropdown.get_model()
self.dropdown.connect("scroll-event", self._on_button_scroll_event)
self.dropdown.connect("notify::active", self._on_item_selected)
self.dropdown.connect("notify::popup-shown", self._on_dropdown_visible)
if label:
label.set_mnemonic_widget(self.widget)
if not has_entry:
for cell in self.dropdown.get_cells():
cell.props.ellipsize = Pango.EllipsizeMode.END
container.add(self.widget)
return
if has_entry_completion:
add_css_class(self.dropdown, "dropdown-scrollbar")
if self.entry is None:
self.entry = self.dropdown.get_child()
self.entry.set_width_chars(8)
else:
self.dropdown.get_child().destroy()
self.dropdown.add(self.entry) # pylint: disable=no-member
self._button = list(self.entry.get_parent())[-1]
container.add(self.widget)
def _create_combobox(self, container, label, has_entry, has_entry_completion):
if GTK_API_VERSION >= 4:
self._create_combobox_gtk4(container, label, has_entry)
else:
self._create_combobox_gtk3(container, label, has_entry, has_entry_completion)
if has_entry:
Accelerator("Up", self.entry, self._on_arrow_key_accelerator, "up")
Accelerator("Down", self.entry, self._on_arrow_key_accelerator, "down")
if has_entry_completion:
self._entry_completion = CompletionEntry(self.entry)
def _update_item_entry_text(self):
"""Set text entry text to the same value as selected item."""
if GTK_API_VERSION >= 4:
item = self.dropdown.get_selected_item()
if item is None:
return
item_text = item.get_string()
if self.get_text() != item_text:
self.set_text(item_text)
self.entry.set_position(-1)
def _update_item_positions(self, start_position, added=False):
if added:
end_position = self.get_num_items() + 1
else:
end_position = self.get_num_items()
new_ids = {}
for position in range(start_position, end_position):
if added:
item_id = self._ids[position - 1]
else:
item_id = self._ids.pop(position + 1)
new_ids[position] = item_id
self._positions[item_id] = position
self._ids.update(new_ids)
# General #
def freeze(self):
"""Called before inserting/deleting items, to avoid redundant UI updates."""
if GTK_API_VERSION >= 4:
self.dropdown.set_model(None)
def unfreeze(self):
"""Called after items have been inserted/deleted, to enable UI updates."""
if GTK_API_VERSION >= 4:
self.dropdown.set_model(self._model)
def insert(self, position, item, item_id=None):
if item_id is None:
item_id = item
if item_id in self._positions:
return
last_position = self.get_num_items()
if position == -1:
position = last_position
if GTK_API_VERSION >= 4:
if last_position == position:
self._model.append(item)
else:
num_removals = (last_position - position)
inserted_items = [item] + [self._model.get_string(i) for i in range(position, last_position)]
self._model.splice(position, num_removals, inserted_items)
else:
self.dropdown.insert_text(position, item)
if self.entry and not self._positions:
self._button.set_sensitive(True)
if self._entry_completion:
self._entry_completion.add_completion(item)
self._update_item_positions(start_position=(position + 1), added=True)
self._ids[position] = item_id
self._positions[item_id] = position
def append(self, item, item_id=None):
self.insert(position=-1, item=item, item_id=item_id)
def prepend(self, item, item_id=None):
self.insert(position=0, item=item, item_id=item_id)
def get_num_items(self):
return len(self._positions)
def get_selected_pos(self):
if GTK_API_VERSION >= 4:
return self.dropdown.get_selected()
return self.dropdown.get_active()
def get_selected_id(self):
return self._ids.get(self.get_selected_pos())
def get_text(self):
if self.entry:
return self.entry.get_text()
return self.get_selected_id()
def set_selected_pos(self, position):
if position is None:
return
if self.get_selected_pos() == position:
return
if GTK_API_VERSION >= 4:
self.dropdown.set_selected(position)
else:
self.dropdown.set_active(position)
def set_selected_id(self, item_id):
self.set_selected_pos(self._positions.get(item_id))
def set_text(self, text):
if self.entry:
self.entry.set_text(text)
return
self.set_selected_id(text)
def remove_pos(self, position):
if position == -1:
position = (self.get_num_items() - 1)
item_id = self._ids.pop(position, None)
if item_id is None:
return
if GTK_API_VERSION >= 4:
self._model.remove(position)
else:
self.dropdown.remove(position)
if self.entry and not self._ids:
self._button.set_sensitive(False)
if self._entry_completion:
self._entry_completion.remove_completion(item_id)
# Update positions for items after the removed one
self._positions.pop(item_id, None)
self._update_item_positions(start_position=position)
def remove_id(self, item_id):
position = self._positions.get(item_id)
self.remove_pos(position)
def clear(self):
self._ids.clear()
self._positions.clear()
if GTK_API_VERSION >= 4:
self._model.splice(position=0, n_removals=self._model.get_n_items())
else:
self.dropdown.remove_all()
if self.entry and self._button:
self._button.set_sensitive(False)
if self._entry_completion:
self._entry_completion.clear()
def grab_focus(self):
self.entry.grab_focus()
def set_visible(self, visible):
self.widget.set_visible(visible)
# Callbacks #
def _on_button_factory_bind(self, _factory, list_item):
label = list_item.get_child()
label.set_text(list_item.get_item().get_string())
def _on_button_factory_setup(self, _factory, list_item):
list_item.set_child(
Gtk.Label(ellipsize=Pango.EllipsizeMode.END, mnemonic_widget=self.widget, xalign=0))
def _on_entry_list_factory_bind(self, _factory, list_item):
label = list_item.get_child()
label.set_text(list_item.get_item().get_string())
def _on_entry_list_factory_setup(self, _factory, list_item):
list_item.set_child(
Gtk.Label(ellipsize=Pango.EllipsizeMode.END, xalign=0))
def _on_arrow_key_accelerator(self, _widget, _unused, direction):
if GTK_API_VERSION == 3:
# Gtk.ComboBox already supports this functionality
return False
if not self._positions:
return False
if self._entry_completion:
completion_popover = list(self.entry)[-1]
if completion_popover.get_visible():
# Completion popup takes precedence
return False
current_position = self._positions.get(self.get_text(), -1)
if direction == "up":
new_position = max(0, current_position - 1)
else:
new_position = min(current_position + 1, len(self._positions) - 1)
self.set_selected_pos(new_position)
self._update_item_entry_text()
return True
def _on_button_scroll_event(self, widget, event, *_args):
"""Prevent scrolling and pass scroll event to parent scrollable (GTK 3)"""
scrollable = widget.get_ancestor(Gtk.ScrolledWindow)
if scrollable is not None:
scrollable.event(event)
return True
def _on_select_callback_status(self, enabled):
self._is_popup_visible = enabled
def _on_dropdown_map(self, *_args):
# Align dropdown with entry and button
popover_content = next(iter(self._popover))
container_width = self.entry.get_parent().get_width()
button_width = self._button.get_width()
self._popover.set_offset(x_offset=-container_width + button_width, y_offset=0)
popover_content.set_size_request(container_width, height=-1)
def _on_dropdown_visible(self, widget, param):
visible = widget.get_property(param.name)
# Only enable item selection callback when an item is selected from the UI
GLib.idle_add(self._on_select_callback_status, visible)
if self.entry is None:
return
if not visible:
return
text = self.get_text()
if text:
self.set_selected_id(text)
def _on_item_selected(self, *_args):
selected_id = self.get_selected_id()
if selected_id is None:
return
if self.entry is not None:
# Update text entry with text from the selected item
self._update_item_entry_text()
if not self._is_popup_visible:
return
if self.entry is not None:
self.entry.grab_focus_without_selecting()
if self.item_selected_callback is not None:
self.item_selected_callback(self, selected_id)
| 14,276 | Python | .py | 323 | 34.216718 | 114 | 0.624158 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,446 | popupmenu.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/popupmenu.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2008-2009 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import clipboard
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.utils import TRANSLATE_PUNCTUATION
class PopupMenu:
popup_id_counter = 0
def __init__(self, application, parent=None, callback=None, connect_events=True):
self.model = Gio.Menu()
self.application = application
self.parent = parent
self.callback = callback
self.popup_menu = None
self.gesture_click = None
self.gesture_press = None
self.valid_parent_widgets = Gtk.Box if GTK_API_VERSION >= 4 else (Gtk.Box, Gtk.EventBox)
if connect_events and parent:
self.connect_events(parent)
self.pending_items = []
self.actions = {}
self.items = {}
self.submenus = []
self.menu_section = None
self.editing = False
PopupMenu.popup_id_counter += 1
self.popup_id = PopupMenu.popup_id_counter
def destroy(self):
self.clear()
self.__dict__.clear()
def set_parent(self, parent):
if parent:
self.connect_events(parent)
self.parent = parent
def create_context_menu(self, parent):
if self.popup_menu:
return self.popup_menu
# Menus can only attach to a Gtk.Box/Gtk.EventBox parent, otherwise sizing and theming issues may occur
while not isinstance(parent, self.valid_parent_widgets):
parent = parent.get_parent()
if GTK_API_VERSION >= 4:
self.popup_menu = Gtk.PopoverMenu.new_from_model_full(self.model, # pylint: disable=no-member
Gtk.PopoverMenuFlags.NESTED)
self.popup_menu.set_parent(parent)
self.popup_menu.set_halign(Gtk.Align.START)
self.popup_menu.set_has_arrow(False)
# Workaround for wrong widget receiving focus after closing menu in GTK 4
self.popup_menu.connect("closed", lambda *_args: self.parent.child_focus(Gtk.DirectionType.TAB_FORWARD))
else:
self.popup_menu = Gtk.Menu.new_from_model(self.model)
self.popup_menu.attach_to_widget(parent)
return self.popup_menu
def _create_action(self, action_id, stateful=False):
state = GLib.Variant.new_boolean(False) if stateful else None
action = Gio.SimpleAction(name=action_id, state=state)
self.application.add_action(action)
return action
def _create_menu_item(self, item):
"""
Types of menu items:
> - submenu
$ - boolean
O - choice
# - regular
= - hidden when disabled
^ - hidden in macOS menu bar
"""
submenu = False
boolean = False
choice = False
item_type = item[0][0]
label = item[0][1:]
if item_type == ">":
submenu = True
elif item_type == "$":
boolean = True
elif item_type == "O":
choice = True
if isinstance(item[1], str):
# Action name provided, don't create action here
action_id = item[1]
action = None
else:
normalized_label = "-".join(label.translate(TRANSLATE_PUNCTUATION).lower().split())
action_id = f"app.menu-{normalized_label}-{self.popup_id}"
action = self._create_action(action_id.replace("app.", "", 1), (boolean or choice))
if choice and len(item) > 2 and isinstance(item[2], str):
# Choice target name
action_id = f"{action_id}::{item[2]}"
menuitem = Gio.MenuItem.new(label, action_id)
if item_type == "=":
menuitem.set_attribute_value("hidden-when", GLib.Variant.new_string("action-disabled"))
elif item_type == "^":
menuitem.set_attribute_value("hidden-when", GLib.Variant.new_string("macos-menubar"))
if submenu:
menuitem.set_submenu(item[1].model)
self.submenus.append(item[1])
if GTK_API_VERSION == 3:
# Ideally, we wouldn't hide disabled submenus, but a GTK limitation forces us to
# https://discourse.gnome.org/t/question-how-do-i-disable-a-menubar-menu-in-gtk-is-it-even-possible/906/9
menuitem.set_attribute_value("hidden-when", GLib.Variant.new_string("action-disabled"))
elif action and item[1]:
# Callback
action_name = "change-state" if boolean or choice else "activate"
action.connect(action_name, *item[1:])
self.items[label] = menuitem
if action is not None:
self.actions[label] = action
return menuitem
def _add_item_to_section(self, item):
if not self.menu_section or not item[0]:
# Create new section
self.menu_section = Gio.Menu()
menuitem = Gio.MenuItem.new_section(label=None, section=self.menu_section)
self.model.append_item(menuitem)
if not item[0]:
return
menuitem = self._create_menu_item(item)
self.menu_section.append_item(menuitem)
def update_model(self):
"""This function is called before a menu model needs to be manipulated
(enabling/disabling actions, showing a menu in the GUI)"""
if not self.pending_items:
return
for item in self.pending_items:
self._add_item_to_section(item)
self.pending_items.clear()
for submenu in self.submenus:
submenu.update_model()
def add_items(self, *items):
for item in items:
self.pending_items.append(item)
def clear(self):
for submenu in self.submenus:
# Ensure we remove all submenu actions
submenu.clear()
self.submenus.clear()
self.model.remove_all()
for action in self.actions.values():
self.application.remove_action(action.get_name())
self.actions.clear()
self.items.clear()
self.menu_section = None
def popup(self, pos_x, pos_y, controller=None, menu=None):
if menu is None:
menu = self.create_context_menu(self.parent)
if GTK_API_VERSION >= 4:
if not pos_x and not pos_y:
pos_x = pos_y = 0
rectangle = Gdk.Rectangle()
rectangle.x = pos_x
rectangle.y = pos_y
# Width/height 4 instead of 1 to work around this GTK bug in most cases:
# https://gitlab.gnome.org/GNOME/gtk/-/issues/5712
rectangle.width = rectangle.height = 4
menu.set_pointing_to(rectangle)
menu.popup()
return
event = None
if controller is not None:
sequence = controller.get_current_sequence()
if sequence is not None:
event = controller.get_last_event(sequence)
menu.popup_at_pointer(event)
# Events #
def _callback(self, controller=None, pos_x=None, pos_y=None):
menu = None
menu_model = self
callback = self.callback
self.update_model()
if isinstance(self.parent, Gtk.TreeView):
if pos_x and pos_y:
from pynicotine.gtkgui.widgets.treeview import set_treeview_selected_row
bin_x, bin_y = self.parent.convert_widget_to_bin_window_coords(pos_x, pos_y)
set_treeview_selected_row(self.parent, bin_x, bin_y)
if not self.parent.get_path_at_pos(bin_x, bin_y):
# Special case for column header menu
menu_model = self.parent.column_menu
menu = menu_model.create_context_menu(menu_model.parent)
callback = menu_model.callback
elif not self.parent.get_selection().count_selected_rows():
# No rows selected, don't show menu
return False
if callback is not None:
callback(menu_model, self.parent)
self.popup(pos_x, pos_y, controller, menu=menu)
return True
def _callback_click_gtk4(self, controller, _num_p, pos_x, pos_y):
return self._callback(controller, pos_x, pos_y)
def _callback_click_gtk4_darwin(self, controller, _num_p, pos_x, pos_y):
event = controller.get_last_event()
if event.triggers_context_menu():
return self._callback(controller, pos_x, pos_y)
return False
def _callback_click_gtk3(self, controller, _num_p, pos_x, pos_y):
sequence = controller.get_current_sequence()
if sequence is not None:
event = controller.get_last_event(sequence)
show_context_menu = event.triggers_context_menu()
else:
# Workaround for GTK 3.22.30
show_context_menu = (controller.get_current_button() == Gdk.BUTTON_SECONDARY)
if show_context_menu:
return self._callback(controller, pos_x, pos_y)
return False
def _callback_menu(self, *_args):
return self._callback()
def connect_events(self, parent):
if GTK_API_VERSION >= 4:
self.gesture_click = Gtk.GestureClick()
self.gesture_click.set_button(Gdk.BUTTON_SECONDARY)
self.gesture_click.connect("pressed", self._callback_click_gtk4)
parent.add_controller(self.gesture_click)
self.gesture_press = Gtk.GestureLongPress()
parent.add_controller(self.gesture_press)
Accelerator("<Shift>F10", parent, self._callback_menu)
if sys.platform == "darwin":
gesture_click_darwin = Gtk.GestureClick()
parent.add_controller(gesture_click_darwin)
gesture_click_darwin.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
gesture_click_darwin.connect("pressed", self._callback_click_gtk4_darwin)
else:
self.gesture_click = Gtk.GestureMultiPress(widget=parent)
self.gesture_click.set_button(0)
self.gesture_click.connect("pressed", self._callback_click_gtk3)
self.gesture_press = Gtk.GestureLongPress(widget=parent)
# Shift+F10
parent.connect("popup-menu", self._callback_menu)
self.gesture_click.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
self.gesture_press.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
self.gesture_press.set_touch_only(True)
self.gesture_press.connect("pressed", self._callback)
class FilePopupMenu(PopupMenu):
def __init__(self, application, parent=None, callback=None, connect_events=True):
super().__init__(application=application, parent=parent, callback=callback,
connect_events=connect_events)
self._setup_file_menu()
def _setup_file_menu(self):
self.add_items(
("#" + "selected_files", None),
("", None)
)
def set_num_selected_files(self, num_files):
self.actions["selected_files"].set_enabled(False)
self.items["selected_files"].set_label(_("%s File(s) Selected") % num_files)
self.model.remove(0)
self.model.prepend_item(self.items["selected_files"])
class UserPopupMenu(PopupMenu):
def __init__(self, application, parent=None, callback=None, connect_events=True, username=None,
tab_name=None):
super().__init__(application=application, parent=parent, callback=callback,
connect_events=connect_events)
self.username = username
self.tab_name = tab_name
self.popup_menu_private_rooms = None
if tab_name != "private_rooms":
self.popup_menu_private_rooms = UserPopupMenu(self.application, username=username, tab_name="private_rooms")
self.setup_user_menu(username)
def setup_user_menu(self, username):
self.set_user(username)
self.add_items(
("#" + "username", self.on_copy_user),
("", None)
)
if self.tab_name != "userinfo":
self.add_items(("#" + _("View User _Profile"), self.on_user_profile))
if self.tab_name != "privatechat":
self.add_items(("#" + _("_Send Message"), self.on_send_message))
if self.tab_name != "userbrowse":
self.add_items(("#" + _("_Browse Files"), self.on_browse_user))
if self.tab_name != "userlist":
self.add_items(("$" + _("_Add Buddy"), self.on_add_to_list))
self.add_items(
("", None),
("$" + _("Ban User"), self.on_ban_user),
("$" + _("Ignore User"), self.on_ignore_user),
("", None),
("$" + _("Ban IP Address"), self.on_ban_ip),
("$" + _("Ignore IP Address"), self.on_ignore_ip),
("#" + _("Show IP A_ddress"), self.on_show_ip_address),
("", None),
(">" + _("Private Rooms"), self.popup_menu_private_rooms)
)
def update_username_item(self):
if not self.username:
return
user_item = self.items.get("username")
if not user_item:
return
user_item.set_label(self.username.replace("_", "__")) # Escape underscores to disable mnemonics
self.model.remove(0)
self.model.prepend_item(user_item)
def set_user(self, username):
if username == self.username:
return
self.username = username
self.update_username_item()
if self.popup_menu_private_rooms is not None:
self.popup_menu_private_rooms.set_user(self.username)
def toggle_user_items(self):
self.editing = True
local_username = core.users.login_username or config.sections["server"]["login"]
add_to_list = _("_Add Buddy")
if add_to_list in self.actions:
self.actions[add_to_list].set_state(GLib.Variant.new_boolean(self.username in core.buddies.users))
for action_id, value in (
(_("Ban User"), core.network_filter.is_user_banned(self.username)),
(_("Ignore User"), core.network_filter.is_user_ignored(self.username)),
(_("Ban IP Address"), core.network_filter.is_user_ip_banned(self.username)),
(_("Ignore IP Address"), core.network_filter.is_user_ip_ignored(self.username))
):
# Disable menu item if it's our own username and we haven't banned ourselves before
self.actions[action_id].set_enabled(GLib.Variant.new_boolean(self.username != local_username or value))
self.actions[action_id].set_state(GLib.Variant.new_boolean(value))
self.popup_menu_private_rooms.populate_private_rooms()
self.popup_menu_private_rooms.update_model()
self.actions[_("Private Rooms")].set_enabled(bool(self.popup_menu_private_rooms.items))
self.editing = False
def populate_private_rooms(self):
self.clear()
for room, data in core.chatrooms.private_rooms.items():
is_owned = core.chatrooms.is_private_room_owned(room)
is_operator = core.chatrooms.is_private_room_operator(room)
if not is_owned and not is_operator:
continue
if self.username == data.owner:
continue
is_user_member = (self.username in data.members)
is_user_operator = (self.username in data.operators)
if not is_user_operator:
if is_user_member:
self.add_items(
("#" + _("Remove from Private Room %s") % room, self.on_private_room_remove_user, room))
else:
self.add_items(
("#" + _("Add to Private Room %s") % room, self.on_private_room_add_user, room))
if not is_owned:
continue
if is_user_operator:
self.add_items(
("#" + _("Remove as Operator of %s") % room, self.on_private_room_remove_operator, room))
elif is_user_member:
self.add_items(
("#" + _("Add as Operator of %s") % room, self.on_private_room_add_operator, room))
self.add_items(("", None))
def update_model(self):
super().update_model()
self.update_username_item()
# Events #
def on_search_user(self, *_args):
self.application.window.lookup_action("search-mode").change_state(GLib.Variant.new_string("user"))
self.application.window.user_search_entry.set_text(self.username)
self.application.window.change_main_page(self.application.window.search_page)
GLib.idle_add(lambda: self.application.window.search_entry.grab_focus() == -1, priority=GLib.PRIORITY_HIGH_IDLE)
def on_send_message(self, *_args):
core.privatechat.show_user(self.username)
def on_show_ip_address(self, *_args):
core.users.request_ip_address(self.username, notify=True)
def on_user_profile(self, *_args):
core.userinfo.show_user(self.username)
def on_browse_user(self, *_args):
core.userbrowse.browse_user(self.username)
def on_private_room_add_user(self, _action, _parameter, room):
core.chatrooms.add_user_to_private_room(room, self.username)
def on_private_room_remove_user(self, _action, _parameter, room):
core.chatrooms.remove_user_from_private_room(room, self.username)
def on_private_room_add_operator(self, _action, _parameter, room):
core.chatrooms.add_operator_to_private_room(room, self.username)
def on_private_room_remove_operator(self, _action, _parameter, room):
core.chatrooms.remove_operator_from_private_room(room, self.username)
def on_add_to_list(self, action, state):
if self.editing:
return
if state.get_boolean():
core.buddies.add_buddy(self.username)
else:
core.buddies.remove_buddy(self.username)
action.set_state(state)
def on_ban_user(self, action, state):
if self.editing:
return
if state.get_boolean():
core.network_filter.ban_user(self.username)
else:
core.network_filter.unban_user(self.username)
action.set_state(state)
def on_ban_ip(self, action, state):
if self.editing:
return
if state.get_boolean():
core.network_filter.ban_user_ip(self.username)
else:
core.network_filter.unban_user_ip(self.username)
action.set_state(state)
def on_ignore_ip(self, action, state):
if self.editing:
return
if state.get_boolean():
core.network_filter.ignore_user_ip(self.username)
else:
core.network_filter.unignore_user_ip(self.username)
action.set_state(state)
def on_ignore_user(self, action, state):
if self.editing:
return
if state.get_boolean():
core.network_filter.ignore_user(self.username)
else:
core.network_filter.unignore_user(self.username)
action.set_state(state)
def on_copy_user(self, *_args):
clipboard.copy_text(self.username)
| 20,665 | Python | .py | 438 | 36.552511 | 121 | 0.616125 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,447 | textview.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/textview.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import re
import time
from gi.repository import Gdk
from gi.repository import Gtk
from pynicotine.core import core
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import clipboard
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.theme import update_tag_visuals
from pynicotine.gtkgui.widgets.theme import USER_STATUS_COLORS
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import find_whole_word
from pynicotine.utils import open_uri
class TextView:
try:
if GTK_API_VERSION >= 4:
DEFAULT_CURSOR = Gdk.Cursor(name="default")
POINTER_CURSOR = Gdk.Cursor(name="pointer")
TEXT_CURSOR = Gdk.Cursor(name="text")
else:
DEFAULT_CURSOR = Gdk.Cursor.new_from_name(Gdk.Display.get_default(), "default")
POINTER_CURSOR = Gdk.Cursor.new_from_name(Gdk.Display.get_default(), "pointer")
TEXT_CURSOR = Gdk.Cursor.new_from_name(Gdk.Display.get_default(), "text")
except TypeError:
# Broken cursor theme, but what can we do...
DEFAULT_CURSOR = POINTER_CURSOR = TEXT_CURSOR = None
MAX_NUM_LINES = 50000
URL_REGEX = re.compile("(\\w+\\://[^\\s]+)|(www\\.\\w+\\.[^\\s]+)|(mailto\\:[^\\s]+)")
def __init__(self, parent, auto_scroll=False, parse_urls=True, editable=True,
horizontal_margin=12, vertical_margin=8, pixels_above_lines=1, pixels_below_lines=1):
self.widget = Gtk.TextView(
accepts_tab=False, editable=editable,
left_margin=horizontal_margin, right_margin=horizontal_margin,
top_margin=vertical_margin, bottom_margin=vertical_margin,
pixels_above_lines=pixels_above_lines, pixels_below_lines=pixels_below_lines,
wrap_mode=Gtk.WrapMode.WORD_CHAR, visible=True
)
if GTK_API_VERSION >= 4:
parent.set_child(self.widget) # pylint: disable=no-member
else:
parent.add(self.widget) # pylint: disable=no-member
self.textbuffer = self.widget.get_buffer()
self.end_iter = self.textbuffer.get_end_iter()
self.scrollable = self.widget.get_ancestor(Gtk.ScrolledWindow)
scrollable_container = self.scrollable.get_ancestor(Gtk.Box)
self.adjustment = self.scrollable.get_vadjustment()
self.auto_scroll = auto_scroll
self.adjustment_bottom = self.adjustment_value = 0
self.notify_upper_handler = self.adjustment.connect("notify::upper", self.on_adjustment_upper_changed)
self.notify_value_handler = self.adjustment.connect("notify::value", self.on_adjustment_value_changed)
self.pressed_x = self.pressed_y = 0
self.default_tags = {}
self.parse_urls = parse_urls
if GTK_API_VERSION >= 4:
self.textbuffer.set_enable_undo(editable)
self.gesture_click_primary = Gtk.GestureClick()
scrollable_container.add_controller(self.gesture_click_primary)
self.gesture_click_secondary = Gtk.GestureClick()
scrollable_container.add_controller(self.gesture_click_secondary)
self.cursor_window = self.widget
self.motion_controller = Gtk.EventControllerMotion()
self.motion_controller.connect("motion", self.on_move_cursor)
self.widget.add_controller(self.motion_controller) # pylint: disable=no-member
else:
self.gesture_click_primary = Gtk.GestureMultiPress(widget=scrollable_container)
self.gesture_click_secondary = Gtk.GestureMultiPress(widget=scrollable_container)
self.cursor_window = None
self.widget.connect("motion-notify-event", self.on_move_cursor_event)
self.gesture_click_primary.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
self.gesture_click_primary.connect("released", self.on_released_primary)
self.gesture_click_secondary.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
self.gesture_click_secondary.set_button(Gdk.BUTTON_SECONDARY)
self.gesture_click_secondary.connect("pressed", self.on_pressed_secondary)
def destroy(self):
# Prevent updates while destroying widget
self.adjustment.disconnect(self.notify_upper_handler)
self.adjustment.disconnect(self.notify_value_handler)
self.__dict__.clear()
def scroll_bottom(self):
self.adjustment_value = (self.adjustment.get_upper() - self.adjustment.get_page_size())
self.adjustment.set_value(self.adjustment_value)
def _insert_text(self, text, tag=None):
if not text:
return
if tag is not None:
start_offset = self.end_iter.get_offset()
self.textbuffer.insert(self.end_iter, text)
if tag is not None:
start_iter = self.textbuffer.get_iter_at_offset(start_offset)
self.textbuffer.apply_tag(tag, start_iter, self.end_iter)
def _remove_old_lines(self, num_lines):
if num_lines < self.MAX_NUM_LINES:
return
# Optimization: remove lines in batches
start_iter = self.textbuffer.get_start_iter()
end_line = (num_lines - (self.MAX_NUM_LINES - 1000))
end_iter = self.get_iter_at_line(end_line)
self.textbuffer.delete(start_iter, end_iter)
self.end_iter = self.textbuffer.get_end_iter()
def append_line(self, line, message_type=None, timestamp=None, timestamp_format=None,
username=None, usertag=None):
tag = self.default_tags.get(message_type)
num_lines = self.textbuffer.get_line_count()
line = str(line).strip("\n")
if timestamp_format:
line = time.strftime(timestamp_format, time.localtime(timestamp)) + " " + line
if self.textbuffer.get_char_count() > 0:
# No tag applied on line breaks to prevent visual glitch where text on the
# next line has the wrong color
self._insert_text("\n")
# Tag usernames with popup menu creating tag, and away/online/offline colors
if username and username in line:
start = line.find(username)
self._insert_text(line[:start], tag)
self._insert_text(username, usertag)
line = line[start + len(username):]
# Highlight urls, if found and tag them
if self.parse_urls and ("://" in line or "www." in line or "mailto:" in line):
# Match first url
match = self.URL_REGEX.search(line)
while match:
self._insert_text(line[:match.start()], tag)
url = match.group()
urltag = self.create_tag("urlcolor", url=url)
self._insert_text(url, urltag)
# Match remaining url
line = line[match.end():]
match = self.URL_REGEX.search(line)
self._insert_text(line, tag)
self._remove_old_lines(num_lines)
def get_iter_at_line(self, line_number):
iterator = self.textbuffer.get_iter_at_line(line_number)
if GTK_API_VERSION >= 4:
_position_found, iterator = iterator
return iterator
def get_has_selection(self):
return self.textbuffer.get_has_selection()
def get_text(self):
start_iter = self.textbuffer.get_start_iter()
self.end_iter = self.textbuffer.get_end_iter()
return self.textbuffer.get_text(start_iter, self.end_iter, include_hidden_chars=True)
def get_tags_for_pos(self, pos_x, pos_y):
buf_x, buf_y = self.widget.window_to_buffer_coords(Gtk.TextWindowType.WIDGET, pos_x, pos_y)
over_text, iterator, _trailing = self.widget.get_iter_at_position(buf_x, buf_y)
if not over_text:
# Iterators are returned for whitespace after the last character, avoid accidental URL clicks
return []
return iterator.get_tags()
def get_url_for_current_pos(self):
for tag in self.get_tags_for_pos(self.pressed_x, self.pressed_y):
if hasattr(tag, "url"):
return tag.url
return ""
def grab_focus(self):
self.widget.grab_focus()
def place_cursor_at_line(self, line_number):
iterator = self.get_iter_at_line(line_number)
self.textbuffer.place_cursor(iterator)
def set_text(self, text):
"""Sets text without any additional processing, and clears the undo stack."""
self.textbuffer.set_text(text)
self.end_iter = self.textbuffer.get_end_iter()
def update_cursor(self, pos_x, pos_y):
cursor = self.TEXT_CURSOR
if self.cursor_window is None:
self.cursor_window = self.widget.get_window(Gtk.TextWindowType.TEXT) # pylint: disable=no-member
for tag in self.get_tags_for_pos(pos_x, pos_y):
if hasattr(tag, "username"):
cursor = self.DEFAULT_CURSOR
break
if hasattr(tag, "url"):
cursor = self.POINTER_CURSOR
break
if cursor != self.cursor_window.get_cursor():
self.cursor_window.set_cursor(cursor)
def clear(self):
self.set_text("")
# Text Tags (Usernames, URLs) #
def create_tag(self, color_id=None, callback=None, username=None, url=None):
tag = self.textbuffer.create_tag()
if color_id:
update_tag_visuals(tag, color_id=color_id)
tag.color_id = color_id
if url:
if url.startswith("www."):
url = "http://" + url
tag.url = url
if username:
tag.callback = callback
tag.username = username
return tag
def update_tag(self, tag, color_id=None):
if color_id is not None:
tag.color_id = color_id
update_tag_visuals(tag, color_id=tag.color_id)
def update_tags(self):
self.textbuffer.get_tag_table().foreach(self.update_tag)
# Events #
def on_released_primary(self, _controller, _num_p, pressed_x, pressed_y):
self.pressed_x = pressed_x
self.pressed_y = pressed_y
if self.textbuffer.get_has_selection():
return False
for tag in self.get_tags_for_pos(pressed_x, pressed_y):
if hasattr(tag, "url"):
open_uri(tag.url)
return True
if hasattr(tag, "username"):
tag.callback(pressed_x, pressed_y, tag.username)
return True
return False
def on_pressed_secondary(self, _controller, _num_p, pressed_x, pressed_y):
self.pressed_x = pressed_x
self.pressed_y = pressed_y
if self.textbuffer.get_has_selection():
return False
for tag in self.get_tags_for_pos(pressed_x, pressed_y):
if hasattr(tag, "username"):
tag.callback(pressed_x, pressed_y, tag.username)
return True
return False
def on_move_cursor(self, _controller, pos_x, pos_y):
self.update_cursor(pos_x, pos_y)
def on_move_cursor_event(self, _widget, event):
self.update_cursor(event.x, event.y)
def on_copy_text(self, *_args):
self.widget.emit("copy-clipboard")
def on_copy_link(self, *_args):
clipboard.copy_text(self.get_url_for_current_pos())
def on_copy_all_text(self, *_args):
clipboard.copy_text(self.get_text())
def on_clear_all_text(self, *_args):
self.clear()
def on_adjustment_upper_changed(self, *_args):
new_adjustment_bottom = (self.adjustment.get_upper() - self.adjustment.get_page_size())
if self.auto_scroll and self.adjustment_value >= self.adjustment_bottom:
# Scroll to bottom if we were at the bottom previously
self.scroll_bottom()
self.adjustment_bottom = new_adjustment_bottom
def on_adjustment_value_changed(self, *_args):
new_value = self.adjustment.get_value()
if new_value.is_integer() and (0 < new_value < self.adjustment_bottom):
# The textview scrolls up on its own sometimes. Ignore these garbage values.
return
self.adjustment_value = new_value
class ChatView(TextView):
def __init__(self, *args, chat_entry=None, status_users=None, username_event=None, **kwargs):
super().__init__(*args, **kwargs)
self.user_tags = self.status_users = {}
self.chat_entry = chat_entry
self.username_event = username_event
if status_users is not None:
# In chatrooms, we only want to set the online status for users that are
# currently in the room, even though we might know their global status
self.status_users = status_users
self.default_tags = {
"remote": self.create_tag("chatremote"),
"local": self.create_tag("chatlocal"),
"command": self.create_tag("chatcommand"),
"action": self.create_tag("chatme"),
"hilite": self.create_tag("chathilite")
}
Accelerator("Down", self.widget, self.on_page_down_accelerator)
Accelerator("Page_Down", self.widget, self.on_page_down_accelerator)
def append_log_lines(self, log_lines, login_username=None):
if not log_lines:
return
login_username_lower = login_username.lower() if login_username else None
for log_line in log_lines:
try:
line = log_line.decode("utf-8")
except UnicodeDecodeError:
line = log_line.decode("latin-1")
user = message_type = usertag = None
if " [" in line and "] " in line:
start = line.find(" [") + 2
end = line.find("] ", start)
if end > start:
user = line[start:end]
usertag = self.get_user_tag(user)
text = line[end + 2:-1]
if user == login_username:
message_type = "local"
elif login_username_lower and find_whole_word(login_username_lower, text.lower()) > -1:
message_type = "hilite"
else:
message_type = "remote"
elif "* " in line:
message_type = "action"
self.append_line(line, message_type=message_type, username=user, usertag=usertag)
self.append_line(_("--- old messages above ---"), message_type="hilite")
def clear(self):
super().clear()
self.user_tags.clear()
def get_user_tag(self, username):
if username not in self.user_tags:
self.user_tags[username] = self.create_tag(callback=self.username_event, username=username)
self.update_user_tag(username)
return self.user_tags[username]
def update_user_tag(self, username):
if username not in self.user_tags:
return
status = UserStatus.OFFLINE
if username in self.status_users:
status = core.users.statuses.get(username, UserStatus.OFFLINE)
color = USER_STATUS_COLORS.get(status)
self.update_tag(self.user_tags[username], color)
def update_user_tags(self):
for username in self.user_tags:
self.update_user_tag(username)
def on_page_down_accelerator(self, *_args):
"""Page_Down, Down: Give focus to text entry if already scrolled at the
bottom."""
if self.textbuffer.props.cursor_position >= self.textbuffer.get_char_count():
# Give focus to text entry upon scrolling down to the bottom
self.chat_entry.grab_focus_without_selecting()
| 16,556 | Python | .py | 333 | 39.468468 | 110 | 0.634237 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,448 | ui.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/ui.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
from gi.repository import Gtk
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.application import GTK_GUI_FOLDER_PATH
from pynicotine.gtkgui.application import GTK_MINOR_VERSION
from pynicotine.utils import encode_path
# UI Builder #
ui_data = {}
def load(scope, path):
if path not in ui_data:
with open(encode_path(os.path.join(GTK_GUI_FOLDER_PATH, "ui", path)), encoding="utf-8") as file_handle:
ui_content = file_handle.read()
# Translate UI strings using Python's gettext
start_tag = ' translatable="yes">'
end_tag = "</property>"
start_tag_len = len(start_tag)
tag_start_pos = ui_content.find(start_tag)
while tag_start_pos > -1:
string_start_pos = (tag_start_pos + start_tag_len)
string_end_pos = ui_content.find(end_tag, string_start_pos)
original_string = ui_content[string_start_pos:string_end_pos]
translated_string = _(original_string)
if original_string != translated_string:
ui_content = ui_content[:string_start_pos] + translated_string + ui_content[string_end_pos:]
# Find next translatable string
new_string_end_pos = (string_end_pos + (len(translated_string) - len(original_string)))
tag_start_pos = ui_content.find(start_tag, new_string_end_pos)
# GTK 4 replacements
if GTK_API_VERSION >= 4:
ui_content = (
ui_content
.replace("GtkRadioButton", "GtkCheckButton")
.replace('"can-focus"', '"focusable"'))
if GTK_MINOR_VERSION >= 10:
ui_content = (
ui_content
.replace("GtkColorButton", "GtkColorDialogButton")
.replace("GtkFontButton", "GtkFontDialogButton"))
ui_data[path] = ui_content
if GTK_API_VERSION >= 4:
builder = Gtk.Builder(scope)
builder.add_from_string(ui_data[path])
Gtk.Buildable.get_name = Gtk.Buildable.get_buildable_id # pylint: disable=no-member
else:
builder = Gtk.Builder()
builder.add_from_string(ui_data[path])
builder.connect_signals(scope) # pylint: disable=no-member
widgets = builder.get_objects()
for obj in list(widgets):
try:
obj_name = Gtk.Buildable.get_name(obj)
if not obj_name.startswith("_"):
continue
except TypeError:
pass
widgets.remove(obj)
widgets.sort(key=Gtk.Buildable.get_name)
return widgets
| 3,496 | Python | .py | 75 | 37.133333 | 112 | 0.629379 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,449 | dialogs.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/dialogs.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
from gi.repository import Gdk
from gi.repository import GLib
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.combobox import ComboBox
from pynicotine.gtkgui.widgets.textview import TextView
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.window import Window
class Dialog(Window):
def __init__(self, widget=None, parent=None, content_box=None, buttons_start=(), buttons_end=(),
default_button=None, show_callback=None, close_callback=None, title="", width=0, height=0,
modal=True, show_title=True, show_title_buttons=True):
self.parent = parent
self.modal = modal
self.default_width = width
self.default_height = height
self.default_button = default_button
self.show_callback = show_callback
self.close_callback = close_callback
if widget:
super().__init__(widget=widget)
self._set_dialog_properties()
return
container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, vexpand=True, visible=True)
widget = Gtk.Window(
destroy_with_parent=True,
default_width=width,
default_height=height,
child=container
)
super().__init__(widget)
Accelerator("Escape", widget, self.close)
if GTK_API_VERSION == 3:
if os.environ.get("GDK_BACKEND") == "broadway":
# Workaround for dialogs being centered at (0,0) coords on startup
position = Gtk.WindowPosition.CENTER
else:
position = Gtk.WindowPosition.CENTER_ON_PARENT
widget.set_position(position) # pylint: disable=no-member
widget.set_type_hint(Gdk.WindowTypeHint.DIALOG) # pylint: disable=no-member
if content_box:
content_box.set_vexpand(True)
if GTK_API_VERSION >= 4:
container.append(content_box) # pylint: disable=no-member
else:
container.add(content_box) # pylint: disable=no-member
if config.sections["ui"]["header_bar"]:
self._init_header_bar(buttons_start, buttons_end, show_title, show_title_buttons)
else:
self._init_action_area(container, buttons_start, buttons_end)
if default_button:
if GTK_API_VERSION >= 4:
widget.set_default_widget(default_button) # pylint: disable=no-member
else:
default_button.set_can_default(True) # pylint: disable=no-member
widget.set_default(default_button) # pylint: disable=no-member
self.set_title(title)
self._set_dialog_properties()
def _init_header_bar(self, buttons_start=(), buttons_end=(), show_title=True, show_title_buttons=True):
header_bar = Gtk.HeaderBar()
self.widget.set_titlebar(header_bar)
if GTK_API_VERSION >= 4:
header_bar.set_show_title_buttons(show_title_buttons) # pylint: disable=no-member
if not show_title:
header_bar.set_title_widget(Gtk.Box()) # pylint: disable=no-member
add_css_class(header_bar, "flat")
else:
header_bar.set_show_close_button(show_title_buttons) # pylint: disable=no-member
if not show_title:
header_bar.set_custom_title(Gtk.Box(visible=False)) # pylint: disable=no-member
for button in buttons_start:
header_bar.pack_start(button)
for button in reversed(buttons_end):
header_bar.pack_end(button)
header_bar.set_visible(True)
def _init_action_area(self, container, buttons_start=(), buttons_end=()):
if not buttons_start and not buttons_end:
return
action_area = Gtk.Box(visible=True)
action_area_start = Gtk.Box(homogeneous=True, margin_start=6, margin_end=6, margin_top=6, margin_bottom=6,
spacing=6, visible=True)
action_area_end = Gtk.Box(halign=Gtk.Align.END, hexpand=True, homogeneous=True,
margin_start=6, margin_end=6, margin_top=6, margin_bottom=6, spacing=6, visible=True)
add_css_class(action_area, "action-area")
if GTK_API_VERSION >= 4:
container.append(action_area) # pylint: disable=no-member
action_area.append(action_area_start) # pylint: disable=no-member
action_area.append(action_area_end) # pylint: disable=no-member
else:
container.add(action_area) # pylint: disable=no-member
action_area.add(action_area_start) # pylint: disable=no-member
action_area.add(action_area_end) # pylint: disable=no-member
for button in buttons_start:
if GTK_API_VERSION >= 4:
action_area_start.append(button) # pylint: disable=no-member
else:
action_area_start.add(button) # pylint: disable=no-member
for button in buttons_end:
if GTK_API_VERSION >= 4:
action_area_end.append(button) # pylint: disable=no-member
else:
action_area_end.add(button) # pylint: disable=no-member
def _on_show(self, *_args):
self._unselect_focus_label()
self._focus_default_button()
if self.show_callback is not None:
self.show_callback(self)
def _on_close_request(self, *_args):
if self not in Window.active_dialogs:
return False
Window.active_dialogs.remove(self)
if self.close_callback is not None:
self.close_callback(self)
# Hide the dialog
self.widget.set_visible(False)
# "Soft-delete" the dialog. This is necessary to prevent the dialog from
# appearing in window peek on Windows
if sys.platform == "win32" and self.widget.get_titlebar() is None:
self.widget.unrealize()
return True
def _set_dialog_properties(self):
if GTK_API_VERSION >= 4:
self.widget.connect("close-request", self._on_close_request)
else:
self.widget.connect("delete-event", self._on_close_request)
self.widget.connect("show", self._on_show)
# Make all dialogs resizable to fix positioning issue.
# Workaround for https://gitlab.gnome.org/GNOME/mutter/-/issues/3099
self.widget.set_resizable(True)
if self.parent:
self.widget.set_transient_for(self.parent.widget)
def _resize_dialog(self):
if self.widget.get_visible():
return
dialog_width = self.default_width
dialog_height = self.default_height
if not dialog_width and not dialog_height:
return
main_window_width = self.parent.get_width()
main_window_height = self.parent.get_height()
if main_window_width and dialog_width > main_window_width:
dialog_width = main_window_width - 30
if main_window_height and dialog_height > main_window_height:
dialog_height = main_window_height - 30
self.widget.set_default_size(dialog_width, dialog_height)
def _focus_default_button(self):
if not self.default_button:
return
if not self.default_button.get_visible():
return
self.default_button.grab_focus()
def _unselect_focus_label(self):
"""Unselect default focus widget if it's a label."""
focus_widget = self.widget.get_focus()
if isinstance(focus_widget, Gtk.Label):
focus_widget.select_region(start_offset=0, end_offset=0)
self.widget.set_focus(None)
def _finish_present(self, present_callback):
self.widget.set_modal(self.modal and self.parent.is_visible())
present_callback()
def set_show_title_buttons(self, visible):
header_bar = self.widget.get_titlebar()
if header_bar is None:
return
if GTK_API_VERSION >= 4:
header_bar.set_show_title_buttons(visible) # pylint: disable=no-member
else:
header_bar.set_show_close_button(visible) # pylint: disable=no-member
def present(self):
if self not in Window.active_dialogs:
Window.active_dialogs.append(self)
# Shrink the dialog if it's larger than the main window
self._resize_dialog()
# Show dialog after slight delay to work around issue where dialogs don't
# close if another one is shown right after
GLib.idle_add(self._finish_present, super().present)
class MessageDialog(Window):
if GTK_API_VERSION == 3:
class InternalMessageDialog(Gtk.Window):
__gtype_name__ = "MessageDialog"
def __init__(self, *args, **kwargs):
self.set_css_name("messagedialog")
super().__init__(*args, **kwargs)
def __init__(self, parent, title, message, callback=None, callback_data=None, long_message=None,
buttons=None, destructive_response_id=None):
# Prioritize non-message dialogs as parent
for active_dialog in reversed(Window.active_dialogs):
if isinstance(active_dialog, Dialog):
parent = active_dialog
break
self.parent = parent
self.callback = callback
self.callback_data = callback_data
self.destructive_response_id = destructive_response_id
self.container = Gtk.Box(hexpand=True, orientation=Gtk.Orientation.VERTICAL, spacing=6, visible=False)
self.message_label = None
self.default_focus_widget = None
if not buttons:
buttons = [("cancel", _("Close"))]
widget = self._create_dialog(title, message, buttons)
super().__init__(widget=widget)
self._add_long_message(long_message)
def _create_dialog(self, title, message, buttons):
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, visible=True)
add_css_class(vbox, "dialog-vbox")
if GTK_API_VERSION >= 4:
window_class = Gtk.Window
window_child = Gtk.WindowHandle(child=vbox, visible=True)
else:
# Need to subclass Gtk.Window in GTK 3 to set CSS name
window_class = self.InternalMessageDialog
window_child = vbox
widget = window_class(
destroy_with_parent=True,
transient_for=self.parent.widget if self.parent else None,
title=title,
resizable=False,
child=window_child
)
Accelerator("Escape", widget, self.close)
for css_class in ("dialog", "message", "messagedialog"):
add_css_class(widget, css_class)
header_bar = Gtk.Box(height_request=16, visible=True)
box = Gtk.Box(margin_start=24, margin_end=24, visible=True)
message_area = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10, hexpand=True, visible=True)
action_box = Gtk.Box(visible=True)
action_area = Gtk.Box(hexpand=True, homogeneous=True, visible=True)
title_label = Gtk.Label(
halign=Gtk.Align.CENTER, label=title, valign=Gtk.Align.START, wrap=True, max_width_chars=60, visible=True
)
self.message_label = Gtk.Label(
margin_bottom=2, halign=Gtk.Align.CENTER, label=message, valign=Gtk.Align.START, vexpand=True, wrap=True,
max_width_chars=60, visible=True
)
add_css_class(title_label, "title-2")
add_css_class(action_box, "dialog-action-box")
add_css_class(action_area, "dialog-action-area")
if GTK_API_VERSION >= 4:
header_bar_handle = Gtk.WindowHandle(child=header_bar, visible=True)
widget.set_titlebar(header_bar_handle)
widget.connect("close-request", self._on_close_request)
internal_vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, visible=True)
vbox.append(internal_vbox) # pylint: disable=no-member
vbox.append(action_box) # pylint: disable=no-member
internal_vbox.append(box) # pylint: disable=no-member
box.append(message_area) # pylint: disable=no-member
message_area.append(title_label) # pylint: disable=no-member
message_area.append(self.message_label) # pylint: disable=no-member
message_area.append(self.container) # pylint: disable=no-member
action_box.append(action_area) # pylint: disable=no-member
else:
widget.set_position(Gtk.WindowPosition.CENTER_ON_PARENT) # pylint: disable=no-member
widget.set_skip_taskbar_hint(True) # pylint: disable=no-member
widget.set_type_hint(Gdk.WindowTypeHint.DIALOG) # pylint: disable=no-member
widget.set_titlebar(header_bar)
widget.connect("delete-event", self._on_close_request)
vbox.set_spacing(20)
vbox.add(box) # pylint: disable=no-member
vbox.add(action_box) # pylint: disable=no-member
box.add(message_area) # pylint: disable=no-member
message_area.add(title_label) # pylint: disable=no-member
message_area.add(self.message_label) # pylint: disable=no-member
message_area.add(self.container) # pylint: disable=no-member
action_box.add(action_area) # pylint: disable=no-member
for response_type, button_label in buttons:
button = Gtk.Button(use_underline=True, hexpand=True, visible=True)
button.connect("clicked", self._on_button_pressed, response_type)
if GTK_API_VERSION >= 4:
action_area.append(button) # pylint: disable=no-member
else:
action_area.add(button) # pylint: disable=no-member
if response_type == self.destructive_response_id:
add_css_class(button, "destructive-action")
elif response_type in {"cancel", "ok"}:
if GTK_API_VERSION >= 4:
widget.set_default_widget(button) # pylint: disable=no-member
else:
button.set_can_default(True) # pylint: disable=no-member
widget.set_default(button) # pylint: disable=no-member
if response_type == "ok":
add_css_class(button, "suggested-action")
self.message_label.set_mnemonic_widget(button)
self.default_focus_widget = button
# Set mnemonic widget before button label in order for screen reader to
# read both labels
button.set_label(button_label)
return widget
def _add_long_message(self, text):
if not text:
return
box = Gtk.Box(visible=True)
scrolled_window = Gtk.ScrolledWindow(min_content_height=75, max_content_height=200,
hexpand=True, vexpand=True, propagate_natural_height=True, visible=True)
frame = Gtk.Frame(child=box, margin_top=6, visible=True)
if GTK_API_VERSION >= 4:
box.append(scrolled_window) # pylint: disable=no-member
self.container.append(frame) # pylint: disable=no-member
else:
box.add(scrolled_window) # pylint: disable=no-member
self.container.add(frame) # pylint: disable=no-member
textview = self.default_focus_widget = TextView(scrolled_window, editable=False)
textview.append_line(text)
self.container.set_visible(True)
def _on_close_request(self, *_args):
if self in Window.active_dialogs:
Window.active_dialogs.remove(self)
self.destroy()
def _on_button_pressed(self, _button, response_type):
if self.callback and response_type != "cancel":
self.callback(self, response_type, self.callback_data)
# "Run in Background" response already closes all dialogs
if response_type != "run_background":
self.close()
def _finish_present(self, present_callback):
self.widget.set_modal(self.parent and self.parent.is_visible())
present_callback()
def present(self):
if self not in Window.active_dialogs:
Window.active_dialogs.append(self)
if self.default_focus_widget:
self.default_focus_widget.grab_focus()
# Show dialog after slight delay to work around issue where dialogs don't
# close if another one is shown right after
GLib.idle_add(self._finish_present, super().present)
class OptionDialog(MessageDialog):
def __init__(self, *args, option_label="", option_value=False, buttons=None, **kwargs):
if not buttons:
buttons = [
("cancel", _("_No")),
("ok", _("_Yes"))
]
super().__init__(*args, buttons=buttons, **kwargs)
self.toggle = None
if option_label:
self.toggle = self.default_focus_widget = self._add_option_toggle(option_label, option_value)
def _add_option_toggle(self, option_label, option_value):
toggle = Gtk.CheckButton(label=option_label, active=option_value, receives_default=True, visible=True)
if option_label:
if GTK_API_VERSION >= 4:
self.container.append(toggle) # pylint: disable=no-member
else:
self.container.add(toggle) # pylint: disable=no-member
self.container.set_visible(True)
return toggle
def get_option_value(self):
if self.toggle is not None:
return self.toggle.get_active()
return None
class EntryDialog(OptionDialog):
def __init__(self, *args, default="", use_second_entry=False, second_entry_editable=True,
second_default="", action_button_label=_("_OK"), droplist=None, second_droplist=None,
visibility=True, show_emoji_icon=False, **kwargs):
super().__init__(*args, buttons=[
("cancel", _("_Cancel")),
("ok", action_button_label)
], **kwargs)
self.entry_container = None
self.entry_combobox = None
self.second_entry_combobox = None
self.entry_combobox = self.default_focus_widget = self._add_entry_combobox(
default, activates_default=not use_second_entry, visibility=visibility,
show_emoji_icon=show_emoji_icon, droplist=droplist
)
if use_second_entry:
self.second_entry_combobox = self._add_entry_combobox(
second_default, has_entry=second_entry_editable, activates_default=False, visibility=visibility,
show_emoji_icon=show_emoji_icon, droplist=second_droplist
)
def _add_combobox(self, items, has_entry=True, visibility=True, activates_default=True):
combobox = ComboBox(container=self.entry_container, has_entry=has_entry, items=items)
if has_entry:
entry = combobox.entry
entry.set_activates_default(activates_default)
entry.set_width_chars(45)
entry.set_visibility(visibility)
if self.entry_combobox is None:
self.message_label.set_mnemonic_widget(entry if has_entry else combobox.widget)
self.container.set_visible(True)
return combobox
def _add_entry(self, visibility=True, show_emoji_icon=False, activates_default=True):
if GTK_API_VERSION >= 4 and not visibility:
entry = Gtk.PasswordEntry(
activates_default=activates_default, show_peek_icon=True, width_chars=50, visible=True)
else:
entry = Gtk.Entry(
activates_default=activates_default, visibility=visibility, show_emoji_icon=show_emoji_icon,
width_chars=50, visible=True)
if GTK_API_VERSION >= 4:
self.entry_container.append(entry) # pylint: disable=no-member
else:
self.entry_container.add(entry) # pylint: disable=no-member
if self.entry_combobox is None:
self.message_label.set_mnemonic_widget(entry)
self.container.set_visible(True)
return entry
def _add_entry_combobox(self, default, activates_default=True, has_entry=True, visibility=True,
show_emoji_icon=False, droplist=None):
if self.entry_container is None:
self.entry_container = Gtk.Box(hexpand=True, orientation=Gtk.Orientation.VERTICAL, spacing=12, visible=True)
if GTK_API_VERSION >= 4:
self.container.prepend(self.entry_container) # pylint: disable=no-member
else:
self.container.add(self.entry_container) # pylint: disable=no-member
self.container.reorder_child(self.entry_container, position=0) # pylint: disable=no-member
if not has_entry or droplist:
entry_combobox = self._add_combobox(
droplist, has_entry=has_entry, activates_default=activates_default, visibility=visibility)
else:
entry_combobox = self._add_entry(
activates_default=activates_default, visibility=visibility, show_emoji_icon=show_emoji_icon)
entry_combobox.set_text(default)
return entry_combobox
def get_entry_value(self):
return self.entry_combobox.get_text()
def get_second_entry_value(self):
if self.second_entry_combobox is not None:
return self.second_entry_combobox.get_text()
return None
| 23,258 | Python | .py | 439 | 41.949886 | 120 | 0.616879 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,450 | infobar.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/infobar.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.theme import remove_css_class
class InfoBar:
class InternalInfoBar(Gtk.Box):
__gtype_name__ = "InfoBar"
def __init__(self, *args, **kwargs):
self.set_css_name("infobar")
super().__init__(*args, **kwargs)
def __init__(self, parent, button=None):
self.widget = self.InternalInfoBar(visible=True)
self.container = Gtk.Box(visible=True)
self.revealer = Gtk.Revealer(
child=self.container, transition_type=Gtk.RevealerTransitionType.SLIDE_DOWN, visible=True
)
self.label = Gtk.Label(
height_request=24, hexpand=True, margin_top=6, margin_bottom=6, margin_start=12, margin_end=6,
wrap=True, visible=True, xalign=0
)
self.button_container = Gtk.Box(margin_top=6, margin_bottom=6, margin_end=6, visible=True)
self.message_type = None
if GTK_API_VERSION >= 4:
parent.append(self.widget) # pylint: disable=no-member
self.widget.append(self.revealer) # pylint: disable=no-member
self.container.append(self.label) # pylint: disable=no-member
self.container.append(self.button_container) # pylint: disable=no-member
if button:
self.button_container.append(button) # pylint: disable=no-member
else:
parent.add(self.widget) # pylint: disable=no-member
self.widget.add(self.revealer) # pylint: disable=no-member
self.container.add(self.label) # pylint: disable=no-member
self.container.add(self.button_container) # pylint: disable=no-member
if button:
self.button_container.add(button) # pylint: disable=no-member
self.set_visible(False)
def destroy(self):
self.__dict__.clear()
def _show_message(self, message, message_type):
previous_message_type = self.message_type
self.message_type = message_type
if previous_message_type:
remove_css_class(self.widget, previous_message_type)
add_css_class(self.widget, message_type)
self.label.set_text(message)
self.set_visible(True)
def set_visible(self, visible):
self.widget.set_visible(visible)
self.revealer.set_reveal_child(visible)
def show_error_message(self, message):
self._show_message(message, message_type="error")
def show_info_message(self, message):
self._show_message(message, message_type="info")
| 3,539 | Python | .py | 71 | 42.295775 | 106 | 0.660865 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,451 | window.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/window.py | # COPYRIGHT (C) 2022-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.application import LIBADWAITA_API_VERSION
class Window:
DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1 = 19
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
active_dialogs = [] # Class variable keeping dialog objects alive
activation_token = None
def __init__(self, widget):
self.widget = widget
self._dark_mode_handler = None
if GTK_API_VERSION == 3:
return
if sys.platform == "win32":
widget.connect("realize", self._on_realize_win32)
# Use dark window controls on Windows when requested
if LIBADWAITA_API_VERSION:
from gi.repository import Adw # pylint: disable=no-name-in-module
self._dark_mode_handler = Adw.StyleManager.get_default().connect(
"notify::dark", self._on_dark_mode_win32
)
def _menu_popup(self, controller, widget):
if controller.is_active():
widget.activate_action("menu.popup")
def _on_realize_win32(self, *_args):
from ctypes import windll
# Don't overlap taskbar when auto-hidden
h_wnd = self.get_surface().get_handle()
windll.user32.SetPropW(h_wnd, "NonRudeHWND", True)
# Set dark window controls
if LIBADWAITA_API_VERSION:
from gi.repository import Adw # pylint: disable=no-name-in-module
self._on_dark_mode_win32(Adw.StyleManager.get_default())
def _on_dark_mode_win32(self, style_manager, *_args):
surface = self.get_surface()
if surface is None:
return
h_wnd = surface.get_handle()
if h_wnd is None:
return
from ctypes import byref, c_int, sizeof, windll
value = c_int(int(style_manager.get_dark()))
if not windll.dwmapi.DwmSetWindowAttribute(
h_wnd, self.DWMWA_USE_IMMERSIVE_DARK_MODE, byref(value), sizeof(value)
):
windll.dwmapi.DwmSetWindowAttribute(
h_wnd, self.DWMWA_USE_IMMERSIVE_DARK_MODE_BEFORE_20H1, byref(value), sizeof(value)
)
def get_surface(self):
if GTK_API_VERSION >= 4:
return self.widget.get_surface()
return self.widget.get_window()
def get_width(self):
if GTK_API_VERSION >= 4:
return self.widget.get_width()
width, _height = self.widget.get_size()
return width
def get_height(self):
if GTK_API_VERSION >= 4:
return self.widget.get_height()
_width, height = self.widget.get_size()
return height
def get_position(self):
if GTK_API_VERSION >= 4:
return None
return self.widget.get_position()
def is_active(self):
return self.widget.is_active()
def is_maximized(self):
return self.widget.is_maximized()
def is_visible(self):
return self.widget.get_visible()
def set_title(self, title):
self.widget.set_title(title)
def present(self):
if self.activation_token is not None:
# Set XDG activation token if provided by tray icon
self.widget.set_startup_id(self.activation_token)
self.widget.present()
def hide(self):
self.widget.set_visible(False)
def close(self, *_args):
self.widget.close()
def destroy(self):
if self._dark_mode_handler is not None:
from gi.repository import Adw # pylint: disable=no-name-in-module
Adw.StyleManager.get_default().disconnect(self._dark_mode_handler)
self.widget.destroy()
self.__dict__.clear()
| 4,464 | Python | .py | 106 | 33.830189 | 98 | 0.650116 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,452 | textentry.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/textentry.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gi
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.theme import add_css_class
class ChatEntry:
"""Custom text entry with support for chat commands and completions."""
def __init__(self, application, send_message_callback, command_callback, enable_spell_check=False):
self.application = application
self.widget = Gtk.Entry(
hexpand=True, placeholder_text=_("Send message…"), primary_icon_name="mail-send-symbolic",
sensitive=False, show_emoji_icon=True, width_chars=8, visible=True
)
self.send_message_callback = send_message_callback
self.command_callback = command_callback
self.spell_checker = None
self.entity = None
self.chat_view = None
self.unsent_messages = {}
self.completions = {}
self.current_completions = []
self.completion_index = 0
self.midway_completion = False # True if the user just used tab completion
self.selecting_completion = False # True if the list box is open with suggestions
self.is_inserting_completion = False
self.model = Gtk.ListStore(str)
self.column_numbers = list(range(self.model.get_n_columns()))
self.entry_completion = Gtk.EntryCompletion(model=self.model, popup_single_match=False)
self.entry_completion.set_text_column(0)
self.entry_completion.set_match_func(self.entry_completion_find_match)
self.entry_completion.connect("match-selected", self.entry_completion_found_match)
self.widget.set_completion(self.entry_completion)
self.widget.connect("activate", self.on_send_message)
self.widget.connect("changed", self.on_changed)
self.widget.connect("icon-press", self.on_icon_pressed)
Accelerator("<Shift>Tab", self.widget, self.on_tab_complete_accelerator, True)
Accelerator("Tab", self.widget, self.on_tab_complete_accelerator)
Accelerator("Down", self.widget, self.on_page_down_accelerator)
Accelerator("Page_Down", self.widget, self.on_page_down_accelerator)
Accelerator("Page_Up", self.widget, self.on_page_up_accelerator)
self.set_spell_check_enabled(enable_spell_check)
def destroy(self):
if self.spell_checker is not None:
self.spell_checker.destroy()
self.__dict__.clear()
def clear_unsent_message(self, entity):
self.unsent_messages.pop(entity, None)
def grab_focus(self):
self.widget.grab_focus()
def grab_focus_without_selecting(self):
self.widget.grab_focus_without_selecting()
def get_buffer(self):
return self.widget.get_buffer()
def get_position(self):
return self.widget.get_position()
def get_sensitive(self):
return self.widget.get_sensitive()
def get_text(self):
return self.widget.get_text()
def is_completion_enabled(self):
return config.sections["words"]["tab"] or config.sections["words"]["dropdown"]
def insert_text(self, new_text, position):
self.widget.insert_text(new_text, position)
def delete_text(self, start_pos, end_pos):
self.widget.delete_text(start_pos, end_pos)
def add_completion(self, item):
if not self.is_completion_enabled():
return
if item in self.completions:
return
if config.sections["words"]["dropdown"]:
iterator = self.model.insert_with_valuesv(-1, self.column_numbers, [item])
else:
iterator = None
self.completions[item] = iterator
def remove_completion(self, item):
if not self.is_completion_enabled():
return
iterator = self.completions.pop(item, None)
if iterator is not None:
self.model.remove(iterator)
def set_parent(self, entity=None, container=None, chat_view=None):
if self.entity:
self.unsent_messages[self.entity] = self.widget.get_text()
self.entity = entity
self.chat_view = chat_view
parent = self.widget.get_parent()
if parent is not None:
parent.remove(self.widget)
if container is None:
return
unsent_message = self.unsent_messages.get(entity, "")
if GTK_API_VERSION >= 4:
container.append(self.widget) # pylint: disable=no-member
else:
container.add(self.widget) # pylint: disable=no-member
self.widget.set_text(unsent_message)
self.widget.set_position(-1)
def set_completions(self, completions):
if self.entry_completion is None:
return
config_words = config.sections["words"]
self.entry_completion.set_popup_completion(config_words["dropdown"])
self.entry_completion.set_minimum_key_length(config_words["characters"])
self.model.clear()
self.completions.clear()
if not self.is_completion_enabled():
return
for word in sorted(completions):
word = str(word)
if config_words["dropdown"]:
iterator = self.model.insert_with_valuesv(-1, self.column_numbers, [word])
else:
iterator = None
self.completions[word] = iterator
def set_spell_check_enabled(self, enabled):
if self.spell_checker is not None:
self.spell_checker.set_enabled(enabled)
return
if enabled and SpellChecker.is_available():
self.spell_checker = SpellChecker(self.widget)
def set_position(self, position):
self.widget.set_position(position)
def set_sensitive(self, sensitive):
self.widget.set_sensitive(sensitive)
def set_text(self, text):
self.widget.set_text(text)
def set_visible(self, visible):
self.widget.set_visible(visible)
def on_send_message(self, *_args):
text = self.widget.get_text().strip()
if not text:
self.chat_view.scroll_bottom()
return
is_double_slash_cmd = text.startswith("//")
is_single_slash_cmd = (text.startswith("/") and not is_double_slash_cmd)
if not is_single_slash_cmd:
# Regular chat message
self.widget.set_text("")
if is_double_slash_cmd:
# Remove first slash and send the rest of the command as plain text
text = text[1:]
self.send_message_callback(self.entity, text)
return
cmd, _separator, args = text.partition(" ")
args = args.strip()
if not self.command_callback(self.entity, cmd[1:], args):
return
# Clear chat entry
self.widget.set_text("")
def on_icon_pressed(self, _entry, icon_pos, *_args):
if icon_pos == Gtk.EntryIconPosition.PRIMARY:
self.on_send_message()
def entry_completion_find_match(self, _completion, entry_text, iterator):
if not entry_text:
return False
# Get word to the left of current position
if " " in entry_text:
i = self.widget.get_position()
split_key = entry_text[:i].split(" ")[-1]
else:
split_key = entry_text
if not split_key or len(split_key) < config.sections["words"]["characters"]:
return False
# Case-insensitive matching
item_text = self.model.get_value(iterator, 0).lower()
if item_text.startswith(split_key) and item_text != split_key:
self.selecting_completion = True
return True
return False
def entry_completion_found_match(self, _completion, model, iterator):
current_text = self.widget.get_text()
completion_value = model.get_value(iterator, 0)
# if more than a word has been typed, we throw away the
# one to the left of our current position because we want
# to replace it with the matching word
if " " in current_text:
i = self.widget.get_position()
prefix = " ".join(current_text[:i].split(" ")[:-1])
suffix = " ".join(current_text[i:].split(" "))
# add the matching word
new_text = f"{prefix} {completion_value}{suffix}"
# set back the whole text
self.widget.set_text(new_text)
# move the cursor at the end
self.widget.set_position(len(prefix) + len(completion_value) + 1)
else:
self.widget.set_text(completion_value)
self.widget.set_position(-1)
# stop the event propagation
return True
def on_changed(self, *_args):
# If the entry was modified, and we don't block entry_changed_handler, we're no longer completing
if not self.is_inserting_completion:
self.midway_completion = self.selecting_completion = False
def on_tab_complete_accelerator(self, _widget, _state, backwards=False):
"""Tab and Shift+Tab: tab complete chat."""
if not config.sections["words"]["tab"]:
return False
text = self.widget.get_text()
if not text:
return False
# "Hello there Miss<tab> how are you doing"
# "0 3 6 9 12 15 18 21 24 27 30 33
# 1 4 7 10 13 16 19 22 25 28 31
# 2 5 8 11 14 17 20 23 26 29 32
#
# i = 16
# last_word = Miss
# preix = 12
i = self.widget.get_position()
last_word = text[:i].split(" ")[-1]
last_word_len = len(last_word)
preix = i - last_word_len
if not self.midway_completion:
if last_word_len < 1:
return False
last_word_lower = last_word.lower()
self.current_completions = [
x for x in self.completions if x.lower().startswith(last_word_lower) and len(x) >= last_word_len
]
if self.current_completions:
self.midway_completion = True
self.completion_index = -1
current_word = last_word
else:
current_word = self.current_completions[self.completion_index]
if self.midway_completion:
# We're still completing, block entry_changed_handler to avoid modifying midway_completion value
self.is_inserting_completion = True
self.widget.delete_text(i - len(current_word), i)
direction = -1 if backwards else 1
self.completion_index = ((self.completion_index + direction) % len(self.current_completions))
new_word = self.current_completions[self.completion_index]
self.widget.insert_text(new_word, preix)
self.widget.set_position(preix + len(new_word))
self.is_inserting_completion = False
return True
def on_page_down_accelerator(self, *_args):
"""Page_Down, Down - Scroll chat view to bottom, and keep input focus in
entry widget."""
if self.selecting_completion:
return False
self.chat_view.scroll_bottom()
return True
def on_page_up_accelerator(self, *_args):
"""Page_Up - Move up into view to begin scrolling message history."""
if self.selecting_completion:
return False
self.chat_view.grab_focus()
return True
class CompletionEntry:
def __init__(self, widget, model=None, column=0):
self.model = model
self.column = column
self.completions = {}
if model is None:
self.model = model = Gtk.ListStore(str)
self.column_numbers = list(range(self.model.get_n_columns()))
completion = Gtk.EntryCompletion(inline_completion=True, inline_selection=True,
popup_single_match=False, model=model)
completion.set_text_column(column)
completion.set_match_func(self.entry_completion_find_match)
widget.set_completion(completion)
def destroy(self):
self.__dict__.clear()
def add_completion(self, item):
if item not in self.completions:
self.completions[item] = self.model.insert_with_valuesv(-1, self.column_numbers, [item])
def remove_completion(self, item):
iterator = self.completions.pop(item, None)
if iterator is not None:
self.model.remove(iterator)
def clear(self):
self.model.clear()
def entry_completion_find_match(self, _completion, entry_text, iterator):
if not entry_text:
return False
item_text = self.model.get_value(iterator, self.column)
if not item_text:
return False
if item_text.lower().startswith(entry_text.lower()):
return True
return False
class SpellChecker:
checker = None
module = None
def __init__(self, entry):
self.buffer = None
self.entry = None
self._set_entry(entry)
@classmethod
def _load_module(cls):
if GTK_API_VERSION >= 4:
# No spell checkers available in GTK 4 yet
return
if SpellChecker.module is not None:
return
try:
gi.require_version("Gspell", "1")
from gi.repository import Gspell
SpellChecker.module = Gspell
except (ImportError, ValueError):
pass
def _set_entry(self, entry):
if self.entry is not None:
return
# Attempt to load spell check module in case it was recently installed
self._load_module()
if SpellChecker.module is None:
return
if SpellChecker.checker is None:
SpellChecker.checker = SpellChecker.module.Checker()
self.buffer = SpellChecker.module.EntryBuffer.get_from_gtk_entry_buffer(entry.get_buffer())
self.buffer.set_spell_checker(SpellChecker.checker)
self.entry = SpellChecker.module.Entry.get_from_gtk_entry(entry)
self.entry.set_inline_spell_checking(True)
@classmethod
def is_available(cls):
cls._load_module()
return bool(SpellChecker.module)
def set_enabled(self, enabled):
self.entry.set_inline_spell_checking(enabled)
def destroy(self):
self.__dict__.clear()
class TextSearchBar:
def __init__(self, textview, search_bar, controller_widget=None, focus_widget=None,
placeholder_text=None):
self.textview = textview
self.search_bar = search_bar
self.focus_widget = focus_widget
container = Gtk.Box(spacing=6, visible=True)
self.entry = Gtk.SearchEntry(
max_width_chars=75, placeholder_text=placeholder_text, width_chars=24, visible=True
)
self.previous_button = Gtk.Button(tooltip_text=_("Find Previous Match"), visible=True)
self.next_button = Gtk.Button(tooltip_text=_("Find Next Match"), visible=True)
if GTK_API_VERSION >= 4:
self.previous_button.set_icon_name("go-up-symbolic") # pylint: disable=no-member
self.next_button.set_icon_name("go-down-symbolic") # pylint: disable=no-member
container.append(self.entry) # pylint: disable=no-member
container.append(self.previous_button) # pylint: disable=no-member
container.append(self.next_button) # pylint: disable=no-member
self.search_bar.set_child(container) # pylint: disable=no-member
else:
self.previous_button.set_image(Gtk.Image(icon_name="go-up-symbolic")) # pylint: disable=no-member
self.next_button.set_image(Gtk.Image(icon_name="go-down-symbolic")) # pylint: disable=no-member
container.add(self.entry) # pylint: disable=no-member
container.add(self.previous_button) # pylint: disable=no-member
container.add(self.next_button) # pylint: disable=no-member
self.search_bar.add(container) # pylint: disable=no-member
if not controller_widget:
controller_widget = textview
for button in (self.previous_button, self.next_button):
add_css_class(button, "flat")
self.search_bar.connect_entry(self.entry)
self.entry.connect("activate", self.on_search_next_match)
self.entry.connect("search-changed", self.on_search_changed)
self.entry.connect("stop-search", self.on_hide_search_accelerator)
self.entry.connect("previous-match", self.on_search_previous_match)
self.entry.connect("next-match", self.on_search_next_match)
self.previous_button.connect("clicked", self.on_search_previous_match)
self.next_button.connect("clicked", self.on_search_next_match)
Accelerator("Up", self.entry, self.on_search_previous_match)
Accelerator("Down", self.entry, self.on_search_next_match)
Accelerator("<Primary>f", controller_widget, self.on_show_search_accelerator)
Accelerator("Escape", controller_widget, self.on_hide_search_accelerator)
for accelerator in ("<Primary>g", "F3"):
Accelerator(accelerator, controller_widget, self.on_search_next_match)
for accelerator in ("<Shift><Primary>g", "<Shift>F3"):
Accelerator(accelerator, controller_widget, self.on_search_previous_match)
def destroy(self):
self.__dict__.clear()
def on_search_match(self, search_type, restarted=False):
if not self.search_bar.get_search_mode():
return
text_buffer = self.textview.get_buffer()
query = self.entry.get_text()
self.textview.emit("select-all", False)
if search_type == "typing":
start, end = text_buffer.get_bounds()
iterator = start
else:
current = text_buffer.get_mark("insert")
iterator = text_buffer.get_iter_at_mark(current)
if search_type == "previous":
match = iterator.backward_search(
query, Gtk.TextSearchFlags.TEXT_ONLY | Gtk.TextSearchFlags.CASE_INSENSITIVE, limit=None)
else:
match = iterator.forward_search(
query, Gtk.TextSearchFlags.TEXT_ONLY | Gtk.TextSearchFlags.CASE_INSENSITIVE, limit=None)
if match is not None and len(match) == 2:
match_start, match_end = match
if search_type == "previous":
text_buffer.place_cursor(match_start)
text_buffer.select_range(match_start, match_end)
else:
text_buffer.place_cursor(match_end)
text_buffer.select_range(match_end, match_start)
self.textview.scroll_to_iter(match_start, 0, False, 0.5, 0.5)
elif not restarted and search_type != "typing":
start, end = text_buffer.get_bounds()
if search_type == "previous":
text_buffer.place_cursor(end)
elif search_type == "next":
text_buffer.place_cursor(start)
self.on_search_match(search_type, restarted=True)
def on_search_changed(self, *_args):
self.on_search_match(search_type="typing")
def on_search_previous_match(self, *_args):
self.on_search_match(search_type="previous")
return True
def on_search_next_match(self, *_args):
self.on_search_match(search_type="next")
return True
def on_hide_search_accelerator(self, *_args):
"""Escape - hide search bar."""
self.set_visible(False)
return True
def on_show_search_accelerator(self, *_args):
"""Ctrl+F - show search bar."""
self.set_visible(True)
return True
def set_visible(self, visible):
self.search_bar.set_search_mode(visible)
if visible:
text_buffer = self.textview.get_buffer()
selection_bounds = text_buffer.get_selection_bounds()
if selection_bounds:
selection_start, selection_end = selection_bounds
selection_content = text_buffer.get_text(
selection_start, selection_end, include_hidden_chars=True)
if self.entry.get_text().lower() != selection_content.lower():
self.entry.set_text(selection_content)
self.entry.grab_focus()
self.entry.set_position(-1)
return
if self.focus_widget is not None and self.focus_widget.get_sensitive():
self.focus_widget.grab_focus()
return
self.textview.grab_focus()
| 21,867 | Python | .py | 459 | 37.581699 | 112 | 0.622856 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,453 | filechooser.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/filechooser.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
from gi.repository import GdkPixbuf
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Pango
from pynicotine.config import config
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.utils import encode_path
from pynicotine.utils import open_folder_path
class FileChooser:
active_chooser = None # Class variable keeping the file chooser object alive
def __init__(self, parent, callback, callback_data=None, title=_("Select a File"),
initial_folder=None, select_multiple=False):
if initial_folder:
initial_folder = os.path.normpath(os.path.expandvars(initial_folder))
initial_folder_encoded = encode_path(initial_folder)
try:
if not os.path.exists(initial_folder_encoded):
os.makedirs(initial_folder_encoded)
except OSError:
pass
self.parent = parent
self.callback = callback
self.callback_data = callback_data
self.select_multiple = select_multiple
try:
# GTK >= 4.10
self.using_new_api = True
self.file_chooser = Gtk.FileDialog(title=title, modal=True)
if select_multiple:
self.select_method = self.file_chooser.open_multiple
self.finish_method = self.file_chooser.open_multiple_finish
else:
self.select_method = self.file_chooser.open
self.finish_method = self.file_chooser.open_finish
if initial_folder:
self.file_chooser.set_initial_folder(Gio.File.new_for_path(initial_folder))
except AttributeError:
# GTK < 4.10
self.using_new_api = False
self.file_chooser = Gtk.FileChooserNative(
transient_for=parent.widget,
title=title,
select_multiple=select_multiple,
modal=True,
action=Gtk.FileChooserAction.OPEN
)
self.file_chooser.connect("response", self.on_response)
if GTK_API_VERSION >= 4:
if initial_folder:
self.file_chooser.set_current_folder(Gio.File.new_for_path(initial_folder))
return
# Display network shares
self.file_chooser.set_local_only(False) # pylint: disable=no-member
if initial_folder:
self.file_chooser.set_current_folder(initial_folder)
def _get_selected_paths(self, selected_file=None, selected_files=None):
selected = []
if selected_files:
for i_file in selected_files:
path = i_file.get_path()
if path:
selected.append(os.path.normpath(path))
elif selected_file is not None:
path = selected_file.get_path()
if path:
selected.append(os.path.normpath(path))
return selected
def on_finish(self, _dialog, result):
FileChooser.active_chooser = None
try:
selected_result = self.finish_method(result)
except GLib.GError:
# Nothing was selected
self.destroy()
return
selected = []
if self.select_multiple:
selected = self._get_selected_paths(selected_files=selected_result)
else:
selected = self._get_selected_paths(selected_file=selected_result)
if selected:
self.callback(selected, self.callback_data)
self.destroy()
def on_response(self, _dialog, response_id):
FileChooser.active_chooser = None
self.file_chooser.destroy()
if response_id != Gtk.ResponseType.ACCEPT:
self.destroy()
return
if self.select_multiple:
selected = self._get_selected_paths(selected_files=self.file_chooser.get_files())
else:
selected = self._get_selected_paths(selected_file=self.file_chooser.get_file())
if selected:
self.callback(selected, self.callback_data)
self.destroy()
def present(self):
FileChooser.active_chooser = self
if not self.using_new_api:
self.file_chooser.show()
return
self.select_method(parent=self.parent.widget, callback=self.on_finish)
def destroy(self):
self.__dict__.clear()
class FolderChooser(FileChooser):
def __init__(self, parent, callback, callback_data=None, title=_("Select a Folder"),
initial_folder=None, select_multiple=False):
super().__init__(parent, callback, callback_data, title, initial_folder, select_multiple=select_multiple)
self.file_chooser.set_accept_label(_("_Select"))
if not self.using_new_api:
self.file_chooser.set_action(Gtk.FileChooserAction.SELECT_FOLDER)
return
if select_multiple:
self.select_method = self.file_chooser.select_multiple_folders
self.finish_method = self.file_chooser.select_multiple_folders_finish
return
self.select_method = self.file_chooser.select_folder
self.finish_method = self.file_chooser.select_folder_finish
class ImageChooser(FileChooser):
def __init__(self, parent, callback, callback_data=None, title=_("Select an Image"),
initial_folder=None, select_multiple=False):
super().__init__(parent, callback, callback_data, title, initial_folder, select_multiple=select_multiple)
# Only show image files
file_filter = Gtk.FileFilter()
file_filter.set_name(_("All images"))
for pattern in ("*.png", "*.jpg", "*.jpeg", "*.bmp", "*.tiff", "*.gif"):
file_filter.add_pattern(pattern)
if self.using_new_api:
filters = Gio.ListStore(item_type=Gtk.FileFilter)
filters.append(file_filter)
self.file_chooser.set_filters(filters)
self.file_chooser.set_default_filter(file_filter)
return
self.file_chooser.add_filter(file_filter)
self.file_chooser.set_filter(file_filter)
if GTK_API_VERSION == 3 and sys.platform not in {"win32", "darwin"}:
# Image preview
self.file_chooser.connect("update-preview", self.on_update_image_preview)
self.preview = Gtk.Image()
self.file_chooser.set_preview_widget(self.preview) # pylint: disable=no-member
def on_update_image_preview(self, chooser):
file_path = chooser.get_preview_filename()
try:
image_data = GdkPixbuf.Pixbuf.new_from_file_at_size(file_path, width=300, height=700)
self.preview.set_from_pixbuf(image_data)
chooser.set_preview_widget_active(True)
except Exception:
chooser.set_preview_widget_active(False)
class FileChooserSave(FileChooser):
def __init__(self, parent, callback, callback_data=None, title=_("Save as…"),
initial_folder=None, initial_file=""):
super().__init__(parent, callback, callback_data, title, initial_folder)
if GTK_API_VERSION == 3:
# Display hidden files
self.file_chooser.set_show_hidden(True) # pylint: disable=no-member
self.file_chooser.set_do_overwrite_confirmation(True) # pylint: disable=no-member
if not self.using_new_api:
self.file_chooser.set_action(Gtk.FileChooserAction.SAVE)
self.file_chooser.set_current_name(initial_file)
return
self.select_method = self.file_chooser.save
self.finish_method = self.file_chooser.save_finish
self.file_chooser.set_initial_name(initial_file)
class FileChooserButton:
def __init__(self, container, window, label=None, end_button=None, chooser_type="file",
is_flat=False, selected_function=None):
self.window = window
self.chooser_type = chooser_type
self.selected_function = selected_function
self.path = ""
widget = Gtk.Box(visible=True)
self.chooser_button = Gtk.Button(hexpand=True, valign=Gtk.Align.CENTER, visible=True)
self.chooser_button.connect("clicked", self.on_open_file_chooser)
if label:
label.set_mnemonic_widget(self.chooser_button)
icon_names = {
"file": "folder-documents-symbolic",
"folder": "folder-symbolic",
"image": "folder-pictures-symbolic"
}
label_container = Gtk.Box(spacing=6, visible=True)
self.icon = Gtk.Image(icon_name=icon_names.get(chooser_type), visible=True)
self.label = Gtk.Label(label=_("(None)"), ellipsize=Pango.EllipsizeMode.END, width_chars=3,
mnemonic_widget=self.chooser_button, xalign=0, visible=True)
self.open_folder_button = Gtk.Button(
tooltip_text=_("Open in File Manager"), valign=Gtk.Align.CENTER, visible=False)
if GTK_API_VERSION >= 4:
container.append(widget) # pylint: disable=no-member
widget.append(self.chooser_button) # pylint: disable=no-member
widget.append(self.open_folder_button) # pylint: disable=no-member
label_container.append(self.icon) # pylint: disable=no-member
label_container.append(self.label) # pylint: disable=no-member
self.chooser_button.set_child(label_container) # pylint: disable=no-member
self.open_folder_button.set_icon_name("external-link-symbolic") # pylint: disable=no-member
if end_button:
widget.append(end_button) # pylint: disable=no-member
else:
container.add(widget) # pylint: disable=no-member
widget.add(self.chooser_button) # pylint: disable=no-member
widget.add(self.open_folder_button) # pylint: disable=no-member
label_container.add(self.icon) # pylint: disable=no-member
label_container.add(self.label) # pylint: disable=no-member
self.chooser_button.add(label_container) # pylint: disable=no-member
self.open_folder_button.set_image( # pylint: disable=no-member
Gtk.Image(icon_name="external-link-symbolic"))
if end_button:
widget.add(end_button) # pylint: disable=no-member
if is_flat:
widget.set_spacing(6)
for button in (self.chooser_button, self.open_folder_button):
add_css_class(button, "flat")
else:
add_css_class(widget, "linked")
self.open_folder_button.connect("clicked", self.on_open_folder)
def destroy(self):
self.__dict__.clear()
def on_open_file_chooser_response(self, selected, _data):
selected_path = next(iter(selected), None)
if not selected_path:
return
if selected_path.startswith(config.data_folder_path):
# Use a dynamic path that can be expanded with os.path.expandvars()
selected_path = selected_path.replace(config.data_folder_path, "${NICOTINE_DATA_HOME}", 1)
self.set_path(selected_path)
try:
self.selected_function()
except TypeError:
# No function defined
pass
def on_open_file_chooser(self, *_args):
if self.chooser_type == "folder":
FolderChooser(
parent=self.window,
callback=self.on_open_file_chooser_response,
initial_folder=self.path
).present()
return
folder_path = os.path.dirname(self.path) if self.path else None
if self.chooser_type == "image":
ImageChooser(
parent=self.window,
callback=self.on_open_file_chooser_response,
initial_folder=folder_path
).present()
return
FileChooser(
parent=self.window,
callback=self.on_open_file_chooser_response,
initial_folder=folder_path
).present()
def on_open_folder(self, *_args):
path = os.path.expandvars(self.path)
folder_path = os.path.expandvars(path if self.chooser_type == "folder" else os.path.dirname(path))
open_folder_path(folder_path, create_folder=True)
def get_path(self):
return self.path
def set_path(self, path):
if not path:
return
self.path = path = os.path.normpath(path)
self.chooser_button.set_tooltip_text(os.path.expandvars(path)) # Show path without env variables
self.label.set_label(os.path.basename(path))
self.open_folder_button.set_visible(True)
def clear(self):
self.path = ""
self.chooser_button.set_tooltip_text(None)
self.label.set_label(_("(None)"))
self.open_folder_button.set_visible(False)
| 14,065 | Python | .py | 289 | 37.934256 | 113 | 0.623325 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,454 | trayicon.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/trayicon.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import sys
from gi.repository import GdkPixbuf
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
import pynicotine
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.application import GTK_GUI_FOLDER_PATH
from pynicotine.gtkgui.widgets.theme import ICON_THEME
from pynicotine.gtkgui.widgets.window import Window
from pynicotine.logfacility import log
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import encode_path
from pynicotine.utils import truncate_string_byte
class ImplementationUnavailable(Exception):
pass
class BaseImplementation:
def __init__(self, application):
self.application = application
self.menu_items = {}
self.menu_item_id = 1
self.activate_callback = application.on_window_hide_unhide
self.is_visible = True
self._create_menu()
def _create_item(self, text=None, callback=None, check=False):
item = {"id": self.menu_item_id, "visible": True}
if text is not None:
item["text"] = text
if callback is not None:
item["callback"] = callback
if check:
item["toggled"] = False
self.menu_items[self.menu_item_id] = item
self.menu_item_id += 1
return item
def _set_item_text(self, item, text):
item["text"] = text
def _set_item_visible(self, item, visible):
item["visible"] = visible
def _set_item_toggled(self, item, toggled):
item["toggled"] = toggled
def _create_menu(self):
self.show_hide_item = self._create_item("placeholder", self.application.on_window_hide_unhide)
self._create_item()
self.downloads_item = self._create_item("placeholder", self.application.on_downloads)
self.uploads_item = self._create_item("placeholder", self.application.on_uploads)
self._create_item()
self._create_item(_("Private Chat"), self.application.on_private_chat)
self._create_item(_("Chat Rooms"), self.application.on_chat_rooms)
self._create_item(_("Searches"), self.application.on_searches)
self._create_item()
self.away_item = self._create_item(_("Away"), self.application.on_away, check=True)
self.connect_item = self._create_item(_("_Connect"), self.application.on_connect)
self.disconnect_item = self._create_item(_("_Disconnect"), self.application.on_disconnect)
self._create_item()
self._create_item(_("Preferences"), self.application.on_preferences)
self._create_item(_("_Quit"), self.application.on_quit_request)
def _update_window_visibility(self):
if self.application.window is None:
return
label = _("Hide Nicotine+") if self.application.window.is_visible() else _("Show Nicotine+")
if self.show_hide_item.get("text") != label:
self._set_item_text(self.show_hide_item, label)
def _update_user_status(self):
should_update = False
connect_visible = core.users.login_status == UserStatus.OFFLINE
away_visible = not connect_visible
away_toggled = core.users.login_status == UserStatus.AWAY
if self.connect_item.get("visible") != connect_visible:
self._set_item_visible(self.connect_item, connect_visible)
should_update = True
if self.disconnect_item.get("visible") == connect_visible:
self._set_item_visible(self.disconnect_item, not connect_visible)
should_update = True
if self.away_item.get("visible") != away_visible:
self._set_item_visible(self.away_item, away_visible)
should_update = True
if self.away_item.get("toggled") != away_toggled:
self._set_item_toggled(self.away_item, away_toggled)
should_update = True
if should_update:
self._update_icon()
def _update_icon(self):
# Check for highlights, and display highlight icon if there is a highlighted room or private chat
if (self.application.window
and (self.application.window.chatrooms.highlighted_rooms
or self.application.window.privatechat.highlighted_users)):
icon_name = "msg"
elif core.users.login_status == UserStatus.ONLINE:
icon_name = "connect"
elif core.users.login_status == UserStatus.AWAY:
icon_name = "away"
else:
icon_name = "disconnect"
icon_name = f"{pynicotine.__application_id__}-{icon_name}"
self._set_icon_name(icon_name)
def _set_icon_name(self, icon_name):
# Implemented in subclasses
pass
def _update_icon_theme(self):
# Implemented in subclasses
pass
def update(self):
self.is_visible = config.sections["ui"]["trayicon"]
self._update_icon_theme()
self._update_icon()
self._update_window_visibility()
self._update_user_status()
def set_download_status(self, status):
self._set_item_text(self.downloads_item, status)
def set_upload_status(self, status):
self._set_item_text(self.uploads_item, status)
def show_notification(self, title, message, action=None, action_target=None, high_priority=False):
# Implemented in subclasses
pass
def unload(self, is_shutdown=True):
# Implemented in subclasses
pass
class StatusNotifierImplementation(BaseImplementation):
class DBusProperty:
def __init__(self, name, signature, value):
self.name = name
self.signature = signature
self.value = value
class DBusSignal:
def __init__(self, name, args):
self.name = name
self.args = args
class DBusMethod:
def __init__(self, name, in_args, out_args, callback):
self.name = name
self.in_args = in_args
self.out_args = out_args
self.callback = callback
class DBusService:
def __init__(self, interface_name, object_path, bus_type):
self._interface_name = interface_name
self._object_path = object_path
self._bus = Gio.bus_get_sync(bus_type)
self._registration_id = None
self.properties = {}
self.signals = {}
self.methods = {}
def register(self):
xml_output = f"<node name='/'><interface name='{self._interface_name}'>"
for property_name, prop in self.properties.items():
xml_output += f"<property name='{property_name}' type='{prop.signature}' access='read'/>"
for method_name, method in self.methods.items():
xml_output += f"<method name='{method_name}'>"
for in_signature in method.in_args:
xml_output += f"<arg type='{in_signature}' direction='in'/>"
for out_signature in method.out_args:
xml_output += f"<arg type='{out_signature}' direction='out'/>"
xml_output += "</method>"
for signal_name, signal in self.signals.items():
xml_output += f"<signal name='{signal_name}'>"
for signature in signal.args:
xml_output += f"<arg type='{signature}'/>"
xml_output += "</signal>"
xml_output += "</interface></node>"
registration_id = self._bus.register_object(
object_path=self._object_path,
interface_info=Gio.DBusNodeInfo.new_for_xml(xml_output).interfaces[0],
method_call_closure=self.on_method_call,
get_property_closure=self.on_get_property,
set_property_closure=None
)
if not registration_id:
raise GLib.Error(f"Failed to register object with path {self._object_path}")
self._registration_id = registration_id
def unregister(self):
if self._registration_id is None:
return
self._bus.unregister_object(self._registration_id)
self._registration_id = None
def add_property(self, name, signature, value):
self.properties[name] = StatusNotifierImplementation.DBusProperty(name, signature, value)
def add_signal(self, name, args):
self.signals[name] = StatusNotifierImplementation.DBusSignal(name, args)
def add_method(self, name, in_args, out_args, callback):
self.methods[name] = StatusNotifierImplementation.DBusMethod(name, in_args, out_args, callback)
def _emit_signal(self, name, parameters=None):
self._bus.emit_signal(
destination_bus_name=None,
object_path=self._object_path,
interface_name=self._interface_name,
signal_name=name,
parameters=parameters
)
def on_method_call(self, _connection, _sender, _path, _interface_name, method_name, parameters, invocation):
method = self.methods[method_name]
out_parameters = method.callback(*parameters.unpack())
invocation.return_value(out_parameters)
def on_get_property(self, _connection, _sender, _path, _interface_name, property_name):
prop = self.properties[property_name]
return GLib.Variant(prop.signature, prop.value)
class DBusMenuService(DBusService):
def __init__(self, menu_items):
super().__init__(
interface_name="com.canonical.dbusmenu",
object_path="/StatusNotifierItem/menu",
bus_type=Gio.BusType.SESSION
)
self._items = menu_items
for method_name, in_args, out_args, callback in (
("GetGroupProperties", ("ai", "as"), ("a(ia{sv})",), self.on_get_group_properties),
("GetLayout", ("i", "i", "as"), ("u", "(ia{sv}av)"), self.on_get_layout),
("Event", ("i", "s", "v", "u"), (), self.on_event),
):
self.add_method(method_name, in_args, out_args, callback)
for signal_name, value in (
("LayoutUpdated", ("u", "i")),
):
self.add_signal(signal_name, value)
def update_item(self, item):
item_id = item["id"]
if item_id not in self._items:
return
self._items[item_id] = item
self._emit_signal(
name="ItemsPropertiesUpdated",
parameters=GLib.Variant.new_tuple(
GLib.Variant.new_array(
children=[
GLib.Variant.new_tuple(
GLib.Variant.new_int32(item_id),
GLib.Variant.new_array(children=self._serialize_item(item))
)
],
),
GLib.Variant.new_array(child_type=GLib.VariantType("(ias)"))
)
)
@staticmethod
def _serialize_item(item):
def dict_entry(key, value):
return GLib.Variant.new_dict_entry(
GLib.Variant.new_string(key),
GLib.Variant.new_variant(value)
)
props = []
if "text" in item:
props.append(dict_entry("label", GLib.Variant.new_string(item["text"])))
if item.get("toggled") is not None:
props.append(dict_entry("toggle-type", GLib.Variant.new_string("checkmark")))
props.append(dict_entry("toggle-state", GLib.Variant.new_int32(int(item["toggled"]))))
else:
props.append(dict_entry("type", GLib.Variant.new_string("separator")))
props.append(dict_entry("visible", GLib.Variant.new_boolean(item["visible"])))
return props
def on_get_group_properties(self, ids, _properties):
item_properties = []
requested_ids = set(ids)
for idx, item in self._items.items():
# According to the spec, if no IDs are requested, we should send the entire menu
if requested_ids and idx not in requested_ids:
continue
item_properties.append(
GLib.Variant.new_tuple(
GLib.Variant.new_int32(idx),
GLib.Variant.new_array(children=self._serialize_item(item))
)
)
return GLib.Variant.new_tuple(
GLib.Variant.new_array(children=item_properties)
)
def on_get_layout(self, _parent_id, _recursion_depth, _property_names):
revision = 0
serialized_items = []
for idx, item in self._items.items():
serialized_item = GLib.Variant.new_variant(
GLib.Variant.new_tuple(
GLib.Variant.new_int32(idx),
GLib.Variant.new_array(children=self._serialize_item(item)),
GLib.Variant.new_array(child_type=GLib.VariantType("v"))
)
)
serialized_items.append(serialized_item)
return GLib.Variant.new_tuple(
GLib.Variant.new_uint32(revision),
GLib.Variant.new_tuple(
GLib.Variant.new_int32(0),
GLib.Variant.new_array(child_type=GLib.VariantType("{sv}")),
GLib.Variant.new_array(children=serialized_items)
)
)
def on_event(self, idx, event_id, _data, _timestamp):
if event_id == "clicked":
self._items[idx]["callback"]()
class StatusNotifierItemService(DBusService):
def __init__(self, activate_callback, menu_items):
super().__init__(
interface_name="org.kde.StatusNotifierItem",
object_path="/StatusNotifierItem",
bus_type=Gio.BusType.SESSION
)
self.menu = StatusNotifierImplementation.DBusMenuService(menu_items)
for property_name, signature, value in (
("Category", "s", "Communications"),
("Id", "s", pynicotine.__application_id__),
("Title", "s", pynicotine.__application_name__),
("ToolTip", "(sa(iiay)ss)", ("", [], pynicotine.__application_name__, "")),
("Menu", "o", "/StatusNotifierItem/menu"),
("ItemIsMenu", "b", False),
("IconName", "s", ""),
("IconThemePath", "s", ""),
("Status", "s", "Active")
):
self.add_property(property_name, signature, value)
for method_name, in_args, out_args, callback in (
("Activate", ("i", "i"), (), activate_callback),
("ProvideXdgActivationToken", ("s",), (), self.on_provide_activation_token)
):
self.add_method(method_name, in_args, out_args, callback)
for signal_name, value in (
("NewIcon", ()),
("NewIconThemePath", ("s",)),
("NewStatus", ("s",))
):
self.add_signal(signal_name, value)
def register(self):
self.menu.register()
super().register()
def unregister(self):
super().unregister()
self.menu.unregister()
def update_icon(self):
self._emit_signal("NewIcon")
def update_icon_theme(self, icon_path):
self._emit_signal(
name="NewIconThemePath",
parameters=GLib.Variant.new_tuple(
GLib.Variant.new_string(icon_path)
)
)
def update_status(self, status):
self._emit_signal(
name="NewStatus",
parameters=GLib.Variant.new_tuple(
GLib.Variant.new_string(status)
)
)
def on_provide_activation_token(self, token):
Window.activation_token = token
def __init__(self, application):
super().__init__(application)
self.tray_icon = None
self.custom_icons = False
try:
self.bus = Gio.bus_get_sync(bus_type=Gio.BusType.SESSION)
self.tray_icon = self.StatusNotifierItemService(
activate_callback=self.activate_callback,
menu_items=self.menu_items
)
self.tray_icon.register()
self.bus.call_sync(
bus_name="org.kde.StatusNotifierWatcher",
object_path="/StatusNotifierWatcher",
interface_name="org.kde.StatusNotifierWatcher",
method_name="RegisterStatusNotifierItem",
parameters=GLib.Variant.new_tuple(
GLib.Variant.new_string(self.bus.get_unique_name())
),
reply_type=None,
flags=Gio.DBusCallFlags.NONE,
timeout_msec=1000,
cancellable=None
)
except GLib.Error as error:
self.unload()
raise ImplementationUnavailable(f"StatusNotifier implementation not available: {error}") from error
@staticmethod
def _check_icon_path(icon_name, icon_path):
"""Check if tray icons exist in the specified icon path."""
if not icon_path:
return False
icon_scheme = f"{pynicotine.__application_id__}-{icon_name}.".encode()
try:
with os.scandir(encode_path(icon_path)) as entries:
for entry in entries:
if entry.is_file() and entry.name.startswith(icon_scheme):
return True
except OSError as error:
log.add_debug("Error accessing tray icon path %s: %s", (icon_path, error))
return False
def _get_icon_path(self):
"""Returns an icon path to use for tray icons, or None to fall back to
system-wide icons."""
self.custom_icons = False
custom_icon_path = os.path.join(config.data_folder_path, ".nicotine-icon-theme")
if hasattr(sys, "real_prefix") or sys.base_prefix != sys.prefix:
# Virtual environment
local_icon_path = os.path.join(sys.prefix, "share", "icons", "hicolor", "scalable", "apps")
else:
# Git folder
local_icon_path = os.path.join(GTK_GUI_FOLDER_PATH, "icons", "hicolor", "scalable", "apps")
for icon_name in ("away", "connect", "disconnect", "msg"):
# Check if custom icons exist
if config.sections["ui"]["icontheme"] and self._check_icon_path(icon_name, custom_icon_path):
self.custom_icons = True
return custom_icon_path
# Check if local icons exist
if self._check_icon_path(icon_name, local_icon_path):
return local_icon_path
return ""
def _set_icon_name(self, icon_name):
icon_name_property = self.tray_icon.properties["IconName"]
if self.custom_icons:
# Use alternative icon names to enforce custom icons, since system-wide icons take precedence
icon_name = icon_name.replace(pynicotine.__application_id__, "nplus-tray")
if icon_name_property.value != icon_name:
icon_name_property.value = icon_name
self.tray_icon.update_icon()
if not self.is_visible:
return
status_property = self.tray_icon.properties["Status"]
status = "Active"
if status_property.value != status:
status_property.value = status
self.tray_icon.update_status(status)
def _update_icon_theme(self):
# If custom icon path was found, use it, otherwise we fall back to system icons
icon_path = self._get_icon_path()
icon_path_property = self.tray_icon.properties["IconThemePath"]
if icon_path_property.value == icon_path:
return
icon_path_property.value = icon_path
self.tray_icon.update_icon_theme(icon_path)
if icon_path:
log.add_debug("Using tray icon path %s", icon_path)
def _set_item_text(self, item, text):
super()._set_item_text(item, text)
self.tray_icon.menu.update_item(item)
def _set_item_visible(self, item, visible):
super()._set_item_visible(item, visible)
self.tray_icon.menu.update_item(item)
def _set_item_toggled(self, item, toggled):
super()._set_item_toggled(item, toggled)
self.tray_icon.menu.update_item(item)
def unload(self, is_shutdown=True):
if self.tray_icon is None:
return
status_property = self.tray_icon.properties["Status"]
status = "Passive"
if status_property.value != status:
status_property.value = status
self.tray_icon.update_status(status)
if is_shutdown:
self.tray_icon.unregister()
self.tray_icon = None
class Win32Implementation(BaseImplementation):
"""Windows NotifyIcon implementation.
https://learn.microsoft.com/en-us/windows/win32/shell/notification-area
https://learn.microsoft.com/en-us/windows/win32/shell/taskbar
"""
WINDOW_CLASS_NAME = "NicotineTrayIcon"
NIM_ADD = 0
NIM_MODIFY = 1
NIM_DELETE = 2
NIF_MESSAGE = 1
NIF_ICON = 2
NIF_TIP = 4
NIF_INFO = 16
NIF_REALTIME = 64
NIIF_NOSOUND = 16
MIIM_STATE = 1
MIIM_ID = 2
MIIM_STRING = 64
MFS_ENABLED = 0
MFS_UNCHECKED = 0
MFS_DISABLED = 3
MFS_CHECKED = 8
MFT_SEPARATOR = 2048
WM_NULL = 0
WM_DESTROY = 2
WM_CLOSE = 16
WM_COMMAND = 273
WM_LBUTTONUP = 514
WM_RBUTTONUP = 517
WM_USER = 1024
WM_TRAYICON = (WM_USER + 1)
NIN_BALLOONHIDE = (WM_USER + 3)
NIN_BALLOONTIMEOUT = (WM_USER + 4)
NIN_BALLOONUSERCLICK = (WM_USER + 5)
CS_VREDRAW = 1
CS_HREDRAW = 2
COLOR_WINDOW = 5
IDC_ARROW = 32512
WS_OVERLAPPED = 0
WS_SYSMENU = 524288
CW_USEDEFAULT = -2147483648
IMAGE_ICON = 1
LR_LOADFROMFILE = 16
SM_CXSMICON = 49
if sys.platform == "win32":
from ctypes import Structure
class WNDCLASSW(Structure):
from ctypes import CFUNCTYPE, wintypes
LPFN_WND_PROC = CFUNCTYPE(
wintypes.INT,
wintypes.HWND,
wintypes.UINT,
wintypes.WPARAM,
wintypes.LPARAM
)
_fields_ = [
("style", wintypes.UINT),
("lpfn_wnd_proc", LPFN_WND_PROC),
("cb_cls_extra", wintypes.INT),
("cb_wnd_extra", wintypes.INT),
("h_instance", wintypes.HINSTANCE),
("h_icon", wintypes.HICON),
("h_cursor", wintypes.HANDLE),
("hbr_background", wintypes.HBRUSH),
("lpsz_menu_name", wintypes.LPCWSTR),
("lpsz_class_name", wintypes.LPCWSTR)
]
class MENUITEMINFOW(Structure):
from ctypes import wintypes
_fields_ = [
("cb_size", wintypes.UINT),
("f_mask", wintypes.UINT),
("f_type", wintypes.UINT),
("f_state", wintypes.UINT),
("w_id", wintypes.UINT),
("h_sub_menu", wintypes.HMENU),
("hbmp_checked", wintypes.HBITMAP),
("hbmp_unchecked", wintypes.HBITMAP),
("dw_item_data", wintypes.LPVOID),
("dw_type_data", wintypes.LPWSTR),
("cch", wintypes.UINT),
("hbmp_item", wintypes.HBITMAP)
]
class NOTIFYICONDATAW(Structure):
from ctypes import wintypes
_fields_ = [
("cb_size", wintypes.DWORD),
("h_wnd", wintypes.HWND),
("u_id", wintypes.UINT),
("u_flags", wintypes.UINT),
("u_callback_message", wintypes.UINT),
("h_icon", wintypes.HICON),
("sz_tip", wintypes.WCHAR * 128),
("dw_state", wintypes.DWORD),
("dw_state_mask", wintypes.DWORD),
("sz_info", wintypes.WCHAR * 256),
("u_version", wintypes.UINT),
("sz_info_title", wintypes.WCHAR * 64),
("dw_info_flags", wintypes.DWORD),
("guid_item", wintypes.CHAR * 16),
("h_balloon_icon", wintypes.HICON)
]
def __init__(self, application):
from ctypes import windll
super().__init__(application)
self._window_class = None
self._h_wnd = None
self._notify_id = None
self._h_icon = None
self._menu = None
self._wm_taskbarcreated = windll.user32.RegisterWindowMessageW("TaskbarCreated")
self._click_action = None
self._click_action_target = None
self._register_class()
self._create_window()
def _register_class(self):
from ctypes import byref, windll
self._window_class = self.WNDCLASSW(
style=(self.CS_VREDRAW | self.CS_HREDRAW),
lpfn_wnd_proc=self.WNDCLASSW.LPFN_WND_PROC(self.on_process_window_message),
h_cursor=windll.user32.LoadCursorW(0, self.IDC_ARROW),
hbr_background=self.COLOR_WINDOW,
lpsz_class_name=self.WINDOW_CLASS_NAME
)
windll.user32.RegisterClassW(byref(self._window_class))
def _unregister_class(self):
if self._window_class is None:
return
from ctypes import windll
windll.user32.UnregisterClassW(self.WINDOW_CLASS_NAME, self._window_class.h_instance)
self._window_class = None
def _create_window(self):
from ctypes import windll
style = self.WS_OVERLAPPED | self.WS_SYSMENU
self._h_wnd = windll.user32.CreateWindowExW(
0,
self.WINDOW_CLASS_NAME,
self.WINDOW_CLASS_NAME,
style,
0,
0,
self.CW_USEDEFAULT,
self.CW_USEDEFAULT,
0,
0,
0,
None
)
windll.user32.UpdateWindow(self._h_wnd)
def _destroy_window(self):
if self._h_wnd is None:
return
from ctypes import windll
windll.user32.DestroyWindow(self._h_wnd)
self._h_wnd = None
def _load_ico_buffer(self, icon_name, icon_size):
ico_buffer = b""
if GTK_API_VERSION >= 4:
icon = ICON_THEME.lookup_icon(icon_name, fallbacks=None, size=icon_size, scale=1, direction=0, flags=0)
icon_path = icon.get_file().get_path()
if not icon_path:
return ico_buffer
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(icon_path, icon_size, icon_size)
else:
icon = ICON_THEME.lookup_icon(icon_name, size=icon_size, flags=0)
if not icon:
return ico_buffer
pixbuf = icon.load_icon()
_success, ico_buffer = pixbuf.save_to_bufferv("ico")
return ico_buffer
def _load_h_icon(self, icon_name):
from ctypes import windll
# Attempt to load custom icons first
icon_size = windll.user32.GetSystemMetrics(self.SM_CXSMICON)
ico_buffer = self._load_ico_buffer(
icon_name.replace(f"{pynicotine.__application_id__}-", "nplus-tray-"), icon_size)
if not ico_buffer:
# No custom icons present, fall back to default icons
ico_buffer = self._load_ico_buffer(icon_name, icon_size)
try:
import tempfile
file_handle = tempfile.NamedTemporaryFile(delete=False)
with file_handle:
file_handle.write(ico_buffer)
return windll.user32.LoadImageA(
0,
encode_path(file_handle.name),
self.IMAGE_ICON,
icon_size,
icon_size,
self.LR_LOADFROMFILE
)
finally:
os.remove(file_handle.name)
def _destroy_h_icon(self):
from ctypes import windll
if self._h_icon:
windll.user32.DestroyIcon(self._h_icon)
self._h_icon = None
def _update_notify_icon(self, title="", message="", icon_name=None, click_action=None,
click_action_target=None, high_priority=False):
# pylint: disable=attribute-defined-outside-init,no-member
if self._h_wnd is None:
return
if icon_name:
self._destroy_h_icon()
self._h_icon = self._load_h_icon(icon_name)
if not self.is_visible and not (title or message):
# When disabled by user, temporarily show tray icon when displaying a notification
return
from ctypes import byref, sizeof, windll
notify_action = self.NIM_MODIFY
if self._notify_id is None:
self._notify_id = self.NOTIFYICONDATAW(
cb_size=sizeof(self.NOTIFYICONDATAW),
h_wnd=self._h_wnd,
u_id=0,
u_flags=(self.NIF_ICON | self.NIF_MESSAGE | self.NIF_TIP | self.NIF_INFO),
u_callback_message=self.WM_TRAYICON,
sz_tip=truncate_string_byte(pynicotine.__application_name__, byte_limit=127)
)
notify_action = self.NIM_ADD
if config.sections["notifications"]["notification_popup_sound"]:
self._notify_id.dw_info_flags &= ~self.NIIF_NOSOUND
else:
self._notify_id.dw_info_flags |= self.NIIF_NOSOUND
if high_priority:
self._notify_id.u_flags &= ~self.NIF_REALTIME
else:
self._notify_id.u_flags |= self.NIF_REALTIME
self._notify_id.h_icon = self._h_icon
self._notify_id.sz_info_title = truncate_string_byte(title, byte_limit=63, ellipsize=True)
self._notify_id.sz_info = truncate_string_byte(message, byte_limit=255, ellipsize=True)
self._click_action = click_action.replace("app.", "") if click_action else None
self._click_action_target = GLib.Variant.new_string(click_action_target) if click_action_target else None
windll.shell32.Shell_NotifyIconW(notify_action, byref(self._notify_id))
def _remove_notify_icon(self):
from ctypes import byref, windll
if self._notify_id:
windll.shell32.Shell_NotifyIconW(self.NIM_DELETE, byref(self._notify_id))
self._notify_id = None
self._destroy_menu()
def _serialize_menu_item(self, item):
# pylint: disable=attribute-defined-outside-init,no-member
from ctypes import sizeof
item_info = self.MENUITEMINFOW(cb_size=sizeof(self.MENUITEMINFOW))
w_id = item["id"]
text = item.get("text")
is_checked = item.get("toggled")
item_info.f_mask |= self.MIIM_ID
item_info.w_id = w_id
if text is not None:
item_info.f_mask |= self.MIIM_STRING
item_info.dw_type_data = text.replace("_", "&") # Mnemonics use &
else:
item_info.f_type |= self.MFT_SEPARATOR
if is_checked is not None:
item_info.f_mask |= self.MIIM_STATE
item_info.f_state |= self.MFS_CHECKED if is_checked else self.MFS_UNCHECKED
return item_info
def _show_menu(self):
from ctypes import byref, windll, wintypes
self._populate_menu()
pos = wintypes.POINT()
windll.user32.GetCursorPos(byref(pos))
# PRB: Menus for Notification Icons Do Not Work Correctly
# https://web.archive.org/web/20121015064650/http://support.microsoft.com/kb/135788
windll.user32.SetForegroundWindow(self._h_wnd)
windll.user32.TrackPopupMenu(
self._menu,
0,
pos.x,
pos.y,
0,
self._h_wnd,
None
)
windll.user32.PostMessageW(self._h_wnd, self.WM_NULL, 0, 0)
def _populate_menu(self):
from ctypes import byref, windll
self._destroy_menu()
if self._menu is None:
self._menu = windll.user32.CreatePopupMenu()
for item in self.menu_items.values():
if not item["visible"]:
continue
item_id = item["id"]
item_info = self._serialize_menu_item(item)
windll.user32.InsertMenuItemW(self._menu, item_id, False, byref(item_info))
def _destroy_menu(self):
if self._menu is None:
return
from ctypes import windll
windll.user32.DestroyMenu(self._menu)
self._menu = None
def _set_icon_name(self, icon_name):
self._update_notify_icon(icon_name=icon_name)
def on_process_window_message(self, h_wnd, msg, w_param, l_param):
from ctypes import windll, wintypes
if msg == self.WM_TRAYICON:
if l_param == self.WM_RBUTTONUP:
# Icon pressed
self._show_menu()
elif l_param == self.WM_LBUTTONUP:
# Icon pressed
self.activate_callback()
elif l_param in {self.NIN_BALLOONHIDE, self.NIN_BALLOONTIMEOUT, self.NIN_BALLOONUSERCLICK}:
if l_param == self.NIN_BALLOONUSERCLICK and self._click_action is not None:
# Notification was clicked, perform action
self.application.lookup_action(self._click_action).activate(self._click_action_target)
self._click_action = self._click_action_target = None
if not config.sections["ui"]["trayicon"]:
# Notification dismissed, but user has disabled tray icon
self._remove_notify_icon()
elif msg == self.WM_COMMAND:
# Menu item pressed
menu_item_id = w_param & 0xFFFF
menu_item_callback = self.menu_items[menu_item_id]["callback"]
menu_item_callback()
elif msg == self._wm_taskbarcreated:
# Taskbar process restarted, create new icon
self._remove_notify_icon()
self._update_notify_icon()
return windll.user32.DefWindowProcW(
wintypes.HWND(h_wnd),
msg,
wintypes.WPARAM(w_param),
wintypes.LPARAM(l_param)
)
def show_notification(self, title, message, action=None, action_target=None, high_priority=False):
self._update_notify_icon(
title=title, message=message, click_action=action, click_action_target=action_target,
high_priority=high_priority)
def unload(self, is_shutdown=True):
self._remove_notify_icon()
if not is_shutdown:
# Keep notification support as long as we're running
return
self._destroy_h_icon()
self._destroy_window()
self._unregister_class()
class StatusIconImplementation(BaseImplementation):
def __init__(self, application):
super().__init__(application)
if not hasattr(Gtk, "StatusIcon") or os.environ.get("WAYLAND_DISPLAY"):
# GtkStatusIcon does not work on Wayland
raise ImplementationUnavailable("StatusIcon implementation not available")
self.tray_icon = Gtk.StatusIcon(tooltip_text=pynicotine.__application_name__)
self.tray_icon.connect("activate", self.activate_callback)
self.tray_icon.connect("popup-menu", self.on_status_icon_popup)
self.gtk_menu = self._build_gtk_menu()
GLib.idle_add(self._update_icon)
def on_status_icon_popup(self, _status_icon, button, _activate_time):
if button == 3:
time = Gtk.get_current_event_time()
self.gtk_menu.popup(None, None, None, None, button, time)
def _set_item_text(self, item, text):
super()._set_item_text(item, text)
item["gtk_menu_item"].set_label(text)
def _set_item_visible(self, item, visible):
super()._set_item_visible(item, visible)
item["gtk_menu_item"].set_visible(visible)
def _set_item_toggled(self, item, toggled):
super()._set_item_toggled(item, toggled)
gtk_menu_item = item["gtk_menu_item"]
with gtk_menu_item.handler_block(item["gtk_handler"]):
gtk_menu_item.set_active(toggled)
def _build_gtk_menu(self):
gtk_menu = Gtk.Menu()
for item in self.menu_items.values():
text = item.get("text")
if text is None:
item["gtk_menu_item"] = gtk_menu_item = Gtk.SeparatorMenuItem(visible=True)
else:
gtk_menu_item_class = Gtk.CheckMenuItem if "toggled" in item else Gtk.MenuItem
item["gtk_menu_item"] = gtk_menu_item = gtk_menu_item_class(
label=text, use_underline=True, visible=True
)
item["gtk_handler"] = gtk_menu_item.connect("activate", item["callback"])
gtk_menu.append(gtk_menu_item)
return gtk_menu
def _set_icon_name(self, icon_name):
if not self.tray_icon.get_visible():
self.tray_icon.set_visible(True)
if self.tray_icon.is_embedded() and self.tray_icon.get_icon_name() != icon_name:
self.tray_icon.set_from_icon_name(icon_name)
def unload(self, is_shutdown=True):
if self.tray_icon.get_visible():
self.tray_icon.set_visible(False)
class TrayIcon:
def __init__(self, application):
self.application = application
self.available = True
self.implementation = None
self.watch_id = None
self._watch_availability()
self.load()
def _watch_availability(self):
if sys.platform in {"win32", "darwin"}:
return
if self.watch_id is not None:
return
self.watch_id = Gio.bus_watch_name(
bus_type=Gio.BusType.SESSION,
name="org.kde.StatusNotifierWatcher",
flags=Gio.BusNameWatcherFlags.NONE,
name_appeared_closure=self.load,
name_vanished_closure=self.unload
)
def _unwatch_availability(self):
if self.watch_id is not None:
Gio.bus_unwatch_name(self.watch_id)
self.watch_id = None
def load(self, *_args):
self.available = True
if sys.platform == "win32":
# Always keep tray icon loaded for Windows notification support
pass
elif not config.sections["ui"]["trayicon"]:
# No need to have tray icon loaded now (unless this is Windows)
return
if self.implementation is None:
if sys.platform == "win32":
self.implementation = Win32Implementation(self.application)
elif sys.platform == "darwin":
self.available = False
else:
try:
self.implementation = StatusNotifierImplementation(self.application)
except ImplementationUnavailable:
try:
self.implementation = StatusIconImplementation(self.application)
self._unwatch_availability()
except ImplementationUnavailable:
self.available = False
return
self.update()
def set_download_status(self, status):
if self.implementation:
self.implementation.set_download_status(status)
def set_upload_status(self, status):
if self.implementation:
self.implementation.set_upload_status(status)
def show_notification(self, title, message, action=None, action_target=None, high_priority=False):
if self.implementation:
self.implementation.show_notification(
title=title, message=message, action=action, action_target=action_target,
high_priority=high_priority)
def update(self):
if self.implementation:
self.implementation.update()
def unload(self, *_args, is_shutdown=True):
if self.implementation:
self.implementation.unload(is_shutdown=is_shutdown)
self.implementation.is_visible = False
if is_shutdown:
self.implementation = None
self.available = False
def destroy(self):
self.unload()
self.__dict__.clear()
| 41,842 | Python | .py | 931 | 33.058002 | 116 | 0.584825 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,455 | popover.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/popover.py | # COPYRIGHT (C) 2022-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets.theme import add_css_class
class Popover:
def __init__(self, window, content_box=None, show_callback=None, close_callback=None, width=0, height=0):
self.window = window
self.show_callback = show_callback
self.close_callback = close_callback
self.default_width = width
self.default_height = height
self.widget = Gtk.Popover(child=content_box)
self.menu_button = None
self.widget.connect("map", self._on_map)
self.widget.connect("unmap", self._on_unmap)
add_css_class(self.widget, "custom")
if GTK_API_VERSION == 3:
return
# Workaround for popover not closing in GTK 4
# https://gitlab.gnome.org/GNOME/gtk/-/issues/4529
self.has_clicked_content = False
for widget, callback in (
(self.widget, self._on_click_popover_gtk4),
(content_box.get_parent(), self._on_click_content_gtk4)
):
gesture_click = Gtk.GestureClick(button=0)
gesture_click.connect("pressed", callback)
widget.add_controller(gesture_click)
def _on_click_popover_gtk4(self, *_args):
if not self.has_clicked_content:
# Clicked outside the popover, close it. Normally GTK handles this,
# but due to a bug, a popover intercepts clicks outside it after
# closing a child popover.
self.close()
self.has_clicked_content = False
def _on_click_content_gtk4(self, *_args):
self.has_clicked_content = True
def _on_map(self, *_args):
self._resize_popover()
if self.show_callback is not None:
self.show_callback(self)
def _on_unmap(self, *_args):
if self.close_callback is not None:
self.close_callback(self)
def _resize_popover(self):
popover_width = self.default_width
popover_height = self.default_height
if not popover_width and not popover_height:
return
if GTK_API_VERSION == 3:
main_window_width = self.window.get_width()
main_window_height = self.window.get_height()
if main_window_width and popover_width > main_window_width:
popover_width = main_window_width - 60
if main_window_height and popover_height > main_window_height:
popover_height = main_window_height - 60
scrollable = self.widget.get_child()
scrollable.set_max_content_width(popover_width)
scrollable.set_max_content_height(popover_height)
def set_menu_button(self, menu_button):
if self.menu_button:
self.menu_button.set_popover(None)
if menu_button:
menu_button.set_popover(self.widget)
self.menu_button = menu_button
def present(self):
self.widget.popup()
def close(self, use_transition=True):
if use_transition:
self.widget.popdown()
return
self.widget.set_visible(False)
def destroy(self):
self.set_menu_button(None)
self.__dict__.clear()
| 3,988 | Python | .py | 91 | 35.604396 | 109 | 0.659067 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,456 | treeview.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/treeview.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2008-2009 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import time
import gi.module
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import GObject
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import clipboard
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.theme import FILE_TYPE_ICON_LABELS
from pynicotine.gtkgui.widgets.theme import USER_STATUS_ICON_LABELS
from pynicotine.gtkgui.widgets.theme import add_css_class
class TreeView:
def __init__(self, window, parent, columns, has_tree=False, multi_select=False,
persistent_sort=False, name=None, secondary_name=None, activate_row_callback=None,
focus_in_callback=None, select_row_callback=None, delete_accelerator_callback=None,
search_entry=None):
self.window = window
self.widget = Gtk.TreeView(fixed_height_mode=True, has_tooltip=True, visible=True)
self.model = None
self.multi_select = multi_select
self.iterators = {}
self.has_tree = has_tree
self._widget_name = name
self._secondary_name = secondary_name
self._columns = columns
self._data_types = []
self._iterator_keys = {}
self._iterator_key_column = 0
self._column_ids = {}
self._column_offsets = {}
self._column_gvalues = {}
self._column_gesture_controllers = []
self._column_numbers = None
self._default_sort_column = None
self._default_sort_type = Gtk.SortType.ASCENDING
self._sort_column = None
self._sort_type = None
self._persistent_sort = persistent_sort
self._columns_changed_handler = None
self._last_redraw_time = 0
self._selection = self.widget.get_selection()
self._h_adjustment = parent.get_hadjustment()
self._v_adjustment = parent.get_vadjustment()
self._v_adjustment_upper = 0
self._v_adjustment_value = 0
self._is_scrolling_to_row = False
self.notify_value_handler = self._v_adjustment.connect("notify::value", self.on_v_adjustment_value)
if GTK_API_VERSION >= 4:
parent.set_child(self.widget) # pylint: disable=no-member
else:
parent.add(self.widget) # pylint: disable=no-member
self._initialise_columns(columns)
Accelerator("<Primary>c", self.widget, self.on_copy_cell_data_accelerator)
Accelerator("<Primary>f", self.widget, self.on_start_search)
Accelerator("Left", self.widget, self.on_collapse_row_accelerator)
Accelerator("minus", self.widget, self.on_collapse_row_blocked_accelerator)
Accelerator("Right", self.widget, self.on_expand_row_accelerator)
Accelerator("plus", self.widget, self.on_expand_row_blocked_accelerator)
Accelerator("equal", self.widget, self.on_expand_row_blocked_accelerator)
Accelerator("backslash", self.widget, self.on_expand_row_level_accelerator)
self._column_menu = self.widget.column_menu = PopupMenu(
self.window.application, self.widget, callback=self.on_column_header_menu, connect_events=False)
if multi_select:
self.widget.set_rubber_banding(True)
self._selection.set_mode(Gtk.SelectionMode.MULTIPLE)
if activate_row_callback:
self.widget.connect("row-activated", self.on_activate_row, activate_row_callback)
if focus_in_callback:
if GTK_API_VERSION >= 4:
focus_controller = Gtk.EventControllerFocus()
focus_controller.connect("enter", self.on_focus_in, focus_in_callback)
self.widget.add_controller(focus_controller) # pylint: disable=no-member
else:
self.widget.connect("focus-in-event", self.on_focus_in, focus_in_callback)
if select_row_callback:
self._selection.connect("changed", self.on_select_row, select_row_callback)
if delete_accelerator_callback:
Accelerator("Delete", self.widget, self.on_delete_accelerator, delete_accelerator_callback)
if search_entry:
self.widget.set_search_entry(search_entry)
self._query_tooltip_handler = self.widget.connect("query-tooltip", self.on_tooltip)
self.widget.connect("move-cursor", self.on_key_move_cursor)
self.widget.set_search_equal_func(self.on_search_match)
add_css_class(self.widget, "treeview-spacing")
def destroy(self):
# Prevent updates while destroying widget
self.widget.disconnect(self._columns_changed_handler)
self.widget.disconnect(self._query_tooltip_handler)
self._v_adjustment.disconnect(self.notify_value_handler)
self._column_menu.destroy()
self.__dict__.clear()
def create_model(self):
# Bypass Tree/ListStore overrides for improved performance in set_value()
gtk_module = gi.module.get_introspection_module("Gtk")
model_class = gtk_module.TreeStore if self.has_tree else gtk_module.ListStore
if hasattr(gtk_module.ListStore, "insert_with_valuesv"):
gtk_module.ListStore.insert_with_values = gtk_module.ListStore.insert_with_valuesv
self.model = model_class()
self.model.set_column_types(self._data_types)
if self._sort_column is not None and self._sort_type is not None:
self.model.set_sort_column_id(self._sort_column, self._sort_type)
self.widget.set_model(self.model)
return self.model
def redraw(self):
"""Workaround for GTK 3 issue where GtkTreeView doesn't refresh changed
values if horizontal scrolling is present while fixed-height mode is
enabled."""
if GTK_API_VERSION != 3 or self._h_adjustment.get_value() <= 0:
return
current_time = time.monotonic()
if (current_time - self._last_redraw_time) < 1:
return
self._last_redraw_time = current_time
self.widget.queue_draw()
def _append_columns(self, cols, column_config):
# Restore column order from config
for column_id in column_config:
column = cols.get(column_id)
if column is not None:
self.widget.append_column(column)
added_columns = self.widget.get_columns()
# If any columns were missing in the config, append them
for index, column in enumerate(cols.values()):
if column not in added_columns:
self.widget.insert_column(column, index)
# Read Show / Hide column settings from last session
for column_id, column in cols.items():
column.set_visible(bool(column_config.get(column_id, {}).get("visible", True)))
def _update_column_properties(self, *_args):
columns = self.widget.get_columns()
resizable_set = False
for column in reversed(columns):
if not column.get_visible():
continue
if not resizable_set:
# Make sure the last visible column isn't resizable
column.set_resizable(False)
column.set_fixed_width(-1)
resizable_set = True
continue
# Make the previously last column resizable again
column.set_resizable(True)
break
# Set first non-icon column as the expander column
for column in columns:
if column.type != "icon" and column.get_visible():
self.widget.set_expander_column(column)
break
def _initialise_column_ids(self, columns):
self._data_types = []
int_types = {GObject.TYPE_UINT, GObject.TYPE_UINT64}
for column_index, (column_id, column_data) in enumerate(columns.items()):
data_type = column_data.get("data_type")
if not data_type:
column_type = column_data.get("column_type")
if column_type == "progress":
data_type = GObject.TYPE_INT
elif column_type == "toggle":
data_type = GObject.TYPE_BOOLEAN
else:
data_type = GObject.TYPE_STRING
self._column_ids[column_id] = column_index
self._data_types.append(data_type)
if data_type in int_types:
self._column_gvalues[column_index] = GObject.Value(data_type)
self._column_numbers = list(self._column_ids.values())
def _initialise_columns(self, columns):
self._initialise_column_ids(columns)
self.model = self.create_model()
progress_padding = 1
height_padding = 4
width_padding = 10 if GTK_API_VERSION >= 4 else 12
column_widgets = {}
column_config = {}
has_visible_column_header = False
for column_index, (column_id, column_data) in enumerate(columns.items()):
title = column_data.get("title")
iterator_key = column_data.get("iterator_key")
sort_data_column = column_data.get("sort_column", column_id)
sort_column_id = self._column_ids[sort_data_column]
default_sort_type = column_data.get("default_sort_type")
if iterator_key:
# Use values from this column as keys for iterator mapping
self._iterator_key_column = column_index
if default_sort_type:
# Sort treeview by values in this column by default
self._default_sort_column = sort_column_id
self._default_sort_type = (Gtk.SortType.DESCENDING if default_sort_type == "descending"
else Gtk.SortType.ASCENDING)
if self._sort_column is None and self._sort_type is None:
self._sort_column = self._default_sort_column
self._sort_type = self._default_sort_type
self.model.set_sort_column_id(self._default_sort_column, self._default_sort_type)
if title is None:
# Hidden data column
continue
column_type = column_data["column_type"]
width = column_data.get("width")
should_expand_column = column_data.get("expand_column")
sensitive_column = column_data.get("sensitive_column")
if self._widget_name:
try:
column_config = config.sections["columns"][self._widget_name][self._secondary_name]
except KeyError:
column_config = config.sections["columns"][self._widget_name]
column_properties = column_config.get(column_id, {})
column_sort_type = column_properties.get("sort")
# Restore saved column width if the column size is fixed. For expandable
# columns, the width becomes the minimum width, so use the default value in those cases.
if not should_expand_column and column_type != "icon":
width = column_properties.get("width", width)
if column_sort_type and self._persistent_sort:
# Sort treeview by values in this column by default
self._sort_column = sort_column_id
self._sort_type = (Gtk.SortType.DESCENDING if column_sort_type == "descending"
else Gtk.SortType.ASCENDING)
self.model.set_sort_column_id(self._sort_column, self._sort_type)
# Allow individual cells to receive visual focus
mode = Gtk.CellRendererMode.ACTIVATABLE if len(columns) > 1 else Gtk.CellRendererMode.INERT
xalign = 0.0
if column_type == "text":
renderer = Gtk.CellRendererText(
mode=mode, single_paragraph_mode=True, xpad=width_padding, ypad=height_padding
)
column = Gtk.TreeViewColumn(title=title, cell_renderer=renderer, text=column_index)
text_underline_column = column_data.get("text_underline_column")
text_weight_column = column_data.get("text_weight_column")
if text_underline_column:
column.add_attribute(renderer, "underline", self._column_ids[text_underline_column])
if text_weight_column:
column.add_attribute(renderer, "weight", self._column_ids[text_weight_column])
elif column_type == "number":
xalign = 1
renderer = Gtk.CellRendererText(mode=mode, xalign=xalign, xpad=width_padding, ypad=height_padding)
column = Gtk.TreeViewColumn(title=title, cell_renderer=renderer, text=column_index)
column.set_alignment(xalign)
elif column_type == "progress":
xalign = 1
renderer = Gtk.CellRendererProgress(mode=mode, ypad=progress_padding)
column = Gtk.TreeViewColumn(title=title, cell_renderer=renderer, value=column_index)
column.set_alignment(xalign)
elif column_type == "toggle":
xalign = 0.5
renderer = Gtk.CellRendererToggle(mode=mode, xalign=xalign, xpad=13)
renderer.connect("toggled", self.on_toggle, column_data["toggle_callback"])
column = Gtk.TreeViewColumn(title=title, cell_renderer=renderer, active=column_index)
elif column_type == "icon":
icon_args = {}
if column_id == "country":
if GTK_API_VERSION >= 4:
# Custom icon size defined in theme.py
icon_args["icon_size"] = Gtk.IconSize.NORMAL # pylint: disable=no-member
else:
# Use the same size as the original icon
icon_args["stock_size"] = 0
renderer = Gtk.CellRendererPixbuf(mode=mode, xalign=1.0, **icon_args)
column = Gtk.TreeViewColumn(title=title, cell_renderer=renderer, icon_name=column_index)
column_header = column.get_button()
if GTK_API_VERSION >= 4:
gesture_click = Gtk.GestureClick()
column_header.add_controller(gesture_click) # pylint: disable=no-member
else:
gesture_click = Gtk.GestureMultiPress(widget=column_header)
gesture_click.set_propagation_phase(Gtk.PropagationPhase.CAPTURE)
gesture_click.connect("released", self.on_column_header_pressed, column_id, sort_column_id)
self._column_gesture_controllers.append(gesture_click)
title_container = next(iter(column_header))
title_widget = next(iter(title_container)) if xalign < 1 else list(title_container)[-1]
if column_data.get("hide_header"):
title_widget.set_visible(False)
else:
has_visible_column_header = True
# Required for fixed height mode
column.set_sizing(Gtk.TreeViewColumnSizing.FIXED)
if width is not None:
column.set_resizable(column_type != "icon")
if isinstance(width, int) and width > 0:
column.set_fixed_width(width)
column.set_reorderable(True)
column.set_min_width(24)
if xalign == 1 and GTK_API_VERSION >= 4:
# Gtk.TreeViewColumn.set_alignment() only changes the sort arrow position in GTK 4
# Actually align the label to the right here instead
title_widget.set_halign(Gtk.Align.END)
if sensitive_column:
column.add_attribute(renderer, "sensitive", self._column_ids[sensitive_column])
if should_expand_column:
column.set_expand(True)
if self._widget_name:
column.connect("notify::x-offset", self.on_column_position_changed)
column.id = column_id
column.type = column_type
column.tooltip_callback = column_data.get("tooltip_callback")
column.set_sort_column_id(sort_column_id)
column_widgets[column_id] = column
self.widget.set_headers_visible(has_visible_column_header)
self._append_columns(column_widgets, column_config)
self._columns_changed_handler = self.widget.connect("columns-changed", self._update_column_properties)
self.widget.emit("columns-changed")
def save_columns(self):
"""Save a treeview's column widths and visibilities for the next
session."""
if not self._widget_name:
return
saved_columns = {}
column_config = config.sections["columns"]
for column in self.widget.get_columns():
title = column.id
width = column.get_width()
visible = column.get_visible()
sort_column_id = column.get_sort_column_id()
# A column width of zero should not be saved to the config.
# When a column is hidden, the correct width will be remembered during the
# run it was hidden. Subsequent runs will yield a zero width, so we
# attempt to re-use a previously saved non-zero column width instead.
try:
if width <= 0:
if not visible:
saved_columns[title] = {
"visible": visible,
"width": column_config[self._widget_name][title]["width"]
}
continue
except KeyError:
# No previously saved width, going with zero
pass
saved_columns[title] = columns = {"visible": visible, "width": width}
if not self._persistent_sort:
continue
if sort_column_id == self._sort_column and sort_column_id != self._default_sort_column:
columns["sort"] = "descending" if self._sort_type == Gtk.SortType.DESCENDING else "ascending"
if self._secondary_name is not None:
if self._widget_name not in column_config:
column_config[self._widget_name] = {}
column_config[self._widget_name][self._secondary_name] = saved_columns
else:
column_config[self._widget_name] = saved_columns
def freeze(self):
self.model.set_sort_column_id(Gtk.TREE_SORTABLE_UNSORTED_SORT_COLUMN_ID, Gtk.SortType.ASCENDING)
def unfreeze(self):
if self._sort_column is not None and self._sort_type is not None:
self.model.set_sort_column_id(self._sort_column, self._sort_type)
def set_show_expanders(self, show):
self.widget.set_show_expanders(show)
def add_row(self, values, select_row=True, parent_iterator=None):
key = values[self._iterator_key_column]
if key in self.iterators:
return None
position = 0 # Insert at the beginning for large performance improvement
value_columns = []
included_values = []
for index, value in enumerate(values):
if not value and index is not self._sort_column:
# Skip empty values if not active sort column to avoid unnecessary work
continue
if index in self._column_gvalues:
# Need gvalue conversion for large integers
gvalue = self._column_gvalues[index]
gvalue.set_value(value or 0)
value = gvalue
value_columns.append(index)
included_values.append(value)
if self.has_tree:
self.iterators[key] = iterator = self.model.insert_with_values(
parent_iterator, position, value_columns, included_values
)
else:
self.iterators[key] = iterator = self.model.insert_with_values(
position, value_columns, included_values
)
self._iterator_keys[iterator] = key
if select_row:
self.select_row(iterator)
return iterator
def get_selected_rows(self):
_model, paths = self._selection.get_selected_rows()
for path in paths:
yield self.model.get_iter(path)
def get_num_selected_rows(self):
return self._selection.count_selected_rows()
def get_focused_row(self):
path, _column = self.widget.get_cursor()
if path is None:
return None
return self.model.get_iter(path)
def get_row_value(self, iterator, column_id):
return self.model.get_value(iterator, self._column_ids[column_id])
def set_row_value(self, iterator, column_id, value):
column_index = self._column_ids[column_id]
if column_index in self._column_gvalues:
# Need gvalue conversion for large integers
gvalue = self._column_gvalues[column_index]
gvalue.set_value(value)
value = gvalue
return self.model.set_value(iterator, column_index, value)
def set_row_values(self, iterator, column_ids, values):
value_columns = []
for index, column_id in enumerate(column_ids):
column_index = self._column_ids[column_id]
if column_index in self._column_gvalues:
# Need gvalue conversion for large integers
gvalue = self._column_gvalues[column_index]
gvalue.set_value(values[index])
values[index] = gvalue
value_columns.append(column_index)
return self.model.set(iterator, value_columns, values)
def remove_row(self, iterator):
del self.iterators[self._iterator_keys[iterator]]
self.model.remove(iterator)
def select_row(self, iterator=None, expand_rows=True, should_scroll=True):
if iterator is None:
# Select first row if available
iterator = self.model.get_iter_first()
if iterator is None:
return
if should_scroll:
path = self.model.get_path(iterator)
if expand_rows:
self.widget.expand_to_path(path)
self._is_scrolling_to_row = True
self.widget.set_cursor(path)
self.widget.scroll_to_cell(path, column=None, use_align=True, row_align=0.5, col_align=0.5)
return
self._selection.select_iter(iterator)
def select_all_rows(self):
self._selection.select_all()
def unselect_all_rows(self):
self._selection.unselect_all()
def expand_row(self, iterator):
path = self.model.get_path(iterator)
return self.widget.expand_row(path, open_all=False)
def collapse_row(self, iterator):
path = self.model.get_path(iterator)
return self.widget.collapse_row(path)
def expand_all_rows(self):
self.widget.expand_all()
def collapse_all_rows(self):
self.widget.collapse_all()
def expand_root_rows(self):
model = self.model
iterator = model.get_iter_first()
while iterator:
path = model.get_path(iterator)
self.widget.expand_row(path, open_all=False)
iterator = model.iter_next(iterator)
def get_focused_column(self):
_path, column = self.widget.get_cursor()
return column.id
def get_visible_columns(self):
for column in self.widget.get_columns():
if column.get_visible():
yield column.id
def is_empty(self):
return not self.iterators
def is_selection_empty(self):
return self._selection.count_selected_rows() <= 0
def is_row_expanded(self, iterator):
path = self.model.get_path(iterator)
return self.widget.row_expanded(path)
def is_row_selected(self, iterator):
return self._selection.iter_is_selected(iterator)
def grab_focus(self):
self.widget.grab_focus()
def clear(self):
self.widget.set_model(None)
self.freeze()
self.model.clear()
self.iterators.clear()
self._iterator_keys.clear()
self.unfreeze()
self.widget.set_model(self.model)
@staticmethod
def get_icon_label(column, icon_name, is_short_country_label=False):
if column.id == "country":
country_code = icon_name[-2:].upper()
if is_short_country_label:
return country_code
country_name = core.network_filter.COUNTRIES.get(country_code, _("Unknown"))
return f"{country_name} ({country_code})"
if column.id == "status":
return USER_STATUS_ICON_LABELS[icon_name]
if column.id == "file_type":
return FILE_TYPE_ICON_LABELS[icon_name]
return icon_name
def on_toggle(self, _widget, path, callback):
callback(self, self.model.get_iter(path))
def on_activate_row(self, _widget, path, column, callback):
callback(self, self.model.get_iter(path), column.id)
def on_focus_in(self, *args):
if GTK_API_VERSION >= 4:
_widget, callback = args
else:
_widget, _controller, callback = args
callback(self)
def on_select_row(self, selection, callback):
iterator = None
if self.multi_select:
iterator = next(self.get_selected_rows(), None)
else:
_model, iterator = selection.get_selected()
callback(self, iterator)
def on_delete_accelerator(self, _treeview, _state, callback):
callback(self)
def on_column_header_pressed(self, controller, _num_p, _pos_x, _pos_y, column_id, sort_column_id):
"""Reset sorting when column header has been pressed three times."""
self._sort_column, self._sort_type = self.model.get_sort_column_id()
if self._default_sort_column is None:
# No default sort column for treeview, keep standard GTK behavior
self.save_columns()
return False
if self._data_types[sort_column_id] == str or column_id in {"in_queue", "queue_position"}:
# String value (or queue position column): ascending sort by default
first_sort_type = Gtk.SortType.ASCENDING
second_sort_type = Gtk.SortType.DESCENDING
else:
# Numerical value: descending sort by default
first_sort_type = Gtk.SortType.DESCENDING
second_sort_type = Gtk.SortType.ASCENDING
if self._sort_column != sort_column_id:
self._sort_column = sort_column_id
self._sort_type = first_sort_type
elif self._sort_type == first_sort_type:
self._sort_type = second_sort_type
elif self._sort_type == second_sort_type:
# Reset treeview to default state
self._sort_column = self._default_sort_column
self._sort_type = self._default_sort_type
self.model.set_sort_column_id(self._sort_column, self._sort_type)
self.save_columns()
controller.set_state(Gtk.EventSequenceState.CLAIMED)
return True
def on_column_header_toggled(self, _action, _state, column):
column.set_visible(not column.get_visible())
self._update_column_properties()
def on_column_header_menu(self, menu, _treeview):
columns = self.widget.get_columns()
visible_columns = [column for column in columns if column.get_visible()]
menu.clear()
for column_num, column in enumerate(columns, start=1):
title = column.get_title()
if not title:
title = _("Column #%i") % column_num
menu.add_items(
("$" + title, None)
)
menu.update_model()
menu.actions[title].set_state(GLib.Variant.new_boolean(column in visible_columns))
if column in visible_columns:
menu.actions[title].set_enabled(len(visible_columns) > 1)
menu.actions[title].connect("activate", self.on_column_header_toggled, column)
def on_column_position_changed(self, column, _param):
"""Save column position and width to config."""
column_id = column.id
offset = column.get_x_offset()
if self._column_offsets.get(column_id) == offset:
return
self._column_offsets[column_id] = offset
self.save_columns()
def on_key_move_cursor(self, _widget, step, *_args):
if step != Gtk.MovementStep.BUFFER_ENDS:
return
# We are scrolling to the end using the End key. Disable the
# auto-scroll workaround to actually change the scroll adjustment value.
self._is_scrolling_to_row = True
def on_v_adjustment_value(self, *_args):
upper = self._v_adjustment.get_upper()
if not self._is_scrolling_to_row and upper != self._v_adjustment_upper and self._v_adjustment_value <= 0:
# When new rows are added while sorting is enabled, treeviews
# auto-scroll to the new position of the currently visible row.
# Disable this behavior while we're at the top to prevent jumping
# to random positions as rows are populated.
self._v_adjustment.set_value(0)
else:
self._v_adjustment_value = self._v_adjustment.get_value()
self._v_adjustment_upper = upper
self._is_scrolling_to_row = False
def on_search_match(self, model, _column, search_term, iterator):
if not search_term:
return True
accepted_column_types = {"text", "number"}
for column_index, column_data in enumerate(self._columns.values()):
if "column_type" not in column_data:
continue
if column_data["column_type"] not in accepted_column_types:
continue
column_value = model.get_value(iterator, column_index)
if column_value and search_term.lower() in column_value.lower():
return False
return True
def on_tooltip(self, _widget, pos_x, pos_y, _keyboard_mode, tooltip):
bin_x, bin_y = self.widget.convert_widget_to_bin_window_coords(pos_x, pos_y)
is_blank, path, column, _cell_x, _cell_y = self.widget.is_blank_at_pos(bin_x, bin_y)
if is_blank:
return False
iterator = self.model.get_iter(path)
if column.tooltip_callback:
value = column.tooltip_callback(self, iterator)
else:
value = self.get_row_value(iterator, column.id)
if not value:
return False
if not isinstance(value, str):
return False
if column.type == "icon":
value = self.get_icon_label(column, value)
# Update tooltip position
self.widget.set_tooltip_cell(tooltip, path, column)
tooltip.set_text(value)
return True
def on_copy_cell_data_accelerator(self, *_args):
"""Ctrl+C: copy cell data."""
path, column = self.widget.get_cursor()
if path is None:
return False
iterator = self.model.get_iter(path)
value = str(self.model.get_value(iterator, column.get_sort_column_id()))
if not value:
return False
if column.type == "icon":
value = self.get_icon_label(column, value, is_short_country_label=True)
clipboard.copy_text(value)
return True
def on_start_search(self, *_args):
"""Ctrl+F: start search."""
self.widget.emit("start-interactive-search")
def on_collapse_row_accelerator(self, *_args):
"""Left: collapse row."""
iterator = self.get_focused_row()
if iterator is None:
return False
return self.collapse_row(iterator)
def on_collapse_row_blocked_accelerator(self, *_args):
"""minus: collapse row (block search)."""
self.on_collapse_row_accelerator()
return True
def on_expand_row_accelerator(self, *_args):
"""Right: expand row."""
iterator = self.get_focused_row()
if iterator is None:
return False
return self.expand_row(iterator)
def on_expand_row_blocked_accelerator(self, *_args):
"""plus, equal: expand row (block search)."""
self.on_expand_row_accelerator()
return True
def on_expand_row_level_accelerator(self, *_args):
"""\backslash: collapse or expand to show subs."""
iterator = self.get_focused_row()
if iterator is None:
return False
self.collapse_row(iterator) # show 2nd level
self.expand_row(iterator)
return True
# Legacy Functions (to be removed) #
def create_grouping_menu(window, active_mode, callback):
action_id = f"grouping-{GLib.uuid_string_random()}"
menu = Gio.Menu()
menuitem = Gio.MenuItem.new(_("Ungrouped"), f"win.{action_id}::ungrouped")
menu.append_item(menuitem)
menuitem = Gio.MenuItem.new(_("Group by Folder"), f"win.{action_id}::folder_grouping")
menu.append_item(menuitem)
menuitem = Gio.MenuItem.new(_("Group by User"), f"win.{action_id}::user_grouping")
menu.append_item(menuitem)
state = GLib.Variant.new_string(active_mode)
action = Gio.SimpleAction(name=action_id, parameter_type=state.get_type(), state=state)
action.connect("change-state", callback)
window.add_action(action)
action.change_state(state)
return menu
def set_treeview_selected_row(treeview, bin_x, bin_y):
"""Handles row selection when right-clicking in a treeview."""
pathinfo = treeview.get_path_at_pos(bin_x, bin_y)
selection = treeview.get_selection()
if pathinfo is not None:
path, column, _cell_x, _cell_y = pathinfo
# Make sure we don't attempt to select a single row if the row is already
# in a selection of multiple rows, otherwise the other rows will be unselected
if selection.count_selected_rows() <= 1 or not selection.path_is_selected(path):
treeview.grab_focus()
treeview.set_cursor(path, column, False)
else:
selection.unselect_all()
| 35,523 | Python | .py | 707 | 38.90099 | 114 | 0.623031 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,457 | clipboard.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/clipboard.py | # COPYRIGHT (C) 2021-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import Gtk
from pynicotine.gtkgui.application import GTK_API_VERSION
# Clipboard #
if GTK_API_VERSION >= 4:
_clipboard = Gdk.Display.get_default().get_clipboard()
else:
_clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
def copy_text(text):
if GTK_API_VERSION >= 4:
_clipboard.set(GObject.Value(str, text))
else:
_clipboard.set_text(text, -1)
def copy_image(image_data):
if GTK_API_VERSION >= 4:
_clipboard.set(GObject.Value(Gdk.Texture, image_data))
else:
_clipboard.set_image(image_data)
| 1,391 | Python | .py | 36 | 35.75 | 71 | 0.749069 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,458 | accelerator.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/accelerator.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from gi.repository import Gdk
from gi.repository import Gtk
from pynicotine.gtkgui.application import GTK_API_VERSION
class Accelerator:
if GTK_API_VERSION >= 4:
shortcut_triggers = {}
else:
KEYMAP = Gdk.Keymap.get_for_display(Gdk.Display.get_default())
keycodes_mods = {}
def __init__(self, accelerator, widget, callback, user_data=None):
if GTK_API_VERSION >= 4:
if sys.platform == "darwin":
# Use Command key instead of Ctrl in accelerators on macOS
accelerator = accelerator.replace("<Primary>", "<Meta>")
shortcut_trigger = self.shortcut_triggers.get(accelerator)
if not hasattr(widget, "shortcut_controller"):
widget.shortcut_controller = Gtk.ShortcutController(
propagation_phase=Gtk.PropagationPhase.CAPTURE
)
widget.add_controller(widget.shortcut_controller)
if not shortcut_trigger:
self.shortcut_triggers[accelerator] = shortcut_trigger = Gtk.ShortcutTrigger.parse_string(accelerator)
widget.shortcut_controller.add_shortcut(
Gtk.Shortcut(
trigger=shortcut_trigger,
action=Gtk.CallbackAction.new(callback, user_data)
)
)
return
# GTK 3 replacement for Gtk.ShortcutController
self.keycodes, self.required_mods = self.parse_accelerator(accelerator)
self.callback = callback
self.user_data = user_data
widget.connect("key-press-event", self._activate_accelerator)
@classmethod
def parse_accelerator(cls, accelerator):
keycodes_mods_accel = cls.keycodes_mods.get(accelerator)
if not keycodes_mods_accel:
*_args, key, mods = Gtk.accelerator_parse(accelerator)
if key:
_valid, keys = cls.KEYMAP.get_entries_for_keyval(key)
keycodes = {key.keycode for key in keys}
else:
keycodes = []
cls.keycodes_mods[accelerator] = keycodes_mods_accel = (keycodes, mods)
return keycodes_mods_accel
def _activate_accelerator(self, widget, event):
activated_mods = event.state
required_mods = self.required_mods
excluded_mods = ALL_MODIFIERS & ~required_mods
if required_mods & ~activated_mods:
# Missing required modifiers
return False
if activated_mods & excluded_mods:
# Too many/irrelevant modifiers
return False
if event.hardware_keycode not in self.keycodes:
# Invalid key
return False
return self.callback(widget, None, self.user_data)
if GTK_API_VERSION == 3:
ALL_MODIFIERS = (Accelerator.parse_accelerator("<Primary>")[1]
| Accelerator.parse_accelerator("<Shift>")[1]
| Accelerator.parse_accelerator("<Alt>")[1])
else:
ALL_MODIFIERS = []
| 3,785 | Python | .py | 84 | 35.797619 | 118 | 0.650967 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,459 | theme.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/theme.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import random
import shutil
import sys
from gi.repository import Gdk
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
from gi.repository import Pango
import pynicotine
from pynicotine.config import config
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.application import GTK_GUI_FOLDER_PATH
from pynicotine.gtkgui.application import LIBADWAITA_API_VERSION
from pynicotine.logfacility import log
from pynicotine.shares import FileTypes
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import encode_path
# Global Style #
CUSTOM_CSS_PROVIDER = Gtk.CssProvider()
GTK_SETTINGS = Gtk.Settings.get_default()
USE_COLOR_SCHEME_PORTAL = (sys.platform not in {"win32", "darwin"} and not LIBADWAITA_API_VERSION)
if USE_COLOR_SCHEME_PORTAL:
# GNOME 42+ system-wide dark mode for GTK without libadwaita
SETTINGS_PORTAL = None
class ColorScheme:
NO_PREFERENCE = 0
PREFER_DARK = 1
PREFER_LIGHT = 2
def read_color_scheme():
color_scheme = None
try:
result = SETTINGS_PORTAL.call_sync(
method_name="Read",
parameters=GLib.Variant.new_tuple(
GLib.Variant.new_string("org.freedesktop.appearance"),
GLib.Variant.new_string("color-scheme")
),
flags=Gio.DBusCallFlags.NONE,
timeout_msec=1000,
cancellable=None
)
color_scheme, = result.unpack()
except Exception as error:
log.add_debug("Cannot read color scheme, falling back to GTK theme preference: %s", error)
return color_scheme
def on_color_scheme_changed(_proxy, _sender_name, signal_name, parameters):
if signal_name != "SettingChanged":
return
namespace, name, color_scheme, *_unused = parameters.unpack()
if (config.sections["ui"]["dark_mode"]
or namespace != "org.freedesktop.appearance" or name != "color-scheme"):
return
set_dark_mode(color_scheme == ColorScheme.PREFER_DARK)
try:
SETTINGS_PORTAL = Gio.DBusProxy.new_for_bus_sync(
bus_type=Gio.BusType.SESSION,
flags=Gio.DBusProxyFlags.NONE,
info=None,
name="org.freedesktop.portal.Desktop",
object_path="/org/freedesktop/portal/desktop",
interface_name="org.freedesktop.portal.Settings",
cancellable=None
)
SETTINGS_PORTAL.connect("g-signal", on_color_scheme_changed)
except Exception as portal_error:
log.add_debug("Cannot start color scheme settings portal, falling back to GTK theme preference: %s",
portal_error)
USE_COLOR_SCHEME_PORTAL = False
def set_dark_mode(enabled):
if LIBADWAITA_API_VERSION:
from gi.repository import Adw # pylint: disable=no-name-in-module
color_scheme = Adw.ColorScheme.FORCE_DARK if enabled else Adw.ColorScheme.DEFAULT
Adw.StyleManager.get_default().set_color_scheme(color_scheme)
return
if USE_COLOR_SCHEME_PORTAL and not enabled:
color_scheme = read_color_scheme()
if color_scheme is not None:
enabled = (color_scheme == ColorScheme.PREFER_DARK)
GTK_SETTINGS.props.gtk_application_prefer_dark_theme = enabled
def set_use_header_bar(enabled):
GTK_SETTINGS.props.gtk_dialogs_use_header = enabled
def set_default_font_size():
if sys.platform not in {"darwin", "win32"}:
return
font = GTK_SETTINGS.props.gtk_font_name
if not font:
return
# Increase default font size to match newer apps on Windows and macOS
font_name, _separator, font_size = font.rpartition(" ")
font_size = str(int(font_size) + 1)
GTK_SETTINGS.props.gtk_font_name = " ".join((font_name, font_size))
if GTK_API_VERSION == 3:
return
# Enable OS-specific font tweaks
GTK_SETTINGS.props.gtk_font_rendering = Gtk.FontRendering.MANUAL # pylint: disable=no-member
def set_visual_settings():
if sys.platform == "darwin":
# Left align window controls on macOS
GTK_SETTINGS.props.gtk_decoration_layout = "close,minimize,maximize:"
elif os.environ.get("GDK_BACKEND") == "broadway":
# Hide minimize/maximize buttons in Broadway backend
GTK_SETTINGS.props.gtk_decoration_layout = ":close"
set_default_font_size()
set_dark_mode(config.sections["ui"]["dark_mode"])
set_use_header_bar(config.sections["ui"]["header_bar"])
def set_global_css():
global_css_provider = Gtk.CssProvider()
css_folder_path = os.path.join(GTK_GUI_FOLDER_PATH, "css")
css = bytearray()
with open(encode_path(os.path.join(css_folder_path, "style.css")), "rb") as file_handle:
css += file_handle.read()
if GTK_API_VERSION >= 4:
add_provider_func = Gtk.StyleContext.add_provider_for_display # pylint: disable=no-member
display = Gdk.Display.get_default()
with open(encode_path(os.path.join(css_folder_path, "style_gtk4.css")), "rb") as file_handle:
css += file_handle.read()
if sys.platform == "win32":
with open(encode_path(os.path.join(css_folder_path, "style_gtk4_win32.css")), "rb") as file_handle:
css += file_handle.read()
elif sys.platform == "darwin":
with open(encode_path(os.path.join(css_folder_path, "style_gtk4_darwin.css")), "rb") as file_handle:
css += file_handle.read()
if LIBADWAITA_API_VERSION:
with open(encode_path(os.path.join(css_folder_path, "style_libadwaita.css")), "rb") as file_handle:
css += file_handle.read()
load_css(global_css_provider, css)
else:
add_provider_func = Gtk.StyleContext.add_provider_for_screen # pylint: disable=no-member
display = Gdk.Screen.get_default()
with open(encode_path(os.path.join(css_folder_path, "style_gtk3.css")), "rb") as file_handle:
css += file_handle.read()
load_css(global_css_provider, css)
add_provider_func(display, global_css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
add_provider_func(display, CUSTOM_CSS_PROVIDER, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
def set_global_style():
set_visual_settings()
set_global_css()
update_custom_css()
# Icons #
if GTK_API_VERSION >= 4:
ICON_THEME = Gtk.IconTheme.get_for_display(Gdk.Display.get_default()) # pylint: disable=no-member
else:
ICON_THEME = Gtk.IconTheme.get_default() # pylint: disable=no-member
CUSTOM_ICON_THEME_NAME = ".nicotine-icon-theme"
FILE_TYPE_ICON_LABELS = {
"application-x-executable-symbolic": _("Executable"),
"folder-music-symbolic": _("Audio"),
"folder-pictures-symbolic": _("Image"),
"package-x-generic-symbolic": _("Archive"),
"folder-documents-symbolic": _("Miscellaneous"),
"folder-videos-symbolic": _("Video"),
"x-office-document-symbolic": _("Document"),
"emblem-documents-symbolic": _("Text")
}
USER_STATUS_ICON_LABELS = {
"nplus-status-available": _("Online"),
"nplus-status-away": _("Away"),
"nplus-status-offline": _("Offline")
}
USER_STATUS_ICON_NAMES = {
UserStatus.ONLINE: "nplus-status-available",
UserStatus.AWAY: "nplus-status-away",
UserStatus.OFFLINE: "nplus-status-offline"
}
def load_custom_icons(update=False):
"""Load custom icon theme if one is selected."""
if update:
GTK_SETTINGS.reset_property("gtk-icon-theme-name")
icon_theme_path = os.path.join(config.data_folder_path, CUSTOM_ICON_THEME_NAME)
icon_theme_path_encoded = encode_path(icon_theme_path)
parent_icon_theme_name = GTK_SETTINGS.props.gtk_icon_theme_name
if parent_icon_theme_name == CUSTOM_ICON_THEME_NAME:
return
try:
# Create internal icon theme folder
if os.path.exists(icon_theme_path_encoded):
shutil.rmtree(icon_theme_path_encoded)
except Exception as error:
log.add_debug("Failed to remove custom icon theme folder %s: %s", (icon_theme_path, error))
return
user_icon_theme_path = config.sections["ui"]["icontheme"]
if not user_icon_theme_path:
return
user_icon_theme_path = os.path.normpath(os.path.expandvars(user_icon_theme_path))
log.add_debug("Loading custom icon theme from %s", user_icon_theme_path)
theme_file_path = os.path.join(icon_theme_path, "index.theme")
theme_file_contents = (
"[Icon Theme]\n"
"Name=Nicotine+ Icon Theme\n"
"Inherits=" + parent_icon_theme_name + "\n"
"Directories=.\n"
"\n"
"[.]\n"
"Size=16\n"
"MinSize=8\n"
"MaxSize=512\n"
"Type=Scalable"
)
try:
# Create internal icon theme folder
os.makedirs(icon_theme_path_encoded)
# Create icon theme index file
with open(encode_path(theme_file_path), "w", encoding="utf-8") as file_handle:
file_handle.write(theme_file_contents)
except Exception as error:
log.add_debug("Failed to enable custom icon theme %s: %s", (user_icon_theme_path, error))
return
icon_names = (
("away", USER_STATUS_ICON_NAMES[UserStatus.AWAY]),
("online", USER_STATUS_ICON_NAMES[UserStatus.ONLINE]),
("offline", USER_STATUS_ICON_NAMES[UserStatus.OFFLINE]),
("hilite", "nplus-tab-highlight"),
("hilite3", "nplus-tab-changed"),
("trayicon_away", "nplus-tray-away"),
("trayicon_away", f"{pynicotine.__application_id__}-away"),
("trayicon_connect", "nplus-tray-connect"),
("trayicon_connect", f"{pynicotine.__application_id__}-connect"),
("trayicon_disconnect", "nplus-tray-disconnect"),
("trayicon_disconnect", f"{pynicotine.__application_id__}-disconnect"),
("trayicon_msg", "nplus-tray-msg"),
("trayicon_msg", f"{pynicotine.__application_id__}-msg"),
("n", pynicotine.__application_id__),
("n", f"{pynicotine.__application_id__}-symbolic")
)
extensions = (".png", ".svg", ".jpg", ".jpeg", ".bmp")
# Move custom icons to internal icon theme location
for original_name, replacement_name in icon_names:
for extension in extensions:
file_path = os.path.join(user_icon_theme_path, original_name + extension)
file_path_encoded = encode_path(file_path)
if not os.path.isfile(file_path_encoded):
continue
try:
shutil.copyfile(
file_path_encoded,
encode_path(os.path.join(icon_theme_path, replacement_name + extension))
)
break
except OSError as error:
log.add(_("Error loading custom icon %(path)s: %(error)s"), {
"path": file_path,
"error": error
})
# Enable custom icon theme
GTK_SETTINGS.props.gtk_icon_theme_name = CUSTOM_ICON_THEME_NAME
def load_icons():
"""Load custom icons necessary for the application to function."""
paths = (
config.data_folder_path, # Custom internal icon theme
os.path.join(GTK_GUI_FOLDER_PATH, "icons"), # Support running from folder, as well as macOS and Windows
os.path.join(sys.prefix, "share", "icons") # Support Python venv
)
for path in paths:
if GTK_API_VERSION >= 4:
ICON_THEME.add_search_path(path)
else:
ICON_THEME.append_search_path(path)
load_custom_icons()
def get_flag_icon_name(country_code):
if not country_code:
return ""
return f"nplus-flag-{country_code.lower()}"
def get_file_type_icon_name(basename):
_basename_no_extension, _separator, extension = basename.rpartition(".")
extension = extension.lower()
if extension in FileTypes.AUDIO:
return "folder-music-symbolic"
if extension in FileTypes.IMAGE:
return "folder-pictures-symbolic"
if extension in FileTypes.VIDEO:
return "folder-videos-symbolic"
if extension in FileTypes.ARCHIVE:
return "package-x-generic-symbolic"
if extension in FileTypes.DOCUMENT:
return "x-office-document-symbolic"
if extension in FileTypes.TEXT:
return "emblem-documents-symbolic"
if extension in FileTypes.EXECUTABLE:
return "application-x-executable-symbolic"
return "folder-documents-symbolic"
def on_icon_theme_changed(*_args):
load_custom_icons()
ICON_THEME.connect("changed", on_icon_theme_changed)
# Fonts and Colors #
PANGO_STYLES = {
Pango.Style.NORMAL: "normal",
Pango.Style.ITALIC: "italic"
}
PANGO_WEIGHTS = {
Pango.Weight.THIN: 100,
Pango.Weight.ULTRALIGHT: 200,
Pango.Weight.LIGHT: 300,
Pango.Weight.SEMILIGHT: 350,
Pango.Weight.BOOK: 380,
Pango.Weight.NORMAL: 400,
Pango.Weight.MEDIUM: 500,
Pango.Weight.SEMIBOLD: 600,
Pango.Weight.BOLD: 700,
Pango.Weight.ULTRABOLD: 800,
Pango.Weight.HEAVY: 900,
Pango.Weight.ULTRAHEAVY: 1000
}
USER_STATUS_COLORS = {
UserStatus.ONLINE: "useronline",
UserStatus.AWAY: "useraway",
UserStatus.OFFLINE: "useroffline"
}
def add_css_class(widget, css_class):
if GTK_API_VERSION >= 4:
widget.add_css_class(css_class) # pylint: disable=no-member
return
widget.get_style_context().add_class(css_class) # pylint: disable=no-member
def remove_css_class(widget, css_class):
if GTK_API_VERSION >= 4:
widget.remove_css_class(css_class) # pylint: disable=no-member
return
widget.get_style_context().remove_class(css_class) # pylint: disable=no-member
def load_css(css_provider, data):
try:
css_provider.load_from_string(data.decode())
except AttributeError:
try:
css_provider.load_from_data(data.decode(), length=-1)
except TypeError:
css_provider.load_from_data(data)
def _get_custom_font_css():
css = bytearray()
for css_selector, font in (
("window, popover", config.sections["ui"]["globalfont"]),
("treeview", config.sections["ui"]["listfont"]),
("textview", config.sections["ui"]["textviewfont"]),
(".chat-view textview", config.sections["ui"]["chatfont"]),
(".search-view treeview", config.sections["ui"]["searchfont"]),
(".transfers-view treeview", config.sections["ui"]["transfersfont"]),
(".userbrowse-view treeview", config.sections["ui"]["browserfont"])
):
font_description = Pango.FontDescription.from_string(font)
if font_description.get_set_fields() & (Pango.FontMask.FAMILY | Pango.FontMask.SIZE):
css += (
f"""
{css_selector} {{
font-family: '{font_description.get_family()}';
font-size: {font_description.get_size() // 1024}pt;
font-style: {PANGO_STYLES.get(font_description.get_style(), "normal")};
font-weight: {PANGO_WEIGHTS.get(font_description.get_weight(), "normal")};
}}
""".encode()
)
return css
def _is_color_valid(color_hex):
return color_hex and Gdk.RGBA().parse(color_hex)
def _get_custom_color_css():
css = bytearray()
# User status colors
online_color = config.sections["ui"]["useronline"]
away_color = config.sections["ui"]["useraway"]
offline_color = config.sections["ui"]["useroffline"]
if _is_color_valid(online_color) and _is_color_valid(away_color) and _is_color_valid(offline_color):
css += (
f"""
.user-status {{
-gtk-icon-palette: success {online_color}, warning {away_color}, error {offline_color};
}}
""".encode()
)
# Text colors
treeview_text_color = config.sections["ui"]["search"]
for css_selector, color in (
(".notebook-tab", config.sections["ui"]["tab_default"]),
(".notebook-tab-changed", config.sections["ui"]["tab_changed"]),
(".notebook-tab-highlight", config.sections["ui"]["tab_hilite"]),
("entry", config.sections["ui"]["inputcolor"]),
("treeview .cell:not(:disabled):not(:selected):not(.progressbar)", treeview_text_color)
):
if _is_color_valid(color):
css += (
f"""
{css_selector} {{
color: {color};
}}
""".encode()
)
# Background colors
for css_selector, color in (
("entry", config.sections["ui"]["textbg"]),
):
if _is_color_valid(color):
css += (
f"""
{css_selector} {{
background: {color};
}}
""".encode()
)
# Reset treeview column header colors
if treeview_text_color:
css += (
b"""
treeview header {
color: initial;
}
"""
)
# Workaround for GTK bug where tree view colors don't update until moving the
# cursor over the widget. Changing the color of the text caret to a random one
# forces the tree view to re-render with new icon/text colors (text carets are
# never visible in our tree views, so usability is unaffected).
css += (
f"""
treeview {{
caret-color: #{random.randint(0, 0xFFFFFF):06x};
}}
treeview popover {{
caret-color: initial;
}}
""".encode()
)
return css
def update_custom_css():
using_custom_icon_theme = (GTK_SETTINGS.props.gtk_icon_theme_name == CUSTOM_ICON_THEME_NAME)
css = bytearray(
f"""
.colored-icon {{
-gtk-icon-style: {"regular" if using_custom_icon_theme else "symbolic"};
}}
""".encode()
)
css += _get_custom_font_css()
css += _get_custom_color_css()
load_css(CUSTOM_CSS_PROVIDER, css)
def update_tag_visuals(tag, color_id):
enable_colored_usernames = config.sections["ui"]["usernamehotspots"]
is_hotspot_tag = (color_id in {"useraway", "useronline", "useroffline"})
color_hex = config.sections["ui"].get(color_id)
tag_props = tag.props
if is_hotspot_tag and not enable_colored_usernames:
color_hex = None
if not color_hex:
if tag_props.foreground_rgba:
tag_props.foreground_rgba = None
else:
current_rgba = tag_props.foreground_rgba
new_rgba = Gdk.RGBA()
new_rgba.parse(color_hex)
if current_rgba is None or not new_rgba.equal(current_rgba):
tag_props.foreground_rgba = new_rgba
# URLs
if color_id == "urlcolor" and tag_props.underline != Pango.Underline.SINGLE:
tag_props.underline = Pango.Underline.SINGLE
# Hotspots
if not is_hotspot_tag:
return
username_style = config.sections["ui"]["usernamestyle"]
weight_style = Pango.Weight.BOLD if username_style == "bold" else Pango.Weight.NORMAL
if tag_props.weight != weight_style:
tag_props.weight = weight_style
italic_style = Pango.Style.ITALIC if username_style == "italic" else Pango.Style.NORMAL
if tag_props.style != italic_style:
tag_props.style = italic_style
underline_style = Pango.Underline.SINGLE if username_style == "underline" else Pango.Underline.NONE
if tag_props.underline != underline_style:
tag_props.underline = underline_style
| 20,427 | Python | .py | 480 | 34.672917 | 112 | 0.640839 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,460 | iconnotebook.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/widgets/iconnotebook.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2008-2009 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from collections import deque
from gi.repository import Gdk
from gi.repository import GLib
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.theme import USER_STATUS_ICON_NAMES
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.theme import remove_css_class
from pynicotine.slskmessages import UserStatus
class TabLabel:
def __init__(self, label, full_text=None, close_button_visible=False, close_callback=None):
self.container = Gtk.Box(hexpand=False, visible=True)
add_css_class(self.container, "notebook-tab")
self.is_important = False
self.centered = False
if GTK_API_VERSION >= 4:
self.gesture_click = Gtk.GestureClick()
self.container.add_controller(self.gesture_click) # pylint: disable=no-member
self.eventbox = Gtk.Box()
else:
self.gesture_click = Gtk.GestureMultiPress(widget=self.container)
self.eventbox = Gtk.EventBox(visible=True)
self.eventbox.add_events(int(Gdk.EventMask.SCROLL_MASK | Gdk.EventMask.SMOOTH_SCROLL_MASK))
self.box = Gtk.Box(spacing=6, visible=True)
self.label = Gtk.Label(halign=Gtk.Align.START, hexpand=True, single_line_mode=True, visible=True)
self.full_text = full_text
self.set_tooltip_text(full_text)
self.set_text(label)
self.close_button = None
self.close_button_visible = close_button_visible and close_callback
self.close_callback = close_callback
if close_callback:
self.gesture_click.set_button(Gdk.BUTTON_MIDDLE)
self.gesture_click.connect("pressed", close_callback)
self.start_icon = Gtk.Image(visible=False)
self.end_icon = Gtk.Image(visible=False)
self._pack_children()
def destroy(self):
self.__dict__.clear()
def _remove_tab_label(self):
if self.eventbox.get_parent() is None:
return
for widget in (self.start_icon, self.label, self.end_icon):
self.box.remove(widget)
self.eventbox.remove(self.box)
self.container.remove(self.eventbox)
def _add_close_button(self):
if self.close_button is not None:
return
if not self.close_button_visible:
return
if GTK_API_VERSION >= 4:
self.close_button = Gtk.Button(icon_name="window-close-symbolic")
self.close_button.is_close_button = True
self.close_button.get_child().is_close_button = True
self.container.append(self.close_button) # pylint: disable=no-member
else:
self.close_button = Gtk.Button(image=Gtk.Image(icon_name="window-close-symbolic"))
self.container.add(self.close_button) # pylint: disable=no-member
self.close_button.add_events( # pylint: disable=no-member
int(Gdk.EventMask.SCROLL_MASK | Gdk.EventMask.SMOOTH_SCROLL_MASK))
add_css_class(self.close_button, "flat")
self.close_button.set_tooltip_text(_("Close Tab"))
self.close_button.set_visible(True)
if self.close_callback is not None:
self.close_button.connect("clicked", self.close_callback)
def _remove_close_button(self):
if self.close_button is not None:
self.container.remove(self.close_button)
self.close_button = None
def _pack_children(self):
self._remove_tab_label()
self._remove_close_button()
if sys.platform == "darwin":
# Left align close button on macOS
self._add_close_button()
if GTK_API_VERSION >= 4:
self.container.append(self.eventbox) # pylint: disable=no-member
self.eventbox.append(self.box) # pylint: disable=no-member
self.box.append(self.start_icon) # pylint: disable=no-member
self.box.append(self.label) # pylint: disable=no-member
self.box.append(self.end_icon) # pylint: disable=no-member
else:
self.container.add(self.eventbox) # pylint: disable=no-member
self.eventbox.add(self.box) # pylint: disable=no-member
self.box.add(self.start_icon) # pylint: disable=no-member
self.box.add(self.label) # pylint: disable=no-member
self.box.add(self.end_icon) # pylint: disable=no-member
if sys.platform != "darwin":
self._add_close_button()
if self.centered:
self.container.set_halign(Gtk.Align.CENTER)
else:
self.container.set_halign(Gtk.Align.FILL)
def set_centered(self, centered):
self.centered = centered
self._pack_children()
def set_close_button_visibility(self, visible):
self.close_button_visible = visible
if visible:
self._add_close_button()
return
self._remove_close_button()
def request_changed(self, is_important=False):
# Chat mentions have priority over normal notifications
if not self.is_important:
self.is_important = is_important
icon_name = "nplus-tab-highlight" if self.is_important else "nplus-tab-changed"
if self.end_icon.get_icon_name() == icon_name:
return
if self.is_important:
remove_css_class(self.box, "notebook-tab-changed")
add_css_class(self.box, "notebook-tab-highlight")
else:
remove_css_class(self.box, "notebook-tab-highlight")
add_css_class(self.box, "notebook-tab-changed")
add_css_class(self.label, "bold")
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.end_icon.set_from_icon_name(icon_name, *icon_args)
self.end_icon.set_visible(True)
add_css_class(self.end_icon, "colored-icon")
def remove_changed(self):
if not self.end_icon.get_icon_name():
return
self.is_important = False
remove_css_class(self.box, "notebook-tab-changed")
remove_css_class(self.box, "notebook-tab-highlight")
remove_css_class(self.label, "bold")
icon_name = None
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.end_icon.set_from_icon_name(icon_name, *icon_args)
self.end_icon.set_visible(False)
remove_css_class(self.end_icon, "colored-icon")
def set_status_icon(self, status):
icon_name = USER_STATUS_ICON_NAMES.get(status)
if not icon_name:
return
self.set_start_icon_name(icon_name)
add_css_class(self.start_icon, "colored-icon")
add_css_class(self.start_icon, "user-status")
def set_start_icon_name(self, icon_name):
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.start_icon.set_from_icon_name(icon_name, *icon_args)
self.start_icon.set_visible(True)
def set_tooltip_text(self, text):
text = text.strip() if text else None
if self.container.get_tooltip_text() == text:
return
# Hide widget to keep tooltips for other widgets visible
self.container.set_visible(False)
self.container.set_tooltip_text(text)
self.container.set_visible(True)
def set_text(self, text):
self.label.set_text(text.strip())
def get_text(self):
return self.label.get_text()
class IconNotebook:
"""This class extends the functionality of a Gtk.Notebook widget. On top of
what a Gtk.Notebook provides:
- Icons on tabs
- Context (right-click) menus for tabs
- Dropdown menu for unread tabs
"""
def __init__(self, window, parent, parent_page=None, switch_page_callback=None, reorder_page_callback=None):
self.window = window
self.parent = parent
self.parent_page = parent_page
self.switch_page_callback = switch_page_callback
self.reorder_page_callback = reorder_page_callback
self.switch_page_handler = None
self.reorder_page_handler = None
self.pages = {}
self.tab_labels = {}
self.unread_pages = {}
self.recently_removed_pages = deque(maxlen=5) # Low limit to prevent excessive server traffic
self.scroll_x = self.scroll_y = 0
self.should_focus_page = True
self.widget = Gtk.Notebook(enable_popup=False, scrollable=True, show_border=False, visible=True)
self.pages_button_container = Gtk.Box(halign=Gtk.Align.CENTER, visible=(self.parent_page is not None))
self.pages_button = Gtk.MenuButton(halign=Gtk.Align.CENTER, valign=Gtk.Align.CENTER, visible=True)
self.widget.set_action_widget(self.pages_button_container, Gtk.PackType.END)
if parent_page is not None:
content_box = next(iter(parent_page))
content_box.connect("show", self.on_show_parent_page)
if GTK_API_VERSION >= 4:
parent.append(self.widget)
self.pages_button.set_has_frame(False) # pylint: disable=no-member
self.pages_button.set_create_popup_func(self.on_pages_button_pressed) # pylint: disable=no-member
self.pages_button_container.append(self.pages_button) # pylint: disable=no-member
self.scroll_controller = Gtk.EventControllerScroll(
flags=int(Gtk.EventControllerScrollFlags.BOTH_AXES | Gtk.EventControllerScrollFlags.DISCRETE)
)
self.scroll_controller.connect("scroll", self.on_tab_scroll)
tab_bar = next(iter(self.widget))
tab_bar.add_controller(self.scroll_controller)
# GTK 4 workaround to prevent notebook tabs from being activated when pressing close button
# https://gitlab.gnome.org/GNOME/gtk/-/issues/4046
self.close_button_pressed = False
self.gesture_click = Gtk.GestureClick(
button=Gdk.BUTTON_PRIMARY, propagation_phase=Gtk.PropagationPhase.CAPTURE
)
self.gesture_click.connect("pressed", self.on_notebook_click_pressed)
self.gesture_click.connect("released", self.on_notebook_click_released)
self.widget.add_controller(self.gesture_click) # pylint: disable=no-member
else:
parent.add(self.widget)
self.pages_button.set_use_popover(False) # pylint: disable=no-member
self.pages_button.connect("toggled", self.on_pages_button_pressed)
self.pages_button_container.add(self.pages_button) # pylint: disable=no-member
self.widget.add_events( # pylint: disable=no-member
int(Gdk.EventMask.SCROLL_MASK | Gdk.EventMask.SMOOTH_SCROLL_MASK))
self.widget.connect("scroll-event", self.on_tab_scroll_event)
for style_class in ("circular", "flat"):
add_css_class(self.pages_button, style_class)
Accelerator("Left", self.widget, self.on_arrow_accelerator)
Accelerator("Right", self.widget, self.on_arrow_accelerator)
self.popup_menu_pages = PopupMenu(self.window.application)
self.update_pages_menu_button()
self.pages_button.set_menu_model(self.popup_menu_pages.model)
def destroy(self):
if self.switch_page_handler is not None:
self.widget.disconnect(self.switch_page_handler)
if self.reorder_page_handler is not None:
self.widget.disconnect(self.reorder_page_handler)
for i in reversed(range(self.get_n_pages())):
page = self.get_nth_page(i)
self.remove_page(page)
self.__dict__.clear()
def grab_focus(self):
self.widget.grab_focus()
# Tabs #
def freeze(self):
"""Use when adding/removing many tabs at once, to stop unnecessary updates."""
self.widget.set_visible(False)
self.widget.set_show_tabs(False)
self.widget.set_scrollable(False)
def unfreeze(self):
self.widget.set_visible(True)
self.widget.set_show_tabs(True)
self.widget.set_scrollable(True)
def get_tab_label(self, page):
return self.tab_labels.get(page)
def get_tab_label_inner(self, page):
return self.get_tab_label(page).eventbox
def set_tab_closers(self):
for i in range(self.get_n_pages()):
page = self.get_nth_page(i)
tab_label = self.get_tab_label(page)
tab_label.set_close_button_visibility(config.sections["ui"]["tabclosers"])
def append_page(self, page, text, focus_callback=None, close_callback=None, user=None):
self.insert_page(page, text, focus_callback, close_callback, user, position=-1)
def insert_page(self, page, text, focus_callback=None, close_callback=None, user=None,
position=None):
full_text = text
text = (text[:25] + "…") if len(text) > 25 else text
self.tab_labels[page] = tab_label = TabLabel(
text, full_text, close_button_visible=config.sections["ui"]["tabclosers"], close_callback=close_callback)
if focus_callback:
page.focus_callback = focus_callback
first_child = next(iter(page))
first_child.set_visible(False)
if position is None:
# Open new tab adjacent to current tab
position = self.widget.get_current_page() + 1
self.widget.insert_page(page, None, position)
self.widget.set_tab_label(page, tab_label.container) # Tab label widget leaks when passed to insert_page()
self.set_tab_reorderable(page, True)
self.parent.set_visible(True)
if user is not None:
status = core.users.statuses.get(user, UserStatus.OFFLINE)
self.set_user_status(page, text, status)
def prepend_page(self, page, text, focus_callback=None, close_callback=None, user=None):
self.insert_page(page, text, focus_callback, close_callback, user, position=0)
def restore_removed_page(self, *_args):
if self.recently_removed_pages:
self.on_restore_removed_page(page_args=self.recently_removed_pages.pop())
def remove_page(self, page, page_args=None):
self.widget.remove_page(self.page_num(page))
self._remove_unread_page(page)
self.popup_menu_pages.clear()
if hasattr(page, "focus_callback"):
del page.focus_callback
tab_label = self.tab_labels.pop(page)
tab_label.destroy()
if page_args:
# Allow for restoring page after closing it
self.recently_removed_pages.append(page_args)
if self.parent_page is not None and self.get_n_pages() <= 0:
if self.window.current_page_id == self.parent_page.id:
self.window.notebook.grab_focus()
self.parent.set_visible(False)
def remove_all_pages(self, *_args):
OptionDialog(
parent=self.window,
title=_("Close All Tabs?"),
message=_("Do you really want to close all tabs?"),
destructive_response_id="ok",
callback=self._on_remove_all_pages
).present()
def _update_pages_menu_button(self, icon_name, tooltip_text):
if self.pages_button.get_tooltip_text() == tooltip_text:
return
if GTK_API_VERSION >= 4:
self.pages_button.set_icon_name(icon_name) # pylint: disable=no-member
else:
self.pages_button.set_image(Gtk.Image(icon_name=icon_name)) # pylint: disable=no-member
# Hide widget to keep tooltips for other widgets visible
self.pages_button.set_visible(False)
self.pages_button.set_tooltip_text(tooltip_text)
self.pages_button.set_visible(True)
def update_pages_menu_button(self):
if self.unread_pages:
icon_name = "emblem-important-symbolic"
tooltip_text = _("%i Unread Tab(s)") % len(self.unread_pages)
else:
icon_name = "pan-down-symbolic"
tooltip_text = _("All Tabs")
self._update_pages_menu_button(icon_name, tooltip_text)
def get_current_page(self):
return self.get_nth_page(self.widget.get_current_page())
def set_current_page(self, page):
page_num = self.page_num(page)
self.widget.set_current_page(page_num)
def get_current_page_num(self):
return self.widget.get_current_page()
def set_current_page_num(self, page_num):
self.widget.set_current_page(page_num)
def set_tab_expand(self, page, expand):
tab_label = self.get_tab_label(page)
if GTK_API_VERSION >= 4:
self.widget.get_page(page).props.tab_expand = expand # pylint: disable=no-member
else:
self.widget.child_set_property(page, "tab-expand", expand) # pylint: disable=no-member
tab_label.set_centered(expand)
def set_tab_reorderable(self, page, reorderable):
self.widget.set_tab_reorderable(page, reorderable)
def set_tab_pos(self, pos):
self.widget.set_tab_pos(pos)
def get_n_pages(self):
return self.widget.get_n_pages()
def get_nth_page(self, page_num):
return self.widget.get_nth_page(page_num)
def page_num(self, page):
return self.widget.page_num(page)
def next_page(self):
return self.widget.next_page()
def prev_page(self):
return self.widget.prev_page()
def reorder_child(self, page, order):
self.widget.reorder_child(page, order)
# Tab Highlights #
def request_tab_changed(self, page, is_important=False, is_quiet=False):
if self.parent_page is not None:
has_tab_changed = False
is_current_parent = (self.window.current_page_id == self.parent_page.id)
is_current_page = (self.get_current_page() == page)
if is_current_parent and is_current_page:
return has_tab_changed
if not is_quiet or is_important:
# Highlight top-level tab, but don't for global feed unless mentioned
self.window.notebook.request_tab_changed(self.parent_page, is_important)
has_tab_changed = self._append_unread_page(page, is_important)
else:
has_tab_changed = True
tab_label = self.get_tab_label(page)
tab_label.request_changed(is_important)
return has_tab_changed
def remove_tab_changed(self, page):
tab_label = self.get_tab_label(page)
tab_label.remove_changed()
if self.parent_page is not None:
self._remove_unread_page(page)
def _append_unread_page(self, page, is_important=False):
# Remove existing page and move it to the end of the dict
is_currently_important = self.unread_pages.pop(page, None)
if is_currently_important and not is_important:
# Important pages are persistent
self.unread_pages[page] = is_currently_important
return False
self.unread_pages[page] = is_important
if is_currently_important == is_important:
return False
self.update_pages_menu_button()
return True
def _remove_unread_page(self, page):
if page not in self.unread_pages:
return
important_page_removed = self.unread_pages.pop(page)
self.update_pages_menu_button()
if self.parent_page is None:
return
if not self.unread_pages:
self.window.notebook.remove_tab_changed(self.parent_page)
return
# No important unread pages left, reset top-level tab highlight
if important_page_removed and not any(is_important for is_important in self.unread_pages.values()):
self.window.notebook.remove_tab_changed(self.parent_page)
self.window.notebook.request_tab_changed(self.parent_page, is_important=False)
# Tab User Status #
def set_user_status(self, page, user, status):
if status == UserStatus.AWAY:
status_text = _("Away")
elif status == UserStatus.ONLINE:
status_text = _("Online")
else:
status_text = _("Offline")
tab_label = self.get_tab_label(page)
tab_label.set_status_icon(status)
tab_label.set_text(user)
tab_label.set_tooltip_text(f"{user} ({status_text})")
# Signals #
def emit_switch_page_signal(self):
curr_page = self.get_current_page()
curr_page_num = self.get_current_page_num()
if curr_page_num >= 0:
self.widget.emit("switch-page", curr_page, curr_page_num)
def connect_signals(self):
self.reorder_page_handler = self.widget.connect("page-reordered", self.on_reorder_page)
self.switch_page_handler = self.widget.connect("switch-page", self.on_switch_page)
self.widget.connect("page-removed", self.on_remove_page)
if self.parent_page is None:
# Show active page and focus default widget
self.emit_switch_page_signal()
def on_focus_page(self, page):
if not hasattr(page, "focus_callback"):
return
if not page.focus_callback():
# Page didn't grab focus, fall back to the notebook
self.widget.grab_focus()
def on_restore_removed_page(self, page_args):
raise NotImplementedError
def on_remove_page(self, _notebook, new_page, _page_num):
self._remove_unread_page(new_page)
def _on_remove_all_pages(self, *args):
self.freeze()
self.on_remove_all_pages(args)
self.unfreeze()
# Don't allow restoring tabs after removing all
self.recently_removed_pages.clear()
def on_remove_all_pages(self, *_args):
raise NotImplementedError
def on_switch_page(self, _notebook, new_page, page_num):
if self.switch_page_callback is not None:
self.switch_page_callback(self, new_page, page_num)
# Hide container widget on previous page for a performance boost
current_page = self.get_current_page()
current_first_child = next(iter(current_page))
new_first_child = next(iter(new_page))
current_first_child.set_visible(False)
new_first_child.set_visible(True)
# Focus the default widget on the page
if (self.should_focus_page
and (self.parent_page is None or self.window.current_page_id == self.parent_page.id
and self.window.notebook.should_focus_page)):
GLib.idle_add(self.on_focus_page, new_page, priority=GLib.PRIORITY_HIGH_IDLE)
# Dismiss tab highlight
if self.parent_page is not None:
self.remove_tab_changed(new_page)
self.should_focus_page = True
def on_reorder_page(self, _notebook, page, page_num):
if self.reorder_page_callback is not None:
self.reorder_page_callback(self, page, page_num)
def on_show_page(self, _action, _state, page):
self.set_current_page(page)
def on_show_parent_page(self, *_args):
self.emit_switch_page_signal()
def on_pages_button_pressed(self, *_args):
if GTK_API_VERSION == 3 and not self.pages_button.get_active():
return
self.popup_menu_pages.clear()
# Unread pages (most recently changed first)
for page in reversed(list(self.unread_pages)):
tab_label = self.get_tab_label(page)
self.popup_menu_pages.add_items(
("#* " + tab_label.get_text(), self.on_show_page, page)
)
# Separator
if self.unread_pages:
self.popup_menu_pages.add_items(("", None))
# All pages
for i in range(self.get_n_pages()):
page = self.get_nth_page(i)
if page in self.unread_pages:
continue
tab_label = self.get_tab_label(page)
self.popup_menu_pages.add_items(
("#" + tab_label.get_text(), self.on_show_page, page)
)
self.popup_menu_pages.add_items(
("", None),
("#" + _("Re_open Closed Tab"), self.restore_removed_page),
("#" + _("Close All Tabs…"), self.remove_all_pages)
)
self.popup_menu_pages.update_model()
self.popup_menu_pages.actions[_("Re_open Closed Tab")].set_enabled(bool(self.recently_removed_pages))
def on_tab_scroll_event(self, _widget, event):
current_page = self.get_current_page()
if not current_page:
return False
if Gtk.get_event_widget(event).is_ancestor(current_page):
return False
if event.direction == Gdk.ScrollDirection.SMOOTH:
return self.on_tab_scroll(scroll_x=event.delta_x, scroll_y=event.delta_y)
if event.direction in (Gdk.ScrollDirection.RIGHT, Gdk.ScrollDirection.DOWN):
self.next_page()
elif event.direction in (Gdk.ScrollDirection.LEFT, Gdk.ScrollDirection.UP):
self.prev_page()
return True
def on_tab_scroll(self, _controller=None, scroll_x=0, scroll_y=0):
# Simulate discrete scrolling with touchpad in GTK 3
self.scroll_x += scroll_x
self.scroll_y += scroll_y
if self.scroll_x >= 1 or self.scroll_y >= 1:
self.next_page()
self.scroll_x = self.scroll_y = 0
elif self.scroll_x <= -1 or self.scroll_y <= -1:
self.prev_page()
self.scroll_x = self.scroll_y = 0
return True
def on_arrow_accelerator(self, *_args):
"""Left, Right - disable page focus callback when moving through tabs."""
self.should_focus_page = False
# Signals (GTK 4) #
def on_notebook_click_pressed(self, controller, _num_p, pressed_x, pressed_y):
widget = self.widget.pick(pressed_x, pressed_y, Gtk.PickFlags.DEFAULT) # pylint: disable=no-member
if not hasattr(widget, "is_close_button"):
return False
self.close_button_pressed = True
controller.set_state(Gtk.EventSequenceState.CLAIMED)
return True
def on_notebook_click_released(self, _controller, _num_p, pressed_x, pressed_y):
if not self.close_button_pressed:
return False
widget = self.widget.pick(pressed_x, pressed_y, Gtk.PickFlags.DEFAULT) # pylint: disable=no-member
self.close_button_pressed = False
if not hasattr(widget, "is_close_button"):
return False
if isinstance(widget, Gtk.Image):
widget = widget.get_parent()
widget.emit("clicked")
return True
| 28,268 | Python | .py | 568 | 40.035211 | 117 | 0.642371 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,461 | transferspeeds.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/popovers/transferspeeds.py | # COPYRIGHT (C) 2022-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.config import config
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.popover import Popover
from pynicotine.gtkgui.widgets.theme import add_css_class
class TransferSpeeds(Popover):
def __init__(self, window, transfer_type):
self.transfer_type = transfer_type
(
self.alt_speed_spinner,
self.container,
self.speed_spinner,
self.use_alt_limit_radio,
self.use_limit_radio,
self.use_unlimited_speed_radio
) = ui.load(scope=self, path=f"popovers/{transfer_type}speeds.ui")
super().__init__(
window=window,
content_box=self.container,
show_callback=self.on_show
)
def set_menu_button(self, menu_button):
super().set_menu_button(menu_button)
if menu_button is not None and GTK_API_VERSION >= 4:
inner_button = next(iter(menu_button))
add_css_class(widget=inner_button, css_class="flat")
@staticmethod
def update_transfer_limits():
raise NotImplementedError
def on_active_limit_toggled(self, *_args):
use_limit_config_key = f"use_{self.transfer_type}_speed_limit"
prev_active_limit = config.sections["transfers"][use_limit_config_key]
if self.use_limit_radio.get_active():
config.sections["transfers"][use_limit_config_key] = "primary"
elif self.use_alt_limit_radio.get_active():
config.sections["transfers"][use_limit_config_key] = "alternative"
else:
config.sections["transfers"][use_limit_config_key] = "unlimited"
if prev_active_limit != config.sections["transfers"][use_limit_config_key]:
self.update_transfer_limits()
def on_limit_changed(self, *_args):
speed_limit = self.speed_spinner.get_value_as_int()
if speed_limit == config.sections["transfers"][f"{self.transfer_type}limit"]:
return
config.sections["transfers"][f"{self.transfer_type}limit"] = speed_limit
self.update_transfer_limits()
def on_alt_limit_changed(self, *_args):
alt_speed_limit = self.alt_speed_spinner.get_value_as_int()
if alt_speed_limit == config.sections["transfers"][f"{self.transfer_type}limitalt"]:
return
config.sections["transfers"][f"{self.transfer_type}limitalt"] = alt_speed_limit
self.update_transfer_limits()
def on_show(self, *_args):
self.alt_speed_spinner.set_value(config.sections["transfers"][f"{self.transfer_type}limitalt"])
self.speed_spinner.set_value(config.sections["transfers"][f"{self.transfer_type}limit"])
use_speed_limit = config.sections["transfers"][f"use_{self.transfer_type}_speed_limit"]
if use_speed_limit == "primary":
self.use_limit_radio.set_active(True)
elif use_speed_limit == "alternative":
self.use_alt_limit_radio.set_active(True)
else:
self.use_unlimited_speed_radio.set_active(True)
| 3,869 | Python | .py | 79 | 41.303797 | 103 | 0.678904 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,462 | downloadspeeds.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/popovers/downloadspeeds.py | # COPYRIGHT (C) 2022-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.core import core
from pynicotine.gtkgui.popovers.transferspeeds import TransferSpeeds
class DownloadSpeeds(TransferSpeeds):
def __init__(self, window):
super().__init__(window=window, transfer_type="download")
self.set_menu_button(window.download_status_button)
@staticmethod
def update_transfer_limits():
core.downloads.update_transfer_limits()
| 1,148 | Python | .py | 26 | 41.576923 | 71 | 0.767234 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,463 | uploadspeeds.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/popovers/uploadspeeds.py | # COPYRIGHT (C) 2022-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.core import core
from pynicotine.gtkgui.popovers.transferspeeds import TransferSpeeds
class UploadSpeeds(TransferSpeeds):
def __init__(self, window):
super().__init__(window=window, transfer_type="upload")
self.set_menu_button(window.upload_status_button)
@staticmethod
def update_transfer_limits():
core.uploads.update_transfer_limits()
| 1,140 | Python | .py | 26 | 41.269231 | 71 | 0.765555 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,464 | roomwall.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/popovers/roomwall.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
from pynicotine.core import core
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.popover import Popover
from pynicotine.gtkgui.widgets.textview import TextView
class RoomWall(Popover):
def __init__(self, window):
(
self.container,
self.message_entry,
self.message_view_container,
) = ui.load(scope=self, path="popovers/roomwall.ui")
super().__init__(
window=window,
content_box=self.container,
show_callback=self._on_show,
width=650,
height=500
)
self.room = None
self.message_view = TextView(self.message_view_container, editable=False, vertical_margin=4,
pixels_above_lines=3, pixels_below_lines=3)
def destroy(self):
self.message_view.destroy()
super().destroy()
def _update_message_list(self):
tickers = core.chatrooms.joined_rooms[self.room].tickers
newline = "\n"
messages = [f"> [{user}] {msg.replace(newline, ' ')}" for user, msg in reversed(list(tickers.items()))]
self.message_view.append_line("\n".join(messages))
self.message_view.place_cursor_at_line(0)
def _clear_room_wall_message(self, update_list=True):
entry_text = self.message_entry.get_text()
self.message_entry.set_text("")
core.chatrooms.joined_rooms[self.room].tickers.pop(core.users.login_username, None)
self.message_view.clear()
if update_list:
core.chatrooms.request_update_ticker(self.room, "")
self._update_message_list()
return entry_text
def on_set_room_wall_message(self, *_args):
entry_text = self._clear_room_wall_message(update_list=False)
core.chatrooms.request_update_ticker(self.room, entry_text)
if entry_text:
user = core.users.login_username
self.message_view.append_line(f"> [{user}] {entry_text}")
self._update_message_list()
def on_icon_pressed(self, _entry, icon_pos, *_args):
if icon_pos == Gtk.EntryIconPosition.PRIMARY:
self.on_set_room_wall_message()
return
self._clear_room_wall_message()
def _on_show(self, *_args):
self.message_view.clear()
self._update_message_list()
login_username = core.users.login_username
message = core.chatrooms.joined_rooms[self.room].tickers.get(login_username)
if message:
self.message_entry.set_text(message)
self.message_entry.select_region(0, -1)
| 3,405 | Python | .py | 77 | 36.402597 | 111 | 0.663636 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,465 | chathistory.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/popovers/chathistory.py | # COPYRIGHT (C) 2022-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import time
from collections import deque
from gi.repository import GObject
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.popover import Popover
from pynicotine.gtkgui.widgets.textentry import CompletionEntry
from pynicotine.gtkgui.widgets.theme import USER_STATUS_ICON_NAMES
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.logfacility import log
from pynicotine.slskmessages import UserStatus
from pynicotine.utils import encode_path
class ChatHistory(Popover):
def __init__(self, window):
(
self.container,
self.list_container,
self.search_entry
) = ui.load(scope=self, path="popovers/chathistory.ui")
super().__init__(
window=window,
content_box=self.container,
width=1000,
height=700
)
self.list_view = TreeView(
window, parent=self.list_container, activate_row_callback=self.on_show_user,
search_entry=self.search_entry,
columns={
"status": {
"column_type": "icon",
"title": _("Status"),
"width": 25,
"hide_header": True
},
"user": {
"column_type": "text",
"title": _("User"),
"width": 175,
"iterator_key": True
},
"latest_message": {
"column_type": "text",
"title": _("Latest Message")
},
# Hidden data columns
"timestamp_data": {
"data_type": GObject.TYPE_UINT64,
"default_sort_type": "descending"
}
}
)
Accelerator("<Primary>f", self.widget, self.on_search_accelerator)
self.completion_entry = CompletionEntry(window.private_entry, self.list_view.model, column=1)
if GTK_API_VERSION >= 4:
inner_button = next(iter(window.private_history_button))
add_css_class(widget=inner_button, css_class="arrow-button")
self.set_menu_button(window.private_history_button)
self.load_users()
for event_name, callback in (
("server-login", self.server_login),
("server-disconnect", self.server_disconnect),
("user-status", self.user_status)
):
events.connect(event_name, callback)
def destroy(self):
self.list_view.destroy()
self.completion_entry.destroy()
super().destroy()
def server_login(self, msg):
if not msg.success:
return
for iterator in self.list_view.iterators.values():
username = self.list_view.get_row_value(iterator, "user")
core.users.watch_user(username, context="chathistory")
def server_disconnect(self, *_args):
for iterator in self.list_view.iterators.values():
self.list_view.set_row_value(iterator, "status", USER_STATUS_ICON_NAMES[UserStatus.OFFLINE])
@staticmethod
def load_user(file_path):
"""Reads the username and latest message from a given log file path.
Usernames are first extracted from the file name. In case the
extracted username contains underscores, attempt to fetch the
original username from logged messages, since illegal filename
characters are substituted with underscores.
"""
username = os.path.basename(file_path[:-4]).decode("utf-8", "replace")
is_safe_username = ("_" not in username)
login_username = config.sections["server"]["login"]
timestamp = os.path.getmtime(file_path)
read_num_lines = 1 if is_safe_username else 25
latest_message = None
with open(file_path, "rb") as lines:
lines = deque(lines, read_num_lines)
for line in lines:
try:
line = line.decode("utf-8")
except UnicodeDecodeError:
line = line.decode("latin-1")
if latest_message is None:
latest_message = line
if is_safe_username:
break
username_chars = set(username.replace("_", ""))
if login_username in line:
continue
if " [" not in line or "] " not in line:
continue
start = line.find(" [") + 2
end = line.find("] ", start)
line_username_len = (end - start)
if len(username) != line_username_len:
continue
line_username = line[start:end]
if username == line_username:
# Nothing to do, username is already correct
break
if username_chars.issubset(line_username):
username = line_username
break
return username, latest_message, timestamp
def load_users(self):
self.list_view.freeze()
try:
with os.scandir(encode_path(log.private_chat_folder_path)) as entries:
for entry in entries:
if not entry.is_file() or not entry.name.endswith(b".log"):
continue
try:
username, latest_message, timestamp = self.load_user(entry.path)
except OSError:
continue
if latest_message is not None:
self.update_user(username, latest_message.strip(), timestamp)
except OSError:
pass
self.list_view.unfreeze()
def remove_user(self, username):
iterator = self.list_view.iterators.get(username)
if iterator is not None:
self.list_view.remove_row(iterator)
def update_user(self, username, message, timestamp=None):
self.remove_user(username)
core.users.watch_user(username, context="chathistory")
if not timestamp:
timestamp_format = config.sections["logging"]["log_timestamp"]
timestamp = time.time()
h_timestamp = time.strftime(timestamp_format)
message = f"{h_timestamp} {message}"
status = core.users.statuses.get(username, UserStatus.OFFLINE)
self.list_view.add_row([
USER_STATUS_ICON_NAMES[status],
username,
message,
int(timestamp)
], select_row=False)
def user_status(self, msg):
iterator = self.list_view.iterators.get(msg.user)
if iterator is None:
return
status_icon_name = USER_STATUS_ICON_NAMES.get(msg.status)
if status_icon_name and status_icon_name != self.list_view.get_row_value(iterator, "status"):
self.list_view.set_row_value(iterator, "status", status_icon_name)
def on_show_user(self, *_args):
for iterator in self.list_view.get_selected_rows():
username = self.list_view.get_row_value(iterator, "user")
core.privatechat.show_user(username)
self.close(use_transition=False)
return
def on_search_accelerator(self, *_args):
"""Ctrl+F - Search users."""
self.search_entry.grab_focus()
return True
| 8,540 | Python | .py | 196 | 32.112245 | 104 | 0.597487 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,466 | roomlist.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/popovers/roomlist.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Pango
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.popover import Popover
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.textentry import CompletionEntry
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.utils import humanize
class RoomList(Popover):
PRIVATE_USERS_OFFSET = 10000000
def __init__(self, window):
(
self.container,
self.list_container,
self.private_room_toggle,
self.public_feed_toggle,
self.refresh_button,
self.search_entry
) = ui.load(scope=self, path="popovers/roomlist.ui")
super().__init__(
window=window,
content_box=self.container,
width=450,
height=500
)
self.list_view = TreeView(
window, parent=self.list_container,
activate_row_callback=self.on_row_activated, search_entry=self.search_entry,
columns={
# Visible columns
"room": {
"column_type": "text",
"title": _("Room"),
"width": 260,
"expand_column": True,
"text_underline_column": "room_underline_data",
"text_weight_column": "room_weight_data"
},
"users": {
"column_type": "number",
"title": _("Users"),
"sort_column": "users_data",
"default_sort_type": "descending"
},
# Hidden data columns
"users_data": {"data_type": GObject.TYPE_UINT},
"is_private_data": {"data_type": GObject.TYPE_BOOLEAN},
"room_weight_data": {"data_type": Pango.Weight},
"room_underline_data": {"data_type": Pango.Underline}
}
)
self.popup_room = None
self.popup_menu = PopupMenu(window.application, self.list_view.widget, self.on_popup_menu)
self.popup_menu.add_items(
("=" + _("Join Room"), self.on_popup_join),
("=" + _("Leave Room"), self.on_popup_leave),
("", None),
("=" + _("Disown Private Room"), self.on_popup_private_room_disown),
("=" + _("Cancel Room Membership"), self.on_popup_private_room_cancel_membership)
)
for toggle in (self.public_feed_toggle, self.private_room_toggle):
parent = next(iter(toggle.get_parent()))
if GTK_API_VERSION >= 4:
parent.gesture_click = Gtk.GestureClick()
parent.add_controller(parent.gesture_click)
else:
parent.set_has_window(True)
parent.gesture_click = Gtk.GestureMultiPress(widget=parent)
parent.gesture_click.connect("released", self.on_toggle_label_pressed, toggle)
self.private_room_toggle.set_active(config.sections["server"]["private_chatrooms"])
self.private_room_toggle.connect("notify::active", self.on_toggle_accept_private_room)
Accelerator("<Primary>f", self.widget, self.on_search_accelerator)
self.completion_entry = CompletionEntry(window.chatrooms_entry, self.list_view.model, column=0)
if GTK_API_VERSION >= 4:
inner_button = next(iter(window.room_list_button))
add_css_class(widget=inner_button, css_class="arrow-button")
self.set_menu_button(window.room_list_button)
for event_name, callback in (
("join-room", self.join_room),
("private-room-added", self.private_room_added),
("remove-room", self.remove_room),
("room-list", self.room_list),
("server-disconnect", self.clear),
("show-room", self.show_room),
("user-joined-room", self.user_joined_room),
("user-left-room", self.user_left_room)
):
events.connect(event_name, callback)
def destroy(self):
self.list_view.destroy()
self.popup_menu.destroy()
self.completion_entry.destroy()
super().destroy()
def get_selected_room(self):
for iterator in self.list_view.get_selected_rows():
return self.list_view.get_row_value(iterator, "room")
return None
def toggle_accept_private_room(self, active):
self.private_room_toggle.set_active(active)
def add_room(self, room, user_count=0, is_private=False, is_owned=False):
h_user_count = humanize(user_count)
if is_private:
# Large internal value to sort private rooms first
user_count += self.PRIVATE_USERS_OFFSET
text_weight = Pango.Weight.BOLD if is_private else Pango.Weight.NORMAL
text_underline = Pango.Underline.SINGLE if is_owned else Pango.Underline.NONE
self.list_view.add_row([
room,
h_user_count,
user_count,
is_private,
text_weight,
text_underline
], select_row=False)
def update_room_user_count(self, room, user_count=None, decrement=False):
iterator = self.list_view.iterators.get(room)
if iterator is None:
return
is_private = self.list_view.get_row_value(iterator, "is_private_data")
if user_count is None:
user_count = self.list_view.get_row_value(iterator, "users_data")
if decrement:
if user_count > 0:
user_count -= 1
else:
user_count += 1
elif is_private:
# Large internal value to sort private rooms first
user_count += self.PRIVATE_USERS_OFFSET
h_user_count = humanize(user_count - self.PRIVATE_USERS_OFFSET) if is_private else humanize(user_count)
self.list_view.set_row_values(
iterator,
column_ids=["users", "users_data"],
values=[h_user_count, user_count]
)
def clear(self, *_args):
self.list_view.clear()
def private_room_added(self, msg):
self.add_room(msg.room, is_private=True)
def join_room(self, msg):
room = msg.room
if room not in core.chatrooms.joined_rooms:
return
user_count = len(msg.users)
if room not in self.list_view.iterators:
self.add_room(
room, user_count, is_private=msg.private,
is_owned=(msg.owner == core.users.login_username)
)
self.update_room_user_count(room, user_count=user_count)
def show_room(self, room, *_args):
if room == core.chatrooms.GLOBAL_ROOM_NAME:
self.public_feed_toggle.set_active(True)
def remove_room(self, room):
if room == core.chatrooms.GLOBAL_ROOM_NAME:
self.public_feed_toggle.set_active(False)
self.update_room_user_count(room, decrement=True)
def user_joined_room(self, msg):
if msg.userdata.username != core.users.login_username:
self.update_room_user_count(msg.room)
def user_left_room(self, msg):
if msg.username != core.users.login_username:
self.update_room_user_count(msg.room, decrement=True)
def room_list(self, msg):
self.list_view.freeze()
self.clear()
for room, user_count in msg.ownedprivaterooms:
self.add_room(room, user_count, is_private=True, is_owned=True)
for room, user_count in msg.otherprivaterooms:
self.add_room(room, user_count, is_private=True)
for room, user_count in msg.rooms:
self.add_room(room, user_count)
self.list_view.unfreeze()
def on_row_activated(self, *_args):
room = self.get_selected_room()
if room is not None:
self.popup_room = room
self.on_popup_join()
def on_popup_menu(self, menu, _widget):
room = self.get_selected_room()
self.popup_room = room
is_private_room_owned = core.chatrooms.is_private_room_owned(room)
is_private_room_member = core.chatrooms.is_private_room_member(room)
menu.actions[_("Join Room")].set_enabled(room not in core.chatrooms.joined_rooms)
menu.actions[_("Leave Room")].set_enabled(room in core.chatrooms.joined_rooms)
menu.actions[_("Disown Private Room")].set_enabled(is_private_room_owned)
menu.actions[_("Cancel Room Membership")].set_enabled(is_private_room_member and not is_private_room_owned)
def on_popup_join(self, *_args):
core.chatrooms.show_room(self.popup_room)
self.close(use_transition=False)
def on_toggle_label_pressed(self, _controller, _num_p, _pos_x, _pos_y, toggle):
toggle.emit("activate")
def on_toggle_public_feed(self, *_args):
global_room_name = core.chatrooms.GLOBAL_ROOM_NAME
if self.public_feed_toggle.get_active():
if global_room_name not in core.chatrooms.joined_rooms:
core.chatrooms.show_room(global_room_name)
self.close(use_transition=False)
return
core.chatrooms.remove_room(global_room_name)
def on_popup_private_room_disown(self, *_args):
core.chatrooms.request_private_room_disown(self.popup_room)
def on_popup_private_room_cancel_membership(self, *_args):
core.chatrooms.request_private_room_cancel_membership(self.popup_room)
def on_popup_leave(self, *_args):
core.chatrooms.remove_room(self.popup_room)
def on_refresh(self, *_args):
core.chatrooms.request_room_list()
def on_toggle_accept_private_room(self, *_args):
active = config.sections["server"]["private_chatrooms"] = self.private_room_toggle.get_active()
core.chatrooms.request_private_room_toggle(active)
def on_search_accelerator(self, *_args):
"""Ctrl+F - Search rooms."""
self.search_entry.grab_focus()
return True
| 11,172 | Python | .py | 239 | 36.631799 | 115 | 0.628053 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,467 | searchfilterhelp.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/popovers/searchfilterhelp.py | # COPYRIGHT (C) 2022-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.popover import Popover
class SearchFilterHelp(Popover):
def __init__(self, window):
(self.container,) = ui.load(scope=self, path="popovers/searchfilterhelp.ui")
super().__init__(
window=window,
content_box=self.container,
width=500,
height=375
)
| 1,145 | Python | .py | 28 | 36.964286 | 84 | 0.729973 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,468 | chatcommandhelp.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/popovers/chatcommandhelp.py | # COPYRIGHT (C) 2022-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
from pynicotine.core import core
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets.popover import Popover
from pynicotine.gtkgui.widgets.theme import add_css_class
class ChatCommandHelp(Popover):
def __init__(self, window, interface):
self.interface = interface
self.scrollable = Gtk.ScrolledWindow(
propagate_natural_height=True, propagate_natural_width=True, visible=True
)
self.container = None
super().__init__(
window=window,
content_box=self.scrollable,
show_callback=self._on_show,
width=600,
height=450
)
def _create_command_section(self, group_name):
section_container = Gtk.Box(
orientation=Gtk.Orientation.VERTICAL, margin_start=18, margin_end=18, margin_top=18, margin_bottom=18,
spacing=12, visible=True
)
section_label = Gtk.Label(label=group_name, selectable=True, wrap=True, xalign=0, visible=True)
add_css_class(section_label, "heading")
if GTK_API_VERSION >= 4:
section_container.append(section_label) # pylint: disable=no-member
self.container.append(section_container) # pylint: disable=no-member
else:
section_container.add(section_label) # pylint: disable=no-member
self.container.add(section_container) # pylint: disable=no-member
return section_container
def _create_command_row(self, parent, command, aliases, parameters, description):
row = Gtk.Box(homogeneous=True, spacing=12, visible=True)
command_label = Gtk.Label(
label=f"/{', /'.join([command] + aliases)} {' '.join(parameters)}".strip(),
selectable=True, wrap=True, xalign=0, yalign=0, visible=True
)
description_label = Gtk.Label(
label=description, selectable=True, wrap=True, xalign=0, yalign=0,
visible=True
)
add_css_class(command_label, "italic")
if GTK_API_VERSION >= 4:
row.append(command_label) # pylint: disable=no-member
row.append(description_label) # pylint: disable=no-member
parent.append(row) # pylint: disable=no-member
else:
row.add(command_label) # pylint: disable=no-member
row.add(description_label) # pylint: disable=no-member
parent.add(row) # pylint: disable=no-member
return row
def _on_show(self, *_args):
if self.container is not None:
if GTK_API_VERSION >= 4:
self.scrollable.set_child(None) # pylint: disable=no-member
else:
self.scrollable.remove(self.container) # pylint: disable=no-member
self.container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, visible=True)
for group_name, command_data in core.pluginhandler.get_command_groups_data(self.interface).items():
section_container = self._create_command_section(group_name)
for command, aliases, parameters, description in command_data:
self._create_command_row(section_container, command, aliases, parameters, description)
if GTK_API_VERSION >= 4:
self.scrollable.set_child(self.container) # pylint: disable=no-member
else:
self.scrollable.add(self.container) # pylint: disable=no-member
self.container.child_focus(Gtk.DirectionType.TAB_FORWARD)
| 4,354 | Python | .py | 86 | 42.069767 | 114 | 0.662188 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,469 | about.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/dialogs/about.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
from gi.repository import Gtk
import pynicotine
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.dialogs import Dialog
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.theme import remove_css_class
from pynicotine.utils import open_uri
class About(Dialog):
AUTHORS = [
"<b>Nicotine+ Team</b>",
("<b>Mat (mathiascode)</b>"
"\n • Maintainer (2020–present)"
"\n • Developer"),
("<b>Adam Cécile (eLvErDe)</b>"
"\n • Maintainer (2013–2016)"
"\n • Domain name administrator"
"\n • Source code migration from SVN to GitHub"
"\n • Developer"),
("<b>Han Boetes</b>"
"\n • Tester"
"\n • Documentation"
"\n • Bug hunting"
"\n • Translation management"),
("<b>alekksander</b>"
"\n • Tester"
"\n • Redesign of some graphics"),
("<b>slook</b>"
"\n • Tester"
"\n • Accessibility improvements"),
("<b>ketacat</b>"
"\n • Tester"),
"\n<b>Nicotine+ Team (Emeritus)</b>",
("<b>daelstorm</b>"
"\n • Maintainer (2004–2009)"
"\n • Developer"),
("<b>quinox</b>"
"\n • Maintainer (2009–2012)"
"\n • Developer"),
("<b>Michael Labouebe (gfarmerfr)</b>"
"\n • Maintainer (2016–2017)"
"\n • Developer"),
("<b>Kip Warner</b>"
"\n • Maintainer (2018–2020)"
"\n • Developer"
"\n • Debianization"),
("<b>gallows (aka 'burp O')</b>"
"\n • Developer"
"\n • Packager"
"\n • Submitted Slack.Build file"),
("<b>hedonist (formerly known as alexbk)</b>"
"\n • OS X Nicotine.app maintainer / developer"
"\n • Author of PySoulSeek, used for Nicotine core"),
("<b>lee8oi</b>"
"\n • Bash commander"
"\n • New and updated /alias"),
("<b>INMCM</b>"
"\n • Nicotine+ topic maintainer on ubuntuforums.org"),
("<b>suser-guru</b>"
"\n • Suse Linux packager"
"\n • Nicotine+ RPM's for Suse 9.1, 9.2, 9.3, 10.0, 10.1"),
("<b>osiris</b>"
"\n • Handy-man"
"\n • Documentation"
"\n • Some GNU/Linux packaging"
"\n • Nicotine+ on Win32"
"\n • Author of Nicotine+ guide"),
("<b>Mutnick</b>"
"\n • Created Nicotine+ GitHub organization"
"\n • Developer"),
("<b>Lene Preuss</b>"
"\n • Python 3 migration"
"\n • Unit and DEP-8 continuous integration testing"),
"\n<b>Nicotine Team (Emeritus)</b>",
("<b>Ingmar K. Steen (Hyriand)</b>"
"\n • Maintainer (2003–2004)"),
("<b>daelstorm</b>"
"\n • Beta tester"
"\n • Designer of most of the settings"
"\n • Made the Nicotine icons"),
("<b>SmackleFunky</b>"
"\n • Beta tester"),
("<b>Wretched</b>"
"\n • Beta tester"
"\n • Bringer of great ideas"),
("<b>(va)\\*10^3</b>"
"\n • Beta tester"
"\n • Designer of Nicotine homepage and artwork (logos)"),
("<b>sierracat</b>"
"\n • MacOSX tester"
"\n • soulseeX developer"),
("<b>Gustavo J. A. M. Carneiro</b>"
"\n • Created the exception dialog"),
("<b>SeeSchloss</b>"
"\n • Developer"
"\n • Created 1.0.8 Win32 installer"
"\n • Created Soulfind, open source Soulseek server written in D"),
("<b>vasi</b>"
"\n • Mac developer"
"\n • Packaged Nicotine on OSX PowerPC"),
"\n<b>PySoulSeek Team (Emeritus)</b>",
("<b>Alexander Kanavin</b>"
"\n • Maintainer (2001–2003)"),
("<b>Nir Arbel</b>"
"\n • Helped with many protocol questions, and of course he designed and implemented the whole system"),
("<b>Brett W. Thompson (Zip)</b>"
"\n • His client code was used to get an initial impression of how the system works"
"\n • Supplied the patch for logging chat conversations"),
("<b>Josselin Mouette</b>"
"\n • Official Debian package maintainer"),
("<b>blueboy</b>"
"\n • Former unofficial Debian package maintainer"),
("<b>Christian Swinehart</b>"
"\n • Fink package maintainer"),
("<b>Ingmar K. Steen (Hyriand)</b>"
"\n • Patches for upload bandwidth management, banning, various UI improvements and more"),
("<b>Geert Kloosterman</b>"
"\n • A script for importing Windows Soulseek configuration"),
("<b>Joe Halliwell</b>"
"\n • Submitted a patch for optionally discarding search results after closing a search tab"),
("<b>Alexey Vyskubov</b>"
"\n • Code cleanups"),
("<b>Jason Green (SmackleFunky)</b>"
"\n • Ignore list and auto-join checkbox, wishlists")]
TRANSLATORS = [
("<b>Albanian</b>"
"\n • W L (2023–2024)"),
("<b>Arabic</b>"
"\n • ButterflyOfFire (2024)"),
("<b>Catalan</b>"
"\n • Maite Guix (2022)"),
("<b>Chinese (Simplified)</b>"
"\n • Ys413 (2024)"
"\n • Bonislaw (2023)"
"\n • hylau (2023)"
"\n • hadwin (2022)"),
("<b>Czech</b>"
"\n • slrslr (2024)"
"\n • burnmail123 (2021–2023)"),
("<b>Danish</b>"
"\n • mathsped (2003–2004)"),
("<b>Dutch</b>"
"\n • Toine Rademacher (toineenzo) (2023–2024)"
"\n • Han Boetes (hboetes) (2021–2024)"
"\n • Kenny Verstraete (2009)"
"\n • nince78 (2007)"
"\n • Ingmar K. Steen (Hyriand) (2003–2004)"),
("<b>English</b>"
"\n • slook (2021–2024)"
"\n • Han Boetes (hboetes) (2021–2024)"
"\n • Mat (mathiascode) (2020–2024)"
"\n • Michael Labouebe (gfarmerfr) (2016)"
"\n • daelstorm (2004–2009)"
"\n • Ingmar K. Steen (Hyriand) (2003–2004)"),
("<b>Esperanto</b>"
"\n • phlostically (2021)"),
("<b>Estonian</b>"
"\n • rimasx (2024)"
"\n • PriitUring (2023)"),
("<b>Euskara</b>"
"\n • Julen (2006–2007)"),
("<b>Finnish</b>"
"\n • Kari Viittanen (Kalevi) (2006–2007)"),
("<b>French</b>"
"\n • Saumon (2023)"
"\n • subu_versus (2023)"
"\n • zniavre (2007–2023)"
"\n • Maxime Leroy (Lisapple) (2021–2022)"
"\n • Mohamed El Morabity (melmorabity) (2021–2024)"
"\n • m-balthazar (2020)"
"\n • Michael Labouebe (gfarmerfr) (2016–2017)"
"\n • Monsieur Poisson (2009–2010)"
"\n • ManWell (2007)"
"\n • systr (2006)"
"\n • Julien Wajsberg (flashfr) (2003–2004)"),
("<b>German</b>"
"\n • Han Boetes (hboetes) (2021–2024)"
"\n • phelissimo_ (2023)"
"\n • Meokater (2007)"
"\n • (._.) (2007)"
"\n • lippel (2004)"
"\n • Ingmar K. Steen (Hyriand) (2003–2004)"),
("<b>Hungarian</b>"
"\n • Szia Tomi (2022–2024)"
"\n • Nils (2009)"
"\n • David Balazs (djbaloo) (2006–2020)"),
("<b>Italian</b>"
"\n • Gabriele (Gabboxl) (2022–2023)"
"\n • ms-afk (2023)"
"\n • Gianluca Boiano (2020–2023)"
"\n • nicola (2007)"
"\n • dbazza (2003–2004)"),
("<b>Latvian</b>"
"\n • Pagal3 (2022–2024)"),
("<b>Lithuanian</b>"
"\n • mantas (2020)"
"\n • Žygimantas Beručka (2006–2009)"),
("<b>Norwegian Bokmål</b>"
"\n • Allan Nordhøy (comradekingu) (2021)"),
("<b>Polish</b>"
"\n • Mariusz (mariachini) (2017–2024)"
"\n • Amun-Ra (2007)"
"\n • thine (2007)"
"\n • Wojciech Owczarek (owczi) (2003–2004)"),
("<b>Portuguese (Brazil)</b>"
"\n • Havokdan (2022–2023)"
"\n • Guilherme Santos (2022)"
"\n • b1llso (2022)"
"\n • Nicolas Abril (2021)"
"\n • yyyyyyyan (2020)"
"\n • Felipe Nogaroto Gonzalez (Suicide|Solution) (2006)"),
("<b>Portuguese (Portugal)</b>"
"\n • ssantos (2023)"
"\n • Vinícius Soares (2023)"),
("<b>Romanian</b>"
"\n • Slendi (xslendix) (2023)"),
("<b>Russian</b>"
"\n • Kirill Feoktistov (SnIPeRSnIPeR) (2022–2024)"
"\n • Mehavoid (2021–2023)"
"\n • AHOHNMYC (2022)"),
("<b>Slovak</b>"
"\n • Jozef Říha (2006–2008)"),
("<b>Spanish (Chile)</b>"
"\n • MELERIX (2021–2023)"
"\n • tagomago (2021–2022)"
"\n • Strange (2021)"
"\n • Silvio Orta (2007)"
"\n • Dreslo (2003–2004)"),
("<b>Spanish (Spain)</b>"
"\n • gallegonovato (2023–2024)"
"\n • MELERIX (2021–2023)"
"\n • tagomago (2021–2022)"
"\n • Strange (2021)"
"\n • Silvio Orta (2007)"
"\n • Dreslo (2003–2004)"),
("<b>Swedish</b>"
"\n • mitramai (2021)"
"\n • Markus Magnuson (alimony) (2003–2004)"),
("<b>Turkish</b>"
"\n • Oğuz Ersen (2021–2024)"),
("<b>Ukrainian</b>"
"\n • Oleg Gritsun (2024)"
"\n • uniss2209 (2022)")]
LICENSE = [
("Nicotine+ is licensed under the <a href='https://www.gnu.org/licenses/gpl-3.0.html'>"
"GNU General Public License v3.0 or later</a>, with the following exceptions:"),
("<b><a href='https://github.com/tinytag/tinytag'>tinytag</a> licensed under the MIT License.</b>"
"\nCopyright (c) 2014-2023 Tom Wallroth, Mat (mathiascode)"
"\n\nPermission is hereby granted, free of charge, to any person obtaining a copy "
'of this software and associated documentation files (the "Software"), to deal '
"in the Software without restriction, including without limitation the rights "
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell "
"copies of the Software, and to permit persons to whom the Software is "
"furnished to do so, subject to the following conditions: "
"\n\nThe above copyright notice and this permission notice shall be included in all "
"copies or substantial portions of the Software."),
("<b><a href='https://github.com/madebybowtie/FlagKit'>FlagKit</a> icons licensed "
"under the MIT License.</b>"
"\nCopyright (c) 2016 Bowtie AB"
"\n\nPermission is hereby granted, free of charge, to any person obtaining a copy "
'of this software and associated documentation files (the "Software"), to deal '
"in the Software without restriction, including without limitation the rights "
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell "
"copies of the Software, and to permit persons to whom the Software is "
"furnished to do so, subject to the following conditions: "
"\n\nThe above copyright notice and this permission notice shall be included in all "
"copies or substantial portions of the Software."),
("<b>IP2Location country data licensed under the "
"<a href='https://creativecommons.org/licenses/by-sa/4.0/'>CC-BY-SA-4.0 License</a>.</b>"
"\nCopyright (c) 2001–2024 Hexasoft Development Sdn. Bhd."
"\nNicotine+ uses the IP2Location LITE database for "
"<a href='https://lite.ip2location.com'>IP geolocation</a>.")]
def __init__(self, application):
(
self.application_version_label,
self.authors_container,
self.container,
self.copyright_label,
self.dependency_versions_label,
self.license_container,
self.main_icon,
self.status_container,
self.status_icon,
self.status_label,
self.status_spinner,
self.translators_container,
self.website_label
) = ui.load(scope=self, path="dialogs/about.ui")
super().__init__(
parent=application.window,
content_box=self.container,
show_callback=self.on_show,
close_callback=self.on_close,
title=_("About"),
width=425,
height=540,
show_title=False
)
self.is_version_outdated = False
icon_name = pynicotine.__application_id__
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
website_text = _('Website')
gtk_version = f"{Gtk.get_major_version()}.{Gtk.get_minor_version()}.{Gtk.get_micro_version()}"
self.main_icon.set_from_icon_name(icon_name, *icon_args)
self.website_label.connect("activate-link", self.on_activate_link)
for label_widget, text in (
(self.application_version_label, f"{pynicotine.__application_name__} {pynicotine.__version__}"),
(self.dependency_versions_label, (f"GTK {gtk_version} • Python {sys.version.split()[0]}")),
(self.website_label, (f"<a href='{pynicotine.__website_url__}' title='{pynicotine.__website_url__}'>"
f"{website_text}</a>")),
(self.copyright_label, f"<small>{pynicotine.__copyright__}</small>")
):
label_widget.set_markup(text)
for entries, container in (
(self.AUTHORS, self.authors_container),
(self.TRANSLATORS, self.translators_container),
(self.LICENSE, self.license_container)
):
for text in entries:
label = Gtk.Label(label=text, use_markup=True, selectable=True, wrap=True, xalign=0, visible=True)
if entries is self.LICENSE:
label.connect("activate-link", self.on_activate_link)
if GTK_API_VERSION >= 4:
container.append(label) # pylint: disable=no-member
else:
container.add(label) # pylint: disable=no-member
events.connect("check-latest-version", self.on_check_latest_version)
def on_activate_link(self, _label, url):
open_uri(url)
return True
def on_check_latest_version(self, latest_version, is_outdated, error):
if error:
icon_name = "emblem-important-symbolic"
css_class = "error"
message = _("Error checking latest version: %s") % error
elif is_outdated:
icon_name = "dialog-warning-symbolic"
css_class = "warning"
message = _("New release available: %s") % latest_version
else:
icon_name = "object-select-symbolic"
css_class = "success"
message = _("Up to date")
self.is_version_outdated = is_outdated
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.status_label.set_label(message)
self.status_icon.set_from_icon_name(icon_name, *icon_args)
self.status_spinner.set_visible(False)
self.status_spinner.stop()
add_css_class(self.status_container, css_class)
def on_show(self, *_args):
if core.update_checker is None:
# Update checker is not loaded
return
if self.is_version_outdated:
# No need to check latest version again
return
if not self.is_visible():
return
for css_class in ("error", "warning", "success"):
remove_css_class(self.status_container, css_class)
self.status_label.set_label(_("Checking latest version…"))
self.status_spinner.set_visible(True)
self.status_spinner.start()
self.status_container.set_visible(True)
core.update_checker.check()
def on_close(self, *_args):
self.main_icon.grab_focus()
self.status_spinner.stop()
self.container.get_vadjustment().set_value(0)
| 17,655 | Python | .py | 390 | 34.361538 | 114 | 0.555609 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,470 | pluginsettings.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/dialogs/pluginsettings.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import GObject
from gi.repository import Gtk
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets.combobox import ComboBox
from pynicotine.gtkgui.widgets.dialogs import Dialog
from pynicotine.gtkgui.widgets.dialogs import EntryDialog
from pynicotine.gtkgui.widgets.filechooser import FileChooserButton
from pynicotine.gtkgui.widgets.textview import TextView
from pynicotine.gtkgui.widgets.theme import add_css_class
class PluginSettings(Dialog):
def __init__(self, application):
self.application = application
self.plugin_id = None
self.plugin_settings = None
self.option_widgets = {}
cancel_button = Gtk.Button(label=_("_Cancel"), use_underline=True, visible=True)
cancel_button.connect("clicked", self.on_cancel)
ok_button = Gtk.Button(label=_("_Apply"), use_underline=True, visible=True)
ok_button.connect("clicked", self.on_ok)
add_css_class(ok_button, "suggested-action")
self.primary_container = Gtk.Box(
orientation=Gtk.Orientation.VERTICAL, width_request=340, visible=True,
margin_top=14, margin_bottom=14, margin_start=18, margin_end=18, spacing=12
)
self.scrolled_window = Gtk.ScrolledWindow(
child=self.primary_container, hexpand=True, vexpand=True, min_content_height=300,
hscrollbar_policy=Gtk.PolicyType.NEVER, vscrollbar_policy=Gtk.PolicyType.AUTOMATIC, visible=True
)
super().__init__(
parent=application.preferences,
content_box=self.scrolled_window,
buttons_start=(cancel_button,),
buttons_end=(ok_button,),
default_button=ok_button,
close_callback=self.on_close,
width=600,
height=425,
show_title_buttons=False
)
def destroy(self):
self.__dict__.clear()
@staticmethod
def _generate_label(text):
return Gtk.Label(label=text, hexpand=True, wrap=True, xalign=0, visible=bool(text))
def _generate_widget_container(self, description, child_widget=None, homogeneous=False,
orientation=Gtk.Orientation.HORIZONTAL):
container = Gtk.Box(homogeneous=homogeneous, orientation=orientation, spacing=12, visible=True)
label = self._generate_label(description)
if GTK_API_VERSION >= 4:
container.append(label) # pylint: disable=no-member
self.primary_container.append(container) # pylint: disable=no-member
if child_widget:
container.append(child_widget) # pylint: disable=no-member
else:
container.add(label) # pylint: disable=no-member
self.primary_container.add(container) # pylint: disable=no-member
if child_widget:
container.add(child_widget) # pylint: disable=no-member
return label
def _add_numerical_option(self, option_name, option_value, description, minimum, maximum, stepsize, decimals):
self.option_widgets[option_name] = button = Gtk.SpinButton(
adjustment=Gtk.Adjustment(
value=0, lower=minimum, upper=maximum, step_increment=stepsize, page_increment=10,
page_size=0
),
climb_rate=1, digits=decimals, valign=Gtk.Align.CENTER, visible=True
)
label = self._generate_widget_container(description, button)
label.set_mnemonic_widget(button)
self.application.preferences.set_widget(button, option_value)
def _add_boolean_option(self, option_name, option_value, description):
self.option_widgets[option_name] = button = Gtk.Switch(
receives_default=True, valign=Gtk.Align.CENTER, visible=True
)
label = self._generate_widget_container(description, button)
label.set_mnemonic_widget(button)
self.application.preferences.set_widget(button, option_value)
def _add_radio_option(self, option_name, option_value, description, items):
box = Gtk.Box(spacing=6, orientation=Gtk.Orientation.VERTICAL, visible=True)
label = self._generate_widget_container(description, box)
last_radio = None
group_radios = []
for option_label in items:
widget_class = Gtk.CheckButton if GTK_API_VERSION >= 4 else Gtk.RadioButton
radio = widget_class(group=last_radio, label=option_label, receives_default=True, visible=True)
if not last_radio:
self.option_widgets[option_name] = radio
last_radio = radio
group_radios.append(radio)
if GTK_API_VERSION >= 4:
box.append(radio) # pylint: disable=no-member
else:
box.add(radio) # pylint: disable=no-member
label.set_mnemonic_widget(self.option_widgets[option_name])
self.option_widgets[option_name].group_radios = group_radios
self.application.preferences.set_widget(self.option_widgets[option_name], option_value)
def _add_dropdown_option(self, option_name, option_value, description, items):
label = self._generate_widget_container(description, homogeneous=True)
self.option_widgets[option_name] = combobox = ComboBox(
container=label.get_parent(), label=label, items=items
)
self.application.preferences.set_widget(combobox, option_value)
def _add_entry_option(self, option_name, option_value, description):
self.option_widgets[option_name] = entry = Gtk.Entry(hexpand=True, valign=Gtk.Align.CENTER,
visible=True)
label = self._generate_widget_container(description, entry, homogeneous=True)
label.set_mnemonic_widget(entry)
self.application.preferences.set_widget(entry, option_value)
def _add_textview_option(self, option_name, option_value, description):
box = Gtk.Box(visible=True)
scrolled_window = Gtk.ScrolledWindow(hexpand=True, vexpand=True, min_content_height=125,
visible=True)
frame_container = Gtk.Frame(child=box, visible=True)
if GTK_API_VERSION >= 4:
box.append(scrolled_window) # pylint: disable=no-member
else:
box.add(scrolled_window) # pylint: disable=no-member
self.option_widgets[option_name] = textview = TextView(scrolled_window)
label = self._generate_widget_container(description, frame_container, orientation=Gtk.Orientation.VERTICAL)
label.set_mnemonic_widget(textview.widget)
self.application.preferences.set_widget(textview, option_value)
def _add_list_option(self, option_name, option_value, description):
scrolled_window = Gtk.ScrolledWindow(
hexpand=True, vexpand=True, min_content_height=125,
hscrollbar_policy=Gtk.PolicyType.AUTOMATIC, vscrollbar_policy=Gtk.PolicyType.AUTOMATIC, visible=True
)
container = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, visible=True)
frame_container = Gtk.Frame(child=container, margin_top=6, visible=True)
add_css_class(scrolled_window, "border-bottom")
from pynicotine.gtkgui.widgets.treeview import TreeView
self.option_widgets[option_name] = treeview = TreeView(
self.application.window, parent=scrolled_window, activate_row_callback=self.on_row_activated,
delete_accelerator_callback=self.on_delete_accelerator,
columns={
# Visible columns
"description": {
"column_type": "text",
"title": description
},
# Hidden data columns
"id_data": {
"data_type": GObject.TYPE_INT,
"default_sort_type": "ascending",
"iterator_key": True
}
}
)
rows = [[item, index] for index, item in enumerate(option_value)]
treeview.description = description
treeview.row_id = len(rows)
self.application.preferences.set_widget(treeview, rows)
button_container = Gtk.Box(margin_end=6, margin_bottom=6, margin_start=6, margin_top=6,
spacing=6, visible=True)
for icon_name, label_text, callback in (
("list-add-symbolic", _("Add…"), self.on_add),
("document-edit-symbolic", _("Edit…"), self.on_edit),
("list-remove-symbolic", _("Remove"), self.on_remove)
):
button = Gtk.Button(visible=True)
label_container = Gtk.Box(spacing=6, visible=True)
icon = Gtk.Image(icon_name=icon_name, visible=True)
label = Gtk.Label(label=label_text, mnemonic_widget=button, visible=True)
button.connect("clicked", callback, treeview)
add_css_class(button, "flat")
if GTK_API_VERSION >= 4:
button.set_child(label_container) # pylint: disable=no-member
label_container.append(icon) # pylint: disable=no-member
label_container.append(label) # pylint: disable=no-member
button_container.append(button) # pylint: disable=no-member
else:
button.add(label_container) # pylint: disable=no-member
label_container.add(icon) # pylint: disable=no-member
label_container.add(label) # pylint: disable=no-member
button_container.add(button) # pylint: disable=no-member
if GTK_API_VERSION >= 4:
self.primary_container.append(frame_container) # pylint: disable=no-member
container.append(scrolled_window) # pylint: disable=no-member
container.append(button_container) # pylint: disable=no-member
else:
self.primary_container.add(frame_container) # pylint: disable=no-member
container.add(scrolled_window) # pylint: disable=no-member
container.add(button_container) # pylint: disable=no-member
def _add_file_option(self, option_name, option_value, description, file_chooser_type):
container = Gtk.Box(visible=True)
label = self._generate_widget_container(description, container, homogeneous=True)
self.option_widgets[option_name] = FileChooserButton(
container, window=self.widget, label=label, chooser_type=file_chooser_type
)
self.application.preferences.set_widget(self.option_widgets[option_name], option_value)
def _add_options(self):
self.option_widgets.clear()
for child in list(self.primary_container):
self.primary_container.remove(child)
for option_name, data in self.plugin_settings.items():
option_type = data.get("type")
if not option_type:
continue
description = data.get("description", "")
option_value = config.sections["plugins"][self.plugin_id.lower()][option_name]
if option_type in {"integer", "int", "float"}:
self._add_numerical_option(
option_name, option_value, description, minimum=data.get("minimum", 0),
maximum=data.get("maximum", 99999), stepsize=data.get("stepsize", 1),
decimals=(0 if option_type in {"integer", "int"} else 2)
)
elif option_type == "bool":
self._add_boolean_option(option_name, option_value, description)
elif option_type == "radio":
self._add_radio_option(
option_name, option_value, description, items=data.get("options", []))
elif option_type == "dropdown":
self._add_dropdown_option(
option_name, option_value, description, items=data.get("options", []))
elif option_type in {"str", "string"}:
self._add_entry_option(option_name, option_value, description)
elif option_type == "textview":
self._add_textview_option(option_name, option_value, description)
elif option_type == "list string":
self._add_list_option(option_name, option_value, description)
elif option_type == "file":
self._add_file_option(
option_name, option_value, description, file_chooser_type=data.get("chooser"))
@staticmethod
def _get_widget_data(widget):
if isinstance(widget, Gtk.SpinButton):
if widget.get_digits() > 0:
return widget.get_value()
return widget.get_value_as_int()
if isinstance(widget, Gtk.Entry):
return widget.get_text()
if isinstance(widget, TextView):
return widget.get_text()
if isinstance(widget, Gtk.Switch):
return widget.get_active()
if isinstance(widget, Gtk.CheckButton):
try:
# Radio button
for radio in widget.group_radios:
if radio.get_active():
return widget.group_radios.index(radio)
return 0
except (AttributeError, TypeError):
# Regular check button
return widget.get_active()
if isinstance(widget, ComboBox):
return widget.get_selected_id()
from pynicotine.gtkgui.widgets.treeview import TreeView
if isinstance(widget, TreeView):
return [
widget.get_row_value(iterator, "description")
for row_id, iterator in sorted(widget.iterators.items())
]
if isinstance(widget, FileChooserButton):
return widget.get_path()
return None
def update_settings(self, plugin_id, plugin_settings):
self.plugin_id = plugin_id
self.plugin_settings = plugin_settings
plugin_name = core.pluginhandler.get_plugin_info(plugin_id).get("Name", plugin_id)
self.set_title(_("%s Settings") % plugin_name)
self._add_options()
def on_add_response(self, window, _response_id, treeview):
value = window.get_entry_value()
if not value:
return
treeview.row_id += 1
treeview.add_row([value, treeview.row_id])
def on_add(self, _button, treeview):
EntryDialog(
parent=self,
title=_("Add Item"),
message=treeview.description,
action_button_label=_("_Add"),
callback=self.on_add_response,
callback_data=treeview
).present()
def on_edit_response(self, window, _response_id, data):
value = window.get_entry_value()
if not value:
return
treeview, row_id = data
iterator = treeview.iterators[row_id]
treeview.remove_row(iterator)
treeview.add_row([value, row_id])
def on_edit(self, _button=None, treeview=None):
for iterator in treeview.get_selected_rows():
value = treeview.get_row_value(iterator, "description") or ""
row_id = treeview.get_row_value(iterator, "id_data")
EntryDialog(
parent=self,
title=_("Edit Item"),
message=treeview.description,
action_button_label=_("_Edit"),
callback=self.on_edit_response,
callback_data=(treeview, row_id),
default=value
).present()
return
def on_remove(self, _button=None, treeview=None):
for iterator in reversed(list(treeview.get_selected_rows())):
row_id = treeview.get_row_value(iterator, "id_data")
orig_iterator = treeview.iterators[row_id]
treeview.remove_row(orig_iterator)
def on_row_activated(self, treeview, *_args):
self.on_edit(treeview=treeview)
def on_delete_accelerator(self, treeview):
self.on_remove(treeview=treeview)
def on_cancel(self, *_args):
self.close()
def on_ok(self, *_args):
plugin = core.pluginhandler.enabled_plugins[self.plugin_id]
for name in self.plugin_settings:
value = self._get_widget_data(self.option_widgets[name])
if value is not None:
plugin.settings[name] = value
self.close()
def on_close(self, *_args):
self.scrolled_window.get_vadjustment().set_value(0)
| 17,666 | Python | .py | 337 | 40.896142 | 115 | 0.622633 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,471 | wishlist.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/dialogs/wishlist.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.dialogs import Dialog
from pynicotine.gtkgui.widgets.dialogs import EntryDialog
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
from pynicotine.gtkgui.widgets.popupmenu import PopupMenu
from pynicotine.gtkgui.widgets.textentry import CompletionEntry
from pynicotine.gtkgui.widgets.treeview import TreeView
class WishList(Dialog):
def __init__(self, application):
(
self.container,
self.list_container,
self.wish_entry
) = ui.load(scope=self, path="dialogs/wishlist.ui")
super().__init__(
parent=application.window,
modal=False,
content_box=self.container,
show_callback=self.on_show,
title=_("Wishlist"),
width=600,
height=600
)
application.add_window(self.widget)
self.application = application
self.list_view = TreeView(
application.window, parent=self.list_container, multi_select=True, activate_row_callback=self.on_edit_wish,
delete_accelerator_callback=self.on_remove_wish,
columns={
"wish": {
"column_type": "text",
"title": _("Wish"),
"default_sort_type": "ascending"
}
}
)
self.list_view.freeze()
for search_item in core.search.searches.values():
if search_item.mode == "wishlist":
self.add_wish(search_item.term, select=False)
self.list_view.unfreeze()
self.completion_entry = CompletionEntry(self.wish_entry, self.list_view.model)
Accelerator("<Shift>Tab", self.list_view.widget, self.on_list_focus_entry_accelerator) # skip column header
self.popup_menu = PopupMenu(application, self.list_view.widget)
self.popup_menu.add_items(
("#" + _("_Search for Item"), self.on_search_wish),
("#" + _("Edit…"), self.on_edit_wish),
("", None),
("#" + _("Remove"), self.on_remove_wish)
)
for event_name, callback in (
("add-wish", self.add_wish),
("remove-wish", self.remove_wish)
):
events.connect(event_name, callback)
def destroy(self):
self.list_view.destroy()
self.completion_entry.destroy()
self.popup_menu.destroy()
super().destroy()
def on_list_focus_entry_accelerator(self, *_args):
self.wish_entry.grab_focus()
return True
def on_add_wish(self, *_args):
wish = self.wish_entry.get_text().strip()
if not wish:
return
wish_exists = (wish in self.list_view.iterators)
self.wish_entry.set_text("")
core.search.add_wish(wish)
if not wish_exists:
return
self.select_wish(wish)
def on_edit_wish_response(self, dialog, _response_id, old_wish):
wish = dialog.get_entry_value().strip()
if not wish:
return
core.search.remove_wish(old_wish)
core.search.add_wish(wish)
self.select_wish(wish)
def on_edit_wish(self, *_args):
for iterator in self.list_view.get_selected_rows():
old_wish = self.list_view.get_row_value(iterator, "wish")
EntryDialog(
parent=self,
title=_("Edit Wish"),
message=_("Enter new value for wish '%s':") % old_wish,
default=old_wish,
action_button_label=_("_Edit"),
callback=self.on_edit_wish_response,
callback_data=old_wish
).present()
return
def on_search_wish(self, *_args):
for iterator in self.list_view.get_selected_rows():
wish = self.list_view.get_row_value(iterator, "wish")
core.search.do_search(wish, mode="global")
return
def on_remove_wish(self, *_args):
for iterator in reversed(list(self.list_view.get_selected_rows())):
wish = self.list_view.get_row_value(iterator, "wish")
core.search.remove_wish(wish)
self.wish_entry.grab_focus()
return True
def clear_wishlist_response(self, *_args):
for wish in self.list_view.iterators.copy():
core.search.remove_wish(wish)
self.wish_entry.grab_focus()
def on_clear_wishlist(self, *_args):
OptionDialog(
parent=self,
title=_("Clear Wishlist?"),
message=_("Do you really want to clear your wishlist?"),
destructive_response_id="ok",
callback=self.clear_wishlist_response
).present()
def add_wish(self, wish, select=True):
self.list_view.add_row([wish], select_row=select)
def remove_wish(self, wish):
iterator = self.list_view.iterators.get(wish)
if iterator is not None:
self.list_view.remove_row(iterator)
def select_wish(self, wish):
iterator = self.list_view.iterators.get(wish)
if iterator is not None:
self.list_view.select_row(iterator)
def on_show(self, *_args):
page = self.application.window.search.get_current_page()
if page is None:
return
text = None
for tab in self.application.window.search.pages.values():
if tab is not None and tab.container == page:
text = tab.text
break
if not text:
self.list_view.unselect_all_rows()
return
iterator = self.list_view.iterators.get(text)
if iterator is not None:
# Highlight existing wish row
self.list_view.select_row(iterator)
self.wish_entry.set_text("")
return
# Pre-fill text field with search term from active search tab
self.list_view.unselect_all_rows()
self.wish_entry.set_text(text)
self.wish_entry.grab_focus()
| 6,966 | Python | .py | 168 | 31.809524 | 119 | 0.617507 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,472 | statistics.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/dialogs/statistics.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import time
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.dialogs import Dialog
from pynicotine.gtkgui.widgets.dialogs import OptionDialog
from pynicotine.utils import human_size
from pynicotine.utils import humanize
class Statistics(Dialog):
def __init__(self, application):
(
self.completed_downloads_session_label,
self.completed_downloads_total_label,
self.completed_uploads_session_label,
self.completed_uploads_total_label,
self.container,
self.current_session_label,
self.downloaded_size_session_label,
self.downloaded_size_total_label,
self.reset_button,
self.since_timestamp_total_label,
self.uploaded_size_session_label,
self.uploaded_size_total_label
) = ui.load(scope=self, path="dialogs/statistics.ui")
self.stat_id_labels = {
"completed_downloads": {
"session": self.completed_downloads_session_label,
"total": self.completed_downloads_total_label
},
"completed_uploads": {
"session": self.completed_uploads_session_label,
"total": self.completed_uploads_total_label
},
"downloaded_size": {
"session": self.downloaded_size_session_label,
"total": self.downloaded_size_total_label
},
"uploaded_size": {
"session": self.uploaded_size_session_label,
"total": self.uploaded_size_total_label
},
"since_timestamp": {
"total": self.since_timestamp_total_label
}
}
super().__init__(
parent=application.window,
content_box=self.container,
show_callback=self.on_show,
title=_("Transfer Statistics"),
width=425
)
events.connect("update-stat", self.update_stat)
def update_stat(self, stat_id, session_value, total_value):
current_stat_id_labels = self.stat_id_labels.get(stat_id)
if not current_stat_id_labels:
return
if not self.widget.get_visible():
return
if stat_id in {"downloaded_size", "uploaded_size"}:
session_value = human_size(session_value)
total_value = human_size(total_value)
elif stat_id == "since_timestamp":
session_value = None
total_value = (_("Total Since %(date)s") % {
"date": time.strftime("%x", time.localtime(total_value))} if total_value > 0 else None)
else:
session_value = humanize(session_value)
total_value = humanize(total_value)
if session_value is not None:
session_label = current_stat_id_labels["session"]
if session_label.get_text() != session_value:
session_label.set_text(session_value)
if total_value is not None:
total_label = current_stat_id_labels["total"]
if total_label.get_text() != total_value:
total_label.set_text(total_value)
def on_reset_statistics_response(self, *_args):
core.statistics.reset_stats()
def on_reset_statistics(self, *_args):
OptionDialog(
parent=self,
title=_("Reset Transfer Statistics?"),
message=_("Do you really want to reset transfer statistics?"),
destructive_response_id="ok",
callback=self.on_reset_statistics_response
).present()
def on_close(self, *_args):
self.close()
def on_show(self, *_args):
core.statistics.update_stats()
| 4,578 | Python | .py | 108 | 32.787037 | 103 | 0.626772 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,473 | fileproperties.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/dialogs/fileproperties.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.core import core
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.dialogs import Dialog
from pynicotine.slskmessages import FileListMessage
from pynicotine.utils import human_length
from pynicotine.utils import human_size
from pynicotine.utils import human_speed
from pynicotine.utils import humanize
class FileProperties(Dialog):
def __init__(self, application):
self.properties = {}
self.total_size = 0
self.total_length = 0
self.current_index = 0
(
self.container,
self.country_row,
self.country_value_label,
self.folder_value_label,
self.length_row,
self.length_value_label,
self.name_value_label,
self.next_button,
self.path_row,
self.path_value_label,
self.previous_button,
self.quality_row,
self.quality_value_label,
self.queue_row,
self.queue_value_label,
self.size_value_label,
self.speed_row,
self.speed_value_label,
self.username_value_label
) = ui.load(scope=self, path="dialogs/fileproperties.ui")
super().__init__(
parent=application.window,
content_box=self.container,
buttons_start=(self.previous_button, self.next_button),
default_button=self.next_button,
title=_("File Properties"),
width=600
)
def update_title(self):
index = self.current_index + 1
total_files = len(self.properties)
total_size = human_size(self.total_size)
if self.total_length:
self.set_title(_("File Properties (%(num)i of %(total)i / %(size)s / %(length)s)") % {
"num": index, "total": total_files, "size": total_size,
"length": human_length(self.total_length)
})
return
self.set_title(_("File Properties (%(num)i of %(total)i / %(size)s)") % {
"num": index, "total": total_files, "size": total_size})
def update_current_file(self):
"""Updates the UI with properties for the selected file."""
properties = self.properties[self.current_index]
for button in (self.previous_button, self.next_button):
button.set_visible(len(self.properties) > 1)
size = properties["size"]
h_size = human_size(size)
self.name_value_label.set_text(properties["basename"])
self.folder_value_label.set_text(properties["virtual_folder_path"])
self.size_value_label.set_text(f"{h_size} ({size} B)") # Don't humanize exact size for easier use in filter
self.username_value_label.set_text(properties["user"])
real_folder_path = properties.get("real_folder_path", "")
h_quality, _bitrate, h_length, _length = FileListMessage.parse_audio_quality_length(
size, properties.get("file_attributes"), always_show_bitrate=True)
queue_position = properties.get("queue_position", 0)
speed = properties.get("speed", 0)
country_code = properties.get("country_code")
country_name = core.network_filter.COUNTRIES.get(country_code)
country = f"{country_name} ({country_code})" if country_name else ""
self.path_value_label.set_text(real_folder_path)
self.path_row.set_visible(bool(real_folder_path))
self.quality_value_label.set_text(h_quality)
self.quality_row.set_visible(bool(h_quality))
self.length_value_label.set_text(h_length)
self.length_row.set_visible(bool(h_length))
self.queue_value_label.set_text(humanize(queue_position))
self.queue_row.set_visible(bool(queue_position))
self.speed_value_label.set_text(human_speed(speed))
self.speed_row.set_visible(bool(speed))
self.country_value_label.set_text(country)
self.country_row.set_visible(bool(country))
self.update_title()
def update_properties(self, properties, total_size=0, total_length=0):
self.properties = properties
self.total_size = total_size
self.total_length = total_length
self.current_index = 0
self.update_current_file()
def on_previous(self, *_args):
self.current_index -= 1
if self.current_index < 0:
self.current_index = len(self.properties) - 1
self.update_current_file()
def on_next(self, *_args):
self.current_index += 1
if self.current_index >= len(self.properties):
self.current_index = 0
self.update_current_file()
| 5,458 | Python | .py | 120 | 36.8 | 116 | 0.647935 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,474 | fastconfigure.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/dialogs/fastconfigure.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2009-2011 quinox <quinox@users.sf.net>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gtk
import pynicotine
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.filechooser import FileChooserButton
from pynicotine.gtkgui.widgets.filechooser import FolderChooser
from pynicotine.gtkgui.widgets.dialogs import Dialog
from pynicotine.gtkgui.widgets.dialogs import EntryDialog
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.slskmessages import UserStatus
class FastConfigure(Dialog):
def __init__(self, application):
self.invalid_password = False
self.rescan_required = False
self.finished = False
(
self.account_page,
self.download_folder_container,
self.invalid_password_label,
self.listen_port_entry,
self.main_icon,
self.next_button,
self.next_label,
self.password_entry,
self.port_page,
self.previous_button,
self.previous_label,
self.set_up_button,
self.share_page,
self.shares_list_container,
self.stack,
self.summary_page,
self.username_entry,
self.welcome_page
) = ui.load(scope=self, path="dialogs/fastconfigure.ui")
self.pages = [self.welcome_page, self.account_page, self.port_page, self.share_page, self.summary_page]
super().__init__(
parent=application.window,
content_box=self.stack,
buttons_start=(self.previous_button,),
buttons_end=(self.next_button,),
default_button=self.next_button,
show_callback=self.on_show,
close_callback=self.on_close,
title=_("Setup Assistant"),
width=720,
height=450,
show_title=False
)
icon_name = pynicotine.__application_id__
icon_args = (Gtk.IconSize.BUTTON,) if GTK_API_VERSION == 3 else () # pylint: disable=no-member
self.main_icon.set_from_icon_name(icon_name, *icon_args)
self.username_entry.set_max_length(core.users.USERNAME_MAX_LENGTH)
self.download_folder_button = FileChooserButton(
self.download_folder_container, window=self, chooser_type="folder",
selected_function=self.on_download_folder_selected
)
self.shares_list_view = TreeView(
application.window, parent=self.shares_list_container, multi_select=True,
activate_row_callback=self.on_edit_shared_folder,
delete_accelerator_callback=self.on_remove_shared_folder,
columns={
"virtual_name": {
"column_type": "text",
"title": _("Virtual Folder"),
"width": 1,
"expand_column": True,
"default_sort_type": "ascending"
},
"folder": {
"column_type": "text",
"title": _("Folder"),
"width": 125,
"expand_column": True
}
}
)
self.reset_completeness()
def destroy(self):
self.download_folder_button.destroy()
self.shares_list_view.destroy()
super().destroy()
def reset_completeness(self):
"""Turns on the complete flag if everything required is filled in."""
page = self.stack.get_visible_child()
page_complete = (
(page in (self.welcome_page, self.port_page, self.summary_page))
or (page == self.account_page and self.username_entry.get_text() and self.password_entry.get_text())
or (page == self.share_page and self.download_folder_button.get_path())
)
self.finished = (page == self.account_page if self.invalid_password else page == self.summary_page)
previous_label = _("_Cancel") if self.invalid_password else _("_Previous")
next_label = _("_Finish") if self.finished else _("_Next")
show_buttons = (page != self.welcome_page)
self.set_show_title_buttons(not show_buttons)
if self.previous_label.get_label() != previous_label:
self.previous_label.set_label(previous_label)
if self.next_label.get_label() != next_label:
self.next_label.set_label(next_label)
self.previous_button.set_visible(show_buttons)
self.next_button.set_visible(show_buttons)
self.next_button.set_sensitive(page_complete)
def on_entry_changed(self, *_args):
self.reset_completeness()
def on_user_entry_activate(self, *_args):
if not self.username_entry.get_text():
self.username_entry.grab_focus()
return
if not self.password_entry.get_text():
self.password_entry.grab_focus()
return
self.on_next()
def on_download_folder_selected(self):
config.sections["transfers"]["downloaddir"] = self.download_folder_button.get_path()
def on_add_shared_folder_selected(self, selected, _data):
for folder_path in selected:
virtual_name = core.shares.add_share(folder_path)
if virtual_name:
self.shares_list_view.add_row([virtual_name, folder_path])
self.rescan_required = True
def on_add_shared_folder(self, *_args):
FolderChooser(
parent=self,
title=_("Add a Shared Folder"),
callback=self.on_add_shared_folder_selected,
select_multiple=True
).present()
def on_edit_shared_folder_response(self, dialog, _response_id, iterator):
new_virtual_name = dialog.get_entry_value()
old_virtual_name = self.shares_list_view.get_row_value(iterator, "virtual_name")
if new_virtual_name == old_virtual_name:
return
self.rescan_required = True
folder_path = self.shares_list_view.get_row_value(iterator, "folder")
orig_iterator = self.shares_list_view.iterators[old_virtual_name]
self.shares_list_view.remove_row(orig_iterator)
core.shares.remove_share(old_virtual_name)
new_virtual_name = core.shares.add_share(
folder_path, virtual_name=new_virtual_name, validate_path=False
)
self.shares_list_view.add_row([new_virtual_name, folder_path])
def on_edit_shared_folder(self, *_args):
for iterator in self.shares_list_view.get_selected_rows():
virtual_name = self.shares_list_view.get_row_value(iterator, "virtual_name")
folder_path = self.shares_list_view.get_row_value(iterator, "folder")
EntryDialog(
parent=self,
title=_("Edit Shared Folder"),
message=_("Enter new virtual name for '%(dir)s':") % {"dir": folder_path},
default=virtual_name,
action_button_label=_("_Edit"),
callback=self.on_edit_shared_folder_response,
callback_data=iterator
).present()
return
def on_remove_shared_folder(self, *_args):
for iterator in reversed(list(self.shares_list_view.get_selected_rows())):
virtual_name = self.shares_list_view.get_row_value(iterator, "virtual_name")
orig_iterator = self.shares_list_view.iterators[virtual_name]
core.shares.remove_share(virtual_name)
self.shares_list_view.remove_row(orig_iterator)
self.rescan_required = True
def on_page_change(self, *_args):
page = self.stack.get_visible_child()
if page == self.welcome_page:
self.set_up_button.grab_focus()
elif page == self.account_page:
self.username_entry.grab_focus_without_selecting()
self.reset_completeness()
def on_next(self, *_args):
if self.finished:
self.on_finished()
return
start_page_index = self.pages.index(self.stack.get_visible_child()) + 1
for page in self.pages[start_page_index:]:
if page.get_visible():
self.next_button.grab_focus()
self.stack.set_visible_child(page)
return
def on_previous(self, *_args):
if self.invalid_password:
self.close()
return
start_page_index = self.pages.index(self.stack.get_visible_child())
for page in reversed(self.pages[:start_page_index]):
if page.get_visible():
self.previous_button.grab_focus()
self.stack.set_visible_child(page)
return
def on_finished(self, *_args):
if self.rescan_required:
core.shares.rescan_shares()
# port_page
listen_port = self.listen_port_entry.get_value_as_int()
config.sections["server"]["portrange"] = (listen_port, listen_port)
# account_page
if self.invalid_password or config.need_config():
config.sections["server"]["login"] = self.username_entry.get_text()
config.sections["server"]["passw"] = self.password_entry.get_text()
if core.users.login_status == UserStatus.OFFLINE:
core.connect()
self.close()
def on_close(self, *_args):
self.invalid_password = False
self.rescan_required = False
def on_show(self, *_args):
transition_type = self.stack.get_transition_type()
self.stack.set_transition_type(Gtk.StackTransitionType.NONE)
self.account_page.set_visible(self.invalid_password or config.need_config())
self.stack.set_visible_child(self.account_page if self.invalid_password else self.welcome_page)
self.stack.set_transition_type(transition_type)
self.on_page_change()
# account_page
if self.invalid_password:
self.invalid_password_label.set_label(
_("User %s already exists, and the password you entered is invalid. Please choose another username "
"if this is your first time logging in.") % config.sections["server"]["login"])
self.invalid_password_label.set_visible(self.invalid_password)
self.username_entry.set_text(config.sections["server"]["login"])
self.password_entry.set_text(config.sections["server"]["passw"])
# port_page
listen_port, _unused_port = config.sections["server"]["portrange"]
self.listen_port_entry.set_value(listen_port)
# share_page
self.download_folder_button.set_path(core.downloads.get_default_download_folder())
self.shares_list_view.clear()
self.shares_list_view.freeze()
for virtual_name, folder_path, *_unused in config.sections["transfers"]["shared"]:
self.shares_list_view.add_row([virtual_name, folder_path], select_row=False)
self.shares_list_view.unfreeze()
| 11,928 | Python | .py | 251 | 37.163347 | 116 | 0.631919 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,475 | shortcuts.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/dialogs/shortcuts.py | # COPYRIGHT (C) 2021-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.dialogs import Dialog
class Shortcuts(Dialog):
def __init__(self, application):
self.dialog, self.emoji_shortcut = ui.load(scope=self, path="dialogs/shortcuts.ui")
super().__init__(
widget=self.dialog,
parent=application.window
)
application.window.set_help_overlay(self.dialog)
# Workaround for off-centered dialog on first run
self.dialog.set_visible(True)
self.dialog.set_visible(False)
| 1,298 | Python | .py | 30 | 39.233333 | 91 | 0.73751 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,476 | preferences.py | nicotine-plus_nicotine-plus/pynicotine/gtkgui/dialogs/preferences.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2016-2017 Michael Labouebe <gfarmerfr@free.fr>
# COPYRIGHT (C) 2016 Mutnick <muhing@yahoo.com>
# COPYRIGHT (C) 2008-2011 quinox <quinox@users.sf.net>
# COPYRIGHT (C) 2008 gallows <g4ll0ws@gmail.com>
# COPYRIGHT (C) 2006-2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2003-2004 Hyriand <hyriand@thegraveyard.org>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import sys
import time
from operator import itemgetter
from gi.repository import Gdk
from gi.repository import GObject
from gi.repository import Gtk
from gi.repository import Pango
import pynicotine
from pynicotine.config import config
from pynicotine.core import core
from pynicotine.events import events
from pynicotine.gtkgui.application import GTK_API_VERSION
from pynicotine.gtkgui.application import GTK_MINOR_VERSION
from pynicotine.gtkgui.dialogs.pluginsettings import PluginSettings
from pynicotine.gtkgui.popovers.searchfilterhelp import SearchFilterHelp
from pynicotine.gtkgui.widgets import ui
from pynicotine.gtkgui.widgets.accelerator import Accelerator
from pynicotine.gtkgui.widgets.combobox import ComboBox
from pynicotine.gtkgui.widgets.dialogs import Dialog
from pynicotine.gtkgui.widgets.dialogs import EntryDialog
from pynicotine.gtkgui.widgets.dialogs import MessageDialog
from pynicotine.gtkgui.widgets.filechooser import FileChooserButton
from pynicotine.gtkgui.widgets.filechooser import FileChooserSave
from pynicotine.gtkgui.widgets.filechooser import FolderChooser
from pynicotine.gtkgui.widgets.textentry import SpellChecker
from pynicotine.gtkgui.widgets.textview import TextView
from pynicotine.gtkgui.widgets.theme import USER_STATUS_ICON_NAMES
from pynicotine.gtkgui.widgets.theme import add_css_class
from pynicotine.gtkgui.widgets.theme import load_custom_icons
from pynicotine.gtkgui.widgets.theme import set_dark_mode
from pynicotine.gtkgui.widgets.theme import update_custom_css
from pynicotine.gtkgui.widgets.treeview import TreeView
from pynicotine.i18n import LANGUAGES
from pynicotine.logfacility import log
from pynicotine.shares import PermissionLevel
from pynicotine.slskmessages import UserStatus
from pynicotine.slskproto import NetworkInterfaces
from pynicotine.utils import encode_path
from pynicotine.utils import open_folder_path
from pynicotine.utils import open_uri
from pynicotine.utils import unescape
class NetworkPage:
def __init__(self, application):
(
self.auto_away_spinner,
self.auto_connect_startup_toggle,
self.auto_reply_message_entry,
self.check_port_status_label,
self.container,
self.current_port_label,
self.listen_port_spinner,
self.network_interface_label,
self.soulseek_server_entry,
self.upnp_toggle,
self.username_entry
) = self.widgets = ui.load(scope=self, path="settings/network.ui")
self.application = application
self.portmap_required = None
self.username_entry.set_max_length(core.users.USERNAME_MAX_LENGTH)
self.check_port_status_label.connect("activate-link", self.on_activate_link)
self.network_interface_combobox = ComboBox(
container=self.network_interface_label.get_parent(), has_entry=True,
label=self.network_interface_label
)
self.options = {
"server": {
"server": None, # Special case in set_settings
"login": self.username_entry,
"portrange": None, # Special case in set_settings
"autoaway": self.auto_away_spinner,
"autoreply": self.auto_reply_message_entry,
"interface": self.network_interface_combobox,
"upnp": self.upnp_toggle,
"auto_connect_startup": self.auto_connect_startup_toggle
}
}
for event_name, callback in (
("server-disconnect", self.update_port_label),
("server-login", self.update_port_label)
):
events.connect(event_name, callback)
def destroy(self):
self.network_interface_combobox.destroy()
self.__dict__.clear()
def update_port_label(self, *_args):
unknown_label = _("Unknown")
if core.users.public_port:
url = pynicotine.__port_checker_url__ % str(core.users.public_port)
port_status_text = _("Check Port Status")
self.current_port_label.set_markup(_("<b>%(ip)s</b>, port %(port)s") % {
"ip": core.users.public_ip_address or unknown_label,
"port": core.users.public_port or unknown_label
})
self.check_port_status_label.set_markup(f"<a href='{url}' title='{url}'>{port_status_text}</a>")
self.check_port_status_label.set_visible(True)
else:
self.current_port_label.set_text(unknown_label)
self.check_port_status_label.set_visible(False)
def set_settings(self):
# Network interfaces
self.network_interface_combobox.freeze()
self.network_interface_combobox.clear()
self.network_interface_combobox.append("")
for interface in NetworkInterfaces.get_interface_addresses():
self.network_interface_combobox.append(interface)
self.network_interface_combobox.unfreeze()
self.application.preferences.set_widgets_data(self.options)
# Listening port status
self.update_port_label()
# Special options
server_hostname, server_port = config.sections["server"]["server"]
self.soulseek_server_entry.set_text(f"{server_hostname}:{server_port}")
listen_port, _unused_port = config.sections["server"]["portrange"]
self.listen_port_spinner.set_value(listen_port)
self.portmap_required = None
def get_settings(self):
try:
server_address, server_port = self.soulseek_server_entry.get_text().split(":")
server_addr = (server_address.strip(), int(server_port.strip()))
except ValueError:
server_addr = config.defaults["server"]["server"]
listen_port = self.listen_port_spinner.get_value_as_int()
return {
"server": {
"server": server_addr,
"login": self.username_entry.get_text(),
"portrange": (listen_port, listen_port),
"autoaway": self.auto_away_spinner.get_value_as_int(),
"autoreply": self.auto_reply_message_entry.get_text(),
"interface": self.network_interface_combobox.get_text(),
"upnp": self.upnp_toggle.get_active(),
"auto_connect_startup": self.auto_connect_startup_toggle.get_active()
}
}
def on_activate_link(self, _label, url):
open_uri(url)
return True
def on_change_password_response(self, dialog, _response_id, user_status):
password = dialog.get_entry_value()
if user_status != core.users.login_status:
MessageDialog(
parent=self.application.preferences,
title=_("Password Change Rejected"),
message=("Since your login status changed, your password has not been changed. Please try again.")
).present()
return
if not password:
self.on_change_password()
return
if core.users.login_status == UserStatus.OFFLINE:
config.sections["server"]["passw"] = password
config.write_configuration()
return
core.users.request_change_password(password)
def on_change_password(self, *_args):
if core.users.login_status != UserStatus.OFFLINE:
message = _("Enter a new password for your Soulseek account:")
else:
message = (_("You are currently logged out of the Soulseek network. If you want to change "
"the password of an existing Soulseek account, you need to be logged into that account.")
+ "\n\n"
+ _("Enter password to use when logging in:"))
EntryDialog(
parent=self.application.preferences,
title=_("Change Password"),
message=message,
visibility=False,
action_button_label=_("_Change"),
callback=self.on_change_password_response,
callback_data=core.users.login_status
).present()
def on_toggle_upnp(self, *_args):
self.portmap_required = "add" if self.upnp_toggle.get_active() else "remove"
def on_default_server(self, *_args):
server_address, server_port = config.defaults["server"]["server"]
self.soulseek_server_entry.set_text(f"{server_address}:{server_port}")
class DownloadsPage:
def __init__(self, application):
(
self.accept_sent_files_toggle,
self.alt_speed_spinner,
self.autoclear_downloads_toggle,
self.container,
self.download_double_click_label,
self.download_folder_default_button,
self.download_folder_label,
self.enable_filters_toggle,
self.enable_username_subfolders_toggle,
self.file_finished_command_entry,
self.filter_list_container,
self.filter_status_label,
self.folder_finished_command_entry,
self.incomplete_folder_default_button,
self.incomplete_folder_label,
self.received_folder_default_button,
self.received_folder_label,
self.sent_files_permission_container,
self.speed_spinner,
self.use_alt_speed_limit_radio,
self.use_speed_limit_radio,
self.use_unlimited_speed_radio
) = self.widgets = ui.load(scope=self, path="settings/downloads.ui")
self.application = application
self.sent_files_permission_combobox = ComboBox(
container=self.sent_files_permission_container,
items=(
(_("No one"), None),
(_("Everyone"), None),
(_("Buddies"), None),
(_("Trusted buddies"), None)
)
)
self.download_double_click_combobox = ComboBox(
container=self.download_double_click_label.get_parent(), label=self.download_double_click_label,
items=(
(_("Nothing"), None),
(_("Open File"), None),
(_("Open in File Manager"), None),
(_("Search"), None),
(_("Pause"), None),
(_("Remove"), None),
(_("Resume"), None),
(_("Browse Folder"), None)
)
)
self.download_folder_button = FileChooserButton(
self.download_folder_label.get_parent(), window=application.preferences,
label=self.download_folder_label, end_button=self.download_folder_default_button, chooser_type="folder"
)
self.incomplete_folder_button = FileChooserButton(
self.incomplete_folder_label.get_parent(), window=application.preferences,
label=self.incomplete_folder_label, end_button=self.incomplete_folder_default_button, chooser_type="folder"
)
self.received_folder_button = FileChooserButton(
self.received_folder_label.get_parent(), window=application.preferences,
label=self.received_folder_label, end_button=self.received_folder_default_button, chooser_type="folder"
)
self.filter_syntax_description = _("<b>Syntax</b>: Case-insensitive. If enabled, Python regular expressions "
"can be used, otherwise only wildcard * matches "
"are supported.").replace("<b>", "").replace("</b>", "")
self.filter_list_view = TreeView(
application.window, parent=self.filter_list_container, multi_select=True,
activate_row_callback=self.on_edit_filter,
delete_accelerator_callback=self.on_remove_filter,
columns={
"filter": {
"column_type": "text",
"title": _("Filter"),
"width": 150,
"expand_column": True,
"default_sort_type": "ascending"
},
"regex": {
"column_type": "toggle",
"title": _("Regex"),
"width": 0,
"toggle_callback": self.on_toggle_regex
}
}
)
self.options = {
"transfers": {
"autoclear_downloads": self.autoclear_downloads_toggle,
"remotedownloads": self.accept_sent_files_toggle,
"uploadallowed": self.sent_files_permission_combobox,
"incompletedir": self.incomplete_folder_button,
"downloaddir": self.download_folder_button,
"uploaddir": self.received_folder_button,
"enablefilters": self.enable_filters_toggle,
"downloadlimit": self.speed_spinner,
"downloadlimitalt": self.alt_speed_spinner,
"usernamesubfolders": self.enable_username_subfolders_toggle,
"afterfinish": self.file_finished_command_entry,
"afterfolder": self.folder_finished_command_entry,
"download_doubleclick": self.download_double_click_combobox
}
}
def destroy(self):
self.download_folder_button.destroy()
self.incomplete_folder_button.destroy()
self.received_folder_button.destroy()
self.filter_list_view.destroy()
self.__dict__.clear()
def set_settings(self):
self.filter_list_view.clear()
self.application.preferences.set_widgets_data(self.options)
use_speed_limit = config.sections["transfers"]["use_download_speed_limit"]
if use_speed_limit == "primary":
self.use_speed_limit_radio.set_active(True)
elif use_speed_limit == "alternative":
self.use_alt_speed_limit_radio.set_active(True)
else:
self.use_unlimited_speed_radio.set_active(True)
self.filter_list_view.freeze()
for item in config.sections["transfers"]["downloadfilters"]:
if not isinstance(item, list) or len(item) < 2:
continue
dfilter, escaped = item
enable_regex = not escaped
self.filter_list_view.add_row([dfilter, enable_regex], select_row=False)
self.filter_list_view.unfreeze()
def get_settings(self):
if self.use_speed_limit_radio.get_active():
use_speed_limit = "primary"
elif self.use_alt_speed_limit_radio.get_active():
use_speed_limit = "alternative"
else:
use_speed_limit = "unlimited"
download_filters = []
for dfilter, iterator in self.filter_list_view.iterators.items():
enable_regex = self.filter_list_view.get_row_value(iterator, "regex")
download_filters.append([dfilter, not enable_regex])
return {
"transfers": {
"autoclear_downloads": self.autoclear_downloads_toggle.get_active(),
"remotedownloads": self.accept_sent_files_toggle.get_active(),
"uploadallowed": self.sent_files_permission_combobox.get_selected_pos(),
"incompletedir": self.incomplete_folder_button.get_path(),
"downloaddir": self.download_folder_button.get_path(),
"uploaddir": self.received_folder_button.get_path(),
"downloadfilters": download_filters,
"enablefilters": self.enable_filters_toggle.get_active(),
"use_download_speed_limit": use_speed_limit,
"downloadlimit": self.speed_spinner.get_value_as_int(),
"downloadlimitalt": self.alt_speed_spinner.get_value_as_int(),
"usernamesubfolders": self.enable_username_subfolders_toggle.get_active(),
"afterfinish": self.file_finished_command_entry.get_text().strip(),
"afterfolder": self.folder_finished_command_entry.get_text().strip(),
"download_doubleclick": self.download_double_click_combobox.get_selected_pos()
}
}
def on_default_download_folder(self, *_args):
self.download_folder_button.set_path(config.defaults["transfers"]["downloaddir"])
def on_default_incomplete_folder(self, *_args):
self.incomplete_folder_button.set_path(config.defaults["transfers"]["incompletedir"])
def on_default_received_folder(self, *_args):
self.received_folder_button.set_path(config.defaults["transfers"]["uploaddir"])
def on_toggle_regex(self, list_view, iterator):
value = list_view.get_row_value(iterator, "regex")
list_view.set_row_value(iterator, "regex", not value)
self.on_verify_filter()
def on_add_filter_response(self, dialog, _response_id, _data):
dfilter = dialog.get_entry_value()
enable_regex = dialog.get_option_value()
iterator = self.filter_list_view.iterators.get(dfilter)
if iterator is not None:
self.filter_list_view.set_row_value(iterator, "regex", enable_regex)
else:
self.filter_list_view.add_row([dfilter, enable_regex])
self.on_verify_filter()
def on_add_filter(self, *_args):
EntryDialog(
parent=self.application.preferences,
title=_("Add Download Filter"),
message=self.filter_syntax_description + "\n\n" + _("Enter a new download filter:"),
action_button_label=_("_Add"),
callback=self.on_add_filter_response,
option_value=False,
option_label=_("Enable regular expressions"),
droplist=self.filter_list_view.iterators
).present()
def on_edit_filter_response(self, dialog, _response_id, iterator):
new_dfilter = dialog.get_entry_value()
enable_regex = dialog.get_option_value()
dfilter = self.filter_list_view.get_row_value(iterator, "filter")
orig_iterator = self.filter_list_view.iterators[dfilter]
self.filter_list_view.remove_row(orig_iterator)
self.filter_list_view.add_row([new_dfilter, enable_regex])
self.on_verify_filter()
def on_edit_filter(self, *_args):
for iterator in self.filter_list_view.get_selected_rows():
dfilter = self.filter_list_view.get_row_value(iterator, "filter")
enable_regex = self.filter_list_view.get_row_value(iterator, "regex")
EntryDialog(
parent=self.application.preferences,
title=_("Edit Download Filter"),
message=self.filter_syntax_description + "\n\n" + _("Modify the following download filter:"),
action_button_label=_("_Edit"),
callback=self.on_edit_filter_response,
callback_data=iterator,
default=dfilter,
option_value=enable_regex,
option_label=_("Enable regular expressions")
).present()
return
def on_remove_filter(self, *_args):
for iterator in reversed(list(self.filter_list_view.get_selected_rows())):
dfilter = self.filter_list_view.get_row_value(iterator, "filter")
orig_iterator = self.filter_list_view.iterators[dfilter]
self.filter_list_view.remove_row(orig_iterator)
self.on_verify_filter()
def on_default_filters(self, *_args):
self.filter_list_view.clear()
self.filter_list_view.freeze()
for download_filter, escaped in config.defaults["transfers"]["downloadfilters"]:
enable_regex = not escaped
self.filter_list_view.add_row([download_filter, enable_regex], select_row=False)
self.filter_list_view.unfreeze()
self.on_verify_filter()
def on_verify_filter(self, *_args):
failed = {}
outfilter = "(\\\\("
for dfilter, iterator in self.filter_list_view.iterators.items():
dfilter = self.filter_list_view.get_row_value(iterator, "filter")
enable_regex = self.filter_list_view.get_row_value(iterator, "regex")
if not enable_regex:
dfilter = re.escape(dfilter)
dfilter = dfilter.replace("\\*", ".*")
try:
re.compile("(" + dfilter + ")")
outfilter += dfilter
if dfilter != list(self.filter_list_view.iterators)[-1]:
outfilter += "|"
except re.error as error:
failed[dfilter] = error
outfilter += ")$)"
try:
re.compile(outfilter)
except re.error as error:
failed[outfilter] = error
if failed:
errors = ""
for dfilter, error in failed.items():
errors += "Filter: %(filter)s Error: %(error)s " % {
"filter": dfilter,
"error": error
}
error = _("%(num)d Failed! %(error)s " % {
"num": len(failed),
"error": errors}
)
self.filter_status_label.set_text(error)
else:
self.filter_status_label.set_text(_("Filters Successful"))
class SharesPage:
PERMISSION_LEVELS = {
_("Public"): PermissionLevel.PUBLIC,
_("Buddies"): PermissionLevel.BUDDY,
_("Trusted buddies"): PermissionLevel.TRUSTED
}
def __init__(self, application):
(
self.container,
self.rescan_on_startup_toggle,
self.reveal_buddy_shares_toggle,
self.reveal_trusted_shares_toggle,
self.shares_list_container
) = self.widgets = ui.load(scope=self, path="settings/shares.ui")
self.application = application
self.rescan_required = False
self.recompress_shares_required = False
self.last_parent_folder = None
self.shared_folders = []
self.buddy_shared_folders = []
self.trusted_shared_folders = []
self.shares_list_view = TreeView(
application.window, parent=self.shares_list_container, multi_select=True,
activate_row_callback=self.on_edit_shared_folder,
delete_accelerator_callback=self.on_remove_shared_folder,
columns={
"virtual_name": {
"column_type": "text",
"title": _("Virtual Folder"),
"width": 65,
"expand_column": True,
"default_sort_type": "ascending"
},
"folder": {
"column_type": "text",
"title": _("Folder"),
"width": 150,
"expand_column": True
},
"accessible_to": {
"column_type": "text",
"title": _("Accessible To"),
"width": 0
}
}
)
self.options = {
"transfers": {
"rescanonstartup": self.rescan_on_startup_toggle,
"reveal_buddy_shares": self.reveal_buddy_shares_toggle,
"reveal_trusted_shares": self.reveal_trusted_shares_toggle
}
}
def destroy(self):
self.shares_list_view.destroy()
self.__dict__.clear()
def set_settings(self):
self.shares_list_view.clear()
self.shares_list_view.freeze()
self.application.preferences.set_widgets_data(self.options)
self.shared_folders = config.sections["transfers"]["shared"][:]
self.buddy_shared_folders = config.sections["transfers"]["buddyshared"][:]
self.trusted_shared_folders = config.sections["transfers"]["trustedshared"][:]
for virtual_name, folder_path, *_unused in self.shared_folders:
self.shares_list_view.add_row(
[virtual_name, folder_path, _("Public")], select_row=False)
for virtual_name, folder_path, *_unused in self.buddy_shared_folders:
self.shares_list_view.add_row(
[virtual_name, folder_path, _("Buddies")], select_row=False)
for virtual_name, folder_path, *_unused in self.trusted_shared_folders:
self.shares_list_view.add_row(
[virtual_name, folder_path, _("Trusted")], select_row=False)
self.shares_list_view.unfreeze()
self.rescan_required = self.recompress_shares_required = False
def get_settings(self):
return {
"transfers": {
"shared": self.shared_folders[:],
"buddyshared": self.buddy_shared_folders[:],
"trustedshared": self.trusted_shared_folders[:],
"rescanonstartup": self.rescan_on_startup_toggle.get_active(),
"reveal_buddy_shares": self.reveal_buddy_shares_toggle.get_active(),
"reveal_trusted_shares": self.reveal_trusted_shares_toggle.get_active()
}
}
def on_reveal_share_changed(self, *_args):
self.recompress_shares_required = True
def on_add_shared_folder_selected(self, selected, _data):
for folder_path in selected:
virtual_name = core.shares.add_share(
folder_path, share_groups=(self.shared_folders, self.buddy_shared_folders, self.trusted_shared_folders)
)
if not virtual_name:
continue
self.last_parent_folder = os.path.dirname(folder_path)
self.rescan_required = True
self.shares_list_view.add_row([virtual_name, folder_path, _("Public")])
def on_add_shared_folder(self, *_args):
# By default, show parent folder of last added share as initial folder
initial_folder = self.last_parent_folder
# If present, show parent folder of selected share as initial folder
for iterator in self.shares_list_view.get_selected_rows():
initial_folder = os.path.dirname(self.shares_list_view.get_row_value(iterator, "folder"))
break
if initial_folder and not os.path.exists(encode_path(initial_folder)):
initial_folder = None
FolderChooser(
parent=self.application.preferences,
callback=self.on_add_shared_folder_selected,
title=_("Add a Shared Folder"),
initial_folder=initial_folder,
select_multiple=True
).present()
def on_edit_shared_folder_response(self, dialog, _response_id, iterator):
new_virtual_name = dialog.get_entry_value()
new_accessible_to = dialog.get_second_entry_value()
new_accessible_to_short = new_accessible_to.replace(_("Trusted buddies"), _("Trusted"))
virtual_name = self.shares_list_view.get_row_value(iterator, "virtual_name")
accessible_to = self.shares_list_view.get_row_value(iterator, "accessible_to")
if new_virtual_name == virtual_name and new_accessible_to_short == accessible_to:
return
self.rescan_required = True
folder_path = self.shares_list_view.get_row_value(iterator, "folder")
permission_level = self.PERMISSION_LEVELS.get(new_accessible_to)
orig_iterator = self.shares_list_view.iterators[virtual_name]
self.shares_list_view.remove_row(orig_iterator)
core.shares.remove_share(
virtual_name, share_groups=(self.shared_folders, self.buddy_shared_folders, self.trusted_shared_folders)
)
new_virtual_name = core.shares.add_share(
folder_path, permission_level=permission_level, virtual_name=new_virtual_name,
share_groups=(self.shared_folders, self.buddy_shared_folders, self.trusted_shared_folders),
validate_path=False
)
self.shares_list_view.add_row([new_virtual_name, folder_path, new_accessible_to_short])
def on_edit_shared_folder(self, *_args):
for iterator in self.shares_list_view.get_selected_rows():
virtual_name = self.shares_list_view.get_row_value(iterator, "virtual_name")
folder_path = self.shares_list_view.get_row_value(iterator, "folder")
default_item = self.shares_list_view.get_row_value(iterator, "accessible_to")
EntryDialog(
parent=self.application.preferences,
title=_("Edit Shared Folder"),
message=_("Enter new virtual name for '%(dir)s':") % {"dir": folder_path},
default=virtual_name,
second_default=default_item.replace(_("Trusted"), _("Trusted buddies")),
second_droplist=list(self.PERMISSION_LEVELS),
use_second_entry=True,
second_entry_editable=False,
action_button_label=_("_Edit"),
callback=self.on_edit_shared_folder_response,
callback_data=iterator
).present()
return
def on_remove_shared_folder(self, *_args):
iterators = reversed(list(self.shares_list_view.get_selected_rows()))
for iterator in iterators:
virtual_name = self.shares_list_view.get_row_value(iterator, "virtual_name")
orig_iterator = self.shares_list_view.iterators[virtual_name]
core.shares.remove_share(
virtual_name, share_groups=(self.shared_folders, self.buddy_shared_folders, self.trusted_shared_folders)
)
self.shares_list_view.remove_row(orig_iterator)
if iterators:
self.rescan_required = True
class UploadsPage:
def __init__(self, application):
(
self.alt_speed_spinner,
self.autoclear_uploads_toggle,
self.container,
self.limit_total_transfers_radio,
self.max_queued_files_spinner,
self.max_queued_size_spinner,
self.no_buddy_limits_toggle,
self.prioritize_buddies_toggle,
self.speed_spinner,
self.upload_bandwidth_spinner,
self.upload_double_click_label,
self.upload_queue_type_label,
self.upload_slots_spinner,
self.use_alt_speed_limit_radio,
self.use_speed_limit_radio,
self.use_unlimited_speed_radio,
self.use_upload_slots_bandwidth_radio,
self.use_upload_slots_fixed_radio
) = self.widgets = ui.load(scope=self, path="settings/uploads.ui")
self.application = application
self.upload_double_click_combobox = ComboBox(
container=self.upload_double_click_label.get_parent(), label=self.upload_double_click_label,
items=(
(_("Nothing"), None),
(_("Open File"), None),
(_("Open in File Manager"), None),
(_("Search"), None),
(_("Abort"), None),
(_("Remove"), None),
(_("Retry"), None),
(_("Browse Folder"), None)
)
)
self.upload_queue_type_combobox = ComboBox(
container=self.upload_queue_type_label.get_parent(), label=self.upload_queue_type_label,
items=(
(_("Round Robin"), None),
(_("First In, First Out"), None)
)
)
self.options = {
"transfers": {
"autoclear_uploads": self.autoclear_uploads_toggle,
"uploadbandwidth": self.upload_bandwidth_spinner,
"useupslots": self.use_upload_slots_fixed_radio,
"uploadslots": self.upload_slots_spinner,
"uploadlimit": self.speed_spinner,
"uploadlimitalt": self.alt_speed_spinner,
"fifoqueue": self.upload_queue_type_combobox,
"limitby": self.limit_total_transfers_radio,
"queuelimit": self.max_queued_size_spinner,
"filelimit": self.max_queued_files_spinner,
"friendsnolimits": self.no_buddy_limits_toggle,
"preferfriends": self.prioritize_buddies_toggle,
"upload_doubleclick": self.upload_double_click_combobox
}
}
def destroy(self):
self.upload_double_click_combobox.destroy()
self.upload_queue_type_combobox.destroy()
self.__dict__.clear()
def set_settings(self):
self.application.preferences.set_widgets_data(self.options)
use_speed_limit = config.sections["transfers"]["use_upload_speed_limit"]
if use_speed_limit == "primary":
self.use_speed_limit_radio.set_active(True)
elif use_speed_limit == "alternative":
self.use_alt_speed_limit_radio.set_active(True)
else:
self.use_unlimited_speed_radio.set_active(True)
def get_settings(self):
if self.use_speed_limit_radio.get_active():
use_speed_limit = "primary"
elif self.use_alt_speed_limit_radio.get_active():
use_speed_limit = "alternative"
else:
use_speed_limit = "unlimited"
return {
"transfers": {
"autoclear_uploads": self.autoclear_uploads_toggle.get_active(),
"uploadbandwidth": self.upload_bandwidth_spinner.get_value_as_int(),
"useupslots": self.use_upload_slots_fixed_radio.get_active(),
"uploadslots": self.upload_slots_spinner.get_value_as_int(),
"use_upload_speed_limit": use_speed_limit,
"uploadlimit": self.speed_spinner.get_value_as_int(),
"uploadlimitalt": self.alt_speed_spinner.get_value_as_int(),
"fifoqueue": bool(self.upload_queue_type_combobox.get_selected_pos()),
"limitby": self.limit_total_transfers_radio.get_active(),
"queuelimit": self.max_queued_size_spinner.get_value_as_int(),
"filelimit": self.max_queued_files_spinner.get_value_as_int(),
"friendsnolimits": self.no_buddy_limits_toggle.get_active(),
"preferfriends": self.prioritize_buddies_toggle.get_active(),
"upload_doubleclick": self.upload_double_click_combobox.get_selected_pos()
}
}
class UserProfilePage:
def __init__(self, application):
(
self.container,
self.description_view_container,
self.reset_picture_button,
self.select_picture_label
) = self.widgets = ui.load(scope=self, path="settings/userinfo.ui")
self.application = application
self.user_profile_required = False
self.description_view = TextView(self.description_view_container, parse_urls=False)
self.select_picture_button = FileChooserButton(
self.select_picture_label.get_parent(), window=application.preferences, label=self.select_picture_label,
end_button=self.reset_picture_button, chooser_type="image", is_flat=True
)
self.options = {
"userinfo": {
"descr": self.description_view,
"pic": self.select_picture_button
}
}
def destroy(self):
self.description_view.destroy()
self.select_picture_button.destroy()
self.__dict__.clear()
def set_settings(self):
self.description_view.clear()
self.application.preferences.set_widgets_data(self.options)
self.user_profile_required = False
def get_settings(self):
description = repr(self.description_view.get_text())
picture_path = self.select_picture_button.get_path()
if (description != config.sections["userinfo"]["descr"]
or picture_path != config.sections["userinfo"]["pic"]):
self.user_profile_required = True
return {
"userinfo": {
"descr": description,
"pic": picture_path
}
}
def on_reset_picture(self, *_args):
self.select_picture_button.clear()
class IgnoredUsersPage:
def __init__(self, application):
(
self.container,
self.ignored_ips_container,
self.ignored_users_container
) = self.widgets = ui.load(scope=self, path="settings/ignore.ui")
self.application = application
self.added_users = set()
self.added_ips = set()
self.removed_users = set()
self.removed_ips = set()
self.ignored_users = []
self.ignored_users_list_view = TreeView(
application.window, parent=self.ignored_users_container, multi_select=True,
delete_accelerator_callback=self.on_remove_ignored_user,
columns={
"username": {
"column_type": "text",
"title": _("Username"),
"default_sort_type": "ascending"
}
}
)
self.ignored_ips = {}
self.ignored_ips_list_view = TreeView(
application.window, parent=self.ignored_ips_container, multi_select=True,
delete_accelerator_callback=self.on_remove_ignored_ip,
columns={
"ip_address": {
"column_type": "text",
"title": _("IP Address"),
"width": 50,
"expand_column": True
},
"user": {
"column_type": "text",
"title": _("User"),
"expand_column": True,
"default_sort_type": "ascending"
}
}
)
self.options = {
"server": {
"ignorelist": self.ignored_users_list_view,
"ipignorelist": self.ignored_ips_list_view
}
}
def destroy(self):
self.ignored_users_list_view.destroy()
self.ignored_ips_list_view.destroy()
self.__dict__.clear()
def set_settings(self):
self.clear_changes()
self.ignored_users_list_view.clear()
self.ignored_ips_list_view.clear()
self.ignored_users.clear()
self.ignored_ips.clear()
self.application.preferences.set_widgets_data(self.options)
self.ignored_users = config.sections["server"]["ignorelist"][:]
self.ignored_ips = config.sections["server"]["ipignorelist"].copy()
def get_settings(self):
return {
"server": {
"ignorelist": self.ignored_users[:],
"ipignorelist": self.ignored_ips.copy()
}
}
def clear_changes(self):
self.added_users.clear()
self.added_ips.clear()
self.removed_users.clear()
self.removed_ips.clear()
def on_add_ignored_user_response(self, dialog, _response_id, _data):
user = dialog.get_entry_value().strip()
if user and user not in self.ignored_users:
self.ignored_users.append(user)
self.ignored_users_list_view.add_row([str(user)])
self.added_users.add(user)
self.removed_users.discard(user)
def on_add_ignored_user(self, *_args):
EntryDialog(
parent=self.application.preferences,
title=_("Ignore User"),
message=_("Enter the name of the user you want to ignore:"),
action_button_label=_("_Add"),
callback=self.on_add_ignored_user_response
).present()
def on_remove_ignored_user(self, *_args):
for iterator in reversed(list(self.ignored_users_list_view.get_selected_rows())):
user = self.ignored_users_list_view.get_row_value(iterator, "username")
orig_iterator = self.ignored_users_list_view.iterators[user]
self.ignored_users_list_view.remove_row(orig_iterator)
self.ignored_users.remove(user)
if user not in self.added_users:
self.removed_users.add(user)
self.added_users.discard(user)
def on_add_ignored_ip_response(self, dialog, _response_id, _data):
ip_address = dialog.get_entry_value().strip()
if not core.network_filter.is_ip_address(ip_address):
return
if ip_address not in self.ignored_ips:
user = core.network_filter.get_online_username(ip_address) or ""
user_ip_pair = (user, ip_address)
self.ignored_ips[ip_address] = user
self.ignored_ips_list_view.add_row([ip_address, user])
self.added_ips.add(user_ip_pair)
self.removed_ips.discard(user_ip_pair)
def on_add_ignored_ip(self, *_args):
EntryDialog(
parent=self.application.preferences,
title=_("Ignore IP Address"),
message=_("Enter an IP address you want to ignore:") + " " + _("* is a wildcard"),
action_button_label=_("_Add"),
callback=self.on_add_ignored_ip_response
).present()
def on_remove_ignored_ip(self, *_args):
for iterator in reversed(list(self.ignored_ips_list_view.get_selected_rows())):
ip_address = self.ignored_ips_list_view.get_row_value(iterator, "ip_address")
user = self.ignored_ips_list_view.get_row_value(iterator, "user")
user_ip_pair = (user, ip_address)
orig_iterator = self.ignored_ips_list_view.iterators[ip_address]
self.ignored_ips_list_view.remove_row(orig_iterator)
del self.ignored_ips[ip_address]
if user_ip_pair not in self.added_ips:
self.removed_ips.add(user_ip_pair)
self.added_ips.discard(user_ip_pair)
class BannedUsersPage:
def __init__(self, application):
(
self.ban_message_entry,
self.ban_message_toggle,
self.banned_ips_container,
self.banned_users_container,
self.container,
self.geo_block_country_entry,
self.geo_block_message_entry,
self.geo_block_message_toggle,
self.geo_block_toggle
) = self.widgets = ui.load(scope=self, path="settings/ban.ui")
self.application = application
self.added_users = set()
self.added_ips = set()
self.removed_users = set()
self.removed_ips = set()
self.banned_users = []
self.banned_users_list_view = TreeView(
application.window, parent=self.banned_users_container, multi_select=True,
delete_accelerator_callback=self.on_remove_banned_user,
columns={
"username": {
"column_type": "text",
"title": _("Username"),
"default_sort_type": "ascending"
}
}
)
self.banned_ips = {}
self.banned_ips_list_view = TreeView(
application.window, parent=self.banned_ips_container, multi_select=True,
delete_accelerator_callback=self.on_remove_banned_ip,
columns={
"ip_address": {
"column_type": "text",
"title": _("IP Address"),
"width": 50,
"expand_column": True
},
"user": {
"column_type": "text",
"title": _("User"),
"expand_column": True,
"default_sort_type": "ascending"
}
}
)
self.options = {
"server": {
"banlist": self.banned_users_list_view,
"ipblocklist": self.banned_ips_list_view
},
"transfers": {
"usecustomban": self.ban_message_toggle,
"customban": self.ban_message_entry,
"geoblock": self.geo_block_toggle,
"geoblockcc": None,
"usecustomgeoblock": self.geo_block_message_toggle,
"customgeoblock": self.geo_block_message_entry
}
}
def destroy(self):
self.banned_users_list_view.destroy()
self.banned_ips_list_view.destroy()
self.__dict__.clear()
def set_settings(self):
self.clear_changes()
self.banned_users_list_view.clear()
self.banned_ips_list_view.clear()
self.banned_users.clear()
self.banned_ips.clear()
self.application.preferences.set_widgets_data(self.options)
self.banned_users = config.sections["server"]["banlist"][:]
self.banned_ips = config.sections["server"]["ipblocklist"].copy()
self.geo_block_country_entry.set_text(config.sections["transfers"]["geoblockcc"][0])
def get_settings(self):
return {
"server": {
"banlist": self.banned_users[:],
"ipblocklist": self.banned_ips.copy()
},
"transfers": {
"usecustomban": self.ban_message_toggle.get_active(),
"customban": self.ban_message_entry.get_text(),
"geoblock": self.geo_block_toggle.get_active(),
"geoblockcc": [self.geo_block_country_entry.get_text().upper()],
"usecustomgeoblock": self.geo_block_message_toggle.get_active(),
"customgeoblock": self.geo_block_message_entry.get_text()
}
}
def clear_changes(self):
self.added_users.clear()
self.added_ips.clear()
self.removed_users.clear()
self.removed_ips.clear()
def on_add_banned_user_response(self, dialog, _response_id, _data):
user = dialog.get_entry_value().strip()
if user and user not in self.banned_users:
self.banned_users.append(user)
self.banned_users_list_view.add_row([user])
self.added_users.add(user)
self.removed_users.discard(user)
def on_add_banned_user(self, *_args):
EntryDialog(
parent=self.application.preferences,
title=_("Ban User"),
message=_("Enter the name of the user you want to ban:"),
action_button_label=_("_Add"),
callback=self.on_add_banned_user_response
).present()
def on_remove_banned_user(self, *_args):
for iterator in reversed(list(self.banned_users_list_view.get_selected_rows())):
user = self.banned_users_list_view.get_row_value(iterator, "username")
orig_iterator = self.banned_users_list_view.iterators[user]
self.banned_users_list_view.remove_row(orig_iterator)
self.banned_users.remove(user)
if user not in self.added_users:
self.removed_users.add(user)
self.added_users.discard(user)
def on_add_banned_ip_response(self, dialog, _response_id, _data):
ip_address = dialog.get_entry_value().strip()
if not core.network_filter.is_ip_address(ip_address):
return
if ip_address not in self.banned_ips:
user = core.network_filter.get_online_username(ip_address) or ""
user_ip_pair = (user, ip_address)
self.banned_ips[ip_address] = user
self.banned_ips_list_view.add_row([ip_address, user])
self.added_ips.add(user_ip_pair)
self.removed_ips.discard(user_ip_pair)
def on_add_banned_ip(self, *_args):
EntryDialog(
parent=self.application.preferences,
title=_("Ban IP Address"),
message=_("Enter an IP address you want to ban:") + " " + _("* is a wildcard"),
action_button_label=_("_Add"),
callback=self.on_add_banned_ip_response
).present()
def on_remove_banned_ip(self, *_args):
for iterator in reversed(list(self.banned_ips_list_view.get_selected_rows())):
ip_address = self.banned_ips_list_view.get_row_value(iterator, "ip_address")
user = self.banned_ips_list_view.get_row_value(iterator, "user")
user_ip_pair = (user, ip_address)
orig_iterator = self.banned_ips_list_view.iterators[ip_address]
self.banned_ips_list_view.remove_row(orig_iterator)
del self.banned_ips[ip_address]
if user_ip_pair not in self.added_ips:
self.removed_ips.add(user_ip_pair)
self.added_ips.discard(user_ip_pair)
class ChatsPage:
def __init__(self, application):
(
self.auto_replace_words_toggle,
self.censor_list_container,
self.censor_text_patterns_toggle,
self.complete_buddy_names_toggle,
self.complete_commands_toggle,
self.complete_room_names_toggle,
self.complete_room_usernames_toggle,
self.container,
self.enable_completion_dropdown_toggle,
self.enable_ctcp_toggle,
self.enable_spell_checker_toggle,
self.enable_tab_completion_toggle,
self.enable_tts_toggle,
self.format_codes_label,
self.min_chars_dropdown_spinner,
self.private_room_toggle,
self.recent_private_messages_spinner,
self.recent_room_messages_spinner,
self.reopen_private_chats_toggle,
self.replacement_list_container,
self.timestamp_private_chat_entry,
self.timestamp_room_entry,
self.tts_command_label,
self.tts_private_message_entry,
self.tts_room_message_entry,
) = self.widgets = ui.load(scope=self, path="settings/chats.ui")
self.application = application
self.completion_required = False
self.private_room_required = False
format_codes_url = "https://docs.python.org/3/library/datetime.html#format-codes"
format_codes_label = _("Format codes")
self.format_codes_label.set_markup(
f"<a href='{format_codes_url}' title='{format_codes_url}'>{format_codes_label}</a>")
self.format_codes_label.connect("activate-link", self.on_activate_link)
self.tts_command_combobox = ComboBox(
container=self.tts_command_label.get_parent(), label=self.tts_command_label, has_entry=True,
items=(
("flite -t $", None),
("echo $ | festival --tts", None)
)
)
self.censored_patterns = []
self.censor_list_view = TreeView(
application.window, parent=self.censor_list_container, multi_select=True,
activate_row_callback=self.on_edit_censored,
delete_accelerator_callback=self.on_remove_censored,
columns={
"pattern": {
"column_type": "text",
"title": _("Pattern"),
"default_sort_type": "ascending"
}
}
)
self.replacements = {}
self.replacement_list_view = TreeView(
application.window, parent=self.replacement_list_container, multi_select=True,
activate_row_callback=self.on_edit_replacement,
delete_accelerator_callback=self.on_remove_replacement,
columns={
"pattern": {
"column_type": "text",
"title": _("Pattern"),
"width": 100,
"expand_column": True,
"default_sort_type": "ascending"
},
"replacement": {
"column_type": "text",
"title": _("Replacement"),
"expand_column": True
}
}
)
self.options = {
"server": {
"ctcpmsgs": None, # Special case in set_settings
"private_chatrooms": self.private_room_toggle
},
"logging": {
"readroomlines": self.recent_room_messages_spinner,
"readprivatelines": self.recent_private_messages_spinner,
"rooms_timestamp": self.timestamp_room_entry,
"private_timestamp": self.timestamp_private_chat_entry
},
"privatechat": {
"store": self.reopen_private_chats_toggle
},
"words": {
"tab": self.enable_tab_completion_toggle,
"dropdown": self.enable_completion_dropdown_toggle,
"characters": self.min_chars_dropdown_spinner,
"roomnames": self.complete_room_names_toggle,
"buddies": self.complete_buddy_names_toggle,
"roomusers": self.complete_room_usernames_toggle,
"commands": self.complete_commands_toggle,
"censored": self.censor_list_view,
"censorwords": self.censor_text_patterns_toggle,
"autoreplaced": self.replacement_list_view,
"replacewords": self.auto_replace_words_toggle
},
"ui": {
"spellcheck": self.enable_spell_checker_toggle,
"speechenabled": self.enable_tts_toggle,
"speechcommand": self.tts_command_combobox,
"speechrooms": self.tts_room_message_entry,
"speechprivate": self.tts_private_message_entry
}
}
def destroy(self):
self.tts_command_combobox.destroy()
self.censor_list_view.destroy()
self.replacement_list_view.destroy()
self.__dict__.clear()
def set_settings(self):
self.censor_list_view.clear()
self.replacement_list_view.clear()
self.censored_patterns.clear()
self.replacements.clear()
self.application.preferences.set_widgets_data(self.options)
self.enable_spell_checker_toggle.get_parent().set_visible(SpellChecker.is_available())
self.enable_ctcp_toggle.set_active(not config.sections["server"]["ctcpmsgs"])
self.censored_patterns = config.sections["words"]["censored"][:]
self.replacements = config.sections["words"]["autoreplaced"].copy()
self.completion_required = False
self.private_room_required = False
def get_settings(self):
return {
"server": {
"ctcpmsgs": not self.enable_ctcp_toggle.get_active(),
"private_chatrooms": self.private_room_toggle.get_active()
},
"logging": {
"readroomlines": self.recent_room_messages_spinner.get_value_as_int(),
"readprivatelines": self.recent_private_messages_spinner.get_value_as_int(),
"private_timestamp": self.timestamp_private_chat_entry.get_text(),
"rooms_timestamp": self.timestamp_room_entry.get_text()
},
"privatechat": {
"store": self.reopen_private_chats_toggle.get_active()
},
"words": {
"tab": self.enable_tab_completion_toggle.get_active(),
"dropdown": self.enable_completion_dropdown_toggle.get_active(),
"characters": self.min_chars_dropdown_spinner.get_value_as_int(),
"roomnames": self.complete_room_names_toggle.get_active(),
"buddies": self.complete_buddy_names_toggle.get_active(),
"roomusers": self.complete_room_usernames_toggle.get_active(),
"commands": self.complete_commands_toggle.get_active(),
"censored": self.censored_patterns[:],
"censorwords": self.censor_text_patterns_toggle.get_active(),
"autoreplaced": self.replacements.copy(),
"replacewords": self.auto_replace_words_toggle.get_active()
},
"ui": {
"spellcheck": self.enable_spell_checker_toggle.get_active(),
"speechenabled": self.enable_tts_toggle.get_active(),
"speechcommand": self.tts_command_combobox.get_text().strip(),
"speechrooms": self.tts_room_message_entry.get_text(),
"speechprivate": self.tts_private_message_entry.get_text()
}
}
def on_activate_link(self, _label, url):
open_uri(url)
return True
def on_private_room_changed(self, *_args):
self.private_room_required = True
def on_completion_changed(self, *_args):
self.completion_required = True
def on_default_tts_private_message(self, *_args):
self.tts_private_message_entry.set_text(config.defaults["ui"]["speechprivate"])
def on_default_tts_room_message(self, *_args):
self.tts_room_message_entry.set_text(config.defaults["ui"]["speechrooms"])
def on_default_timestamp_room(self, *_args):
self.timestamp_room_entry.set_text(config.defaults["logging"]["rooms_timestamp"])
def on_default_timestamp_private_chat(self, *_args):
self.timestamp_private_chat_entry.set_text(config.defaults["logging"]["private_timestamp"])
def on_add_censored_response(self, dialog, _response_id, _data):
pattern = dialog.get_entry_value()
if pattern and pattern not in self.censored_patterns:
self.censored_patterns.append(pattern)
self.censor_list_view.add_row([pattern])
def on_add_censored(self, *_args):
EntryDialog(
parent=self.application.preferences,
title=_("Censor Pattern"),
message=_("Enter a pattern you want to censor. Add spaces around the pattern if you don't "
"want to match strings inside words (may fail at the beginning and end of lines)."),
action_button_label=_("_Add"),
callback=self.on_add_censored_response
).present()
def on_edit_censored_response(self, dialog, _response_id, iterator):
pattern = dialog.get_entry_value()
if not pattern:
return
old_pattern = self.censor_list_view.get_row_value(iterator, "pattern")
orig_iterator = self.censor_list_view.iterators[old_pattern]
self.censor_list_view.remove_row(orig_iterator)
self.censored_patterns.remove(old_pattern)
self.censor_list_view.add_row([pattern])
self.censored_patterns.append(pattern)
def on_edit_censored(self, *_args):
for iterator in self.censor_list_view.get_selected_rows():
pattern = self.censor_list_view.get_row_value(iterator, "pattern")
EntryDialog(
parent=self.application.preferences,
title=_("Edit Censored Pattern"),
message=_("Enter a pattern you want to censor. Add spaces around the pattern if you don't "
"want to match strings inside words (may fail at the beginning and end of lines)."),
action_button_label=_("_Edit"),
callback=self.on_edit_censored_response,
callback_data=iterator,
default=pattern
).present()
return
def on_remove_censored(self, *_args):
for iterator in reversed(list(self.censor_list_view.get_selected_rows())):
censor = self.censor_list_view.get_row_value(iterator, "pattern")
orig_iterator = self.censor_list_view.iterators[censor]
self.censor_list_view.remove_row(orig_iterator)
self.censored_patterns.remove(censor)
def on_add_replacement_response(self, dialog, _response_id, _data):
pattern = dialog.get_entry_value()
replacement = dialog.get_second_entry_value()
if not pattern or not replacement:
return
self.replacements[pattern] = replacement
self.replacement_list_view.add_row([pattern, replacement])
def on_add_replacement(self, *_args):
EntryDialog(
parent=self.application.preferences,
title=_("Add Replacement"),
message=_("Enter a text pattern and what to replace it with:"),
action_button_label=_("_Add"),
callback=self.on_add_replacement_response,
use_second_entry=True
).present()
def on_edit_replacement_response(self, dialog, _response_id, iterator):
pattern = dialog.get_entry_value()
replacement = dialog.get_second_entry_value()
if not pattern or not replacement:
return
old_pattern = self.replacement_list_view.get_row_value(iterator, "pattern")
orig_iterator = self.replacement_list_view.iterators[old_pattern]
self.replacement_list_view.remove_row(orig_iterator)
del self.replacements[old_pattern]
self.replacements[pattern] = replacement
self.replacement_list_view.add_row([pattern, replacement])
def on_edit_replacement(self, *_args):
for iterator in self.replacement_list_view.get_selected_rows():
pattern = self.replacement_list_view.get_row_value(iterator, "pattern")
replacement = self.replacement_list_view.get_row_value(iterator, "replacement")
EntryDialog(
parent=self.application.preferences,
title=_("Edit Replacement"),
message=_("Enter a text pattern and what to replace it with:"),
action_button_label=_("_Edit"),
callback=self.on_edit_replacement_response,
callback_data=iterator,
use_second_entry=True,
default=pattern,
second_default=replacement
).present()
return
def on_remove_replacement(self, *_args):
for iterator in reversed(list(self.replacement_list_view.get_selected_rows())):
replacement = self.replacement_list_view.get_row_value(iterator, "pattern")
orig_iterator = self.replacement_list_view.iterators[replacement]
self.replacement_list_view.remove_row(orig_iterator)
del self.replacements[replacement]
class UserInterfacePage:
def __init__(self, application):
(
self.buddy_list_position_label,
self.chat_colored_usernames_toggle,
self.chat_username_appearance_label,
self.close_action_label,
self.color_chat_action_button,
self.color_chat_action_entry,
self.color_chat_command_button,
self.color_chat_command_entry,
self.color_chat_highlighted_button,
self.color_chat_highlighted_entry,
self.color_chat_local_button,
self.color_chat_local_entry,
self.color_chat_remote_button,
self.color_chat_remote_entry,
self.color_input_background_button,
self.color_input_background_entry,
self.color_input_text_button,
self.color_input_text_entry,
self.color_list_text_button,
self.color_list_text_entry,
self.color_status_away_button,
self.color_status_away_entry,
self.color_status_offline_button,
self.color_status_offline_entry,
self.color_status_online_button,
self.color_status_online_entry,
self.color_tab_button,
self.color_tab_changed_button,
self.color_tab_changed_entry,
self.color_tab_entry,
self.color_tab_highlighted_button,
self.color_tab_highlighted_entry,
self.color_url_button,
self.color_url_entry,
self.container,
self.dark_mode_toggle,
self.exact_file_sizes_toggle,
self.font_browse_button,
self.font_browse_clear_button,
self.font_chat_button,
self.font_chat_clear_button,
self.font_global_button,
self.font_global_clear_button,
self.font_list_button,
self.font_list_clear_button,
self.font_search_button,
self.font_search_clear_button,
self.font_text_view_button,
self.font_text_view_clear_button,
self.font_transfers_button,
self.font_transfers_clear_button,
self.header_bar_toggle,
self.icon_theme_clear_button,
self.icon_theme_label,
self.icon_view,
self.language_label,
self.minimize_tray_startup_toggle,
self.notification_chatroom_mention_toggle,
self.notification_chatroom_toggle,
self.notification_download_file_toggle,
self.notification_download_folder_toggle,
self.notification_private_message_toggle,
self.notification_sounds_toggle,
self.notification_window_title_toggle,
self.notification_wish_toggle,
self.reverse_file_paths_toggle,
self.tab_close_buttons_toggle,
self.tab_position_browse_label,
self.tab_position_chatrooms_label,
self.tab_position_main_label,
self.tab_position_private_chat_label,
self.tab_position_search_label,
self.tab_position_userinfo_label,
self.tab_restore_startup_toggle,
self.tab_visible_browse_toggle,
self.tab_visible_chatrooms_toggle,
self.tab_visible_downloads_toggle,
self.tab_visible_interests_toggle,
self.tab_visible_private_chat_toggle,
self.tab_visible_search_toggle,
self.tab_visible_uploads_toggle,
self.tab_visible_userinfo_toggle,
self.tab_visible_userlist_toggle,
self.tray_icon_toggle,
self.tray_options_container
) = self.widgets = ui.load(scope=self, path="settings/userinterface.ui")
self.application = application
self.editing_color = False
languages = [(_("System default"), "")]
languages += [
(language_name, language_code) for language_code, language_name in sorted(LANGUAGES, key=itemgetter(1))
]
self.language_combobox = ComboBox(
container=self.language_label.get_parent(), label=self.language_label,
items=languages
)
self.close_action_combobox = ComboBox(
container=self.close_action_label.get_parent(), label=self.close_action_label,
items=(
(_("Quit Nicotine+"), None),
(_("Show confirmation dialog"), None),
(_("Run in the background"), None)
)
)
self.chat_username_appearance_combobox = ComboBox(
container=self.chat_username_appearance_label.get_parent(),
label=self.chat_username_appearance_label,
items=(
(_("bold"), "bold"),
(_("italic"), "italic"),
(_("underline"), "underline"),
(_("normal"), "normal")
)
)
self.buddy_list_position_combobox = ComboBox(
container=self.buddy_list_position_label.get_parent(), label=self.buddy_list_position_label,
item_selected_callback=self.on_select_buddy_list_position,
items=(
(_("Separate Buddies tab"), "tab"),
(_("Sidebar in Chat Rooms tab"), "chatrooms"),
(_("Always visible sidebar"), "always")
)
)
position_items = (
(_("Top"), "Top"),
(_("Bottom"), "Bottom"),
(_("Left"), "Left"),
(_("Right"), "Right")
)
self.tab_position_main_combobox = ComboBox(
container=self.tab_position_main_label.get_parent(), label=self.tab_position_main_label,
items=position_items)
self.tab_position_search_combobox = ComboBox(
container=self.tab_position_search_label.get_parent(), label=self.tab_position_search_label,
items=position_items)
self.tab_position_browse_combobox = ComboBox(
container=self.tab_position_browse_label.get_parent(), label=self.tab_position_browse_label,
items=position_items)
self.tab_position_private_chat_combobox = ComboBox(
container=self.tab_position_private_chat_label.get_parent(), label=self.tab_position_private_chat_label,
items=position_items)
self.tab_position_userinfo_combobox = ComboBox(
container=self.tab_position_userinfo_label.get_parent(), label=self.tab_position_userinfo_label,
items=position_items)
self.tab_position_chatrooms_combobox = ComboBox(
container=self.tab_position_chatrooms_label.get_parent(), label=self.tab_position_chatrooms_label,
items=position_items)
self.color_buttons = {
"chatlocal": self.color_chat_local_button,
"chatremote": self.color_chat_remote_button,
"chatcommand": self.color_chat_command_button,
"chatme": self.color_chat_action_button,
"chathilite": self.color_chat_highlighted_button,
"textbg": self.color_input_background_button,
"inputcolor": self.color_input_text_button,
"search": self.color_list_text_button,
"useraway": self.color_status_away_button,
"useronline": self.color_status_online_button,
"useroffline": self.color_status_offline_button,
"urlcolor": self.color_url_button,
"tab_default": self.color_tab_button,
"tab_hilite": self.color_tab_highlighted_button,
"tab_changed": self.color_tab_changed_button
}
self.color_entries = {
"chatlocal": self.color_chat_local_entry,
"chatremote": self.color_chat_remote_entry,
"chatcommand": self.color_chat_command_entry,
"chatme": self.color_chat_action_entry,
"chathilite": self.color_chat_highlighted_entry,
"textbg": self.color_input_background_entry,
"inputcolor": self.color_input_text_entry,
"search": self.color_list_text_entry,
"useraway": self.color_status_away_entry,
"useronline": self.color_status_online_entry,
"useroffline": self.color_status_offline_entry,
"urlcolor": self.color_url_entry,
"tab_default": self.color_tab_entry,
"tab_hilite": self.color_tab_highlighted_entry,
"tab_changed": self.color_tab_changed_entry
}
self.font_buttons = {
"globalfont": self.font_global_button,
"listfont": self.font_list_button,
"textviewfont": self.font_text_view_button,
"chatfont": self.font_chat_button,
"searchfont": self.font_search_button,
"transfersfont": self.font_transfers_button,
"browserfont": self.font_browse_button
}
self.font_clear_buttons = {
"globalfont": self.font_global_clear_button,
"listfont": self.font_list_clear_button,
"textviewfont": self.font_text_view_clear_button,
"chatfont": self.font_chat_clear_button,
"searchfont": self.font_search_clear_button,
"transfersfont": self.font_transfers_clear_button,
"browserfont": self.font_browse_clear_button
}
self.tab_position_comboboxes = {
"tabmain": self.tab_position_main_combobox,
"tabrooms": self.tab_position_chatrooms_combobox,
"tabprivate": self.tab_position_private_chat_combobox,
"tabsearch": self.tab_position_search_combobox,
"tabinfo": self.tab_position_userinfo_combobox,
"tabbrowse": self.tab_position_browse_combobox
}
self.tab_visible_toggles = {
"search": self.tab_visible_search_toggle,
"downloads": self.tab_visible_downloads_toggle,
"uploads": self.tab_visible_uploads_toggle,
"userbrowse": self.tab_visible_browse_toggle,
"userinfo": self.tab_visible_userinfo_toggle,
"private": self.tab_visible_private_chat_toggle,
"userlist": self.tab_visible_userlist_toggle,
"chatrooms": self.tab_visible_chatrooms_toggle,
"interests": self.tab_visible_interests_toggle
}
rgba = Gdk.RGBA()
rgba.red = rgba.green = rgba.blue = rgba.alpha = 0
for color_id, button in self.color_buttons.items():
button.set_rgba(rgba)
button.connect("notify::rgba", self.on_color_button_changed, color_id)
for color_id, entry in self.color_entries.items():
entry.connect("icon-press", self.on_default_color, color_id)
entry.connect("changed", self.on_color_entry_changed, color_id)
for font_id, button in self.font_clear_buttons.items():
button.connect("clicked", self.on_clear_font, font_id)
if (GTK_API_VERSION, GTK_MINOR_VERSION) >= (4, 10):
color_dialog = Gtk.ColorDialog()
font_dialog = Gtk.FontDialog()
for button in self.color_buttons.values():
button.set_dialog(color_dialog)
for button in self.font_buttons.values():
button.set_dialog(font_dialog)
button.set_level(Gtk.FontLevel.FONT)
else:
for button in self.color_buttons.values():
button.set_use_alpha(True)
icon_list = [
(USER_STATUS_ICON_NAMES[UserStatus.ONLINE], _("Online"), 16, ("colored-icon", "user-status")),
(USER_STATUS_ICON_NAMES[UserStatus.AWAY], _("Away"), 16, ("colored-icon", "user-status")),
(USER_STATUS_ICON_NAMES[UserStatus.OFFLINE], _("Offline"), 16,
("colored-icon", "user-status")),
("nplus-tab-changed", _("Tab Changed"), 16, ("colored-icon", "notebook-tab-changed")),
("nplus-tab-highlight", _("Tab Highlight"), 16, ("colored-icon", "notebook-tab-highlight")),
(pynicotine.__application_id__, _("Window"), 64, ())]
if application.tray_icon.available:
icon_list += [
(f"{pynicotine.__application_id__}-connect", _("Online (Tray)"), 16, ()),
(f"{pynicotine.__application_id__}-away", _("Away (Tray)"), 16, ()),
(f"{pynicotine.__application_id__}-disconnect", _("Offline (Tray)"), 16, ()),
(f"{pynicotine.__application_id__}-msg", _("Message (Tray)"), 16, ())]
for icon_name, label, pixel_size, css_classes in icon_list:
box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, valign=Gtk.Align.CENTER, spacing=6, visible=True)
icon = Gtk.Image(icon_name=icon_name, pixel_size=pixel_size, visible=True)
label = Gtk.Label(label=label, xalign=0.5, wrap=True, visible=True)
for css_class in css_classes:
add_css_class(icon, css_class)
if GTK_API_VERSION >= 4:
box.append(icon) # pylint: disable=no-member
box.append(label) # pylint: disable=no-member
else:
box.add(icon) # pylint: disable=no-member
box.add(label) # pylint: disable=no-member
self.icon_view.insert(box, -1)
self.icon_theme_button = FileChooserButton(
self.icon_theme_label.get_parent(), window=application.preferences,
label=self.icon_theme_label, end_button=self.icon_theme_clear_button, chooser_type="folder"
)
self.options = {
"notifications": {
"notification_window_title": self.notification_window_title_toggle,
"notification_popup_sound": self.notification_sounds_toggle,
"notification_popup_file": self.notification_download_file_toggle,
"notification_popup_folder": self.notification_download_folder_toggle,
"notification_popup_private_message": self.notification_private_message_toggle,
"notification_popup_chatroom": self.notification_chatroom_toggle,
"notification_popup_chatroom_mention": self.notification_chatroom_mention_toggle,
"notification_popup_wish": self.notification_wish_toggle
},
"ui": {
"dark_mode": self.dark_mode_toggle,
"exitdialog": self.close_action_combobox,
"trayicon": self.tray_icon_toggle,
"startup_hidden": self.minimize_tray_startup_toggle,
"language": self.language_combobox,
"reverse_file_paths": self.reverse_file_paths_toggle,
"file_size_unit": self.exact_file_sizes_toggle,
"tab_select_previous": self.tab_restore_startup_toggle,
"tabclosers": self.tab_close_buttons_toggle,
"icontheme": self.icon_theme_button,
"chatlocal": self.color_chat_local_entry,
"chatremote": self.color_chat_remote_entry,
"chatcommand": self.color_chat_command_entry,
"chatme": self.color_chat_action_entry,
"chathilite": self.color_chat_highlighted_entry,
"textbg": self.color_input_background_entry,
"inputcolor": self.color_input_text_entry,
"search": self.color_list_text_entry,
"useraway": self.color_status_away_entry,
"useronline": self.color_status_online_entry,
"useroffline": self.color_status_offline_entry,
"urlcolor": self.color_url_entry,
"tab_default": self.color_tab_entry,
"tab_hilite": self.color_tab_highlighted_entry,
"tab_changed": self.color_tab_changed_entry,
"usernamestyle": self.chat_username_appearance_combobox,
"usernamehotspots": self.chat_colored_usernames_toggle,
"buddylistinchatrooms": self.buddy_list_position_combobox,
"header_bar": self.header_bar_toggle
}
}
for dictionary in (
self.font_buttons,
self.tab_position_comboboxes
):
self.options["ui"].update(dictionary)
def destroy(self):
self.language_combobox.destroy()
self.close_action_combobox.destroy()
self.chat_username_appearance_combobox.destroy()
self.buddy_list_position_combobox.destroy()
self.icon_theme_button.destroy()
for combobox in self.tab_position_comboboxes.values():
combobox.destroy()
self.__dict__.clear()
def set_settings(self):
self.application.preferences.set_widgets_data(self.options)
self.tray_options_container.set_visible(self.application.tray_icon.available)
for page_id, enabled in config.sections["ui"]["modes_visible"].items():
widget = self.tab_visible_toggles.get(page_id)
if widget is not None:
widget.set_active(enabled)
def get_settings(self):
enabled_tabs = {}
for page_id, widget in self.tab_visible_toggles.items():
enabled_tabs[page_id] = widget.get_active()
return {
"notifications": {
"notification_window_title": self.notification_window_title_toggle.get_active(),
"notification_popup_sound": self.notification_sounds_toggle.get_active(),
"notification_popup_file": self.notification_download_file_toggle.get_active(),
"notification_popup_folder": self.notification_download_folder_toggle.get_active(),
"notification_popup_private_message": self.notification_private_message_toggle.get_active(),
"notification_popup_chatroom": self.notification_chatroom_toggle.get_active(),
"notification_popup_chatroom_mention": self.notification_chatroom_mention_toggle.get_active(),
"notification_popup_wish": self.notification_wish_toggle.get_active()
},
"ui": {
"dark_mode": self.dark_mode_toggle.get_active(),
"exitdialog": self.close_action_combobox.get_selected_pos(),
"trayicon": self.tray_icon_toggle.get_active(),
"startup_hidden": self.minimize_tray_startup_toggle.get_active(),
"language": self.language_combobox.get_selected_id(),
"globalfont": self.get_font(self.font_global_button),
"listfont": self.get_font(self.font_list_button),
"textviewfont": self.get_font(self.font_text_view_button),
"chatfont": self.get_font(self.font_chat_button),
"searchfont": self.get_font(self.font_search_button),
"transfersfont": self.get_font(self.font_transfers_button),
"browserfont": self.get_font(self.font_browse_button),
"reverse_file_paths": self.reverse_file_paths_toggle.get_active(),
"file_size_unit": "B" if self.exact_file_sizes_toggle.get_active() else "",
"tabmain": self.tab_position_main_combobox.get_selected_id(),
"tabrooms": self.tab_position_chatrooms_combobox.get_selected_id(),
"tabprivate": self.tab_position_private_chat_combobox.get_selected_id(),
"tabsearch": self.tab_position_search_combobox.get_selected_id(),
"tabinfo": self.tab_position_userinfo_combobox.get_selected_id(),
"tabbrowse": self.tab_position_browse_combobox.get_selected_id(),
"modes_visible": enabled_tabs,
"tab_select_previous": self.tab_restore_startup_toggle.get_active(),
"tabclosers": self.tab_close_buttons_toggle.get_active(),
"icontheme": self.icon_theme_button.get_path(),
"chatlocal": self.color_chat_local_entry.get_text().strip(),
"chatremote": self.color_chat_remote_entry.get_text().strip(),
"chatcommand": self.color_chat_command_entry.get_text().strip(),
"chatme": self.color_chat_action_entry.get_text().strip(),
"chathilite": self.color_chat_highlighted_entry.get_text().strip(),
"urlcolor": self.color_url_entry.get_text().strip(),
"textbg": self.color_input_background_entry.get_text().strip(),
"inputcolor": self.color_input_text_entry.get_text().strip(),
"search": self.color_list_text_entry.get_text().strip(),
"useraway": self.color_status_away_entry.get_text().strip(),
"useronline": self.color_status_online_entry.get_text().strip(),
"useroffline": self.color_status_offline_entry.get_text().strip(),
"tab_hilite": self.color_tab_highlighted_entry.get_text().strip(),
"tab_default": self.color_tab_entry.get_text().strip(),
"tab_changed": self.color_tab_changed_entry.get_text().strip(),
"usernamestyle": self.chat_username_appearance_combobox.get_selected_id(),
"usernamehotspots": self.chat_colored_usernames_toggle.get_active(),
"buddylistinchatrooms": self.buddy_list_position_combobox.get_selected_id(),
"header_bar": self.header_bar_toggle.get_active()
}
}
# Icons #
def on_clear_icon_theme(self, *_args):
self.icon_theme_button.clear()
# Fonts #
def get_font(self, button):
if GTK_API_VERSION >= 4:
font_desc = button.get_font_desc()
return font_desc.to_string() if font_desc.get_family() else ""
return button.get_font()
def on_clear_font(self, _button, font_id):
font_button = self.font_buttons[font_id]
if GTK_API_VERSION >= 4:
font_button.set_font_desc(Pango.FontDescription())
else:
font_button.set_font("")
# Colors #
def on_color_entry_changed(self, entry, color_id):
self.editing_color = True
rgba = Gdk.RGBA()
color_hex = entry.get_text().strip()
if color_hex:
rgba.parse(color_hex)
else:
rgba.red = rgba.green = rgba.blue = rgba.alpha = 0
color_button = self.color_buttons[color_id]
color_button.set_rgba(rgba)
self.editing_color = False
def on_color_button_changed(self, button, _param, color_id):
if self.editing_color:
return
rgba = button.get_rgba()
if rgba.alpha <= 0:
# Unset color if transparent
color_hex = ""
else:
red_color = round(rgba.red * 255)
green_color = round(rgba.green * 255)
blue_color = round(rgba.blue * 255)
color_hex = f"#{red_color:02X}{green_color:02X}{blue_color:02X}"
if rgba.alpha < 1 and GTK_API_VERSION >= 4:
alpha_value = round(rgba.alpha * 255)
color_hex += f"{alpha_value:02X}"
entry = self.color_entries[color_id]
if entry.get_text() != color_hex:
entry.set_text(color_hex)
def on_default_color(self, entry, *args):
if GTK_API_VERSION >= 4:
_icon_pos, color_id = args
else:
_icon_pos, _event, color_id = args
entry.set_text(config.defaults["ui"][color_id])
# Tabs #
def on_select_buddy_list_position(self, _combobox, selected_id):
buddies_tab_active = (selected_id == "tab")
self.tab_visible_userlist_toggle.set_active(buddies_tab_active)
self.tab_visible_userlist_toggle.set_sensitive(buddies_tab_active)
class LoggingPage:
def __init__(self, application):
(
self.chatroom_log_folder_default_button,
self.chatroom_log_folder_label,
self.container,
self.debug_log_folder_default_button,
self.debug_log_folder_label,
self.format_codes_label,
self.log_chatroom_toggle,
self.log_debug_toggle,
self.log_private_chat_toggle,
self.log_timestamp_format_entry,
self.log_transfer_toggle,
self.private_chat_log_folder_default_button,
self.private_chat_log_folder_label,
self.transfer_log_folder_default_button,
self.transfer_log_folder_label
) = self.widgets = ui.load(scope=self, path="settings/log.ui")
self.application = application
format_codes_url = "https://docs.python.org/3/library/datetime.html#format-codes"
format_codes_label = _("Format codes")
self.format_codes_label.set_markup(
f"<a href='{format_codes_url}' title='{format_codes_url}'>{format_codes_label}</a>")
self.format_codes_label.connect("activate-link", self.on_activate_link)
self.private_chat_log_folder_button = FileChooserButton(
self.private_chat_log_folder_label.get_parent(), window=application.preferences,
label=self.private_chat_log_folder_label, end_button=self.private_chat_log_folder_default_button,
chooser_type="folder"
)
self.chatroom_log_folder_button = FileChooserButton(
self.chatroom_log_folder_label.get_parent(), window=application.preferences,
label=self.chatroom_log_folder_label, end_button=self.chatroom_log_folder_default_button,
chooser_type="folder"
)
self.transfer_log_folder_button = FileChooserButton(
self.transfer_log_folder_label.get_parent(), window=application.preferences,
label=self.transfer_log_folder_label, end_button=self.transfer_log_folder_default_button,
chooser_type="folder"
)
self.debug_log_folder_button = FileChooserButton(
self.debug_log_folder_label.get_parent(), window=application.preferences,
label=self.debug_log_folder_label, end_button=self.debug_log_folder_default_button,
chooser_type="folder"
)
self.options = {
"logging": {
"privatechat": self.log_private_chat_toggle,
"privatelogsdir": self.private_chat_log_folder_button,
"chatrooms": self.log_chatroom_toggle,
"roomlogsdir": self.chatroom_log_folder_button,
"transfers": self.log_transfer_toggle,
"transferslogsdir": self.transfer_log_folder_button,
"debug_file_output": self.log_debug_toggle,
"debuglogsdir": self.debug_log_folder_button,
"log_timestamp": self.log_timestamp_format_entry
}
}
def destroy(self):
self.private_chat_log_folder_button.destroy()
self.chatroom_log_folder_button.destroy()
self.transfer_log_folder_button.destroy()
self.debug_log_folder_button.destroy()
self.__dict__.clear()
def set_settings(self):
self.application.preferences.set_widgets_data(self.options)
def get_settings(self):
return {
"logging": {
"privatechat": self.log_private_chat_toggle.get_active(),
"privatelogsdir": self.private_chat_log_folder_button.get_path(),
"chatrooms": self.log_chatroom_toggle.get_active(),
"roomlogsdir": self.chatroom_log_folder_button.get_path(),
"transfers": self.log_transfer_toggle.get_active(),
"transferslogsdir": self.transfer_log_folder_button.get_path(),
"debug_file_output": self.log_debug_toggle.get_active(),
"debuglogsdir": self.debug_log_folder_button.get_path(),
"log_timestamp": self.log_timestamp_format_entry.get_text()
}
}
def on_activate_link(self, _label, url):
open_uri(url)
return True
def on_default_timestamp(self, *_args):
self.log_timestamp_format_entry.set_text(config.defaults["logging"]["log_timestamp"])
def on_default_private_chat_log_folder(self, *_args):
self.private_chat_log_folder_button.set_path(config.defaults["logging"]["privatelogsdir"])
def on_default_chatroom_log_folder(self, *_args):
self.chatroom_log_folder_button.set_path(config.defaults["logging"]["roomlogsdir"])
def on_default_transfer_log_folder(self, *_args):
self.transfer_log_folder_button.set_path(config.defaults["logging"]["transferslogsdir"])
def on_default_debug_log_folder(self, *_args):
self.debug_log_folder_button.set_path(config.defaults["logging"]["debuglogsdir"])
class SearchesPage:
def __init__(self, application):
(
self.clear_filter_history_icon,
self.clear_filter_history_success_icon,
self.clear_search_history_icon,
self.clear_search_history_success_icon,
self.container,
self.enable_default_filters_toggle,
self.enable_search_history_toggle,
self.filter_bitrate_entry,
self.filter_country_entry,
self.filter_exclude_entry,
self.filter_file_size_entry,
self.filter_file_type_entry,
self.filter_free_slot_toggle,
self.filter_help_button,
self.filter_include_entry,
self.filter_length_entry,
self.max_displayed_results_spinner,
self.max_sent_results_spinner,
self.min_search_term_length_spinner,
self.repond_search_requests_toggle,
self.show_private_results_toggle
) = self.widgets = ui.load(scope=self, path="settings/search.ui")
self.application = application
self.search_required = False
self.filter_help = SearchFilterHelp(application.preferences)
self.filter_help.set_menu_button(self.filter_help_button)
self.options = {
"searches": {
"maxresults": self.max_sent_results_spinner,
"enablefilters": self.enable_default_filters_toggle,
"defilter": None,
"search_results": self.repond_search_requests_toggle,
"max_displayed_results": self.max_displayed_results_spinner,
"min_search_chars": self.min_search_term_length_spinner,
"enable_history": self.enable_search_history_toggle,
"private_search_results": self.show_private_results_toggle
}
}
def destroy(self):
self.filter_help.destroy()
self.__dict__.clear()
def set_settings(self):
searches = config.sections["searches"]
self.application.preferences.set_widgets_data(self.options)
self.search_required = False
if searches["defilter"] is not None:
num_filters = len(searches["defilter"])
if num_filters > 0:
self.filter_include_entry.set_text(str(searches["defilter"][0]))
if num_filters > 1:
self.filter_exclude_entry.set_text(str(searches["defilter"][1]))
if num_filters > 2:
self.filter_file_size_entry.set_text(str(searches["defilter"][2]))
if num_filters > 3:
self.filter_bitrate_entry.set_text(str(searches["defilter"][3]))
if num_filters > 4:
self.filter_free_slot_toggle.set_active(searches["defilter"][4])
if num_filters > 5:
self.filter_country_entry.set_text(str(searches["defilter"][5]))
if num_filters > 6:
self.filter_file_type_entry.set_text(str(searches["defilter"][6]))
if num_filters > 7:
self.filter_length_entry.set_text(str(searches["defilter"][7]))
self.clear_search_history_icon.get_parent().set_visible_child(self.clear_search_history_icon)
self.clear_filter_history_icon.get_parent().set_visible_child(self.clear_filter_history_icon)
def get_settings(self):
return {
"searches": {
"maxresults": self.max_sent_results_spinner.get_value_as_int(),
"enablefilters": self.enable_default_filters_toggle.get_active(),
"defilter": [
self.filter_include_entry.get_text().strip(),
self.filter_exclude_entry.get_text().strip(),
self.filter_file_size_entry.get_text().strip(),
self.filter_bitrate_entry.get_text().strip(),
self.filter_free_slot_toggle.get_active(),
self.filter_country_entry.get_text().strip(),
self.filter_file_type_entry.get_text().strip(),
self.filter_length_entry.get_text().strip()
],
"search_results": self.repond_search_requests_toggle.get_active(),
"max_displayed_results": self.max_displayed_results_spinner.get_value_as_int(),
"min_search_chars": self.min_search_term_length_spinner.get_value_as_int(),
"enable_history": self.enable_search_history_toggle.get_active(),
"private_search_results": self.show_private_results_toggle.get_active()
}
}
def on_toggle_search_history(self, *_args):
self.search_required = True
def on_clear_search_history(self, *_args):
self.application.window.search.clear_search_history()
stack = self.clear_search_history_success_icon.get_parent()
stack.set_visible_child(self.clear_search_history_success_icon)
def on_clear_filter_history(self, *_args):
self.application.window.search.clear_filter_history()
stack = self.clear_filter_history_success_icon.get_parent()
stack.set_visible_child(self.clear_filter_history_success_icon)
class UrlHandlersPage:
def __init__(self, application):
(
self.container,
self.file_manager_label,
self.protocol_list_container
) = self.widgets = ui.load(scope=self, path="settings/urlhandlers.ui")
self.application = application
self.file_manager_combobox = ComboBox(
container=self.file_manager_label.get_parent(), label=self.file_manager_label, has_entry=True,
items=(
("", None),
("xdg-open $", None),
("explorer $", None),
("nautilus $", None),
("nemo $", None),
("caja $", None),
("thunar $", None),
("dolphin $", None),
("konqueror $", None),
("krusader --left $", None),
("xterm -e mc $", None)
)
)
self.options = {
"urls": {
"protocols": None
},
"ui": {
"filemanager": self.file_manager_combobox
}
}
self.default_protocols = [
"http://",
"https://",
"audio",
"image",
"video",
"document",
"text",
"archive",
".mp3",
".jpg",
".pdf"
]
self.default_commands = [
"xdg-open $",
"firefox $",
"firefox --new-tab $",
"epiphany $",
"chromium-browser $",
"falkon $",
"links -g $",
"dillo $",
"konqueror $",
'"c:\\Program Files\\Mozilla Firefox\\Firefox.exe" $'
]
self.protocols = {}
self.protocol_list_view = TreeView(
application.window, parent=self.protocol_list_container, multi_select=True,
activate_row_callback=self.on_edit_handler,
delete_accelerator_callback=self.on_remove_handler,
columns={
"protocol": {
"column_type": "text",
"title": _("Protocol"),
"width": 120,
"expand_column": True,
"iterator_key": True,
"default_sort_type": "ascending"
},
"command": {
"column_type": "text",
"title": _("Command"),
"expand_column": True
}
}
)
def destroy(self):
self.file_manager_combobox.destroy()
self.protocol_list_view.destroy()
self.__dict__.clear()
def set_settings(self):
self.protocol_list_view.clear()
self.protocol_list_view.freeze()
self.protocols.clear()
self.application.preferences.set_widgets_data(self.options)
self.protocols = config.sections["urls"]["protocols"].copy()
for protocol, command in self.protocols.items():
self.protocol_list_view.add_row([str(protocol), str(command)], select_row=False)
self.protocol_list_view.unfreeze()
def get_settings(self):
return {
"urls": {
"protocols": self.protocols.copy()
},
"ui": {
"filemanager": self.file_manager_combobox.get_text().strip()
}
}
def on_add_handler_response(self, dialog, _response_id, _data):
protocol = dialog.get_entry_value().strip()
command = dialog.get_second_entry_value().strip()
if not protocol or not command:
return
if protocol.startswith("."):
# Only keep last part of file extension (e.g. .tar.gz -> .gz)
protocol = "." + protocol.rpartition(".")[-1]
elif not protocol.endswith("://") and protocol not in self.default_protocols:
protocol += "://"
iterator = self.protocol_list_view.iterators.get(protocol)
self.protocols[protocol] = command
if iterator:
self.protocol_list_view.set_row_value(iterator, "command", command)
return
self.protocol_list_view.add_row([protocol, command])
def on_add_handler(self, *_args):
EntryDialog(
parent=self.application.preferences,
title=_("Add URL Handler"),
message=_("Enter the protocol and the command for the URL handler:"),
action_button_label=_("_Add"),
callback=self.on_add_handler_response,
use_second_entry=True,
droplist=self.default_protocols,
second_droplist=self.default_commands
).present()
def on_edit_handler_response(self, dialog, _response_id, iterator):
command = dialog.get_entry_value().strip()
if not command:
return
protocol = self.protocol_list_view.get_row_value(iterator, "protocol")
self.protocols[protocol] = command
self.protocol_list_view.set_row_value(iterator, "command", command)
def on_edit_handler(self, *_args):
for iterator in self.protocol_list_view.get_selected_rows():
protocol = self.protocol_list_view.get_row_value(iterator, "protocol")
command = self.protocol_list_view.get_row_value(iterator, "command")
EntryDialog(
parent=self.application.preferences,
title=_("Edit Command"),
message=_("Enter a new command for protocol %s:") % protocol,
action_button_label=_("_Edit"),
callback=self.on_edit_handler_response,
callback_data=iterator,
droplist=self.default_commands,
default=command
).present()
return
def on_remove_handler(self, *_args):
for iterator in reversed(list(self.protocol_list_view.get_selected_rows())):
protocol = self.protocol_list_view.get_row_value(iterator, "protocol")
orig_iterator = self.protocol_list_view.iterators[protocol]
self.protocol_list_view.remove_row(orig_iterator)
del self.protocols[protocol]
def on_default_file_manager(self, *_args):
default_file_manager = config.defaults["ui"]["filemanager"]
self.file_manager_combobox.set_text(default_file_manager)
class NowPlayingPage:
def __init__(self, application):
(
self.command_entry,
self.command_label,
self.container,
self.format_help_label,
self.format_message_label,
self.lastfm_radio,
self.listenbrainz_radio,
self.mpris_radio,
self.other_radio,
self.output_label,
self.test_configuration_button
) = self.widgets = ui.load(scope=self, path="settings/nowplaying.ui")
self.application = application
self.format_message_combobox = ComboBox(
container=self.format_message_label.get_parent(), label=self.format_message_label,
has_entry=True
)
self.options = {
"players": {
"npformat": self.format_message_combobox,
"npothercommand": self.command_entry
}
}
self.player_replacers = []
# Default format list
self.default_format_list = [
"$n",
"$n ($f)",
"/me np: $n",
"$a - $t",
"[$a] $t",
"$a - $b - $t",
"$a - $b - $t ($l/$r KBps) from $y $c"
]
self.custom_format_list = []
# Supply the information needed for the Now Playing class to return a song
self.test_configuration_button.connect(
"clicked",
core.now_playing.display_now_playing,
self.set_now_playing_output, # Callback to update the song displayed
self.get_player, # Callback to retrieve selected player
self.get_command, # Callback to retrieve command text
self.get_format # Callback to retrieve format text
)
self.mpris_radio.set_visible(
sys.platform not in {"win32", "darwin"} and "SNAP_NAME" not in os.environ)
def destroy(self):
self.format_message_combobox.destroy()
self.__dict__.clear()
def set_settings(self):
# Add formats
self.format_message_combobox.freeze()
self.format_message_combobox.clear()
for item in self.default_format_list:
self.format_message_combobox.append(str(item))
if self.custom_format_list:
for item in self.custom_format_list:
self.format_message_combobox.append(str(item))
self.format_message_combobox.unfreeze()
self.application.preferences.set_widgets_data(self.options)
# Save reference to format list for get_settings()
self.custom_format_list = config.sections["players"]["npformatlist"]
# Update UI with saved player
self.set_player(config.sections["players"]["npplayer"])
self.update_now_playing_info()
def get_player(self):
if self.lastfm_radio.get_active():
player = "lastfm"
elif self.mpris_radio.get_active():
player = "mpris"
elif self.listenbrainz_radio.get_active():
player = "listenbrainz"
elif self.other_radio.get_active():
player = "other"
if player == "mpris" and (sys.platform in {"win32", "darwin"} or "SNAP_NAME" in os.environ):
player = "lastfm"
return player
def get_command(self):
return self.command_entry.get_text().strip()
def get_format(self):
return self.format_message_combobox.get_text()
def set_player(self, player):
if player == "mpris" and (sys.platform in {"win32", "darwin"} or "SNAP_NAME" in os.environ):
player = "lastfm"
if player == "lastfm":
self.lastfm_radio.set_active(True)
elif player == "listenbrainz":
self.listenbrainz_radio.set_active(True)
elif player == "other":
self.other_radio.set_active(True)
else:
self.mpris_radio.set_active(True)
def update_now_playing_info(self, *_args):
if self.lastfm_radio.get_active():
self.player_replacers = ["$n", "$t", "$a", "$b"]
self.command_label.set_text(_("Username;APIKEY"))
elif self.mpris_radio.get_active():
self.player_replacers = ["$n", "$p", "$a", "$b", "$t", "$y", "$c", "$r", "$k", "$l", "$f"]
self.command_label.set_text(_("Music player (e.g. amarok, audacious, exaile); leave empty to autodetect:"))
elif self.listenbrainz_radio.get_active():
self.player_replacers = ["$n", "$t", "$a", "$b"]
self.command_label.set_text(_("Username: "))
elif self.other_radio.get_active():
self.player_replacers = ["$n"]
self.command_label.set_text(_("Command:"))
legend = ""
for item in self.player_replacers:
legend += item + "\t"
if item == "$t":
legend += _("Title")
elif item == "$n":
legend += _('Now Playing (typically "%(artist)s - %(title)s")') % {
"artist": _("Artist"), "title": _("Title")}
elif item == "$l":
legend += _("Duration")
elif item == "$r":
legend += _("Bitrate")
elif item == "$c":
legend += _("Comment")
elif item == "$a":
legend += _("Artist")
elif item == "$b":
legend += _("Album")
elif item == "$k":
legend += _("Track Number")
elif item == "$y":
legend += _("Year")
elif item == "$f":
legend += _("Filename (URI)")
elif item == "$p":
legend += _("Program")
legend += "\n"
self.format_help_label.set_text(legend[:-1])
def set_now_playing_output(self, title):
self.output_label.set_text(title)
def get_settings(self):
npformat = self.get_format()
if (npformat and not npformat.isspace()
and npformat not in self.custom_format_list
and npformat not in self.default_format_list):
self.custom_format_list.append(npformat)
return {
"players": {
"npplayer": self.get_player(),
"npothercommand": self.get_command(),
"npformat": npformat,
"npformatlist": self.custom_format_list
}
}
class PluginsPage:
def __init__(self, application):
(
self.container,
self.enable_plugins_toggle,
self.plugin_authors_label,
self.plugin_description_view_container,
self.plugin_list_container,
self.plugin_name_label,
self.plugin_settings_button,
self.plugin_version_label
) = self.widgets = ui.load(scope=self, path="settings/plugin.ui")
self.application = application
self.selected_plugin = None
self.plugin_settings = None
self.options = {
"plugins": {
"enable": self.enable_plugins_toggle
}
}
self.plugin_description_view = TextView(self.plugin_description_view_container, editable=False,
pixels_below_lines=2)
self.plugin_list_view = TreeView(
application.window, parent=self.plugin_list_container,
activate_row_callback=self.on_row_activated, select_row_callback=self.on_select_plugin,
columns={
# Visible columns
"enabled": {
"column_type": "toggle",
"title": _("Enabled"),
"width": 0,
"toggle_callback": self.on_plugin_toggle,
"hide_header": True
},
"plugin": {
"column_type": "text",
"title": _("Plugin"),
"default_sort_type": "ascending"
},
# Hidden data columns
"plugin_id": {"data_type": GObject.TYPE_STRING, "iterator_key": True}
}
)
def destroy(self):
self.plugin_description_view.destroy()
self.plugin_list_view.destroy()
if self.plugin_settings is not None:
self.plugin_settings.destroy()
self.__dict__.clear()
def set_settings(self):
self.plugin_list_view.clear()
self.plugin_list_view.freeze()
self.application.preferences.set_widgets_data(self.options)
for plugin_id in core.pluginhandler.list_installed_plugins():
try:
info = core.pluginhandler.get_plugin_info(plugin_id)
except OSError:
continue
plugin_name = info.get("Name", plugin_id)
enabled = (plugin_id in config.sections["plugins"]["enabled"])
self.plugin_list_view.add_row([enabled, plugin_name, plugin_id], select_row=False)
self.plugin_list_view.unfreeze()
def get_settings(self):
return {
"plugins": {
"enable": self.enable_plugins_toggle.get_active()
}
}
def check_plugin_settings_button(self, plugin):
self.plugin_settings_button.set_sensitive(bool(core.pluginhandler.get_plugin_settings(plugin)))
def on_select_plugin(self, list_view, iterator):
if iterator is None:
self.selected_plugin = _("No Plugin Selected")
info = {}
else:
self.selected_plugin = list_view.get_row_value(iterator, "plugin_id")
info = core.pluginhandler.get_plugin_info(self.selected_plugin)
plugin_name = info.get("Name", self.selected_plugin)
plugin_version = info.get("Version", "-")
plugin_authors = ", ".join(info.get("Authors", "-"))
plugin_description = info.get("Description", "").replace(r"\n", "\n")
self.plugin_name_label.set_text(plugin_name)
self.plugin_version_label.set_text(plugin_version)
self.plugin_authors_label.set_text(plugin_authors)
self.plugin_description_view.clear()
self.plugin_description_view.append_line(plugin_description)
self.plugin_description_view.place_cursor_at_line(0)
self.check_plugin_settings_button(self.selected_plugin)
def on_plugin_toggle(self, list_view, iterator):
plugin_id = list_view.get_row_value(iterator, "plugin_id")
enabled = core.pluginhandler.toggle_plugin(plugin_id)
list_view.set_row_value(iterator, "enabled", enabled)
self.check_plugin_settings_button(plugin_id)
def on_enable_plugins(self, *_args):
enabled_plugin_ids = config.sections["plugins"]["enabled"].copy()
if self.enable_plugins_toggle.get_active():
# Enable all selected plugins
for plugin_id in enabled_plugin_ids:
core.pluginhandler.enable_plugin(plugin_id)
self.check_plugin_settings_button(self.selected_plugin)
return
# Disable all plugins
for plugin in core.pluginhandler.enabled_plugins.copy():
core.pluginhandler.disable_plugin(plugin)
config.sections["plugins"]["enabled"] = enabled_plugin_ids
self.plugin_settings_button.set_sensitive(False)
def on_add_plugins(self, *_args):
open_folder_path(core.pluginhandler.user_plugin_folder, create_folder=True)
def on_plugin_settings(self, *_args):
if self.selected_plugin is None:
return
settings = core.pluginhandler.get_plugin_settings(self.selected_plugin)
if not settings:
return
if self.plugin_settings is None:
self.plugin_settings = PluginSettings(self.application)
self.plugin_settings.update_settings(plugin_id=self.selected_plugin, plugin_settings=settings)
self.plugin_settings.present()
def on_row_activated(self, _list_view, _iterator, column_id):
if column_id == "plugin":
self.on_plugin_settings()
class Preferences(Dialog):
PAGE_IDS = [
("network", NetworkPage, _("Network"), "network-wireless-symbolic"),
("user-interface", UserInterfacePage, _("User Interface"), "view-grid-symbolic"),
("shares", SharesPage, _("Shares"), "folder-symbolic"),
("downloads", DownloadsPage, _("Downloads"), "folder-download-symbolic"),
("uploads", UploadsPage, _("Uploads"), "emblem-shared-symbolic"),
("searches", SearchesPage, _("Searches"), "system-search-symbolic"),
("user-profile", UserProfilePage, _("User Profile"), "avatar-default-symbolic"),
("chats", ChatsPage, _("Chats"), "insert-text-symbolic"),
("now-playing", NowPlayingPage, _("Now Playing"), "folder-music-symbolic"),
("logging", LoggingPage, _("Logging"), "folder-documents-symbolic"),
("banned-users", BannedUsersPage, _("Banned Users"), "action-unavailable-symbolic"),
("ignored-users", IgnoredUsersPage, _("Ignored Users"), "microphone-sensitivity-muted-symbolic"),
("url-handlers", UrlHandlersPage, _("URL Handlers"), "insert-link-symbolic"),
("plugins", PluginsPage, _("Plugins"), "application-x-addon-symbolic")
]
def __init__(self, application):
self.application = application
(
self.apply_button,
self.cancel_button,
self.container,
self.content,
self.export_button,
self.ok_button,
self.preferences_list,
self.viewport
) = self.widgets = ui.load(scope=self, path="dialogs/preferences.ui")
super().__init__(
parent=application.window,
modal=False,
content_box=self.container,
buttons_start=(self.cancel_button, self.export_button),
buttons_end=(self.apply_button, self.ok_button),
default_button=self.ok_button,
close_callback=self.on_close,
title=_("Preferences"),
width=960,
height=650,
show_title_buttons=False
)
add_css_class(self.widget, "preferences-border")
if GTK_API_VERSION == 3:
# Scroll to focused widgets
self.viewport.set_focus_vadjustment(self.content.get_vadjustment())
self.pages = {}
for _page_id, _page_class, label, icon_name in self.PAGE_IDS:
box = Gtk.Box(margin_top=8, margin_bottom=8, margin_start=12, margin_end=12, spacing=12, visible=True)
icon = Gtk.Image(icon_name=icon_name, visible=True)
label = Gtk.Label(label=label, xalign=0, visible=True)
if GTK_API_VERSION >= 4:
box.append(icon) # pylint: disable=no-member
box.append(label) # pylint: disable=no-member
else:
box.add(icon) # pylint: disable=no-member
box.add(label) # pylint: disable=no-member
self.preferences_list.insert(box, -1)
Accelerator("Tab", self.preferences_list, self.on_sidebar_tab_accelerator)
Accelerator("<Shift>Tab", self.preferences_list, self.on_sidebar_shift_tab_accelerator)
def destroy(self):
for page in self.pages.values():
page.destroy()
super().destroy()
def set_active_page(self, page_id):
if page_id is None:
return
for index, (n_page_id, _page_class, _label, _icon_name) in enumerate(self.PAGE_IDS):
if n_page_id != page_id:
continue
row = self.preferences_list.get_row_at_index(index)
self.preferences_list.select_row(row)
break
def set_widgets_data(self, options):
for section, keys in options.items():
if section not in config.sections:
continue
for key in keys:
widget = options[section][key]
if widget is None:
continue
self.set_widget(widget, config.sections[section][key])
@staticmethod
def set_widget(widget, value):
if isinstance(widget, Gtk.SpinButton):
try:
widget.set_value(value)
except TypeError:
# Not a numerical value
pass
elif isinstance(widget, Gtk.Entry):
if isinstance(value, (str, int)) and widget.get_text() != value:
widget.set_text(value)
elif isinstance(widget, TextView):
if isinstance(value, str):
widget.set_text(unescape(value))
elif isinstance(widget, Gtk.Switch):
widget.set_active(value)
elif isinstance(widget, Gtk.CheckButton):
try:
# Radio button
if isinstance(value, int) and value < len(widget.group_radios):
widget.group_radios[value].set_active(True)
except (AttributeError, TypeError):
# Regular check button
widget.set_active(value)
elif isinstance(widget, ComboBox):
if isinstance(value, str):
if widget.entry is not None:
widget.set_text(value)
else:
widget.set_selected_id(value)
elif isinstance(value, int):
widget.set_selected_pos(value)
elif isinstance(widget, Gtk.FontButton):
widget.set_font(value)
elif isinstance(widget, TreeView):
widget.freeze()
if isinstance(value, list):
for item in value:
if isinstance(item, list):
row = item
else:
row = [item]
widget.add_row(row, select_row=False)
elif isinstance(value, dict):
for item1, item2 in value.items():
widget.add_row([str(item1), str(item2)], select_row=False)
widget.unfreeze()
elif isinstance(widget, FileChooserButton):
widget.set_path(value)
elif isinstance(widget, Gtk.FontDialogButton):
widget.set_font_desc(Pango.FontDescription.from_string(value))
def set_settings(self):
for page in self.pages.values():
page.set_settings()
def get_settings(self):
options = {
"server": {},
"transfers": {},
"userinfo": {},
"logging": {},
"searches": {},
"privatechat": {},
"ui": {},
"urls": {},
"players": {},
"words": {},
"notifications": {},
"plugins": {}
}
for page in self.pages.values():
for key, data in page.get_settings().items():
options[key].update(data)
try:
portmap_required = self.pages["network"].portmap_required
except KeyError:
portmap_required = False
try:
rescan_required = self.pages["shares"].rescan_required
except KeyError:
rescan_required = False
try:
recompress_shares_required = self.pages["shares"].recompress_shares_required
except KeyError:
recompress_shares_required = False
try:
user_profile_required = self.pages["user-profile"].user_profile_required
except KeyError:
user_profile_required = False
try:
private_room_required = self.pages["chats"].private_room_required
except KeyError:
private_room_required = False
try:
completion_required = self.pages["chats"].completion_required
except KeyError:
completion_required = False
try:
search_required = self.pages["searches"].search_required
except KeyError:
search_required = False
return (
portmap_required,
rescan_required,
recompress_shares_required,
user_profile_required,
private_room_required,
completion_required,
search_required,
options
)
def update_settings(self, settings_closed=False):
(
portmap_required,
rescan_required,
recompress_shares_required,
user_profile_required,
private_room_required,
completion_required,
search_required,
options
) = self.get_settings()
for key, data in options.items():
config.sections[key].update(data)
banned_page = self.pages.get("banned-users")
ignored_page = self.pages.get("ignored-users")
if banned_page is not None:
for username in banned_page.added_users:
core.network_filter.ban_user(username)
for username, ip_address in banned_page.added_ips:
core.network_filter.ban_user_ip(username, ip_address)
for username in banned_page.removed_users:
core.network_filter.unban_user(username)
for username, ip_address in banned_page.removed_ips:
core.network_filter.unban_user_ip(username, ip_address)
banned_page.clear_changes()
if ignored_page is not None:
for username in ignored_page.added_users:
core.network_filter.ignore_user(username)
for username, ip_address in ignored_page.added_ips:
core.network_filter.ignore_user_ip(username, ip_address)
for username in ignored_page.removed_users:
core.network_filter.unignore_user(username)
for username, ip_address in ignored_page.removed_ips:
core.network_filter.unignore_user_ip(username, ip_address)
ignored_page.clear_changes()
if portmap_required == "add":
core.portmapper.add_port_mapping()
elif portmap_required == "remove":
core.portmapper.remove_port_mapping()
if user_profile_required:
core.userinfo.show_user(refresh=True, switch_page=False)
if private_room_required:
active = config.sections["server"]["private_chatrooms"]
self.application.window.chatrooms.room_list.toggle_accept_private_room(active)
if completion_required:
core.chatrooms.update_completions()
core.privatechat.update_completions()
if search_required:
self.application.window.search.populate_search_history()
if recompress_shares_required and not rescan_required:
core.shares.rescan_shares(init=True, rescan=False)
# Dark mode
dark_mode_state = config.sections["ui"]["dark_mode"]
set_dark_mode(dark_mode_state)
# Header bar
header_bar_state = config.sections["ui"]["header_bar"]
self.application.window.set_use_header_bar(header_bar_state)
# Icons
load_custom_icons(update=True)
# Fonts and colors
update_custom_css()
# Chats
self.application.window.chatrooms.update_widgets()
self.application.window.privatechat.update_widgets()
# Buddies
self.application.window.buddies.set_buddy_list_position()
# Transfers
core.downloads.update_transfer_limits()
core.downloads.update_download_filters()
core.uploads.update_transfer_limits()
# Logging
log.update_folder_paths()
# Tray icon
if not config.sections["ui"]["trayicon"]:
self.application.tray_icon.unload(is_shutdown=False)
else:
self.application.tray_icon.load()
# Main notebook
self.application.window.set_tab_positions()
self.application.window.set_main_tabs_visibility()
for tab in self.application.window.tabs.values():
self.application.window.set_tab_expand(tab.page)
# Other notebooks
for notebook in (self.application.window.chatrooms, self.application.window.privatechat,
self.application.window.userinfo, self.application.window.userbrowse,
self.application.window.search):
notebook.set_tab_closers()
# Update configuration
config.write_configuration()
if not settings_closed:
return
self.close()
if not config.sections["ui"]["trayicon"]:
self.application.window.present()
if rescan_required:
core.shares.rescan_shares()
if config.need_config():
core.setup()
@staticmethod
def on_back_up_config_response(selected, _data):
file_path = next(iter(selected), None)
if file_path:
config.write_config_backup(file_path)
def on_back_up_config(self, *_args):
current_date_time = time.strftime("%Y-%m-%d_%H-%M-%S")
FileChooserSave(
parent=self,
callback=self.on_back_up_config_response,
initial_folder=os.path.dirname(config.config_file_path),
initial_file=f"config_backup_{current_date_time}.tar.bz2",
title=_("Pick a File Name for Config Backup")
).present()
def on_toggle_label_pressed(self, _controller, _num_p, _pos_x, _pos_y, toggle):
toggle.emit("activate")
def on_widget_scroll_event(self, _widget, event):
"""Prevent scrolling in GtkSpinButton and pass scroll event to container (GTK 3)"""
self.content.event(event)
return True
def on_widget_scroll(self, _controller, _scroll_x, scroll_y):
"""Prevent scrolling in GtkSpinButton and emulate scrolling in the container (GTK 4)"""
adjustment = self.content.get_vadjustment()
value = adjustment.get_value()
if scroll_y < 0:
value -= adjustment.get_step_increment()
else:
value += adjustment.get_step_increment()
adjustment.set_value(value)
return True
def on_switch_page(self, _listbox, row):
if row is None:
return
page_id, page_class, _label, _icon_name = self.PAGE_IDS[row.get_index()]
old_page = self.viewport.get_child()
if old_page:
if GTK_API_VERSION >= 4:
self.viewport.set_child(None)
else:
self.viewport.remove(old_page)
if page_id not in self.pages:
self.pages[page_id] = page = page_class(self.application)
page.set_settings()
for obj in page.widgets:
if isinstance(obj, Gtk.CheckButton):
if GTK_API_VERSION >= 4:
try:
check_button_label = list(obj)[-1]
check_button_label.set_wrap(True) # pylint: disable=no-member
except AttributeError:
pass
else:
check_button_label = obj.get_child()
check_button_label.set_line_wrap(True) # pylint: disable=no-member
obj.set_receives_default(True)
elif isinstance(obj, Gtk.Switch):
switch_container = obj.get_parent()
switch_label = next(iter(switch_container))
if GTK_API_VERSION >= 4:
switch_label.gesture_click = Gtk.GestureClick()
switch_label.add_controller(switch_label.gesture_click)
else:
switch_label.set_has_window(True)
switch_label.gesture_click = Gtk.GestureMultiPress(widget=switch_label)
obj.set_receives_default(True)
switch_label.gesture_click.connect("released", self.on_toggle_label_pressed, obj)
elif isinstance(obj, Gtk.SpinButton):
if GTK_API_VERSION >= 4:
scroll_controller = Gtk.EventControllerScroll(
flags=int(Gtk.EventControllerScrollFlags.VERTICAL)
)
scroll_controller.connect("scroll", self.on_widget_scroll)
obj.add_controller(scroll_controller)
else:
obj.connect("scroll-event", self.on_widget_scroll_event)
elif (isinstance(obj, Gtk.FontButton)
or ((GTK_API_VERSION, GTK_MINOR_VERSION) >= (4, 10) and isinstance(obj, Gtk.FontDialogButton))):
if GTK_API_VERSION >= 4:
inner_button = next(iter(obj))
font_button_container = next(iter(inner_button))
font_button_label = next(iter(font_button_container))
else:
font_button_container = obj.get_child()
font_button_label = next(iter(font_button_container))
try:
font_button_label.set_ellipsize(Pango.EllipsizeMode.END)
except AttributeError:
pass
page.container.set_margin_start(18)
page.container.set_margin_end(18)
page.container.set_margin_top(14)
page.container.set_margin_bottom(18)
if GTK_API_VERSION >= 4:
self.viewport.set_child(self.pages[page_id].container) # pylint: disable=no-member
else:
self.viewport.add(self.pages[page_id].container) # pylint: disable=no-member
# Scroll to the top
self.content.get_vadjustment().set_value(0)
def on_sidebar_tab_accelerator(self, *_args):
"""Tab - navigate to widget after preferences sidebar."""
self.content.child_focus(Gtk.DirectionType.TAB_FORWARD)
return True
def on_sidebar_shift_tab_accelerator(self, *_args):
"""Shift+Tab - navigate to widget before preferences sidebar."""
self.ok_button.grab_focus()
return True
def on_cancel(self, *_args):
self.close()
def on_apply(self, *_args):
self.update_settings()
def on_ok(self, *_args):
self.update_settings(settings_closed=True)
def on_close(self, *_args):
self.content.get_vadjustment().set_value(0)
| 134,241 | Python | .py | 2,799 | 35.507324 | 120 | 0.591595 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,477 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/now_playing_search/__init__.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.np_format = None
def outgoing_global_search_event(self, text):
return (self.get_np(text),)
def outgoing_room_search_event(self, rooms, text):
return rooms, self.get_np(text)
def outgoing_buddy_search_event(self, text):
return (self.get_np(text),)
def outgoing_user_search_event(self, users, text):
return users, self.get_np(text)
def get_np(self, text):
self.np_format = text
now_playing = self.core.now_playing.get_np(get_format=self.get_format)
if now_playing:
return now_playing
return text
def get_format(self):
return self.np_format
| 1,574 | Python | .py | 38 | 36.684211 | 78 | 0.708279 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,478 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/anti_shout/__init__.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
# COPYRIGHT (C) 2009 quinox <quinox@users.sf.net>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"maxscore": 0.6,
"minlength": 10
}
self.metasettings = {
"maxscore": {
"description": "The maximum ratio of capitals before converting",
"type": "float", "minimum": 0, "maximum": 1, "stepsize": 0.1
},
"minlength": {
"description": "Lines shorter than this will be ignored", "type": "integer",
"minimum": 0
}
}
@staticmethod
def capitalize(text):
# Dont alter words that look like protocol links (fe http://, ftp://)
if text.find("://") > -1:
return text
return text.capitalize()
def incoming_private_chat_event(self, user, line):
return user, self.antishout(line)
def incoming_public_chat_event(self, room, user, line):
return room, user, self.antishout(line)
def antishout(self, line):
lowers = len([x for x in line if x.islower()])
uppers = len([x for x in line if x.isupper()])
score = -2 # unknown state (could be: no letters at all)
if uppers > 0:
score = -1 # We have at least some upper letters
if lowers > 0:
score = uppers / float(lowers)
newline = line
if len(line) > self.settings["minlength"] and (score == -1 or score > self.settings["maxscore"]):
newline = ". ".join([self.capitalize(x) for x in line.split(". ")])
if newline == line:
return newline
return newline + " [as]"
| 2,539 | Python | .py | 60 | 34.8 | 105 | 0.621951 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,479 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/multipaste/__init__.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
# COPYRIGHT (C) 2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2008 quinox <quinox@users.sf.net>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
from pynicotine.pluginsystem import returncode
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"maxpubliclines": 4,
"maxprivatelines": 8
}
self.metasettings = {
"maxpubliclines": {
"description": "The maximum number of lines that will be pasted in public",
"type": "int"
},
"maxprivatelines": {
"description": "The maximum number of lines that will be pasted in private",
"type": "int"
}
}
def outgoing_private_chat_event(self, user, line):
lines = [x for x in line.splitlines() if x]
if len(lines) > 1:
if len(lines) > self.settings["maxprivatelines"]:
self.log("Posting %s of %s lines.", (self.settings["maxprivatelines"], len(lines)))
else:
self.log("Splitting lines.")
for split_line in lines[:self.settings["maxprivatelines"]]:
self.send_private(user, split_line)
return returncode["zap"]
return None
def outgoing_public_chat_event(self, room, line):
lines = [x for x in line.splitlines() if x]
if len(lines) > 1:
if len(lines) > self.settings["maxpubliclines"]:
self.log("Posting %s of %s lines.", (self.settings["maxpubliclines"], len(lines)))
else:
self.log("Splitting lines.")
for split_line in lines[:self.settings["maxpubliclines"]]:
self.send_public(room, split_line)
return returncode["zap"]
return None
| 2,623 | Python | .py | 60 | 35.316667 | 99 | 0.629761 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,480 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/auto_user_browse/__init__.py | # COPYRIGHT (C) 2021-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.events import events
from pynicotine.pluginsystem import BasePlugin
from pynicotine.slskmessages import UserStatus
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"users": []
}
self.metasettings = {
"users": {
"description": "Username",
"type": "list string"
}
}
self.processed_users = set()
def browse_user(self, user):
if user in self.processed_users:
self.core.userbrowse.browse_user(user, switch_page=False)
def user_status_notification(self, user, status, _privileged):
if status == UserStatus.OFFLINE:
self.processed_users.discard(user)
return
if user not in self.settings["users"]:
return
if user not in self.processed_users:
# Wait 30 seconds before browsing shares to ensure they are ready
# and the server doesn't send an invalid port for the user
self.processed_users.add(user)
events.schedule(delay=30, callback=self.browse_user, callback_args=(user,))
def server_disconnect_notification(self, userchoice):
self.processed_users.clear()
| 2,056 | Python | .py | 49 | 35.244898 | 87 | 0.676692 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,481 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/spamfilter/__init__.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
# COPYRIGHT (C) 2009 daelstorm <daelstorm@gmail.com>
# COPYRIGHT (C) 2009 quinox <quinox@users.sf.net>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
from pynicotine.pluginsystem import returncode
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"minlength": 200,
"maxlength": 400,
"maxdiffcharacters": 10,
"badprivatephrases": []
}
self.metasettings = {
"minlength": {
"description": "The minimum length of a line before it's considered as ASCII spam",
"type": "integer"
},
"maxdiffcharacters": {
"description": "The maximum number of different characters that is still considered ASCII spam",
"type": "integer"
},
"maxlength": {
"description": "The maximum length of a line before it's considered as spam.",
"type": "integer"
},
"badprivatephrases": {
"description": "Filter chat messages containing phrase:",
"type": "list string"
}
}
def loaded_notification(self):
self.log("A line should be at least %s long with a maximum of %s different characters "
"before it's considered ASCII spam.",
(self.settings["minlength"], self.settings["maxdiffcharacters"]))
def check_phrases(self, user, line):
for phrase in self.settings["badprivatephrases"]:
if line.lower().find(phrase) > -1:
self.log("Blocked spam from %s: %s", (user, line))
return returncode["zap"]
return None
def incoming_public_chat_event(self, room, user, line):
if len(line) >= self.settings["minlength"] and len(set(line)) < self.settings["maxdiffcharacters"]:
self.log('Filtered ASCII spam from "%s" in room "%s"', (user, room))
return returncode["zap"]
if len(line) > self.settings["maxlength"]:
self.log('Filtered really long line (%s characters) from "%s" in room "%s"', (len(line), user, room))
return returncode["zap"]
return self.check_phrases(user, line)
def incoming_private_chat_event(self, user, line):
return self.check_phrases(user, line)
| 3,159 | Python | .py | 68 | 37.661765 | 113 | 0.627642 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,482 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/core_commands/__init__.py | # COPYRIGHT (C) 2022-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
from pynicotine.shares import PermissionLevel
from pynicotine.slskmessages import UserStatus
class _CommandGroup:
CHAT = _("Chat")
CHAT_ROOMS = _("Chat Rooms")
PRIVATE_CHAT = _("Private Chat")
NETWORK_FILTERS = _("Network Filters")
SEARCH_FILES = _("Search Files")
SHARES = _("Shares")
USERS = _("Users")
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.commands = {
"help": {
"aliases": ["?"],
"callback": self.help_command,
"description": _("List available commands"),
"parameters": ["[query]"]
},
"connect": {
"callback": self.connect_command,
"description": _("Connect to the server"),
},
"disconnect": {
"callback": self.disconnect_command,
"description": _("Disconnect from the server"),
},
"away": {
"aliases": ["a"],
"callback": self.away_command,
"description": _("Toggle away status"),
},
"plugin": {
"callback": self.plugin_handler_command,
"description": _("Manage plugins"),
"parameters": ["<toggle|reload|info>", "<plugin name>"]
},
"quit": {
"aliases": ["q", "exit"],
"callback": self.quit_command,
"description": _("Quit Nicotine+"),
"parameters": ["[force]"]
},
"clear": {
"aliases": ["cl"],
"callback": self.clear_command,
"description": _("Clear chat window"),
"disable": ["cli"],
"group": _CommandGroup.CHAT,
},
"me": {
"callback": self.me_command,
"description": _("Say something in the third-person"),
"disable": ["cli"],
"group": _CommandGroup.CHAT,
"parameters": ["<something..>"]
},
"now": {
"callback": self.now_command,
"description": _("Announce the song currently playing"),
"disable": ["cli"],
"group": _CommandGroup.CHAT
},
"join": {
"aliases": ["j"],
"callback": self.join_command,
"description": _("Join chat room"),
"disable": ["cli"],
"group": _CommandGroup.CHAT_ROOMS,
"parameters": ["<room>"]
},
"leave": {
"aliases": ["l"],
"callback": self.leave_command,
"description": _("Leave chat room"),
"disable": ["cli"],
"group": _CommandGroup.CHAT_ROOMS,
"parameters": ["<room>"],
"parameters_chatroom": ["[room]"]
},
"say": {
"callback": self.say_command,
"description": _("Say message in specified chat room"),
"disable": ["cli"],
"group": _CommandGroup.CHAT_ROOMS,
"parameters": ["<room>", "<message..>"]
},
"pm": {
"callback": self.pm_command,
"description": _("Open private chat"),
"disable": ["cli"],
"group": _CommandGroup.PRIVATE_CHAT,
"parameters": ["<user>"]
},
"close": {
"aliases": ["c"],
"callback": self.close_command,
"description": _("Close private chat"),
"disable": ["cli"],
"group": _CommandGroup.PRIVATE_CHAT,
"parameters_chatroom": ["<user>"],
"parameters_private_chat": ["[user]"]
},
"ctcpversion": {
"callback": self.ctcpversion_command,
"description": _("Request user's client version"),
"disable": ["cli"],
"group": _CommandGroup.PRIVATE_CHAT,
"parameters_chatroom": ["<user>"],
"parameters_private_chat": ["[user]"]
},
"msg": {
"aliases": ["m"],
"callback": self.msg_command,
"description": _("Send private message to user"),
"disable": ["cli"],
"group": _CommandGroup.PRIVATE_CHAT,
"parameters": ["<user>", "<message..>"]
},
"add": {
"aliases": ["buddy"],
"callback": self.add_buddy_command,
"description": _("Add user to buddy list"),
"group": _CommandGroup.USERS,
"parameters": ["<user>"],
"parameters_private_chat": ["[user]"]
},
"rem": {
"aliases": ["unbuddy"],
"callback": self.remove_buddy_command,
"description": _("Remove buddy from buddy list"),
"group": _CommandGroup.USERS,
"parameters": ["<user>"],
"parameters_private_chat": ["[user]"]
},
"browse": {
"aliases": ["b"],
"callback": self.browse_user_command,
"description": _("Browse files of user"),
"disable": ["cli"],
"group": _CommandGroup.USERS,
"parameters": ["<user>"],
"parameters_private_chat": ["[user]"]
},
"whois": {
"aliases": ["info", "w"],
"callback": self.whois_command,
"description": _("Show user profile information"),
"disable": ["cli"],
"group": _CommandGroup.USERS,
"parameters": ["<user>"],
"parameters_private_chat": ["[user]"]
},
"ip": {
"callback": self.ip_address_command,
"description": _("Show IP address or username"),
"group": _CommandGroup.NETWORK_FILTERS,
"parameters": ["<user or ip>"],
"parameters_private_chat": ["[user or ip]"]
},
"ban": {
"callback": self.ban_command,
"description": _("Block connections from user or IP address"),
"group": _CommandGroup.NETWORK_FILTERS,
"parameters": ["<user or ip>"],
"parameters_private_chat": ["[user or ip]"]
},
"unban": {
"callback": self.unban_command,
"description": _("Remove user or IP address from ban lists"),
"group": _CommandGroup.NETWORK_FILTERS,
"parameters": ["<user or ip>"],
"parameters_private_chat": ["[user or ip]"]
},
"ignore": {
"callback": self.ignore_command,
"description": _("Silence messages from user or IP address"),
"disable": ["cli"],
"group": _CommandGroup.NETWORK_FILTERS,
"parameters": ["<user or ip>"],
"parameters_private_chat": ["[user or ip]"]
},
"unignore": {
"callback": self.unignore_command,
"description": _("Remove user or IP address from ignore lists"),
"disable": ["cli"],
"group": _CommandGroup.NETWORK_FILTERS,
"parameters": ["<user or ip>"],
"parameters_private_chat": ["[user or ip]"]
},
"share": {
"callback": self.share_command,
"description": _("Add share"),
"group": _CommandGroup.SHARES,
"parameters": ["<public|buddy|trusted>", "<folder path>"]
},
"unshare": {
"callback": self.unshare_command,
"description": _("Remove share"),
"group": _CommandGroup.SHARES,
"parameters": ["<virtual name or folder path>"]
},
"shares": {
"aliases": ["ls"],
"callback": self.list_shares_command,
"description": _("List shares"),
"group": _CommandGroup.SHARES,
"parameters": ["[public|buddy|trusted]"]
},
"rescan": {
"callback": self.rescan_command,
"description": _("Rescan shares"),
"group": _CommandGroup.SHARES,
"parameters": ["[force|rebuild]"]
},
"search": {
"aliases": ["s"],
"callback": self.search_command,
"description": _("Start global file search"),
"disable": ["cli"],
"group": _CommandGroup.SEARCH_FILES,
"parameters": ["<query>"]
},
"rsearch": {
"aliases": ["rs"],
"callback": self.search_rooms_command,
"description": _("Search files in joined rooms"),
"disable": ["cli"],
"group": _CommandGroup.SEARCH_FILES,
"parameters": ["<query>"]
},
"bsearch": {
"aliases": ["bs"],
"callback": self.search_buddies_command,
"description": _("Search files of all buddies"),
"disable": ["cli"],
"group": _CommandGroup.SEARCH_FILES,
"parameters": ["<query>"]
},
"usearch": {
"aliases": ["us"],
"callback": self.search_user_command,
"description": _("Search a user's shared files"),
"disable": ["cli"],
"group": _CommandGroup.SEARCH_FILES,
"parameters": ["<user>", "<query>"]
}
}
# Application Commands #
def help_command(self, args, user=None, room=None):
if user is not None:
command_interface = "private_chat"
elif room is not None:
command_interface = "chatroom"
else:
command_interface = "cli"
search_query = " ".join(args.lower().split(" ", maxsplit=1))
command_groups = self.parent.get_command_groups_data(command_interface, search_query=search_query)
num_commands = sum(len(command_groups[x]) for x in command_groups)
output_text = ""
if not search_query:
output_text += _("Listing %(num)i available commands:") % {"num": num_commands}
else:
output_text += _('Listing %(num)i available commands matching "%(query)s":') % {
"num": num_commands,
"query": search_query
}
for group_name, command_data in command_groups.items():
output_text += f"\n\n{group_name}:"
for command, aliases, parameters, description in command_data:
command_message = f"/{', /'.join([command] + aliases)} {' '.join(parameters)}".strip()
output_text += f"\n\t{command_message} - {description}"
if not search_query:
output_text += "\n\n" + _("Type %(command)s to list similar commands") % {"command": "/help [query]"}
elif not num_commands:
output_text += "\n" + _("Type %(command)s to list available commands") % {"command": "/help"}
self.output(output_text)
def connect_command(self, _args, **_unused):
if self.core.users.login_status == UserStatus.OFFLINE:
self.core.connect()
def disconnect_command(self, _args, **_unused):
if self.core.users.login_status != UserStatus.OFFLINE:
self.core.disconnect()
def away_command(self, _args, **_unused):
if self.core.users.login_status == UserStatus.OFFLINE:
self.output(_("%(user)s is offline") % {"user": self.config.sections["server"]["login"]})
return
self.core.users.set_away_mode(self.core.users.login_status != UserStatus.AWAY, save_state=True)
if self.core.users.login_status == UserStatus.ONLINE:
self.output(_("%(user)s is online") % {"user": self.core.users.login_username})
else:
self.output(_("%(user)s is away") % {"user": self.core.users.login_username})
def quit_command(self, args, **_unused):
force = (args.lstrip("-") in {"force", "f"})
if force:
self.core.quit()
else:
self.core.confirm_quit()
# Chat #
def clear_command(self, _args, user=None, room=None):
if room is not None:
self.core.chatrooms.clear_room_messages(room)
elif user is not None:
self.core.privatechat.clear_private_messages(user)
def me_command(self, args, **_unused):
self.send_message("/me " + args) # /me is sent as plain text
def now_command(self, _args, **_unused):
self.core.now_playing.display_now_playing(callback=self.send_message)
# Chat Rooms #
def join_command(self, args, **_unused):
room = self.core.chatrooms.sanitize_room_name(args)
self.core.chatrooms.show_room(room)
def leave_command(self, args, room=None, **_unused):
if args:
room = args
if room not in self.core.chatrooms.joined_rooms:
self.output(_("Not joined in room %s") % room)
return False
self.core.chatrooms.remove_room(room)
return True
def say_command(self, args, **_unused):
room, text = args.split(maxsplit=1)
if room not in self.core.chatrooms.joined_rooms:
self.output(_("Not joined in room %s") % room)
return False
self.send_public(room, text)
return True
# Private Chat #
def pm_command(self, args, **_unused):
self.core.privatechat.show_user(args)
def close_command(self, args, user=None, **_unused):
if args:
user = args
if user not in self.core.privatechat.users:
self.output(_("Not messaging with user %s") % user)
return False
self.core.privatechat.remove_user(user)
self.output(_("Closed private chat of user %s") % user)
return True
def ctcpversion_command(self, args, user=None, **_unused):
if args:
user = args
self.send_private(user, self.core.privatechat.CTCP_VERSION, show_ui=True)
def msg_command(self, args, **_unused):
user, text = args.split(maxsplit=1)
self.send_private(user, text, show_ui=True, switch_page=False)
# Users #
def add_buddy_command(self, args, user=None, **_unused):
if args:
user = args
self.core.buddies.add_buddy(user)
def remove_buddy_command(self, args, user=None, **_unused):
if args:
user = args
self.core.buddies.remove_buddy(user)
def browse_user_command(self, args, user=None, **_unused):
if args:
user = args
self.core.userbrowse.browse_user(user)
def whois_command(self, args, user=None, **_unused):
if args:
user = args
self.core.userinfo.show_user(user)
# Network Filters #
def ip_address_command(self, args, user=None, **_unused):
if self.core.network_filter.is_ip_address(args):
self.output(self.core.network_filter.get_online_username(args))
return
if args:
user = args
self.core.users.request_ip_address(user, notify=True)
def ban_command(self, args, user=None, **_unused):
if self.core.network_filter.is_ip_address(args):
banned_ip_address = self.core.network_filter.ban_user_ip(ip_address=args)
else:
if args:
user = args
banned_ip_address = None
self.core.network_filter.ban_user(user)
self.output(_("Banned %s") % (banned_ip_address or user))
def unban_command(self, args, user=None, **_unused):
if self.core.network_filter.is_ip_address(args):
unbanned_ip_addresses = self.core.network_filter.unban_user_ip(ip_address=args)
self.core.network_filter.unban_user(self.core.network_filter.get_online_username(args))
else:
if args:
user = args
unbanned_ip_addresses = self.core.network_filter.unban_user_ip(user)
self.core.network_filter.unban_user(user)
self.output(_("Unbanned %s") % (" & ".join(unbanned_ip_addresses) or user))
def ignore_command(self, args, user=None, **_unused):
if self.core.network_filter.is_ip_address(args):
ignored_ip_address = self.core.network_filter.ignore_user_ip(ip_address=args)
else:
if args:
user = args
ignored_ip_address = None
self.core.network_filter.ignore_user(user)
self.output(_("Ignored %s") % (ignored_ip_address or user))
def unignore_command(self, args, user=None, **_unused):
if self.core.network_filter.is_ip_address(args):
unignored_ip_addresses = self.core.network_filter.unignore_user_ip(ip_address=args)
self.core.network_filter.unignore_user(self.core.network_filter.get_online_username(args))
else:
if args:
user = args
unignored_ip_addresses = self.core.network_filter.unignore_user_ip(user)
self.core.network_filter.unignore_user(user)
self.output(_("Unignored %s") % (" & ".join(unignored_ip_addresses) or user))
# Configure Shares #
def rescan_command(self, args, **_unused):
rebuild = ("rebuild" in args)
force = ("force" in args) or rebuild
self.core.shares.rescan_shares(rebuild=rebuild, force=force)
def list_shares_command(self, args, **_unused):
permission_levels = {
0: PermissionLevel.PUBLIC,
1: PermissionLevel.BUDDY,
2: PermissionLevel.TRUSTED
}
share_groups = self.core.shares.get_shared_folders()
num_total = num_listed = 0
for group_index, share_group in enumerate(share_groups):
permission_level = permission_levels.get(group_index)
num_shares = len(share_group)
num_total += num_shares
if not num_shares or args and permission_level not in args.lower():
continue
self.output("\n" + f"{num_shares} {permission_level} shares:")
for virtual_name, folder_path, *_ignored in share_group:
self.output(f'• "{virtual_name}" {folder_path}')
num_listed += num_shares
self.output("\n" + _("%(num_listed)s shares listed (%(num_total)s configured)") % {
"num_listed": num_listed,
"num_total": num_total
})
def share_command(self, args, **_unused):
permission_level, folder_path = args.split(maxsplit=1)
folder_path = folder_path.strip(' "')
virtual_name = self.core.shares.add_share(folder_path, permission_level=permission_level)
if not virtual_name:
self.output(_("Cannot share inaccessible folder \"%s\"") % folder_path)
return False
self.output(_("Added %(group_name)s share \"%(virtual_name)s\" (rescan required)") % {
"group_name": permission_level,
"virtual_name": virtual_name
})
return True
def unshare_command(self, args, **_unused):
virtual_name_or_folder_path = args.strip(' "')
if not self.core.shares.remove_share(virtual_name_or_folder_path):
self.output(_("No share with name \"%s\"") % virtual_name_or_folder_path)
return False
self.output(_("Removed share \"%s\" (rescan required)") % virtual_name_or_folder_path)
return True
# Search Files #
def search_command(self, args, **_unused):
self.core.search.do_search(args, "global")
def search_rooms_command(self, args, **_unused):
self.core.search.do_search(args, "rooms")
def search_buddies_command(self, args, **_unused):
self.core.search.do_search(args, "buddies")
def search_user_command(self, args, **_unused):
user, query = args.split(maxsplit=1)
self.core.search.do_search(query, "user", users=[user])
# Plugin Commands #
def plugin_handler_command(self, args, **_unused):
action, plugin_name = args.split(maxsplit=1)
if action == "toggle":
self.parent.toggle_plugin(plugin_name)
elif action == "reload":
self.parent.reload_plugin(plugin_name)
elif action == "info":
plugin_info = self.parent.get_plugin_info(plugin_name)
for key, value in plugin_info.items():
self.output(f"• {key}: {value}")
| 21,967 | Python | .py | 495 | 31.844444 | 113 | 0.530988 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,483 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/now_playing_sender/__init__.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from gi.repository import Gio
from pynicotine.pluginsystem import BasePlugin
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"rooms": ["testroom"]
}
self.metasettings = {
"rooms": {
"description": "Rooms to broadcast in",
"type": "list string"
}
}
self.last_song_url = ""
self.stop = False
self.bus = Gio.bus_get_sync(bus_type=Gio.BusType.SESSION)
self.signal_id = None
self.dbus_mpris_service = "org.mpris.MediaPlayer2."
self.add_mpris_signal_receiver()
def disable(self):
self.remove_mpris_signal_receiver()
def add_mpris_signal_receiver(self):
"""Receive updates related to MPRIS."""
self.signal_id = self.bus.signal_subscribe(
sender=None,
interface_name="org.freedesktop.DBus.Properties",
member="PropertiesChanged",
object_path="/org/mpris/MediaPlayer2",
arg0=None,
flags=Gio.DBusSignalFlags.NONE,
callback=self.song_change,
user_data=None
)
def remove_mpris_signal_receiver(self):
"""Stop receiving updates related to MPRIS."""
self.bus.signal_unsubscribe(self.signal_id)
def get_current_mpris_player(self):
"""Returns the MPRIS client currently selected in Now Playing."""
player = self.config.sections["players"]["npothercommand"]
if not player:
dbus_proxy = Gio.DBusProxy.new_sync(
connection=self.bus,
flags=Gio.DBusProxyFlags.NONE,
info=None,
name="org.freedesktop.DBus",
object_path="/org/freedesktop/DBus",
interface_name="org.freedesktop.DBus",
cancellable=None
)
names = dbus_proxy.ListNames()
for name in names:
if name.startswith(self.dbus_mpris_service):
player = name[len(self.dbus_mpris_service):]
break
return player
def get_current_mpris_song_url(self, player):
"""Returns the current song url for the selected MPRIS client."""
dbus_proxy = Gio.DBusProxy.new_sync(
connection=self.bus,
flags=Gio.DBusProxyFlags.NONE,
info=None,
name=self.dbus_mpris_service + player,
object_path="/org/mpris/MediaPlayer2",
interface_name="org.freedesktop.DBus.Properties",
cancellable=None
)
metadata = dbus_proxy.Get("(ss)", "org.mpris.MediaPlayer2.Player", "Metadata")
song_url = metadata.get("xesam:url")
return song_url
def send_now_playing(self):
"""Broadcast Now Playing in selected rooms."""
for room in self.settings["rooms"]:
playing = self.core.now_playing.get_np()
if playing:
self.send_public(room, playing)
def song_change(self, _connection, _sender_name, _object_path, _interface_name,
_signal_name, parameters, _user_data):
if self.config.sections["players"]["npplayer"] != "mpris":
# MPRIS is not active, exit
return
# Get the changed song url received from the the signal
try:
changed_song_url = parameters[1].get("Metadata").get("xesam:url")
except AttributeError:
return
if not changed_song_url:
# Song url empty, the player most likely stopped playing
self.last_song_url = ""
return
if changed_song_url == self.last_song_url:
# A new song didn't start playing, exit
return
try:
player = self.get_current_mpris_player()
selected_client_song_url = self.get_current_mpris_song_url(player)
except Exception as error:
# Selected player is invalid
self.log("Cannot retrieve currently playing song. Error: %s", error)
return
if selected_client_song_url != changed_song_url:
# Song change was from another MPRIS client than the selected one, exit
return
# Keep track of which song is playing
self.last_song_url = changed_song_url
self.send_now_playing()
| 5,196 | Python | .py | 123 | 32.203252 | 86 | 0.612865 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,484 | choices.py | nicotine-plus_nicotine-plus/pynicotine/plugins/examplars/preferences/choices.py | # COPYRIGHT (C) 2021-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
class Plugin(BasePlugin):
"""Radio Button/Dropdown Example."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"player_radio": 2, # id, starts from 0
"player_dropdown": "Clementine" # can be either string or id starting from 0
}
self.metasettings = {
"player_radio": {
"description": "Choose an audio player",
"type": "radio",
"options": (
"Exaile",
"Audacious",
"Clementine"
)
},
"player_dropdown": {
"description": "Choose an audio player",
"type": "dropdown",
"options": (
"Exaile",
"Audacious",
"Clementine"
)
}
}
| 1,742 | Python | .py | 46 | 28.73913 | 90 | 0.576923 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,485 | filechooser.py | nicotine-plus_nicotine-plus/pynicotine/plugins/examplars/preferences/filechooser.py | # COPYRIGHT (C) 2021-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
class Plugin(BasePlugin):
"""File Chooser Example."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"file": "/home/example/file.pdf",
"folder": "/home/example/folder",
"image": "/home/example/image.jpg",
}
self.metasettings = {
"file": {
"description": "Select a file",
"type": "file",
"chooser": "file"},
"folder": {
"description": "Select a folder",
"type": "file",
"chooser": "folder"},
"image": {
"description": "Select an image",
"type": "file",
"chooser": "image"},
}
| 1,579 | Python | .py | 41 | 30.926829 | 71 | 0.605744 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,486 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/examplars/testreplier/__init__.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
# COPYRIGHT (C) 2008-2010 quinox <quinox@users.sf.net>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from random import choice
from pynicotine.pluginsystem import BasePlugin, ResponseThrottle
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"replies": ["Test failed."]
}
self.metasettings = {
"replies": {
"description": "Replies:",
"type": "list string"
}
}
self.throttle = ResponseThrottle(self.core, self.human_name)
def incoming_public_chat_event(self, room, user, line):
if line.lower() != "test":
return
if self.throttle.ok_to_respond(room, user, line):
self.throttle.responded()
self.send_public(room, choice(self.settings["replies"]).lstrip("!"))
| 1,606 | Python | .py | 39 | 35.410256 | 80 | 0.673732 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,487 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/examplars/commands/__init__.py | # COPYRIGHT (C) 2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.commands = {
"sample": {
"aliases": ["demo"],
"description": "Sample command description",
"disable": ["private_chat"],
"callback": self.sample_command,
"callback_private_chat": self.sample_command,
"parameters": ["<choice1|choice2>", "<something..>"],
"parameters_chatroom": ["<choice55|choice2>"]
}
}
def sample_command(self, _args, **_unused):
self.output("Hello")
| 1,440 | Python | .py | 34 | 35.970588 | 71 | 0.656183 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,488 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/examplars/memory_debugger/__init__.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
# COPYRIGHT (C) 2009 quinox <quinox@users.sf.net>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import gc
from pynicotine.pluginsystem import BasePlugin
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
import tracemalloc
super().__init__(*args, **kwargs)
self.log(
"Tweaking garbage collection. Is it currently turned on? %s\n"
"Current thresholds: %s\n"
"Current counts: %s\n"
"Enabling GB debug output (check stderr)\n"
"Enabling tracemalloc",
(str(gc.isenabled()), repr(gc.get_threshold()), repr(gc.get_count()))) # pylint: disable=no-member
gc.set_debug(gc.DEBUG_STATS | gc.DEBUG_COLLECTABLE | gc.DEBUG_UNCOLLECTABLE) # pylint: disable=no-member
tracemalloc.start() # pylint: disable=no-member
for i in range(3):
self.log("Forcing collection of generation %s...", i)
self.log("Collected %s objects", gc.collect(i))
unclaimed = [f"A total of {len(gc.garbage)} objects that could not be freed:"]
for i in gc.garbage:
unclaimed.append(f"{type(i)}: {str(i)} ({repr(i)})")
self.log("\n".join(unclaimed))
self.log("Done.")
def disable(self):
import tracemalloc
gc.set_debug(0) # pylint: disable=no-member
snapshot = tracemalloc.take_snapshot()
self.log("[ Top 50 memory allocations ]\n")
for i in range(50):
memory_stat = snapshot.statistics("lineno")[i]
self.log(memory_stat)
tb_stat = snapshot.statistics("traceback")[i]
self.log("%s memory blocks: %.1f KiB", (tb_stat.count, tb_stat.size / 1024))
for line in tb_stat.traceback.format():
self.log(line)
self.log("")
tracemalloc.stop() # pylint: disable=no-member
| 2,643 | Python | .py | 55 | 40.636364 | 113 | 0.634593 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,489 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/examplars/port_checker/__init__.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2008-2011 quinox <quinox@users.sf.net>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import socket
import threading
from pynicotine.pluginsystem import BasePlugin, ResponseThrottle
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"keyword_enabled": False,
"socket_timeout": 10
}
self.metasettings = {
"keyword_enabled": {
"description": 'Enable "portscan" keyword trigger',
"type": "bool"
},
"socket_timeout": {
"description": "Socket timeout (in seconds)",
"type": "int"
}
}
self.commands = {
"port": {
"callback": self.port_checker_command,
"description": "Check firewall state of user",
"parameters": ["<user>"],
"parameters_private_chat": ["[user]"]
}
}
self.throttle = ResponseThrottle(self.core, self.human_name)
self.checkroom = "nicotine"
def incoming_public_chat_notification(self, room, user, line):
if room != self.checkroom or not self.settings["keyword_enabled"] or self.core.users.login_username == user:
return
if not self.throttle.ok_to_respond(room, user, line, 10):
return
if "portscan" in line.lower():
self.log("%s requested a port scan", user)
self.resolve(user, True)
def resolve(self, user, announce):
user_address = self.core.users.addresses.get(user)
if user_address is not None:
ip_address, port = user_address
threading.Thread(target=self.check_port, args=(user, ip_address, port, announce)).start()
def check_port(self, user, ip_address, port, announce):
status = self._check_port(ip_address, port)
if announce and status in {"open", "closed"}:
self.throttle.responded()
self.send_public(self.checkroom, f"{user}: Your port is {status}")
self.log("User %s on %s:%s port is %s.", (user, ip_address, port, status))
def _check_port(self, ip_address, port):
if ip_address == "0.0.0.0" or not port:
return "unknown"
timeout = self.settings["socket_timeout"]
self.log("Scanning %s:%d (socket timeout %d seconds)...", (ip_address, port, timeout))
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(timeout)
result = sock.connect_ex((ip_address, port))
sock.close()
if not result:
return "open"
return "closed"
def port_checker_command(self, args, user=None, **_room):
if args:
user = args
self.resolve(user, False)
| 3,571 | Python | .py | 83 | 34.409639 | 116 | 0.618786 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,490 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/plugin_debugger/__init__.py | # COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
# COPYRIGHT (C) 2009 quinox <quinox@users.sf.net>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.log("__init__()")
def init(self):
self.log("init()")
def disable(self):
self.log("disable()")
def loaded_notification(self):
self.log("loaded_notification()")
def unloaded_notification(self):
self.log("unloaded_notification()")
def shutdown_notification(self):
self.log("shutdown_notification()")
def public_room_message_notification(self, room, user, line):
self.log("public_room_message_notification(room=%s, user=%s, line=%s)", (room, user, line))
def search_request_notification(self, searchterm, user, token):
self.log("search_request_notification(searchterm=%s, user=%s, token=%s)", (searchterm, user, token))
def distrib_search_notification(self, searchterm, user, token):
# Verbose:
# self.log('distrib_search_notification(searchterm=%s, user=%s, token=%s)', (searchterm, user, token))
pass
def incoming_private_chat_event(self, user, line):
self.log("incoming_private_chat_event(user=%s, line=%s)", (user, line))
def incoming_private_chat_notification(self, user, line):
self.log("incoming_private_chat_notification(user=%s, line=%s)", (user, line))
def incoming_public_chat_event(self, room, user, line):
self.log("incoming_public_chat_event(room=%s, user=%s, line=%s)", (room, user, line))
def incoming_public_chat_notification(self, room, user, line):
self.log("incoming_public_chat_notification(room=%s, user=%s, line=%s)", (room, user, line))
def outgoing_private_chat_event(self, user, line):
self.log("outgoing_private_chat_event(user=%s, line=%s)", (user, line))
def outgoing_private_chat_notification(self, user, line):
self.log("outgoing_private_chat_notification(user=%s, line=%s)", (user, line))
def outgoing_public_chat_event(self, room, line):
self.log("outgoing_public_chat_event(room=%s, line=%s)", (room, line))
def outgoing_public_chat_notification(self, room, line):
self.log("outgoing_public_chat_notification(room=%s, line=%s)", (room, line))
def outgoing_global_search_event(self, text):
self.log("outgoing_global_search_event(text=%s)", (text,))
def outgoing_room_search_event(self, rooms, text):
self.log("outgoing_room_search_event(rooms=%s, text=%s)", (rooms, text))
def outgoing_buddy_search_event(self, text):
self.log("outgoing_buddy_search_event(text=%s)", (text,))
def outgoing_user_search_event(self, users, text):
self.log("outgoing_user_search_event(users=%s, text=%s)", (users, text))
def user_resolve_notification(self, user, ip_address, port, country):
self.log("user_resolve_notification(user=%s, ip_address=%s, port=%s, country=%s)",
(user, ip_address, port, country))
def server_connect_notification(self):
self.log("server_connect_notification()")
def server_disconnect_notification(self, userchoice):
self.log("server_disconnect_notification(userchoice=%s)", (userchoice,))
def join_chatroom_notification(self, room):
self.log("join_chatroom_notification(room=%s)", (room,))
def leave_chatroom_notification(self, room):
self.log("leave_chatroom_notification(room=%s)", (room,))
def user_join_chatroom_notification(self, room, user):
self.log("user_join_chatroom_notification(room=%s, user=%s)", (room, user,))
def user_leave_chatroom_notification(self, room, user):
self.log("user_leave_chatroom_notification(room=%s, user=%s)", (room, user,))
def user_stats_notification(self, user, stats):
self.log("user_stats_notification(user=%s, stats=%s)", (user, stats))
def user_status_notification(self, user, status, privileged):
self.log("user_status_notification(user=%s, status=%s, privileged=%s)", (user, status, privileged))
def upload_queued_notification(self, user, virtual_path, real_path):
self.log("upload_queued_notification(user=%s, virtual_path=%s, real_path=%s)",
(user, virtual_path, real_path))
def upload_started_notification(self, user, virtual_path, real_path):
self.log("upload_started_notification(user=%s, virtual_path=%s, real_path=%s)",
(user, virtual_path, real_path))
def upload_finished_notification(self, user, virtual_path, real_path):
self.log("upload_finished_notification(user=%s, virtual_path=%s, real_path=%s)",
(user, virtual_path, real_path))
def download_started_notification(self, user, virtual_path, real_path):
self.log("download_started_notification(user=%s, virtual_path=%s, real_path=%s)",
(user, virtual_path, real_path))
def download_finished_notification(self, user, virtual_path, real_path):
self.log("download_finished_notification(user=%s, virtual_path=%s, real_path=%s)",
(user, virtual_path, real_path))
| 5,930 | Python | .py | 99 | 52.979798 | 110 | 0.681057 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,491 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/leech_detector/__init__.py | # COPYRIGHT (C) 2020-2024 Nicotine+ Contributors
# COPYRIGHT (C) 2011 quinox <quinox@users.sf.net>
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from pynicotine.pluginsystem import BasePlugin
class Plugin(BasePlugin):
PLACEHOLDERS = {
"%files%": "num_files",
"%folders%": "num_folders"
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"message": "Please consider sharing more files if you would like to download from me again. Thanks :)",
"open_private_chat": True,
"num_files": 1,
"num_folders": 1,
"detected_leechers": []
}
self.metasettings = {
"message": {
"description": ("Private chat message to send to leechers. Each line is sent as a separate message, "
"too many message lines may get you temporarily banned for spam!"),
"type": "textview"
},
"open_private_chat": {
"description": "Open chat tabs when sending private messages to leechers",
"type": "bool"
},
"num_files": {
"description": "Require users to have a minimum number of shared files:",
"type": "int", "minimum": 0
},
"num_folders": {
"description": "Require users to have a minimum number of shared folders:",
"type": "int", "minimum": 1
},
"detected_leechers": {
"description": "Detected leechers",
"type": "list string"
}
}
self.probed_users = {}
def loaded_notification(self):
min_num_files = self.metasettings["num_files"]["minimum"]
min_num_folders = self.metasettings["num_folders"]["minimum"]
if self.settings["num_files"] < min_num_files:
self.settings["num_files"] = min_num_files
if self.settings["num_folders"] < min_num_folders:
self.settings["num_folders"] = min_num_folders
self.log(
"Require users have a minimum of %d files in %d shared public folders.",
(self.settings["num_files"], self.settings["num_folders"])
)
def check_user(self, user, num_files, num_folders, source="server"):
if user not in self.probed_users:
# We are not watching this user
return
if self.probed_users[user] == "okay":
# User was already accepted previously, nothing to do
return
if self.probed_users[user] == "requesting_shares" and source != "peer":
# Waiting for stats from peer, but received stats from server. Ignore.
return
is_user_accepted = (num_files >= self.settings["num_files"] and num_folders >= self.settings["num_folders"])
if is_user_accepted or user in self.core.buddies.users:
if user in self.settings["detected_leechers"]:
self.settings["detected_leechers"].remove(user)
self.probed_users[user] = "okay"
if is_user_accepted:
self.log("User %s is okay, sharing %s files in %s folders.", (user, num_files, num_folders))
else:
self.log("Buddy %s is sharing %s files in %s folders. Not complaining.",
(user, num_files, num_folders))
return
if not self.probed_users[user].startswith("requesting"):
# We already dealt with the user this session
return
if user in self.settings["detected_leechers"]:
# We already messaged the user in a previous session
self.probed_users[user] = "processed_leecher"
return
if (num_files <= 0 or num_folders <= 0) and self.probed_users[user] != "requesting_shares":
# SoulseekQt only sends the number of shared files/folders to the server once on startup.
# Verify user's actual number of files/folders.
self.log("User %s has no shared files according to the server, requesting shares to verify…", user)
self.probed_users[user] = "requesting_shares"
self.core.userbrowse.request_user_shares(user)
return
if self.settings["message"]:
log_message = ("Leecher detected, %s is only sharing %s files in %s folders. Going to message "
"leecher after transfer…")
else:
log_message = ("Leecher detected, %s is only sharing %s files in %s folders. Going to log "
"leecher after transfer…")
self.probed_users[user] = "pending_leecher"
self.log(log_message, (user, num_files, num_folders))
def upload_queued_notification(self, user, virtual_path, real_path):
if user in self.probed_users:
return
self.probed_users[user] = "requesting_stats"
if user not in self.core.users.watched:
# Transfer manager will request the stats from the server shortly
return
# We've received the user's stats in the past. They could be outdated by
# now, so request them again.
self.core.users.request_user_stats(user)
def user_stats_notification(self, user, stats):
self.check_user(user, num_files=stats["files"], num_folders=stats["dirs"], source=stats["source"])
def upload_finished_notification(self, user, *_):
if user not in self.probed_users:
return
if self.probed_users[user] != "pending_leecher":
return
self.probed_users[user] = "processed_leecher"
if not self.settings["message"]:
self.log("Leecher %s doesn't share enough files. No message is specified in plugin settings.", user)
return
for line in self.settings["message"].splitlines():
for placeholder, option_key in self.PLACEHOLDERS.items():
# Replace message placeholders with actual values specified in the plugin settings
line = line.replace(placeholder, str(self.settings[option_key]))
self.send_private(user, line, show_ui=self.settings["open_private_chat"], switch_page=False)
if user not in self.settings["detected_leechers"]:
self.settings["detected_leechers"].append(user)
self.log("Leecher %s doesn't share enough files. Message sent.", user)
| 7,176 | Python | .py | 140 | 40.35 | 117 | 0.612335 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,492 | __init__.py | nicotine-plus_nicotine-plus/pynicotine/plugins/youtube_info/__init__.py | # COPYRIGHT (C) 2021-2023 Nicotine+ Contributors
# COPYRIGHT (C) 2021 Inso-m-niaC
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import json
import re
from pynicotine.pluginsystem import BasePlugin
from pynicotine.utils import human_length
from pynicotine.utils import humanize
class Plugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.settings = {
"api_key": "",
"color": "Local",
"format": [
"* Title: %title%",
"* Duration: %duration% - Views: %views%"]
}
self.metasettings = {
"api_key": {
"description": "YouTube Data v3 API key:",
"type": "string"
},
"color": {
"description": "Message color:",
"type": "dropdown",
"options": ("Remote", "Local", "Action", "Hilite")
},
"format": {
"description": "Message format",
"type": "list string"
}
}
self.last_video_id = {
"private": {},
"public": {}
}
def incoming_public_chat_notification(self, room, user, line):
if (self.core.network_filter.is_user_ignored(user)
or self.core.network_filter.is_user_ip_ignored(user)):
return
video_id = self.get_video_id("public", room, line)
if not video_id:
return
parsed = self.parse_response(video_id)
if not parsed:
return
for msg in self.settings["format"]:
self.echo_public(room, self.str_replace(msg, parsed), self.settings["color"].lower())
def incoming_private_chat_notification(self, user, line):
if (self.core.network_filter.is_user_ignored(user)
or self.core.network_filter.is_user_ip_ignored(user)):
return
video_id = self.get_video_id("private", user, line)
if not video_id:
return
parsed = self.parse_response(video_id)
if not parsed:
return
for msg in self.settings["format"]:
self.echo_private(user, self.str_replace(msg, parsed), self.settings["color"].lower())
def get_video_id(self, mode, source, line):
match = re.search(r"(https?://((m|music)\.)?|www\.)youtu(\.be/|be\.com/(shorts/|watch\S+v=))"
r"(?P<video_id>[-\w]{11})", line)
if not match:
return None
video_id = match.group("video_id")
if source in self.last_video_id[mode] and self.last_video_id[mode][source] == video_id:
return None
self.last_video_id[mode][source] = video_id
return video_id
def parse_response(self, video_id):
api_key = self.settings["api_key"]
if not api_key:
self.log("No API key specified")
return None
try:
from urllib.request import urlopen
with urlopen((f"https://www.googleapis.com/youtube/v3/videos?part=snippet,statistics,contentDetails"
f"&id={video_id}&key={api_key}"), timeout=10) as response:
response_body = response.read().decode("utf-8", "replace")
except Exception as error:
self.log("Failed to connect to www.googleapis.com: %s", error)
return None
try:
data = json.loads(response_body)
except Exception as error:
self.log("Failed to parse response from www.googleapis.com: %s", error)
return None
if "error" in data:
error_message = data["error"].get("message", False)
if not error_message:
# This should not occur
error_message = data["error"]
self.log(error_message)
return None
total_results = data.get("pageInfo", {}).get("totalResults", False)
if not total_results:
if isinstance(total_results, int):
# Video removed / invalid id
self.log("Video unavailable")
elif isinstance(total_results, bool):
# This should not occur
self.log("Youtube API appears to be broken")
return None
try:
data = data["items"][0]
title = data["snippet"]["title"]
description = data["snippet"]["description"]
channel = data["snippet"]["channelTitle"]
live = data["snippet"]["liveBroadcastContent"]
duration = data["contentDetails"]["duration"]
quality = data["contentDetails"]["definition"].upper()
views = data["statistics"].get("viewCount", "RESTRICTED")
likes = data["statistics"].get("likeCount", "LIKES")
except KeyError:
# This should not occur
self.log('An error occurred while parsing id "%s"', video_id)
return None
if likes != "LIKES":
likes = humanize(int(likes))
if views != "RESTRICTED":
views = humanize(int(views))
if live in {"live", "upcoming"}:
duration = live.upper()
else:
duration = self.get_duration(duration)
return {
"%title%": title, "%description%": description, "%duration%": duration, "%quality%": quality,
"%channel%": channel, "%views%": views, "%likes%": likes
}
@staticmethod
def str_replace(subject, replacements):
for string, replacement in replacements.items():
if string in subject:
subject = subject.replace(string, replacement)
return subject
@staticmethod
def get_duration(iso_8601_duration):
seconds = 0
intervals = {"D": 86400, "H": 3600, "M": 60, "S": 1}
for num, designator in re.findall(r"(\d+)([DHMS])", iso_8601_duration):
seconds += intervals[designator] * int(num)
return human_length(seconds)
| 6,729 | Python | .py | 159 | 31.823899 | 112 | 0.576227 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,493 | upload_pypi_release.py | nicotine-plus_nicotine-plus/packaging/pypi/upload_pypi_release.py | #!/usr/bin/env python3
# COPYRIGHT (C) 2020-2023 Nicotine+ Contributors
#
# GNU GENERAL PUBLIC LICENSE
# Version 3, 29 June 2007
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import subprocess
import sys
def create_packages():
"""Prepare source distribution and wheel."""
subprocess.check_call([sys.executable, "-m", "build", "--sdist", "--wheel"])
def upload_packages():
"""Upload release to PyPI."""
subprocess.check_call([sys.executable, "-m", "twine", "upload", "dist/*"])
if __name__ == "__main__":
create_packages()
upload_packages()
| 1,166 | Python | .pyp | 29 | 38.068966 | 80 | 0.73227 | nicotine-plus/nicotine-plus | 1,670 | 133 | 79 | GPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,494 | update_license_header.py | pupil-labs_pupil/update_license_header.py | """
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) 2012-2021 Pupil Labs
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
---------------------------------------------------------------------------~(*)
"""
import argparse
import fnmatch
import os
import re
license_txt = """\
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) Pupil Labs
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
---------------------------------------------------------------------------~(*)\
"""
pattern = re.compile(
"(\"{3}|'{3}|[/][*])\n\\([*]\\)~(.+?)~\\([*]\\)\n(\"{3}|'{3}|[*][/])(\r\n|\r|\n)*",
re.DOTALL | re.MULTILINE,
)
# choose files types to include
# choose directories to exclude from search
includes = ["*.py", "*.c", "*.cpp", "*.hpp", "*.h", "*.pxd", "*.pyx", "*.pxi"]
excludes = [
"recordings*",
"shader.py",
"singleeyefitter*",
"vertex_buffer.py",
"gprof2dot.py",
"git_version.py",
"transformations.py",
"libuvcc*",
".gitignore",
"version_utils.py",
"update_license_header.py",
".venv*",
]
# transform glob patterns to regular expressions
includes = r"|".join([fnmatch.translate(x) for x in includes])
excludes = r"|".join([fnmatch.translate(x) for x in excludes]) or r"$."
def get_files(start_dir, includes, excludes):
# use os.walk to recursively dig down into the Pupil directory
match_files = []
for root, dirs, files in os.walk(start_dir):
if not re.search(excludes, root):
files = [
f
for f in files
if re.search(includes, f) and not re.search(excludes, f)
]
files = [os.path.join(root, f) for f in files]
match_files += files
else:
print("Excluding '%s'" % root)
return match_files
def write_header(file_name, license_txt, delete_header=False, dry_run: bool = False):
# find and replace license header
# or add new header if not existing
c_comment = ["/*\n", "\n*/\n"]
py_comment = ['"""\n', '\n"""\n']
file_type = os.path.splitext(file_name)[-1]
if file_type in (".py", ".pxd", ".pyx", ".pxi"):
license_txt = py_comment[0] + license_txt + py_comment[1]
elif file_type in (".c", ".cpp", ".hpp", ".h"):
license_txt = c_comment[0] + license_txt + c_comment[1]
else:
raise Exception("Dont know how to deal with this filetype")
try:
with open(file_name) as original:
data = original.read()
except UnicodeDecodeError:
return
if not dry_run:
with open(file_name, "w") as modified:
if re.findall(pattern, data):
if delete_header:
license_txt = ""
# if header already exists, then update, but dont add the last newline.
modified.write(re.sub(pattern, license_txt, data))
else:
# else write the license header
modified.write(license_txt + data)
else:
print(f"Would have modified {file_name}")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--directory", default=".")
parser.add_argument("--delete", action="store_true")
parser.add_argument("-n", "--dry-run", action="store_true")
args = parser.parse_args()
# Add a license/docstring header to selected files
match_files = get_files(args.directory, includes, excludes)
print(f"Number of files to check: {len(match_files)}")
for f in match_files:
print(f"Checking {f}")
write_header(f, license_txt, delete_header=args.delete, dry_run=args.dry_run)
| 3,956 | Python | .py | 102 | 32.813725 | 87 | 0.560626 | pupil-labs/pupil | 1,451 | 673 | 73 | LGPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,495 | runtime_hook_sounddevice.py | pupil-labs_pupil/deployment/runtime_hook_sounddevice.py | """Workaround to find sounddevice on Linux during runtime
See this issue for details:
https://github.com/spatialaudio/python-sounddevice/issues/130#issuecomment-1367883016
"""
import ctypes.util
import functools
import logging
logger = logging.getLogger(__name__)
logger.debug("Patching `ctypes.util.find_library` to find sounddevice...")
_find_library_original = ctypes.util.find_library
@functools.wraps(_find_library_original)
def _find_library_patched(name):
if name == "portaudio":
return "libportaudio.so.2"
else:
return _find_library_original(name)
ctypes.util.find_library = _find_library_patched
import sounddevice
logger.info("sounddevice import successful!")
logger.debug("Restoring original `ctypes.util.find_library`...")
ctypes.util.find_library = _find_library_original
del _find_library_patched
logger.debug("Original `ctypes.util.find_library` restored.")
| 907 | Python | .py | 23 | 36.956522 | 85 | 0.787185 | pupil-labs/pupil | 1,451 | 673 | 73 | LGPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,496 | linux.py | pupil-labs_pupil/deployment/_packaging/linux.py | import pathlib
import shutil
import subprocess
from . import ParsedVersion
def create_zipped_deb_packages(dist_root: pathlib.Path, app_version: ParsedVersion):
deb_folder = dist_root / "debs"
deb_folder.mkdir(exist_ok=True)
for folder in dist_root.glob("Pupil */"):
deb_pkg = create_deb_package(dist_root, folder.name, app_version)
deb_pkg.rename(deb_folder / deb_pkg.name)
shutil.make_archive(str(dist_root), "zip", deb_folder)
def create_deb_package(
dist_root: pathlib.Path, app_name: str, app_version: ParsedVersion
) -> pathlib.Path:
# lets build the structure for our deb package_name.
package_name = app_name.lower().replace(" ", "_")
deb_folder = f"{package_name}_v{app_version}"
deb_root = (dist_root / deb_folder).resolve()
if deb_root.exists():
shutil.rmtree(str(deb_root))
control = deb_root / "DEBIAN" / "control"
desktop = deb_root / "usr" / "share" / "applications" / f"{package_name}.desktop"
starter = deb_root / "usr" / "local" / "bin" / package_name
opt_dir = deb_root / "opt"
ico_dir = deb_root / "usr" / "share" / "icons" / "hicolor" / "scalable" / "apps"
control.parent.mkdir(mode=0o755, exist_ok=True, parents=True)
starter.parent.mkdir(mode=0o755, exist_ok=True, parents=True)
desktop.parent.mkdir(mode=0o755, exist_ok=True, parents=True)
ico_dir.mkdir(mode=0o755, exist_ok=True, parents=True)
startup_WM_class = app_name
if startup_WM_class == "Pupil Capture":
startup_WM_class += " - World"
# DEB control file
with control.open("w") as f:
dist_size = sum(f.stat().st_size for f in dist_root.rglob("*"))
content = f"""\
Package: {package_name.replace("_", "-")}
Version: {app_version}
Architecture: amd64
Maintainer: Pupil Labs <info@pupil-labs.com>
Priority: optional
Description: {app_name} - Find more information on https://docs.pupil-labs.com/core/
Installed-Size: {round(dist_size / 1024)}
"""
# See this link regarding the calculation of the Installed-Size field
# https://www.debian.org/doc/debian-policy/ch-controlfields.html#installed-size
f.write(content)
control.chmod(0o644)
# bin_starter script
with starter.open("w") as f:
content = f'''\
#!/bin/sh
exec /opt/{package_name}/{package_name} "$@"'''
f.write(content)
starter.chmod(0o755)
# .desktop entry
# ATTENTION: In order for the bundle icon to display correctly
# two things are necessary:
# 1. Icon needs to be the icon's base name/stem
# 2. The window title must be equivalent to StartupWMClass
with desktop.open("w") as f:
content = f"""\
[Desktop Entry]
Version={app_version}
Type=Application
Name={app_name}
Comment=Preview Pupil Invisible data streams
Exec=/opt/{package_name}/{package_name}
Terminal=false
Icon={package_name.replace('_', '-')}
Categories=Application;
Name[en_US]={app_name}
Actions=Terminal;
StartupWMClass={startup_WM_class}
[Desktop Action Terminal]
Name=Open in Terminal
Exec=x-terminal-emulator -e {package_name}"""
f.write(content)
desktop.chmod(0o644)
svg_file_name = f"{package_name.replace('_', '-')}.svg"
src_path = pathlib.Path("icons", svg_file_name)
dst_path = ico_dir / svg_file_name
shutil.copy(str(src_path), str(dst_path))
dst_path.chmod(0o755)
# copy the actual application
shutil.copytree(str(dist_root / app_name), str(opt_dir / package_name))
for f in opt_dir.rglob("*"):
if f.is_file():
if f.name == package_name:
f.chmod(0o755)
else:
f.chmod(0o644)
elif f.is_dir():
f.chmod(0o755)
opt_dir.chmod(0o755)
subprocess.call(["fakeroot", "dpkg-deb", "--build", deb_root])
shutil.rmtree(str(deb_root))
return deb_root.with_name(deb_root.name + ".deb")
| 3,872 | Python | .py | 98 | 34.540816 | 87 | 0.667288 | pupil-labs/pupil | 1,451 | 673 | 73 | LGPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,497 | windows.py | pupil-labs_pupil/deployment/_packaging/windows.py | import logging
import os
import pathlib
import re
import shutil
import subprocess
import textwrap
from contextlib import contextmanager
from typing import List
from uuid import UUID
from uuid import uuid4 as new_guid
from . import ParsedVersion
def create_compressed_msi(directory: pathlib.Path, parsed_version: ParsedVersion):
generate_msi_installer(directory, parsed_version)
subprocess.call(
[
r"C:\Program Files\WinRAR\Rar.exe",
"a",
f"{directory.name}.msi.rar",
f"{directory.name}.msi",
]
)
# NOTE: you will need to have the WiX Toolset installed in order to run this script!
# 1. Download `wix311.exe` from https://github.com/wixtoolset/wix3/releases/tag/wix3112rtm
# 2. Then install, e.g. to default location.
# 3. Now add the binaries to the PATH. For default installation, they should be in
# C:\Program Files (x86)\WiX Toolset v3.11\bin
def generate_msi_installer(base_dir: pathlib.Path, parsed_version: ParsedVersion):
logging.info(f"Generating msi installer for Pupil Core {parsed_version}")
# NOTE: MSI only allows versions in the form of x.x.x.x, where all x are
# integers, so we need to replace the '-' before patch with a '.'. Also we
# want to prefix 'v' for display.
raw_version = (
f"{parsed_version.major}.{parsed_version.minor}.{parsed_version.micro}"
)
version = f"v{raw_version}"
product_name = f"Pupil Core {version}"
company_short = "Pupil Labs"
manufacturer = "Pupil Labs GmbH"
package_description = f"{company_short} {product_name}"
# NOTE: Generating new GUIDs for product and upgrade code means that different
# installations will not conflict. This is the easiest workflow for enabling customers
# to install different versions alongside. This will however also mean that in the case
# of a patch, the users will always also have to uninstall the old version manually.
product_guid = new_guid()
product_upgrade_code = new_guid()
capture_data = SoftwareComponent(base_dir, "capture", version)
player_data = SoftwareComponent(base_dir, "player", version)
service_data = SoftwareComponent(base_dir, "service", version)
wix_file = base_dir / f"{base_dir.name}.wxs"
logging.debug(f"Generating WiX file at {wix_file}")
with wix_file.open("w") as f:
f.write(
fill_template(
capture_data=capture_data,
player_data=player_data,
service_data=service_data,
company_short=company_short,
manufacturer=manufacturer,
package_description=package_description,
product_name=product_name,
product_guid=product_guid,
product_upgrade_code=product_upgrade_code,
raw_version=raw_version,
version=version,
)
)
with set_directory(base_dir):
logging.debug("Running candle")
subprocess.call(
[
r"C:\Program Files (x86)\WiX Toolset v3.11\bin\candle.exe",
f"{base_dir.name}.wxs",
]
)
logging.debug("Running light")
subprocess.call(
[
r"C:\Program Files (x86)\WiX Toolset v3.11\bin\light.exe",
"-ext",
"WixUIExtension",
f"{base_dir.name}.wixobj",
]
)
logging.debug("Copy Installer")
shutil.move(f"{base_dir.name}.msi", f"../{base_dir.name}.msi")
logging.debug("Cleanup")
pathlib.Path(base_dir.name + ".wxs").unlink()
pathlib.Path(base_dir.name + ".wixobj").unlink()
pathlib.Path(base_dir.name + ".wixpdb").unlink()
logging.debug("Finished!")
@contextmanager
def set_directory(path: pathlib.Path):
# https://dev.to/teckert/changing-directory-with-a-python-context-manager-2bj8
origin = pathlib.Path().absolute()
try:
os.chdir(path)
yield
finally:
os.chdir(origin)
class SoftwareComponent:
"""Represents capture, player or service and collects all info for WiX XML."""
def __init__(self, base_dir: pathlib.Path, name: str, version: str):
self.name = name
self.dir = base_dir / f"Pupil {name.capitalize()}"
self.display_name = f"Pupil {self.name.capitalize()} {version}"
self.counter = 0
self.component_ids: list[str] = []
self.directory_root = []
self.crawl_directory(directory=self.dir, tree_root=self.directory_root)
def crawl_directory(
self, directory: pathlib.Path, tree_root: list[dict[str, str]]
) -> None:
for p in directory.iterdir():
self.counter += 1
if p.is_file():
if re.search(r"pupil_\w*\.exe", p.name):
# skip executable
continue
component: dict[str, str] = {
"type": "component",
"id": f"FileComponent{self.counter}{self.name}",
"guid": new_guid(),
"file_id": f"File{self.counter}{self.name}",
"file_name": p.name,
}
tree_root.append(component)
self.component_ids.append(component["id"])
else:
directory = {
"type": "directory",
"id": f"Dir{self.counter}{self.name}",
"name": p.name,
"content": [],
}
tree_root.append(directory)
self.crawl_directory(p, tree_root=directory["content"])
def parse_dir_data(self, root: List, indent: int = 0) -> str:
text = ""
for child in root:
if child["type"] == "component":
text += (
f"<Component Id='{child['id']}' Guid='{child['guid']}'>\n"
f" <File Id='{child['file_id']}' Name='{child['file_name']}' DiskId='1' KeyPath='yes' />\n"
f"</Component>\n"
)
elif child["type"] == "directory":
text += (
f"<Directory Id='{child['id']}' Name='{child['name']}'>\n"
f"{self.parse_dir_data(root=child['content'], indent=1)}"
f"</Directory>\n"
)
return textwrap.indent(text, " " * indent)
def directory_data(self) -> str:
cap = self.name.capitalize()
return f"""
<Directory Id='{cap}Dir' Name='{self.display_name}' FileSource="{self.dir.name}">
<Component Id='{cap}Executable' Guid='{new_guid()}'>
<File Id='{cap}EXE' Name='pupil_{self.name}.exe' DiskId='1' KeyPath='yes'>
<Shortcut Id="startmenu{cap}" Directory="ProgramMenuDir" Name="{self.display_name}" WorkingDirectory='INSTALLDIR' Icon="{cap}Icon.exe" IconIndex="0" Advertise="yes" />
<Shortcut Id="desktop{cap}" Directory="DesktopFolder" Name="{self.display_name}" WorkingDirectory='INSTALLDIR' Icon="{cap}Icon.exe" IconIndex="0" Advertise="yes" />
</File>
</Component>
{self.parse_dir_data(root=self.directory_root, indent=7).strip()}
</Directory>
"""
def feature_data(self) -> str:
cap = self.name.capitalize()
return f"""
<Feature Id='Pupil{cap}Feature' Title='Pupil {cap}' Description='The Pupil {cap} software component.' Level='1'>
<ComponentRef Id='{cap}Executable' />
{
"".join(f'''
<ComponentRef Id='{component_id}' />'''
for component_id in self.component_ids
)
}
</Feature>
"""
def icon_data(self) -> str:
cap = self.name.capitalize()
return rf"""
<Icon Id="{cap}Icon.exe" SourceFile="{self.dir.name}\pupil_{self.name}.exe" />"""
def fill_template(
capture_data: SoftwareComponent,
player_data: SoftwareComponent,
service_data: SoftwareComponent,
company_short: str,
manufacturer: str,
package_description: str,
product_name: str,
product_guid: str | UUID,
product_upgrade_code: str | UUID,
raw_version: str,
version: str,
):
return f"""
<?xml version='1.0' encoding='windows-1252'?>
<Wix xmlns='http://schemas.microsoft.com/wix/2006/wi'>
<Product Name='{product_name}' Id='{product_guid}' UpgradeCode='{product_upgrade_code}'
Language='1033' Codepage='1252' Version='{raw_version}' Manufacturer='{manufacturer}'>
<Package Id='*' Keywords='Installer'
Description="{package_description}" Manufacturer='{manufacturer}'
InstallerVersion='100' Languages='1033' Compressed='yes' SummaryCodepage='1252'
InstallScope='perMachine' />
<Media Id='1' Cabinet='Cabinet.cab' EmbedCab='yes' DiskPrompt="CD-ROM #1" />
<Property Id='DiskPrompt' Value="{package_description} Installer [1]" />
<Directory Id='TARGETDIR' Name='SourceDir'>
<Directory Id='ProgramFilesFolder' Name='PFiles'>
<Directory Id='PupilLabs' Name='{company_short}'>
<Directory Id='INSTALLDIR' Name='{product_name}'>
{capture_data.directory_data()}
{player_data.directory_data()}
{service_data.directory_data()}
</Directory>
</Directory>
</Directory>
<Directory Id="ProgramMenuFolder" Name="Programs">
<Directory Id="ProgramMenuDir" Name="{product_name}">
<Component Id="ProgramMenuDir" Guid="{new_guid()}">
<RemoveFolder Id='ProgramMenuDir' On='uninstall' />
<RegistryValue Root='HKCU' Key='Software\\[Manufacturer]\\[ProductName]\\{version}' Type='string' Value='' KeyPath='yes' />
</Component>
</Directory>
</Directory>
<Directory Id="DesktopFolder" Name="Desktop" />
</Directory>
<Feature Id='Complete' Title='{product_name}' Description='The full suite of Pupil Capture, Player and Service.'
Display='collapse' Level='1' ConfigurableDirectory='INSTALLDIR'>
<ComponentRef Id='ProgramMenuDir' />
{capture_data.feature_data()}
{player_data.feature_data()}
{service_data.feature_data()}
</Feature>
{capture_data.icon_data()}
{player_data.icon_data()}
{service_data.icon_data()}
<WixVariable Id="WixUIBannerBmp" Value="..\\msi_graphics\\banner.bmp" />
<WixVariable Id="WixUIDialogBmp" Value="..\\msi_graphics\\dialog.bmp" />
<!--
Copied from https://github.com/wixtoolset/wix3/blob/2d8b37764ec8453dc78dbc91c0fd444feaa6666d/src/ext/UIExtension/wixlib/WixUI_FeatureTree.wxs
And adjusted to not contain the License Dialog anymore.
-->
<UI Id="WixUI_FeatureTree">
<TextStyle Id="WixUI_Font_Normal" FaceName="Tahoma" Size="8" />
<TextStyle Id="WixUI_Font_Bigger" FaceName="Tahoma" Size="12" />
<TextStyle Id="WixUI_Font_Title" FaceName="Tahoma" Size="9" Bold="yes" />
<Property Id="DefaultUIFont" Value="WixUI_Font_Normal" />
<Property Id="WixUI_Mode" Value="FeatureTree" />
<DialogRef Id="ErrorDlg" />
<DialogRef Id="FatalError" />
<DialogRef Id="FilesInUse" />
<DialogRef Id="MsiRMFilesInUse" />
<DialogRef Id="PrepareDlg" />
<DialogRef Id="ProgressDlg" />
<DialogRef Id="ResumeDlg" />
<DialogRef Id="UserExit" />
<Publish Dialog="ExitDialog" Control="Finish" Event="EndDialog" Value="Return" Order="999">1</Publish>
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="CustomizeDlg">NOT Installed</Publish>
<Publish Dialog="WelcomeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg">Installed AND PATCH</Publish>
<Publish Dialog="CustomizeDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" Order="1">Installed</Publish>
<Publish Dialog="CustomizeDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" Order="2">NOT Installed</Publish>
<Publish Dialog="CustomizeDlg" Control="Next" Event="NewDialog" Value="VerifyReadyDlg">1</Publish>
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="CustomizeDlg" Order="1">NOT Installed OR WixUI_InstallMode = "Change"</Publish>
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="MaintenanceTypeDlg" Order="2">Installed AND NOT PATCH</Publish>
<Publish Dialog="VerifyReadyDlg" Control="Back" Event="NewDialog" Value="WelcomeDlg" Order="3">Installed AND PATCH</Publish>
<Publish Dialog="MaintenanceWelcomeDlg" Control="Next" Event="NewDialog" Value="MaintenanceTypeDlg">1</Publish>
<Publish Dialog="MaintenanceTypeDlg" Control="ChangeButton" Event="NewDialog" Value="CustomizeDlg">1</Publish>
<Publish Dialog="MaintenanceTypeDlg" Control="RepairButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish>
<Publish Dialog="MaintenanceTypeDlg" Control="RemoveButton" Event="NewDialog" Value="VerifyReadyDlg">1</Publish>
<Publish Dialog="MaintenanceTypeDlg" Control="Back" Event="NewDialog" Value="MaintenanceWelcomeDlg">1</Publish>
</UI>
<UIRef Id="WixUI_Common" />
</Product>
</Wix>
""".strip()
| 13,888 | Python | .py | 276 | 38.789855 | 203 | 0.59463 | pupil-labs/pupil | 1,451 | 673 | 73 | LGPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,498 | macos.py | pupil-labs_pupil/deployment/_packaging/macos.py | import json
import logging
import os
import pathlib
import subprocess
from . import ParsedVersion
def package_bundles_as_dmg(base: pathlib.Path, version: ParsedVersion):
should_sign_and_notarize = (
os.environ.get("MACOS_SHOULD_SIGN_AND_NOTARIZE", "false").strip() == "true"
)
if should_sign_and_notarize:
for app in base.glob("*.app"):
sign_app(app)
logging.info(f"Creating dmg file for Pupil Core {version}")
dmg_file = create_dmg(create_and_fill_dmg_srcfolder(base), base.name, version)
sign_object(dmg_file)
notarize_bundle(dmg_file)
else:
logging.info("Skipping signing, notarization, and creation of dmg file")
for app in base.glob("*.app"):
app.rename(app.name)
def create_and_fill_dmg_srcfolder(
base: pathlib.Path, name: str = "bundles"
) -> pathlib.Path:
bundle_dir = base / name
bundle_dir.mkdir(exist_ok=True)
for app in base.glob("*.app"):
app.rename(bundle_dir / app.name)
applications_target = pathlib.Path("/Applications")
applications_symlink = bundle_dir / "Applications"
if applications_symlink.exists():
applications_symlink.unlink()
applications_symlink.symlink_to(applications_target, target_is_directory=True)
return bundle_dir
def create_dmg(
bundle_dir: pathlib.Path, name: str, version: ParsedVersion
) -> pathlib.Path:
volumen_size = get_size(bundle_dir)
dmg_name = f"{name}.dmg"
dmg_cmd = (
"hdiutil",
"create",
"-volname",
f"Install Pupil Core {version}",
"-srcfolder",
bundle_dir,
"-format",
"ULMO",
"-size",
f"{volumen_size}b ",
dmg_name,
)
subprocess.check_call(dmg_cmd)
return pathlib.Path(dmg_name)
def get_size(start_path: str | pathlib.Path = "."):
total_size = 0
for dirpath, _, filenames in os.walk(start_path):
for f in filenames:
fp = os.path.join(dirpath, f)
# skip if it is symbolic link
if not os.path.islink(fp):
total_size += os.path.getsize(fp)
return total_size
def sign_app(path: pathlib.Path):
for obj in path.rglob(".dylibs/*.dylib"):
sign_object(obj)
sign_object(path)
def sign_object(path: pathlib.Path):
logging.info(f"Attempting to sign '{path}'")
subprocess.check_call(
[
"codesign",
"--all-architectures",
"--force",
"--timestamp",
"--strict=all",
"--options",
"runtime",
"--entitlements",
"entitlements.plist",
"--continue",
"--verify",
"--verbose=4",
"-s",
os.environ["MACOS_CODESIGN_IDENTITY"],
str(path),
]
)
logging.info(f"Successfully signed '{path}'")
def notarize_bundle(path: pathlib.Path):
logging.info(f"Attempting to notarize '{path}'")
auth_args = [
"--apple-id",
os.environ["MACOS_NOTARYTOOL_APPLE_ID"],
"--team-id",
os.environ["MACOS_NOTARYTOOL_TEAM_ID"],
"--password",
os.environ["MACOS_NOTARYTOOL_APPSPECIFIC_PASSWORD"],
]
format_args = ["-f", "json"]
submit_result = subprocess.check_output(
["xcrun", "notarytool", "submit", str(path), *auth_args, *format_args]
)
submit_result = json.loads(submit_result)
logging.info(f"{submit_result['message']} (ID: {submit_result['id']})")
try:
wait_result = subprocess.check_output(
[
"xcrun",
"notarytool",
"wait",
submit_result["id"],
"--timeout",
"1h",
*auth_args,
*format_args,
]
)
wait_result = json.loads(wait_result)
logging.info(f"{wait_result['message']}. Status: {wait_result['status']}")
if wait_result["status"] == "Accepted":
staple_bundle_notarization(path)
logging.info(f"Successfully notarized '{path}'")
except subprocess.CalledProcessError:
logging.exception("Issue during processing notarization:")
log_result = subprocess.check_output(
[
"xcrun",
"notarytool",
"log",
submit_result["id"],
str(path.with_suffix(".json")),
*auth_args,
*format_args,
]
)
log_result = json.loads(log_result)
logging.info(f"Notarization logs saved to {log_result['location']}")
def staple_bundle_notarization(path: pathlib.Path):
subprocess.check_call(["xcrun", "stapler", "staple", "-v", str(path)])
| 4,747 | Python | .py | 140 | 25.521429 | 86 | 0.581243 | pupil-labs/pupil | 1,451 | 673 | 73 | LGPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |
30,499 | __init__.py | pupil-labs_pupil/deployment/_packaging/__init__.py | import enum
from version_utils import ParsedVersion, pupil_version, write_version_file
from . import linux, macos, windows
class SupportedPlatform(enum.Enum):
macos = "Darwin"
linux = "Linux"
windows = "Windows"
ICON_EXT = {
SupportedPlatform.macos: ".icns",
SupportedPlatform.linux: ".svg",
SupportedPlatform.windows: ".ico",
}
LIB_EXT = {
SupportedPlatform.macos: ".dylib",
SupportedPlatform.linux: ".so",
SupportedPlatform.windows: ".dll",
}
__all__ = [
"ParsedVersion",
"SupportedPlatform",
"ICON_EXT",
"LIB_EXT",
"linux",
"macos",
"pupil_version",
"windows",
"write_version_file",
]
| 667 | Python | .py | 28 | 20 | 74 | 0.672468 | pupil-labs/pupil | 1,451 | 673 | 73 | LGPL-3.0 | 9/5/2024, 5:14:14 PM (Europe/Amsterdam) |