Welcome to mirror list, hosted at ThFree Co, Russian Federation.

dev.gajim.org/gajim/gajim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorlovetox <philipp@hoerist.com>2022-07-24 13:33:05 +0300
committerlovetox <philipp@hoerist.com>2022-07-24 15:49:01 +0300
commitb0fbea240d0722c8fa5a1515ff327384f299f8b1 (patch)
treee5689a84fc99c88c25d713e4fdce5c3ede88ee6c
parent1514becae21286a3763927d9f24b258531762afc (diff)
refactor: Use single quotes
-rw-r--r--gajim/common/app.py36
-rw-r--r--gajim/common/application.py2
-rw-r--r--gajim/common/cert_store.py4
-rw-r--r--gajim/common/client.py12
-rw-r--r--gajim/common/const.py52
-rw-r--r--gajim/common/dbus/remote_control.py20
-rw-r--r--gajim/common/exceptions.py8
-rw-r--r--gajim/common/file_props.py6
-rw-r--r--gajim/common/helpers.py68
-rw-r--r--gajim/common/i18n.py16
-rw-r--r--gajim/common/idle.py4
-rw-r--r--gajim/common/jingle_content.py42
-rw-r--r--gajim/common/jingle_ft.py28
-rw-r--r--gajim/common/jingle_ftstates.py2
-rw-r--r--gajim/common/jingle_rtp.py28
-rw-r--r--gajim/common/jingle_session.py99
-rw-r--r--gajim/common/jingle_transport.py32
-rw-r--r--gajim/common/jingle_xtls.py34
-rw-r--r--gajim/common/logging_helpers.py56
-rw-r--r--gajim/common/modules/bits_of_binary.py8
-rw-r--r--gajim/common/modules/bytestream.py40
-rw-r--r--gajim/common/modules/httpupload.py2
-rw-r--r--gajim/common/modules/jingle.py16
-rw-r--r--gajim/common/passwords.py8
-rw-r--r--gajim/common/preview.py4
-rw-r--r--gajim/common/proxy65_manager.py52
-rw-r--r--gajim/common/regex.py8
-rw-r--r--gajim/common/setting_values.py8
-rw-r--r--gajim/common/settings.py2
-rw-r--r--gajim/common/storage/archive.py2
-rw-r--r--gajim/common/storage/base.py4
-rw-r--r--gajim/common/storage/cache.py12
-rw-r--r--gajim/gtk/account_wizard.py2
-rw-r--r--gajim/gtk/adhoc_muc.py4
-rw-r--r--gajim/gtk/application.py6
-rw-r--r--gajim/gtk/avatar.py4
-rw-r--r--gajim/gtk/builder.py2
-rw-r--r--gajim/gtk/conversation/rows/muc_subject.py2
-rw-r--r--gajim/gtk/css_config.py6
-rw-r--r--gajim/gtk/dialogs.py16
-rw-r--r--gajim/gtk/discovery.py318
-rw-r--r--gajim/gtk/features.py2
-rw-r--r--gajim/gtk/filetransfer.py56
-rw-r--r--gajim/gtk/groupchat_nick_completion.py4
-rw-r--r--gajim/gtk/groupchat_roster.py4
-rw-r--r--gajim/gtk/message_input.py4
-rw-r--r--gajim/gtk/preferences.py4
-rw-r--r--gajim/gtk/preview.py2
-rw-r--r--gajim/gtk/roster.py6
-rw-r--r--gajim/gtk/roster_item_exchange.py4
-rw-r--r--gajim/gtk/ssl_error_dialog.py2
-rw-r--r--gajim/gtk/synchronize_accounts.py4
-rw-r--r--gajim/gtk/tooltips.py8
-rw-r--r--gajim/gtk/util.py42
-rw-r--r--gajim/gtk/xml_console.py2
-rw-r--r--gajim/gui_interface.py20
-rw-r--r--gajim/plugins/repository.py4
-rwxr-xr-xmac/makebundle.py4
-rwxr-xr-xscripts/bump_version.py2
-rw-r--r--setup.py10
-rw-r--r--win/misc/depcheck.py48
61 files changed, 653 insertions, 654 deletions
diff --git a/gajim/common/app.py b/gajim/common/app.py
index 4a1d618ef..9d0544d34 100644
--- a/gajim/common/app.py
+++ b/gajim/common/app.py
@@ -339,18 +339,18 @@ def get_jid_without_resource(jid: str) -> str:
def get_number_of_accounts() -> int:
- """
+ '''
Return the number of ALL accounts
- """
+ '''
return len(connections.keys())
def get_number_of_connected_accounts(
accounts_list: Optional[list[str]] = None) -> int:
- """
+ '''
Returns the number of connected accounts. You can optionally pass an
accounts_list and if you do those will be checked, else all will be checked
- """
+ '''
connected_accounts = 0
if accounts_list is None:
accounts = connections.keys()
@@ -371,9 +371,9 @@ def get_available_clients() -> list[types.Client]:
def get_connected_accounts(exclude_local: bool = False) -> list[str]:
- """
+ '''
Returns a list of CONNECTED accounts
- """
+ '''
account_list: list[str] = []
for account in connections:
if account == 'Local' and exclude_local:
@@ -395,10 +395,10 @@ def get_accounts_sorted() -> list[str]:
def get_enabled_accounts_with_labels(
connected_only: bool = False,
private_storage_only: bool = False) -> list[list[str]]:
- """
+ '''
Returns a list with [account, account_label] entries.
Order by account_label
- """
+ '''
accounts: list[list[str]] = []
for acc in connections:
if connected_only and not account_is_connected(acc):
@@ -443,11 +443,11 @@ def get_transport_name_from_jid(
jid: str,
use_config_setting: bool = True) -> Optional[str]:
- """
+ '''
Returns 'gg', 'irc' etc
If JID is not from transport returns None.
- """
+ '''
# TODO: Rewrite/remove
# FIXME: jid can be None! one TB I saw had this problem:
@@ -485,9 +485,9 @@ def jid_is_transport(jid: str) -> bool:
def get_jid_from_account(account_name: str) -> str:
- """
+ '''
Return the jid we use in the given account
- """
+ '''
name = settings.get_account_setting(account_name, 'name')
hostname = settings.get_account_setting(account_name, 'hostname')
jid = name + '@' + hostname
@@ -501,9 +501,9 @@ def get_account_from_jid(jid: str) -> Optional[str]:
def get_hostname_from_account(account_name: str, use_srv: bool = False) -> str:
- """
+ '''
Returns hostname (if custom hostname is used, that is returned)
- """
+ '''
if use_srv and connections[account_name].connected_hostname:
return connections[account_name].connected_hostname
if settings.get_account_setting(account_name, 'use_custom_host'):
@@ -512,9 +512,9 @@ def get_hostname_from_account(account_name: str, use_srv: bool = False) -> str:
def get_notification_image_prefix(jid: str) -> str:
- """
+ '''
Returns the prefix for the notification images
- """
+ '''
transport_name = get_transport_name_from_jid(jid)
if transport_name in ['icq', 'facebook']:
prefix = transport_name
@@ -549,9 +549,9 @@ def add_recent_groupchat(account: str, room_jid: str, nickname: str) -> None:
def get_priority(account: str, show: str) -> int:
- """
+ '''
Return the priority an account must have
- """
+ '''
if not show:
show = 'online'
diff --git a/gajim/common/application.py b/gajim/common/application.py
index 2a58f80f0..2a2930946 100644
--- a/gajim/common/application.py
+++ b/gajim/common/application.py
@@ -203,7 +203,7 @@ class CoreApplication:
filename, lineno, line))
warnings.showwarning = warn_with_traceback
- warnings.filterwarnings(action="always")
+ warnings.filterwarnings(action='always')
def _network_status_changed(self,
monitor: Gio.NetworkMonitor,
diff --git a/gajim/common/cert_store.py b/gajim/common/cert_store.py
index 485a7a21e..9ec5e6fcb 100644
--- a/gajim/common/cert_store.py
+++ b/gajim/common/cert_store.py
@@ -51,7 +51,7 @@ class CertificateStore:
try:
cert = Gio.TlsCertificate.new_from_file(str(path))
except GLib.Error as error:
- log.warning('Can\'t load certificate: %s, %s', path, error)
+ log.warning("Can't load certificate: %s, %s", path, error)
continue
log.info('Loaded: %s', path.stem)
@@ -91,7 +91,7 @@ class CertificateStore:
error: Optional[GLib.Error],
path: Path):
if error is not None:
- log.error('Can\'t store certificate: %s', error.message)
+ log.error("Can't store certificate: %s", error.message)
return
log.info('Certificate stored: %s', path)
diff --git a/gajim/common/client.py b/gajim/common/client.py
index 9a57b91e1..acd3b5a06 100644
--- a/gajim/common/client.py
+++ b/gajim/common/client.py
@@ -349,10 +349,10 @@ class Client(Observable):
stanza=stanza))
def get_own_jid(self) -> JID:
- """
+ '''
Return the last full JID we received on a bind event.
In case we were never connected it returns the bare JID from config.
- """
+ '''
if self._client is not None:
jid = self._client.get_bound_jid()
if jid is not None:
@@ -381,7 +381,7 @@ class Client(Observable):
helpers.to_one_line(message))
if self._state.is_disconnecting:
- log.warning('Can\'t change status while '
+ log.warning("Can\'t change status while "
'disconnect is in progress')
return
@@ -472,9 +472,9 @@ class Client(Observable):
modules.send_stored_publish(self._account)
def send_stanza(self, stanza: Any) -> None:
- """
+ '''
Send a stanza untouched
- """
+ '''
return self._client.send_stanza(stanza)
def send_message(self, message: OutgoingMessage) -> None:
@@ -570,7 +570,7 @@ class Client(Observable):
def _schedule_reconnect(self) -> None:
self._set_state(ClientState.RECONNECT_SCHEDULED)
- log.info("Reconnect to %s in 3s", self._account)
+ log.info('Reconnect to %s in 3s', self._account)
self._reconnect_timer_source = GLib.timeout_add_seconds(
3, self._prepare_for_connect)
diff --git a/gajim/common/const.py b/gajim/common/const.py
index 0f0d45ef4..15feaffe0 100644
--- a/gajim/common/const.py
+++ b/gajim/common/const.py
@@ -424,38 +424,38 @@ LOCATION_DATA = {
SSLError = {
- 2: _("Unable to get issuer certificate"),
- 3: _("Unable to get certificate CRL"),
+ 2: _('Unable to get issuer certificate'),
+ 3: _('Unable to get certificate CRL'),
4: _("Unable to decrypt certificate's signature"),
5: _("Unable to decrypt CRL's signature"),
- 6: _("Unable to decode issuer public key"),
- 7: _("Certificate signature failure"),
- 8: _("CRL signature failure"),
- 9: _("Certificate is not yet valid"),
- 10: _("Certificate has expired"),
- 11: _("CRL is not yet valid"),
- 12: _("CRL has expired"),
+ 6: _('Unable to decode issuer public key'),
+ 7: _('Certificate signature failure'),
+ 8: _('CRL signature failure'),
+ 9: _('Certificate is not yet valid'),
+ 10: _('Certificate has expired'),
+ 11: _('CRL is not yet valid'),
+ 12: _('CRL has expired'),
13: _("Format error in certificate's notBefore field"),
14: _("Format error in certificate's notAfter field"),
15: _("Format error in CRL's lastUpdate field"),
16: _("Format error in CRL's nextUpdate field"),
- 17: _("Out of memory"),
- 18: _("Self signed certificate"),
- 19: _("Self signed certificate in certificate chain"),
- 20: _("Unable to get local issuer certificate"),
- 21: _("Unable to verify the first certificate"),
- 22: _("Certificate chain too long"),
- 23: _("Certificate revoked"),
- 24: _("Invalid CA certificate"),
- 25: _("Path length constraint exceeded"),
- 26: _("Unsupported certificate purpose"),
- 27: _("Certificate not trusted"),
- 28: _("Certificate rejected"),
- 29: _("Subject issuer mismatch"),
- 30: _("Authority and subject key identifier mismatch"),
- 31: _("Authority and issuer serial number mismatch"),
- 32: _("Key usage does not include certificate signing"),
- 50: _("Application verification failure"),
+ 17: _('Out of memory'),
+ 18: _('Self signed certificate'),
+ 19: _('Self signed certificate in certificate chain'),
+ 20: _('Unable to get local issuer certificate'),
+ 21: _('Unable to verify the first certificate'),
+ 22: _('Certificate chain too long'),
+ 23: _('Certificate revoked'),
+ 24: _('Invalid CA certificate'),
+ 25: _('Path length constraint exceeded'),
+ 26: _('Unsupported certificate purpose'),
+ 27: _('Certificate not trusted'),
+ 28: _('Certificate rejected'),
+ 29: _('Subject issuer mismatch'),
+ 30: _('Authority and subject key identifier mismatch'),
+ 31: _('Authority and issuer serial number mismatch'),
+ 32: _('Key usage does not include certificate signing'),
+ 50: _('Application verification failure'),
}
diff --git a/gajim/common/dbus/remote_control.py b/gajim/common/dbus/remote_control.py
index f91196cb7..0b839f847 100644
--- a/gajim/common/dbus/remote_control.py
+++ b/gajim/common/dbus/remote_control.py
@@ -101,10 +101,10 @@ INTERFACE_DESC = '''
def get_dbus_struct(obj: Any) -> GLib.Variant:
- """
+ '''
Recursively go through all the items and replace them with their casted dbus
equivalents
- """
+ '''
if isinstance(obj, str):
return GLib.Variant('s', obj)
if isinstance(obj, int):
@@ -299,10 +299,10 @@ class GajimRemote(Server):
@staticmethod
def change_status(status: str, message: str, account: str) -> bool:
- """
+ '''
change_status(status, message, account). Account is optional - if not
specified status is changed for all accounts
- """
+ '''
if status not in ('offline', 'online', 'chat', 'away', 'xa', 'dnd'):
status = ''
if account:
@@ -330,9 +330,9 @@ class GajimRemote(Server):
@staticmethod
def list_accounts() -> list[str]:
- """
+ '''
List register accounts
- """
+ '''
result = app.settings.get_active_accounts()
result_array: list[str] = []
if result:
@@ -342,9 +342,9 @@ class GajimRemote(Server):
@staticmethod
def account_info(account: str) -> dict[str, str]:
- """
+ '''
Show info on account: resource, jid, nick, prio, message
- """
+ '''
result: dict[str, str] = {}
if account in app.connections:
# account is valid
@@ -379,9 +379,9 @@ class GajimRemote(Server):
@staticmethod
def _contacts_as_dbus_structure(contact: BareContact
) -> dict[str, GLib.Variant]:
- """
+ '''
Get info from list of Contact objects and create dbus dict
- """
+ '''
contact_dict: dict[str, GLib.Variant] = {}
diff --git a/gajim/common/exceptions.py b/gajim/common/exceptions.py
index 52e8c809f..b21fcebff 100644
--- a/gajim/common/exceptions.py
+++ b/gajim/common/exceptions.py
@@ -19,9 +19,9 @@
class GajimGeneralException(Exception):
- """
+ '''
This exception is our general exception
- """
+ '''
def __init__(self, text: str = '') -> None:
Exception.__init__(self)
@@ -32,9 +32,9 @@ class GajimGeneralException(Exception):
class PluginsystemError(Exception):
- """
+ '''
Error in the pluginsystem
- """
+ '''
def __init__(self, text: str = '') -> None:
Exception.__init__(self)
diff --git a/gajim/common/file_props.py b/gajim/common/file_props.py
index c1170e76a..58f8c7d11 100644
--- a/gajim/common/file_props.py
+++ b/gajim/common/file_props.py
@@ -1,4 +1,4 @@
-"""
+'''
This module is in charge of taking care of all the information related to
individual files. Files are identified by the account name and its sid.
@@ -15,7 +15,7 @@ Exception: this class should not be instatiated
>>> fp2 = FilesProp.getFileProp('jabberid', '10')
>>> fp == fp2
True
-"""
+'''
from __future__ import annotations
@@ -173,6 +173,6 @@ class FileProp:
sid = property(getsid, setsid)
-if __name__ == "__main__":
+if __name__ == '__main__':
import doctest
doctest.testmod()
diff --git a/gajim/common/helpers.py b/gajim/common/helpers.py
index 53a7024a1..80173a68b 100644
--- a/gajim/common/helpers.py
+++ b/gajim/common/helpers.py
@@ -132,10 +132,10 @@ def parse_jid(jidstring: str) -> str:
def idn_to_ascii(host: str) -> str:
- """
+ '''
Convert IDN (Internationalized Domain Names) to ACE (ASCII-compatible
encoding)
- """
+ '''
from encodings import idna
labels = idna.dots.split(host)
converted_labels: list[str] = []
@@ -144,26 +144,26 @@ def idn_to_ascii(host: str) -> str:
converted_labels.append(idna.ToASCII(label).decode('utf-8'))
else:
converted_labels.append('')
- return ".".join(converted_labels)
+ return '.'.join(converted_labels)
def ascii_to_idn(host: str) -> str:
- """
+ '''
Convert ACE (ASCII-compatible encoding) to IDN (Internationalized Domain
Names)
- """
+ '''
from encodings import idna
labels = idna.dots.split(host)
converted_labels: list[str] = []
for label in labels:
converted_labels.append(idna.ToUnicode(label))
- return ".".join(converted_labels)
+ return '.'.join(converted_labels)
def parse_resource(resource: str) -> Optional[str]:
- """
+ '''
Perform stringprep on resource and return it
- """
+ '''
if not resource:
return None
@@ -304,9 +304,9 @@ def from_one_line(msg: str) -> str:
def get_uf_chatstate(chatstate: str) -> str:
- """
+ '''
Remove chatstate jargon and returns user friendly messages
- """
+ '''
if chatstate == 'active':
return _('is paying attention to the conversation')
if chatstate == 'inactive':
@@ -325,11 +325,11 @@ def exec_command(command: str,
use_shell: bool = False,
posix: bool = True
) -> None:
- """
+ '''
execute a command. if use_shell is True, we run the command as is it was
typed in a console. So it may be dangerous if you are not sure about what
is executed.
- """
+ '''
if use_shell:
subprocess.Popen(f'{command} &', shell=True).wait()
else:
@@ -360,10 +360,10 @@ def get_file_path_from_dnd_dropped_uri(uri: str) -> str:
def sanitize_filename(filename: str) -> str:
- """
+ '''
Make sure the filename we will write does contain only acceptable and latin
characters, and is not too long (in that case hash it)
- """
+ '''
# 48 is the limit
if len(filename) > 48:
hash_ = hashlib.md5(filename.encode('utf-8'))
@@ -386,10 +386,10 @@ def sanitize_filename(filename: str) -> str:
def get_contact_dict_for_account(account: str) -> dict[str, types.BareContact]:
- """
+ '''
Creates a dict of jid -> contact with all contacts of account
Can be used for completion lists
- """
+ '''
contacts_dict: dict[str, types.BareContact] = {}
client = app.get_client(account)
for contact in client.get_module('Roster').iter_contacts():
@@ -413,14 +413,14 @@ def play_sound(sound_event: str,
def check_soundfile_path(file_: str,
dirs: Optional[list[Path]] = None
) -> Optional[Path]:
- """
+ '''
Check if the sound file exists
:param file_: the file to check, absolute or relative to 'dirs' path
:param dirs: list of knows paths to fallback if the file doesn't exists
(eg: ~/.gajim/sounds/, DATADIR/sounds...).
:return the path to file or None if it doesn't exists.
- """
+ '''
if not file_:
return None
if Path(file_).exists():
@@ -440,7 +440,7 @@ def check_soundfile_path(file_: str,
def strip_soundfile_path(file_: Union[Path, str],
dirs: Optional[list[Path]] = None,
abs_: bool = True):
- """
+ '''
Remove knowns paths from a sound file
Filechooser returns an absolute path.
@@ -450,7 +450,7 @@ def strip_soundfile_path(file_: Union[Path, str],
param: file_: the filename to strip
param: dirs: list of knowns paths from which the filename should be stripped
param: abs_: force absolute path on dirs
- """
+ '''
if not file_:
return None
@@ -520,9 +520,9 @@ def get_global_status_message() -> str:
def statuses_unified() -> bool:
- """
+ '''
Test if all statuses are the same
- """
+ '''
reference = None
for account in app.connections:
if not app.settings.get_account_setting(account,
@@ -538,9 +538,9 @@ def statuses_unified() -> bool:
def get_full_jid_from_iq(iq_obj: Iq) -> Optional[str]:
- """
+ '''
Return the full jid (with resource) from an iq
- """
+ '''
jid = iq_obj.getFrom()
if jid is None:
return None
@@ -548,9 +548,9 @@ def get_full_jid_from_iq(iq_obj: Iq) -> Optional[str]:
def get_jid_from_iq(iq_obj: Iq) -> Optional[str]:
- """
+ '''
Return the jid (without resource) from an iq
- """
+ '''
jid = get_full_jid_from_iq(iq_obj)
if jid is None:
return None
@@ -558,9 +558,9 @@ def get_jid_from_iq(iq_obj: Iq) -> Optional[str]:
def get_auth_sha(sid: str, initiator: str, target: str) -> str:
- """
+ '''
Return sha of sid + initiator + target used for proxy auth
- """
+ '''
return hashlib.sha1(
(f'{sid}{initiator}{target}').encode('utf-8')).hexdigest()
@@ -572,11 +572,11 @@ def remove_invalid_xml_chars(string_: str) -> str:
def get_random_string(count: int = 16) -> str:
- """
+ '''
Create random string of count length
WARNING: Don't use this for security purposes
- """
+ '''
allowed = string.ascii_uppercase + string.digits
return ''.join(random.choice(allowed) for char in range(count))
@@ -597,10 +597,10 @@ def get_os_info() -> str:
def message_needs_highlight(text: str, nickname: str, own_jid: str) -> bool:
- """
+ '''
Check text to see whether any of the words in (muc_highlight_words and
nick) appear
- """
+ '''
special_words = app.settings.get('muc_highlight_words').split(';')
special_words.append(nickname)
special_words.append(own_jid)
@@ -1060,10 +1060,10 @@ def open_file(path: Union[str, Path]) -> None:
def file_is_locked(path_to_file: str) -> bool:
- """
+ '''
Return True if file is locked
NOTE: Windows only.
- """
+ '''
if os.name != 'nt':
return False
diff --git a/gajim/common/i18n.py b/gajim/common/i18n.py
index 8289e2f2d..9de60a0db 100644
--- a/gajim/common/i18n.py
+++ b/gajim/common/i18n.py
@@ -87,10 +87,10 @@ def get_darwin_default_lang() -> str:
def get_default_lang() -> str:
- if sys.platform == "win32":
+ if sys.platform == 'win32':
return get_win32_default_lang()
- if sys.platform == "darwin":
+ if sys.platform == 'darwin':
return get_darwin_default_lang()
return locale.getdefaultlocale()[0] or 'en'
@@ -118,12 +118,12 @@ def initialize_direction_mark() -> None:
def paragraph_direction_mark(text: str) -> str:
- """
+ '''
Determine paragraph writing direction according to
http://www.unicode.org/reports/tr9/#The_Paragraph_Level
Returns either Unicode LTR mark or RTL mark.
- """
+ '''
for char in text:
bidi = unicodedata.bidirectional(char)
if bidi == 'L':
@@ -135,7 +135,7 @@ def paragraph_direction_mark(text: str) -> str:
def Q_(text: str) -> str:
- """
+ '''
Translate the given text, optionally qualified with a special
construction, which will help translators to disambiguate between
same terms, but in different contexts.
@@ -148,7 +148,7 @@ def Q_(text: str) -> str:
Everything between ? and : - is the qualifier to convey the context
to the translators. Everything after : - is the text itself.
- """
+ '''
text = _(text)
if text.startswith('?'):
text = text.split(':', 1)[1]
@@ -164,13 +164,13 @@ def ngettext(s_sing: str,
n: int,
replace_sing: Optional[str] = None,
replace_plural: Optional[str] = None) -> str:
- """
+ '''
Use as:
i18n.ngettext(
'leave room %s', 'leave rooms %s', len(rooms), 'a', 'a, b, c')
In other words this is a hack to ngettext() to support %s %d etc..
- """
+ '''
text = _translation.ngettext(s_sing, s_plural, n)
if n == 1 and replace_sing is not None:
text = text % replace_sing
diff --git a/gajim/common/idle.py b/gajim/common/idle.py
index a391431f0..bbaa84630 100644
--- a/gajim/common/idle.py
+++ b/gajim/common/idle.py
@@ -360,9 +360,9 @@ class IdleMonitorManager(GObject.Object):
return self._idle_monitor.get_idle_sec()
def _poll(self) -> bool:
- """
+ '''
Check to see if we should change state
- """
+ '''
assert self._idle_monitor is not None
if self._idle_monitor.is_extended_away():
diff --git a/gajim/common/jingle_content.py b/gajim/common/jingle_content.py
index 0d1b01038..cc4efb0f1 100644
--- a/gajim/common/jingle_content.py
+++ b/gajim/common/jingle_content.py
@@ -12,9 +12,9 @@
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.
-"""
-Handles Jingle contents (XEP 0166)
-"""
+
+# Handles Jingle contents (XEP 0166)
+
from __future__ import annotations
@@ -46,15 +46,15 @@ def get_jingle_content(node: nbxmpp.Node):
class JingleContentSetupException(Exception):
- """
+ '''
Exception that should be raised when a content fails to setup.
- """
+ '''
class JingleContent:
- """
+ '''
An abstraction of content in Jingle sessions
- """
+ '''
def __init__(self,
session: JingleSession,
@@ -136,9 +136,9 @@ class JingleContent:
self.session.content_negotiated(self.media)
def add_remote_candidates(self, candidates):
- """
+ '''
Add a list of candidates to the list of remote candidates
- """
+ '''
self.transport.remote_candidates = candidates
def on_stanza(self,
@@ -147,9 +147,9 @@ class JingleContent:
error: Optional[nbxmpp.Node],
action: str
) -> None:
- """
+ '''
Called when something related to our content was sent by peer
- """
+ '''
if action in self.callbacks:
for callback in self.callbacks[action]:
callback(stanza, content, error, action)
@@ -168,9 +168,9 @@ class JingleContent:
error: Optional[nbxmpp.Node],
action: str
) -> None:
- """
+ '''
Got a new transport candidate
- """
+ '''
candidates = self.transport.parse_transport_stanza(
content.getTag('transport'))
if candidates:
@@ -179,9 +179,9 @@ class JingleContent:
def __content(self,
payload: Optional[list[nbxmpp.Node]] = None
) -> nbxmpp.Node:
- """
+ '''
Build a XML content-wrapper for our data
- """
+ '''
if payload is None:
payload = []
return nbxmpp.Node('content',
@@ -191,17 +191,17 @@ class JingleContent:
payload=payload)
def send_candidate(self, candidate: dict[str, Any]) -> None:
- """
+ '''
Send a transport candidate for a previously defined transport.
- """
+ '''
content = self.__content()
content.addChild(node=self.transport.make_transport([candidate]))
self.session.send_transport_info(content)
def send_error_candidate(self) -> None:
- """
+ '''
Sends a candidate-error when we can't connect to a candidate.
- """
+ '''
content = self.__content()
tp = self.transport.make_transport(add_candidates=False)
tp.addChild(name='candidate-error')
@@ -219,9 +219,9 @@ class JingleContent:
error: Optional[nbxmpp.Node],
action: str
) -> None:
- """
+ '''
Add our things to session-initiate stanza
- """
+ '''
self._fill_content(content)
self.sent = True
content.addChild(node=self.transport.make_transport())
diff --git a/gajim/common/jingle_ft.py b/gajim/common/jingle_ft.py
index 0c3861803..491c6ed93 100644
--- a/gajim/common/jingle_ft.py
+++ b/gajim/common/jingle_ft.py
@@ -12,9 +12,9 @@
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.
-"""
-Handles Jingle File Transfer (XEP 0234)
-"""
+
+# Handles Jingle File Transfer (XEP 0234)
+
from __future__ import annotations
@@ -85,7 +85,7 @@ class JingleFileTransfer(JingleContent):
) -> None:
JingleContent.__init__(self, session, transport, senders)
- log.info("transport value: %s", transport)
+ log.info('transport value: %s', transport)
# events we might be interested in
self.callbacks['session-initiate'] += [self.__on_session_initiate]
self.callbacks['session-initiate-sent'] += [
@@ -163,7 +163,7 @@ class JingleFileTransfer(JingleContent):
error: Optional[nbxmpp.Node],
action: str
) -> None:
- log.debug("Jingle FT request received")
+ log.debug('Jingle FT request received')
self._raise_event(stanza, content)
account = self.session.connection.name
@@ -332,7 +332,7 @@ class JingleFileTransfer(JingleContent):
error: Optional[nbxmpp.Node],
action: str
) -> None:
- log.info("__on_session_accept")
+ log.info('__on_session_accept')
con = self.session.connection
security = content.getTag('security')
if not security: # responder can not verify our fingerprint
@@ -392,7 +392,7 @@ class JingleFileTransfer(JingleContent):
error: Optional[nbxmpp.Node],
action: str
) -> None:
- log.info("__on_session_terminate")
+ log.info('__on_session_terminate')
def __on_session_info(self,
stanza: nbxmpp.Node,
@@ -408,7 +408,7 @@ class JingleFileTransfer(JingleContent):
error: Optional[nbxmpp.Node],
action: str
) -> None:
- log.info("__on_transport_accept")
+ log.info('__on_transport_accept')
def __on_transport_replace(self,
stanza: nbxmpp.Node,
@@ -416,7 +416,7 @@ class JingleFileTransfer(JingleContent):
error: Optional[nbxmpp.Node],
action: str
) -> None:
- log.info("__on_transport_replace")
+ log.info('__on_transport_replace')
def __on_transport_reject(self,
stanza: nbxmpp.Node,
@@ -424,7 +424,7 @@ class JingleFileTransfer(JingleContent):
error: Optional[nbxmpp.Node],
action: str
) -> None:
- log.info("__on_transport_reject")
+ log.info('__on_transport_reject')
def __on_transport_info(self,
stanza: nbxmpp.Node,
@@ -432,7 +432,7 @@ class JingleFileTransfer(JingleContent):
error: Optional[nbxmpp.Node],
action: str
) -> None:
- log.info("__on_transport_info")
+ log.info('__on_transport_info')
cand_error = content.getTag('transport').getTag('candidate-error')
cand_used = content.getTag('transport').getTag('candidate-used')
if (cand_error or cand_used) and \
@@ -488,7 +488,7 @@ class JingleFileTransfer(JingleContent):
error: Optional[nbxmpp.Node],
action: str
) -> None:
- log.info("__on_iq_result")
+ log.info('__on_iq_result')
if self.state in (State.NOT_STARTED, State.CAND_RECEIVED):
self.__state_changed(State.INITIALIZED)
@@ -516,9 +516,9 @@ class JingleFileTransfer(JingleContent):
self._listen_host()
def on_connect(self, streamhost):
- """
+ '''
send candidate-used stanza
- """
+ '''
log.info('send_candidate_used')
if streamhost is None:
return
diff --git a/gajim/common/jingle_ftstates.py b/gajim/common/jingle_ftstates.py
index 1e5592d4b..6ccff985f 100644
--- a/gajim/common/jingle_ftstates.py
+++ b/gajim/common/jingle_ftstates.py
@@ -118,7 +118,7 @@ class StateCandReceived(JingleFileTransferStates):
streamhost_used = cand
break
if streamhost_used is None:
- log.info("unknown streamhost")
+ log.info('unknown streamhost')
return
# We save the candidate nominated by peer
self.jft.nominated_cand['peer-cand'] = streamhost_used
diff --git a/gajim/common/jingle_rtp.py b/gajim/common/jingle_rtp.py
index 3975c2450..5e721bb95 100644
--- a/gajim/common/jingle_rtp.py
+++ b/gajim/common/jingle_rtp.py
@@ -12,9 +12,9 @@
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.
-"""
-Handles Jingle RTP sessions (XEP 0167)
-"""
+
+# Handles Jingle RTP sessions (XEP 0167)
+
from __future__ import annotations
@@ -164,11 +164,11 @@ class JingleRTPContent(JingleContent):
self.p2pstream.add_remote_candidates(candidates)
def batch_dtmf(self, events: list[str]) -> None:
- """
+ '''
Send several DTMF tones
- """
+ '''
if self._dtmf_running:
- raise Exception("There is a DTMF batch already running")
+ raise Exception('There is a DTMF batch already running')
d_events = deque(events)
self._dtmf_running = True
self.start_dtmf(d_events.popleft())
@@ -313,9 +313,9 @@ class JingleRTPContent(JingleContent):
_error: Optional[nbxmpp.Node],
_action: str
) -> None:
- """
+ '''
Get peer codecs from what we get from peer
- """
+ '''
codecs: list[Farstream.Codec] = []
for codec in content.getTag('description').iterTags('payload-type'):
if not codec['id'] or not codec['name'] or not codec['clockrate']:
@@ -374,10 +374,10 @@ class JingleRTPContent(JingleContent):
class JingleAudio(JingleRTPContent):
- """
+ '''
Jingle VoIP sessions consist of audio content transported over an ICE UDP
protocol
- """
+ '''
def __init__(self,
session: JingleSession,
@@ -387,15 +387,15 @@ class JingleAudio(JingleRTPContent):
self.setup_stream()
def set_mic_volume(self, vol: float) -> None:
- """
+ '''
vol must be between 0 and 1
- """
+ '''
self.mic_volume.set_property('volume', vol)
def set_out_volume(self, vol: float) -> None:
- """
+ '''
vol must be between 0 and 1
- """
+ '''
self.out_volume.set_property('volume', vol)
def setup_stream(self) -> None:
diff --git a/gajim/common/jingle_session.py b/gajim/common/jingle_session.py
index 112a6b3a9..e281adeee 100644
--- a/gajim/common/jingle_session.py
+++ b/gajim/common/jingle_session.py
@@ -12,9 +12,8 @@
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.
-"""
-Handles Jingle sessions (XEP 0166)
-"""
+
+# Handles Jingle sessions (XEP 0166)
# TODO:
# * 'senders' attribute of 'content' element
@@ -60,7 +59,7 @@ if TYPE_CHECKING:
from gajim.common.jingle_transport import JingleTransport
-log = logging.getLogger("app.c.jingle_session")
+log = logging.getLogger('app.c.jingle_session')
JINGLE_EVENTS = {
@@ -75,40 +74,40 @@ JINGLE_EVENTS = {
# FIXME: Move it to JingleSession.States?
@unique
class JingleStates(Enum):
- """
+ '''
States in which jingle session may exist
- """
+ '''
ENDED = 0
PENDING = 1
ACTIVE = 2
class OutOfOrder(Exception):
- """
+ '''
Exception that should be raised when an action is received when in the wrong
state
- """
+ '''
class TieBreak(Exception):
- """
+ '''
Exception that should be raised in case of a tie, when we overrule the other
action
- """
+ '''
class FailedApplication(Exception):
- """
+ '''
Exception that should be raised in case responder supports none of the
payload-types offered by the initiator
- """
+ '''
class JingleSession:
- """
+ '''
This represents one jingle session, that is, one or more content types
negotiated between an initiator and a responder.
- """
+ '''
def __init__(self,
con: Client,
@@ -118,11 +117,11 @@ class JingleSession:
sid: Optional[str] = None,
werequest: bool = False
) -> None:
- """
+ '''
con -- connection object,
weinitiate -- boolean, are we the initiator?
jid - jid of the other entity
- """
+ '''
# negotiated contents
self.contents: dict[tuple[str, str], JingleContent] = {}
self.connection = con # connection to use
@@ -194,23 +193,23 @@ class JingleSession:
self.iq_ids.append(iq_id)
def approve_session(self) -> None:
- """
+ '''
Called when user accepts session in UI (when we aren't the initiator)
- """
+ '''
self.accept_session()
def decline_session(self) -> None:
- """
+ '''
Called when user declines session in UI (when we aren't the initiator)
- """
+ '''
reason = nbxmpp.Node('reason')
reason.addChild('decline')
self._session_terminate(reason)
def cancel_session(self) -> None:
- """
+ '''
Called when user declines session in UI (when we aren't the initiator)
- """
+ '''
reason = nbxmpp.Node('reason')
reason.addChild('cancel')
self._session_terminate(reason)
@@ -230,9 +229,9 @@ class JingleSession:
self.on_session_state_changed()
def end_session(self) -> None:
- """
+ '''
Called when user stops or cancel session in UI
- """
+ '''
reason = nbxmpp.Node('reason')
if self.state == JingleStates.ACTIVE:
reason.addChild('success')
@@ -257,12 +256,12 @@ class JingleSession:
content: JingleContent,
creator: str = 'we'
) -> None:
- """
+ '''
Add new content to session. If the session is active, this will send
proper stanza to update session
Creator must be one of ('we', 'peer', 'initiator', 'responder')
- """
+ '''
assert creator in ('we', 'peer', 'initiator', 'responder')
if ((creator == 'we' and self.weinitiate) or
(creator == 'peer' and not self.weinitiate)):
@@ -282,11 +281,11 @@ class JingleSession:
name: str,
reason: Optional[nbxmpp.Node] = None
) -> None:
- """
+ '''
Remove the content `name` created by `creator`
by sending content-remove, or by sending session-terminate if
there is no content left.
- """
+ '''
if (creator, name) in self.contents:
content = self.contents[(creator, name)]
self.__content_remove(content, reason)
@@ -345,23 +344,23 @@ class JingleSession:
self.__content_accept(content)
def is_ready(self) -> bool:
- """
+ '''
Return True when all codecs and candidates are ready (for all contents)
- """
+ '''
ready = [content.is_ready() for content in self.contents.values()]
return all(ready) and self.accepted
def accept_session(self) -> None:
- """
+ '''
Mark the session as accepted
- """
+ '''
self.accepted = True
self.on_session_state_changed()
def start_session(self) -> None:
- """
+ '''
Mark the session as ready to be started
- """
+ '''
self.accepted = True
self.on_session_state_changed()
@@ -388,11 +387,11 @@ class JingleSession:
self.connection.connection.send(stanza)
def on_stanza(self, stanza: nbxmpp.Node) -> None:
- """
+ '''
A callback for ConnectionJingle. It gets stanza, then tries to send
it to all internally registered callbacks. First one to raise
nbxmpp.NodeProcessed breaks function
- """
+ '''
jingle = stanza.getTag('jingle')
error = stanza.getTag('error')
if error:
@@ -434,9 +433,9 @@ class JingleSession:
error: Optional[nbxmpp.Node],
action: str
) -> None:
- """
+ '''
Default callback for action stanzas -- simple ack and stop processing
- """
+ '''
response = stanza.buildReply('result')
response.delChild(response.getQuery())
self.connection.connection.send(response)
@@ -584,10 +583,10 @@ class JingleSession:
error: Optional[nbxmpp.Node],
action: str
) -> None:
- """
+ '''
Called when we get content-accept stanza or equivalent one (like
session-accept)
- """
+ '''
# check which contents are accepted
# for content in jingle.iterTags('content'):
# creator = content['creator']
@@ -618,10 +617,10 @@ class JingleSession:
error: Optional[nbxmpp.Node],
action: str
) -> None:
- """
+ '''
We got a jingle session request from other entity, therefore we are the
receiver... Unpack the data, inform the user
- """
+ '''
if self.state != JingleStates.ENDED:
raise OutOfOrder
@@ -715,9 +714,9 @@ class JingleSession:
error: Optional[nbxmpp.Node],
action: str
) -> None:
- """
+ '''
Broadcast the stanza contents to proper content handlers
- """
+ '''
# if jingle is None: # it is a iq-result stanza
# for cn in self.contents.values():
# cn.on_stanza(stanza, None, error, action)
@@ -776,9 +775,9 @@ class JingleSession:
error: Optional[nbxmpp.Node],
action: str
) -> None:
- """
+ '''
Broadcast the stanza to all content handlers
- """
+ '''
for content in self.contents.values():
content.on_stanza(stanza, None, error, action)
@@ -890,18 +889,18 @@ class JingleSession:
@staticmethod
def __append_content(jingle: nbxmpp.Node, content: JingleContent) -> None:
- """
+ '''
Append <content/> element to <jingle/> element
- """
+ '''
jingle.addChild('content',
attrs={'name': content.name,
'creator': content.creator,
'senders': content.senders})
def __append_contents(self, jingle: nbxmpp.Node) -> None:
- """
+ '''
Append all <content/> elements to <jingle/>
- """
+ '''
# TODO: integrate with __appendContent?
# TODO: parameters 'name', 'content'?
for content in self.contents.values():
diff --git a/gajim/common/jingle_transport.py b/gajim/common/jingle_transport.py
index 2da4958bc..85f31bef2 100644
--- a/gajim/common/jingle_transport.py
+++ b/gajim/common/jingle_transport.py
@@ -12,9 +12,9 @@
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.
-"""
-Handles Jingle Transports (currently only ICE-UDP)
-"""
+
+# Handles Jingle Transports (currently only ICE-UDP)
+
from __future__ import annotations
@@ -53,18 +53,18 @@ def get_jingle_transport(node: nbxmpp.Node):
@unique
class TransportType(IntEnum):
- """
+ '''
Possible types of a JingleTransport
- """
+ '''
ICEUDP = 1
SOCKS5 = 2
IBB = 3
class JingleTransport:
- """
+ '''
An abstraction of a transport in Jingle sessions
- """
+ '''
__slots__ = ['type_', 'candidates', 'remote_candidates', 'connection',
'file_props', 'ourjid', 'sid']
@@ -84,17 +84,17 @@ class JingleTransport:
yield self.make_candidate(candidate)
def make_candidate(self, candidate: dict[str, Any]) -> Any:
- """
+ '''
Build a candidate stanza for the given candidate
- """
+ '''
def make_transport(self,
candidates: Optional[list[dict[str, Any]]] = None
) -> nbxmpp.Node:
- """
+ '''
Build a transport stanza with the given candidates (or self.candidates
if candidates is None)
- """
+ '''
if not candidates:
candidates = list(self._iter_candidates())
else:
@@ -104,9 +104,9 @@ class JingleTransport:
return transport
def parse_transport_stanza(self, transport: nbxmpp.Node) -> list[Any]:
- """
+ '''
Return the list of transport candidates from a transport stanza
- """
+ '''
return []
def set_connection(self, conn: Client) -> None:
@@ -125,10 +125,10 @@ class JingleTransport:
class JingleTransportSocks5(JingleTransport):
- """
+ '''
Socks5 transport in jingle scenario
Note: Don't forget to call set_file_props after initialization
- """
+ '''
def __init__(self, node: Optional[nbxmpp.Node] = None) -> None:
JingleTransport.__init__(self, TransportType.SOCKS5)
self.connection = None
@@ -368,7 +368,7 @@ class JingleTransportSocks5(JingleTransport):
return
iq = nbxmpp.Iq(to=proxy['jid'], frm=self.ourjid, typ='set')
- auth_id = "au_" + proxy['sid']
+ auth_id = 'au_' + proxy['sid']
iq.setID(auth_id)
query = iq.setTag('query', namespace=Namespace.BYTESTREAM)
query.setAttr('sid', proxy['sid'])
diff --git a/gajim/common/jingle_xtls.py b/gajim/common/jingle_xtls.py
index 50aaaa33b..6bd45ea07 100644
--- a/gajim/common/jingle_xtls.py
+++ b/gajim/common/jingle_xtls.py
@@ -50,14 +50,14 @@ DEFAULT_DH_PARAMS = 'dh4096.pem'
def default_callback(connection, certificate, error_num, depth, return_code):
- log.info("certificate: %s", certificate)
+ log.info('certificate: %s', certificate)
return return_code
def load_cert_file(cert_path, cert_store=None):
- """
+ '''
This is almost identical to the one in nbxmpp.tls_nb
- """
+ '''
if not cert_path.is_file():
return None
try:
@@ -92,9 +92,9 @@ def load_cert_file(cert_path, cert_store=None):
def get_context(fingerprint, verify_cb=None, remote_jid=None):
- """
+ '''
constructs and returns the context objects
- """
+ '''
ctx = SSL.Context(SSL.SSLv23_METHOD)
flags = (SSL.OP_NO_SSLv2 | SSL.OP_NO_SSLv3 | SSL.OP_SINGLE_DH_USE |
SSL.OP_NO_TICKET)
@@ -116,13 +116,13 @@ def get_context(fingerprint, verify_cb=None, remote_jid=None):
# First try user DH parameters, if this fails load the default DH parameters
dh_params_name = configpaths.get('MY_CERT') / DH_PARAMS
try:
- with open(dh_params_name, "r", encoding='utf8'):
+ with open(dh_params_name, 'r', encoding='utf8'):
ctx.load_tmp_dh(dh_params_name.encode('utf-8'))
except FileNotFoundError:
default_dh_params_name = (configpaths.get('DATA') / 'other' /
DEFAULT_DH_PARAMS)
try:
- with open(default_dh_params_name, "r", encoding='utf8'):
+ with open(default_dh_params_name, 'r', encoding='utf8'):
ctx.load_tmp_dh(str(default_dh_params_name).encode('utf-8'))
except FileNotFoundError as err:
log.error('Unable to load default DH parameter file: %s, %s',
@@ -211,20 +211,20 @@ def send_cert_request(con, to_jid):
def createKeyPair(type_, bits):
- """
+ '''
Create a public/private key pair.
Arguments: type_ - Key type, must be one of TYPE_RSA and TYPE_DSA
bits - Number of bits to use in the key
Returns: The public/private key pair in a PKey object
- """
+ '''
pkey = crypto.PKey()
pkey.generate_key(type_, bits)
return pkey
-def createCertRequest(pkey, digest="sha256", **name):
- """
+def createCertRequest(pkey, digest='sha256', **name):
+ '''
Create a certificate request.
Arguments: pkey - The key to associate with the request
@@ -239,7 +239,7 @@ def createCertRequest(pkey, digest="sha256", **name):
CN - Common name
emailAddress - E-mail address
Returns: The certificate request in an X509Req object
- """
+ '''
req = crypto.X509Req()
subj = req.get_subject()
@@ -252,8 +252,8 @@ def createCertRequest(pkey, digest="sha256", **name):
def createCertificate(req, issuerCert, issuerKey, serial, notBefore, notAfter,
- digest="sha256"):
- """
+ digest='sha256'):
+ '''
Generate a certificate given a certificate request.
Arguments: req - Certificate request to use
@@ -266,7 +266,7 @@ def createCertificate(req, issuerCert, issuerKey, serial, notBefore, notAfter,
stops being valid
digest - Digest method to use for signing, default is sha256
Returns: The signed certificate in an X509 object
- """
+ '''
cert = crypto.X509()
cert.set_serial_number(serial)
cert.gmtime_adj_notBefore(notBefore)
@@ -279,12 +279,12 @@ def createCertificate(req, issuerCert, issuerKey, serial, notBefore, notAfter,
def make_certs(filepath, CN):
- """
+ '''
make self signed certificates
filepath : absolute path of certificate file, will be appended the '.pkey'
and '.cert' extensions
CN : common name
- """
+ '''
key = createKeyPair(TYPE_RSA, 4096)
req = createCertRequest(key, CN=CN)
# five years
diff --git a/gajim/common/logging_helpers.py b/gajim/common/logging_helpers.py
index c19391dd0..14fc474be 100644
--- a/gajim/common/logging_helpers.py
+++ b/gajim/common/logging_helpers.py
@@ -27,9 +27,9 @@ from gajim.common.i18n import _
def parseLogLevel(arg: str) -> int:
- """
+ '''
Either numeric value or level name from logging module
- """
+ '''
if arg.isdigit():
return int(arg)
if arg.isupper() and hasattr(logging, arg):
@@ -39,11 +39,11 @@ def parseLogLevel(arg: str) -> int:
def parseLogTarget(arg: str) -> str:
- """
+ '''
[gajim.]c.x.y -> gajim.c.x.y
.other_logger -> other_logger
<None> -> gajim
- """
+ '''
arg = arg.lower()
if not arg:
return 'gajim'
@@ -55,7 +55,7 @@ def parseLogTarget(arg: str) -> str:
def parseAndSetLogLevels(arg: str) -> None:
- """
+ '''
[=]LOGLEVEL -> gajim=LOGLEVEL
gajim=LOGLEVEL -> gajim=LOGLEVEL
.other=10 -> other=10
@@ -64,7 +64,7 @@ def parseAndSetLogLevels(arg: str) -> None:
gajim.c.z=20
gajim=10,c.x=20 -> gajim=10
gajim.c.x=20
- """
+ '''
for directive in arg.split(','):
directive = directive.strip()
if not directive:
@@ -77,28 +77,28 @@ def parseAndSetLogLevels(arg: str) -> None:
target = parseLogTarget(target.strip())
if target:
logging.getLogger(target).setLevel(level)
- print("Logger %s level set to %d" % (target, level),
+ print('Logger %s level set to %d' % (target, level),
file=sys.stderr)
class colors:
- NONE = chr(27) + "[0m"
- BLACK = chr(27) + "[30m"
- RED = chr(27) + "[31m"
- GREEN = chr(27) + "[32m"
- BROWN = chr(27) + "[33m"
- BLUE = chr(27) + "[34m"
- MAGENTA = chr(27) + "[35m"
- CYAN = chr(27) + "[36m"
- LIGHT_GRAY = chr(27) + "[37m"
- DARK_GRAY = chr(27) + "[30;1m"
- BRIGHT_RED = chr(27) + "[31;1m"
- BRIGHT_GREEN = chr(27) + "[32;1m"
- YELLOW = chr(27) + "[33;1m"
- BRIGHT_BLUE = chr(27) + "[34;1m"
- PURPLE = chr(27) + "[35;1m"
- BRIGHT_CYAN = chr(27) + "[36;1m"
- WHITE = chr(27) + "[37;1m"
+ NONE = chr(27) + '[0m'
+ BLACK = chr(27) + '[30m'
+ RED = chr(27) + '[31m'
+ GREEN = chr(27) + '[32m'
+ BROWN = chr(27) + '[33m'
+ BLUE = chr(27) + '[34m'
+ MAGENTA = chr(27) + '[35m'
+ CYAN = chr(27) + '[36m'
+ LIGHT_GRAY = chr(27) + '[37m'
+ DARK_GRAY = chr(27) + '[30;1m'
+ BRIGHT_RED = chr(27) + '[31;1m'
+ BRIGHT_GREEN = chr(27) + '[32;1m'
+ YELLOW = chr(27) + '[33;1m'
+ BRIGHT_BLUE = chr(27) + '[34;1m'
+ PURPLE = chr(27) + '[35;1m'
+ BRIGHT_CYAN = chr(27) + '[36;1m'
+ WHITE = chr(27) + '[37;1m'
def colorize(text: str, color: str) -> str:
@@ -106,9 +106,9 @@ def colorize(text: str, color: str) -> str:
class FancyFormatter(logging.Formatter):
- """
+ '''
An eye-candy formatter with colors
- """
+ '''
colors_mapping = {
'DEBUG': colors.BLUE,
'INFO': colors.GREEN,
@@ -147,9 +147,9 @@ class FancyFormatter(logging.Formatter):
def init() -> None:
- """
+ '''
Iinitialize the logging system
- """
+ '''
if app.get_debug_mode():
_cleanup_debug_logs()
diff --git a/gajim/common/modules/bits_of_binary.py b/gajim/common/modules/bits_of_binary.py
index 8d9a096c7..c860ed9bd 100644
--- a/gajim/common/modules/bits_of_binary.py
+++ b/gajim/common/modules/bits_of_binary.py
@@ -71,9 +71,9 @@ class BitsOfBinary(BaseModule):
result: Iq,
cid: str
) -> None:
- """
+ '''
Called when we receive BoB data
- """
+ '''
if cid not in self.awaiting_cids:
return
@@ -112,11 +112,11 @@ class BitsOfBinary(BaseModule):
args: Any,
position: int
) -> None:
- """
+ '''
Request for BoB (XEP-0231) and when data will arrive, call callback
with given args, after having replaced cid by it's data in
args[position]
- """
+ '''
if cid in self.awaiting_cids:
self.awaiting_cids[cid].appends((callback, args, position))
else:
diff --git a/gajim/common/modules/bytestream.py b/gajim/common/modules/bytestream.py
index 74b72b20f..594ecd8f2 100644
--- a/gajim/common/modules/bytestream.py
+++ b/gajim/common/modules/bytestream.py
@@ -140,15 +140,15 @@ class Bytestream(BaseModule):
return helpers.parse_jid(streamhost.getAttr('jid'))
def send_file_approval(self, file_props: FileProp) -> None:
- """
+ '''
Send iq, confirming that we want to download the file
- """
+ '''
# user response to ConfirmationDialog may come after we've disconnected
if not app.account_is_available(self._account):
return
# file transfer initiated by a jingle session
- log.info("send_file_approval: jingle session accept")
+ log.info('send_file_approval: jingle session accept')
session = self._con.get_module('Jingle').get_jingle_session(
file_props.sender, file_props.sid)
@@ -180,12 +180,12 @@ class Bytestream(BaseModule):
session.approve_content('file', content.name)
def send_file_rejection(self, file_props: FileProp) -> None:
- """
+ '''
Inform sender that we refuse to download the file
typ is used when code = '400', in this case typ can be 'stream' for
invalid stream or 'profile' for invalid profile
- """
+ '''
# user response to ConfirmationDialog may come after we've disconnected
if not app.account_is_available(self._account):
return
@@ -197,9 +197,9 @@ class Bytestream(BaseModule):
def send_success_connect_reply(self,
streamhost: Optional[dict[str, Any]]
) -> None:
- """
+ '''
Send reply to the initiator of FT that we made a connection
- """
+ '''
if not app.account_is_available(self._account):
return
if streamhost is None:
@@ -214,9 +214,9 @@ class Bytestream(BaseModule):
self._con.connection.send(iq)
def stop_all_active_file_transfers(self, contact: types.ChatContactT):
- """
+ '''
Stop all active transfer to or from the given contact
- """
+ '''
for file_props in FilesProp.getAllFileProp():
if is_transfer_stopped(file_props):
continue
@@ -236,9 +236,9 @@ class Bytestream(BaseModule):
self.remove_transfer(file_props)
def remove_all_transfers(self) -> None:
- """
+ '''
Stop and remove all active connections from the socks5 pool
- """
+ '''
for file_props in FilesProp.getAllFileProp():
self.remove_transfer(file_props)
@@ -261,9 +261,9 @@ class Bytestream(BaseModule):
app.socks5queue.remove_sender(host['idx'])
def _send_socks5_info(self, file_props: FileProp) -> None:
- """
+ '''
Send iq for the present streamhosts and proxies
- """
+ '''
if not app.account_is_available(self._account):
return
receiver = file_props.receiver
@@ -521,9 +521,9 @@ class Bytestream(BaseModule):
@staticmethod
def _result_socks5_sid(sid: str, hash_id: str) -> None:
- """
+ '''
Store the result of SHA message from auth
- """
+ '''
file_props = FilesProp.getFilePropBySid(sid)
file_props.hash_ = hash_id
@@ -533,10 +533,10 @@ class Bytestream(BaseModule):
error_type: str,
msg: Optional[str] = None
) -> None:
- """
+ '''
Called when there is an error establishing BS connection, or when
connection is rejected
- """
+ '''
if not app.account_is_available(self._account):
return
file_props = FilesProp.getFileProp(self._account, sid)
@@ -563,14 +563,14 @@ class Bytestream(BaseModule):
error_msg=msg))
def _proxy_auth_ok(self, proxy: dict[str, Any]) -> None:
- """
+ '''
Called after authentication to proxy server
- """
+ '''
if not app.account_is_available(self._account):
return
file_props = FilesProp.getFileProp(self._account, proxy['sid'])
iq = nbxmpp.Iq(to=proxy['initiator'], typ='set')
- auth_id = "au_" + proxy['sid']
+ auth_id = 'au_' + proxy['sid']
iq.setID(auth_id)
query = iq.setTag('query', namespace=Namespace.BYTESTREAM)
query.setAttr('sid', proxy['sid'])
diff --git a/gajim/common/modules/httpupload.py b/gajim/common/modules/httpupload.py
index 3e460e62f..a0bbc3052 100644
--- a/gajim/common/modules/httpupload.py
+++ b/gajim/common/modules/httpupload.py
@@ -133,7 +133,7 @@ class HTTPUpload(BaseModule):
mime = mimetypes.MimeTypes().guess_type(path)[0]
if not mime:
mime = 'application/octet-stream' # fallback mime type
- self._log.info("Detected MIME type of file: %s", mime)
+ self._log.info('Detected MIME type of file: %s', mime)
return HTTPFileTransfer(self._account,
path,
diff --git a/gajim/common/modules/jingle.py b/gajim/common/modules/jingle.py
index b4cf8f2d8..8aeb7db1f 100644
--- a/gajim/common/modules/jingle.py
+++ b/gajim/common/modules/jingle.py
@@ -12,9 +12,9 @@
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.
-"""
-Handles the jingle signalling protocol
-"""
+
+# Handles the jingle signalling protocol
+
# TODO:
# * things in XEP 0176, including:
@@ -90,9 +90,9 @@ class Jingle(BaseModule):
self.files: list[dict[str, Any]] = []
def delete_jingle_session(self, sid: str) -> None:
- """
+ '''
Remove a jingle session from a jingle stanza dispatcher
- """
+ '''
if sid in self._sessions:
# FIXME: Move this elsewhere?
for content in list(self._sessions[sid].contents.values()):
@@ -125,7 +125,7 @@ class Jingle(BaseModule):
stanza: Iq,
_properties: IqProperties
) -> None:
- """
+ '''
The jingle stanza dispatcher
Route jingle stanza to proper JingleSession object, or create one if it
@@ -133,7 +133,7 @@ class Jingle(BaseModule):
TODO: Also check if the stanza isn't an error stanza, if so route it
adequately.
- """
+ '''
# get data
try:
jid = helpers.get_full_jid_from_iq(stanza)
@@ -234,7 +234,7 @@ class Jingle(BaseModule):
file_props: FileProp,
request: bool = False
) -> Optional[str]:
- logger.info("start file transfer with file: %s", file_props)
+ logger.info('start file transfer with file: %s', file_props)
contact = self._con.get_module('Contacts').get_contact(jid)
use_security = contact.supports(Namespace.JINGLE_XTLS)
jingle = JingleSession(self._con,
diff --git a/gajim/common/passwords.py b/gajim/common/passwords.py
index 6dad6c542..ac71cb15b 100644
--- a/gajim/common/passwords.py
+++ b/gajim/common/passwords.py
@@ -63,9 +63,9 @@ class Interface:
class SecretPasswordStorage:
- """
+ '''
Store password using Keyring
- """
+ '''
@staticmethod
def save_password(account_name: str, password: str) -> bool:
@@ -112,9 +112,9 @@ class SecretPasswordStorage:
class ConfigPasswordStorage:
- """
+ '''
Store password directly in Gajim's config
- """
+ '''
@staticmethod
def get_password(account_name: str) -> str:
diff --git a/gajim/common/preview.py b/gajim/common/preview.py
index 90c2269ee..80375ddce 100644
--- a/gajim/common/preview.py
+++ b/gajim/common/preview.py
@@ -434,13 +434,13 @@ class PreviewManager:
return
if file_size == 0:
- log.info('File size is unknown (zero) for URL: \'%s\'', uri)
+ log.info('File size is unknown (zero) for URL: "%s"', uri)
session.cancel_message(message, Soup.Status.CANCELLED)
return
if file_size > int(app.settings.get('preview_max_file_size')):
log.info(
- 'File size (%s) too big for URL: \'%s\'',
+ 'File size (%s) too big for URL: "%s"',
file_size, uri)
if force:
preview.info_message = None
diff --git a/gajim/common/proxy65_manager.py b/gajim/common/proxy65_manager.py
index bc84e14ec..b66de36d1 100644
--- a/gajim/common/proxy65_manager.py
+++ b/gajim/common/proxy65_manager.py
@@ -42,12 +42,12 @@ CONNECT_TIMEOUT = 20
class Proxy65Manager:
- """
+ '''
Keep records for file transfer proxies. Each time account establishes a
connection to its server call proxy65manger.resolve(proxy) for every proxy
that is configured within the account. The class takes care to resolve and
test each proxy only once
- """
+ '''
def __init__(self, idlequeue):
# dict {proxy: proxy properties}
@@ -58,10 +58,10 @@ class Proxy65Manager:
def resolve(self, proxy, connection, sender_jid, default=None,
testit=True):
- """
+ '''
Start
if testit=False, Gajim won't try to resolve it
- """
+ '''
if proxy in self.proxies:
resolver = self.proxies[proxy]
else:
@@ -117,9 +117,9 @@ class Proxy65Manager:
class ProxyResolver:
def resolve_result(self, host, port, jid):
- """
+ '''
Test if host has a real proxy65 listening on port
- """
+ '''
self.host = str(host)
self.port = int(port)
self.jid = str(jid)
@@ -199,25 +199,25 @@ class ProxyResolver:
self.try_next_connection()
def try_next_connection(self):
- """
+ '''
Try to resolve proxy with the next possible connection
- """
+ '''
if self.connections:
connection = self.connections.pop(0)
self.start_resolve(connection)
def add_connection(self, connection):
- """
+ '''
Add a new connection in case the first fails
- """
+ '''
self.connections.append(connection)
if self.state == S_INITIAL:
self.start_resolve(connection)
def start_resolve(self, connection):
- """
+ '''
Request network address from proxy
- """
+ '''
self.state = S_STARTED
self.active_connection = connection
iq = nbxmpp.Protocol(name='iq', to=self.proxy, typ='get')
@@ -226,9 +226,9 @@ class ProxyResolver:
connection.send(iq)
def __init__(self, proxy, sender_jid, testit):
- """
+ '''
if testit is False, don't test it, only get IP/port
- """
+ '''
self.proxy = proxy
self.state = S_INITIAL
self.active_connection = None
@@ -244,9 +244,9 @@ class ProxyResolver:
class HostTester(Socks5, IdleObject):
- """
+ '''
Fake proxy tester
- """
+ '''
def __init__(self,
host,
@@ -256,11 +256,11 @@ class HostTester(Socks5, IdleObject):
sender_jid,
on_success,
on_failure):
- """
+ '''
Try to establish and auth to proxy at (host, port)
Calls on_success, or on_failure according to the result.
- """
+ '''
IdleObject.__init__(self)
self.host = host
self.port = port
@@ -276,9 +276,9 @@ class HostTester(Socks5, IdleObject):
self.sid = sid
def connect(self):
- """
+ '''
Create the socket and plug it to the idlequeue
- """
+ '''
if self.host is None:
self.on_failure()
return None
@@ -373,9 +373,9 @@ class HostTester(Socks5, IdleObject):
class ReceiverTester(Socks5, IdleObject):
- """
+ '''
Fake proxy tester
- """
+ '''
def __init__(self,
host,
@@ -385,11 +385,11 @@ class ReceiverTester(Socks5, IdleObject):
sender_jid,
on_success,
on_failure):
- """
+ '''
Try to establish and auth to proxy at (host, port)
Call on_success, or on_failure according to the result.
- """
+ '''
IdleObject.__init__(self)
self.host = host
self.port = port
@@ -405,9 +405,9 @@ class ReceiverTester(Socks5, IdleObject):
self.sid = sid
def connect(self):
- """
+ '''
Create the socket and plug it to the idlequeue
- """
+ '''
if self.host is None:
self.on_failure()
return None
diff --git a/gajim/common/regex.py b/gajim/common/regex.py
index 3c0237cde..abc7b6a8c 100644
--- a/gajim/common/regex.py
+++ b/gajim/common/regex.py
@@ -28,17 +28,17 @@ def _get_link_pattern():
# so http://be) will match http://be and http://be)be) will match
# http://be)be
- legacy_prefixes = r"((?<=\()(www|ftp)\.([A-Za-z0-9\.\-_~:/\?#\[\]@!\$"\
+ legacy_prefixes = r'((?<=\()(www|ftp)\.([A-Za-z0-9\.\-_~:/\?#\[\]@!\$'\
r"&'\(\)\*\+,;=]|%[A-Fa-f0-9]{2})+(?=\)))"\
r"|((www|ftp)\.([A-Za-z0-9\.\-_~:/\?#\[\]@!\$&'\(\)\*\+,;=]"\
- r"|%[A-Fa-f0-9]{2})+"\
+ r'|%[A-Fa-f0-9]{2})+'\
r"\.([A-Za-z0-9\.\-_~:/\?#\[\]@!\$&'\(\)\*\+,;=]|%[A-Fa-f0-9]{2})+)"
# NOTE: it's ok to catch www.gr such stuff exist!
# FIXME: recognize xmpp: and treat it specially
- links = r"((?<=\()[A-Za-z][A-Za-z0-9\+\.\-]*:"\
+ links = r'((?<=\()[A-Za-z][A-Za-z0-9\+\.\-]*:'\
r"([\w\.\-_~:/\?#\[\]@!\$&'\(\)\*\+,;=]|%[A-Fa-f0-9]{2})+"\
- r"(?=\)))|(\w[\w\+\.\-]*:([^<>\s]|%[A-Fa-f0-9]{2})+)"
+ r'(?=\)))|(\w[\w\+\.\-]*:([^<>\s]|%[A-Fa-f0-9]{2})+)'
# 2nd one: at_least_one_char@at_least_one_char.at_least_one_char
mail = r'\bmailto:\S*[^\s\W]|' r'\b\S+@\S+\.\S*[^\s\W]'
diff --git a/gajim/common/setting_values.py b/gajim/common/setting_values.py
index 27c667690..7d99e297b 100644
--- a/gajim/common/setting_values.py
+++ b/gajim/common/setting_values.py
@@ -649,7 +649,7 @@ ADVANCED_SETTINGS = {
'developer_modus': '',
'dictionary_url': _(
'Either a custom URL with %%s in it (where %%s is the word/phrase)'
- ' or \'WIKTIONARY\' (which means use Wikitionary).'),
+ ' or "WIKTIONARY" (which means use Wikitionary).'),
'enable_negative_priority': _(
'If enabled, you will be able to set a negative priority to your '
'account in the Accounts window. BE CAREFUL, when you are logged '
@@ -673,7 +673,7 @@ ADVANCED_SETTINGS = {
'Hides the group chat participants list in a group chat window.'),
'ignore_incoming_attention': _(
'If enabled, Gajim will ignore incoming attention '
- 'requests (\'wizz\').'),
+ 'requests ("wizz").'),
'key_up_lines': _(
'How many lines to store for Ctrl+KeyUP '
'(previously sent messages).'),
@@ -684,7 +684,7 @@ ADVANCED_SETTINGS = {
'muclumbus_api_http_uri': '',
'muclumbus_api_jid': '',
'muclumbus_api_pref': _(
- 'API Preferences. Possible values: \'http\', \'iq\''),
+ 'API Preferences. Possible values: "http", "iq"'),
'notification_preview_message': _(
'Preview new messages in notification popup?'),
'notification_timeout': '',
@@ -712,7 +712,7 @@ ADVANCED_SETTINGS = {
'Enables libappindicator, an alternative tray icon provider'),
'use_stun_server': _(
'If enabled, Gajim will try to use a STUN server when using Jingle.'
- ' The one in \'stun_server\' option, or the one given by '
+ ' The one in "stun_server" option, or the one given by '
'the XMPP server.'),
'use_urgency_hint': _(
'If enabled, Gajim makes the window flash (the default behaviour '
diff --git a/gajim/common/settings.py b/gajim/common/settings.py
index 1e51149cb..60999c3b5 100644
--- a/gajim/common/settings.py
+++ b/gajim/common/settings.py
@@ -240,7 +240,7 @@ class Settings:
def _namedtuple_factory(cursor: sqlite3.Cursor,
row: tuple[Any, ...]) -> NamedTuple:
fields = [col[0] for col in cursor.description]
- return namedtuple("Row", fields)(*row) # type: ignore
+ return namedtuple('Row', fields)(*row) # type: ignore
def _connect_database(self) -> None:
path = configpaths.get('SETTINGS')
diff --git a/gajim/common/storage/archive.py b/gajim/common/storage/archive.py
index 2b0bd4ea9..e3dac697e 100644
--- a/gajim/common/storage/archive.py
+++ b/gajim/common/storage/archive.py
@@ -1164,7 +1164,7 @@ class MessageArchiveStorage(SqliteStorage):
if not kwargs['additional_data']:
del kwargs['additional_data']
else:
- serialized_dict = json.dumps(kwargs["additional_data"].data)
+ serialized_dict = json.dumps(kwargs['additional_data'].data)
kwargs['additional_data'] = serialized_dict
sql = '''
diff --git a/gajim/common/storage/base.py b/gajim/common/storage/base.py
index fc2c843da..816300ad7 100644
--- a/gajim/common/storage/base.py
+++ b/gajim/common/storage/base.py
@@ -207,10 +207,10 @@ class SqliteStorage:
raise NotImplementedError
def _execute_multiple(self, statements: list[str]) -> None:
- """
+ '''
Execute multiple statements with the option to fail on duplicates
but still continue
- """
+ '''
for sql in statements:
try:
self._con.execute(sql)
diff --git a/gajim/common/storage/cache.py b/gajim/common/storage/cache.py
index 95262565c..a7a381cbf 100644
--- a/gajim/common/storage/cache.py
+++ b/gajim/common/storage/cache.py
@@ -177,9 +177,9 @@ class CacheStorage(SqliteStorage):
@timeit
def _clean_caps_table(self) -> None:
- """
+ '''
Remove caps which was not seen for 3 months
- """
+ '''
timestamp = int(time.time()) - 3 * 30 * 24 * 3600
self._con.execute('DELETE FROM caps_cache WHERE last_seen < ?',
(timestamp,))
@@ -199,14 +199,14 @@ class CacheStorage(SqliteStorage):
def get_last_disco_info(self,
jid: JID,
max_age: int = 0) -> Optional[DiscoInfo]:
- """
+ '''
Get last disco info from jid
:param jid: The jid
:param max_age: max age in seconds of the DiscoInfo record
- """
+ '''
disco_info = self._disco_info_cache.get(jid)
if disco_info is not None:
@@ -220,14 +220,14 @@ class CacheStorage(SqliteStorage):
jid: JID,
disco_info: DiscoInfo,
cache_only: bool = False) -> None:
- """
+ '''
Get last disco info from jid
:param jid: The jid
:param disco_info: A DiscoInfo object
- """
+ '''
log.info('Save disco info from %s', jid)
diff --git a/gajim/gtk/account_wizard.py b/gajim/gtk/account_wizard.py
index 6e899c375..00a154ca0 100644
--- a/gajim/gtk/account_wizard.py
+++ b/gajim/gtk/account_wizard.py
@@ -925,7 +925,7 @@ class SecurityWarning(Page):
self._domain = domain
self._ui.error_list.foreach(self._ui.error_list.remove)
- unknown_error = _('Unknown TLS error \'%s\'')
+ unknown_error = _('Unknown TLS error "%s"')
for error in errors:
error_text = GIO_TLS_ERRORS.get(error, unknown_error % error)
box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
diff --git a/gajim/gtk/adhoc_muc.py b/gajim/gtk/adhoc_muc.py
index fe26160d5..467a910c9 100644
--- a/gajim/gtk/adhoc_muc.py
+++ b/gajim/gtk/adhoc_muc.py
@@ -31,10 +31,10 @@ log = logging.getLogger('gajim.gui.adhoc_muc')
class AdhocMUC(Gtk.ApplicationWindow):
def __init__(self, account, contact, preselected=None):
- """
+ '''
This window is used to transform a one-to-one chat to a MUC. We do 2
things: first select the server and then make a guests list
- """
+ '''
Gtk.ApplicationWindow.__init__(self)
self.set_application(app.app)
self.set_position(Gtk.WindowPosition.CENTER)
diff --git a/gajim/gtk/application.py b/gajim/gtk/application.py
index eecc7287c..89ed1ce01 100644
--- a/gajim/gtk/application.py
+++ b/gajim/gtk/application.py
@@ -110,7 +110,7 @@ class GajimApplication(Gtk.Application, CoreApplication):
ord('V'),
GLib.OptionFlags.NONE,
GLib.OptionArg.NONE,
- _('Show the application\'s version'))
+ _("Show the application's version"))
self.add_main_option(
'quiet',
@@ -743,9 +743,9 @@ class GajimApplication(Gtk.Application, CoreApplication):
@staticmethod
def _on_ipython_action(_action: Gio.SimpleAction,
_param: Optional[GLib.Variant]) -> None:
- """
+ '''
Show/hide the ipython window
- """
+ '''
win = cast(Gtk.Window, app.ipython_window)
if win and win.is_visible():
win.present()
diff --git a/gajim/gtk/avatar.py b/gajim/gtk/avatar.py
index 964e3b7e4..ad32c3151 100644
--- a/gajim/gtk/avatar.py
+++ b/gajim/gtk/avatar.py
@@ -487,13 +487,13 @@ class AvatarStorage(metaclass=Singleton):
@staticmethod
def save_avatar(data: bytes) -> Optional[str]:
- """
+ '''
Save an avatar to the harddisk
:param data: bytes
returns SHA1 value of the avatar or None on error
- """
+ '''
if data is None:
return None
diff --git a/gajim/gtk/builder.py b/gajim/gtk/builder.py
index a73244547..8f437423e 100644
--- a/gajim/gtk/builder.py
+++ b/gajim/gtk/builder.py
@@ -61,7 +61,7 @@ class Builder:
def _load_string_from_filename(filename: str, gettext_: Any) -> str:
file_path = str(configpaths.get('GUI') / filename)
- if sys.platform == "win32":
+ if sys.platform == 'win32':
# This is a workaround for non working translation on Windows
tree = ET.parse(file_path)
for node in tree.iter():
diff --git a/gajim/gtk/conversation/rows/muc_subject.py b/gajim/gtk/conversation/rows/muc_subject.py
index 19aea49f6..6a84f5ddf 100644
--- a/gajim/gtk/conversation/rows/muc_subject.py
+++ b/gajim/gtk/conversation/rows/muc_subject.py
@@ -56,7 +56,7 @@ class MUCSubject(BaseRow):
date = ''
if subject.timestamp is not None:
- time_str = time.strftime("%c", time.localtime(subject.timestamp))
+ time_str = time.strftime('%c', time.localtime(subject.timestamp))
date = f' ({time_str})'
meta_str = f'{author}{date}'
diff --git a/gajim/gtk/css_config.py b/gajim/gtk/css_config.py
index ba7c040ad..eeb80bd25 100644
--- a/gajim/gtk/css_config.py
+++ b/gajim/gtk/css_config.py
@@ -42,7 +42,7 @@ settings = Gtk.Settings.get_default()
class CSSConfig:
def __init__(self) -> None:
- """
+ '''
CSSConfig handles loading and storing of all relevant Gajim style files
The order in which CSSConfig loads the styles
@@ -70,7 +70,7 @@ class CSSConfig:
These are the themes the Themes Dialog stores. Because they are
loaded at last they overwrite everything else. Users should add custom
- css here."""
+ css here.'''
# Delete empty rules
css_parser.ser.prefs.keepEmptyRules = False
@@ -165,7 +165,7 @@ class CSSConfig:
) -> None:
path = configpaths.get('STYLE') / filename
try:
- with open(path, "r", encoding='utf8') as file_:
+ with open(path, 'r', encoding='utf8') as file_:
css = file_.read()
except Exception as exc:
log.error('Error loading css: %s', exc)
diff --git a/gajim/gtk/dialogs.py b/gajim/gtk/dialogs.py
index 8dfa7cb90..589839985 100644
--- a/gajim/gtk/dialogs.py
+++ b/gajim/gtk/dialogs.py
@@ -147,9 +147,9 @@ class HigDialog(Gtk.MessageDialog):
return None
def popup(self) -> None:
- """
+ '''
Show dialog
- """
+ '''
# Give focus to top vbox
box = cast(Gtk.Box, self.get_children()[0])
inner_box = cast(Gtk.Box, box.get_children()[0])
@@ -158,9 +158,9 @@ class HigDialog(Gtk.MessageDialog):
class WarningDialog(HigDialog):
- """
+ '''
HIG compliant warning dialog
- """
+ '''
def __init__(self,
pritext: str,
@@ -181,9 +181,9 @@ class WarningDialog(HigDialog):
class InformationDialog(HigDialog):
- """
+ '''
HIG compliant info dialog
- """
+ '''
def __init__(self,
pritext: str,
@@ -204,9 +204,9 @@ class InformationDialog(HigDialog):
class ErrorDialog(HigDialog):
- """
+ '''
HIG compliant error dialog
- """
+ '''
def __init__(self,
pritext: str,
diff --git a/gajim/gtk/discovery.py b/gajim/gtk/discovery.py
index 4911a6e8c..b8c2d70d3 100644
--- a/gajim/gtk/discovery.py
+++ b/gajim/gtk/discovery.py
@@ -131,11 +131,11 @@ _cat_to_descr = {
class CacheDictionary:
- """
+ '''
A dictionary that keeps items around for only a specific time. Lifetime is
in minutes. Getrefresh specifies whether to refresh when an item is merely
accessed instead of set as well
- """
+ '''
def __init__(self, lifetime, getrefresh=True):
self.lifetime = lifetime * 1000 * 60
@@ -143,9 +143,9 @@ class CacheDictionary:
self.cache = {}
class CacheItem:
- """
+ '''
An object to store cache items and their timeouts
- """
+ '''
def __init__(self, value):
self.value = value
self.source = None
@@ -161,17 +161,17 @@ class CacheDictionary:
del self.cache[key]
def _expire_timeout(self, key):
- """
+ '''
The timeout has expired, remove the object
- """
+ '''
if key in self.cache:
del self.cache[key]
return False
def _refresh_timeout(self, key):
- """
+ '''
The object was accessed, refresh the timeout
- """
+ '''
item = self.cache[key]
if item.source:
GLib.source_remove(item.source)
@@ -205,16 +205,16 @@ _icon_cache = CacheDictionary(15)
def get_agent_address(jid, node=None):
- """
+ '''
Get an agent's address for displaying in the GUI
- """
+ '''
if node:
return '%s@%s' % (node, str(jid))
return str(jid)
class Closure:
- """
+ '''
A weak reference to a callback with arguments as an object
Weak references to methods immediately die, even if the object is still
@@ -222,7 +222,7 @@ class Closure:
that keeps a reference to the object instead.
Userargs and removeargs must be tuples.
- """
+ '''
def __init__(self, cb, userargs=(), remove=None, removeargs=()):
self.userargs = userargs
@@ -252,10 +252,10 @@ class Closure:
class ServicesCache:
- """
+ '''
Class that caches our query results. Each connection will have it's own
ServiceCache instance
- """
+ '''
def __init__(self, account):
self.account = account
@@ -282,9 +282,9 @@ class ServicesCache:
del self._cbs[cbkey]
def get_icon(self, identities=None, addr=''):
- """
+ '''
Return the icon for an agent
- """
+ '''
if identities is None:
identities = []
# Grab the first identity with an icon
@@ -308,9 +308,9 @@ class ServicesCache:
return 'gajim-agent-jabber'
def get_browser(self, identities=None, features=None):
- """
+ '''
Return the browser class for an agent
- """
+ '''
if identities is None:
identities = []
if features is None:
@@ -347,9 +347,9 @@ class ServicesCache:
return None
def get_info(self, jid, node, cb, force=False, nofetch=False, args=()):
- """
+ '''
Get info for an agent
- """
+ '''
addr = get_agent_address(jid, node)
# Check the cache
if addr in self._info and not force:
@@ -373,9 +373,9 @@ class ServicesCache:
jid, node, callback=self._disco_info_received)
def get_items(self, jid, node, cb, force=False, nofetch=False, args=()):
- """
+ '''
Get a list of items in an agent
- """
+ '''
addr = get_agent_address(jid, node)
# Check the cache
if addr in self._items and not force:
@@ -399,10 +399,10 @@ class ServicesCache:
jid, node, callback=self._disco_items_received)
def _disco_info_received(self, task):
- """
+ '''
Callback for when we receive an agent's info
array is (agent, node, identities, features, data)
- """
+ '''
try:
result = task.finish()
@@ -421,10 +421,10 @@ class ServicesCache:
result.features, result.dataforms)
def _disco_info_error(self, result):
- """
+ '''
Callback for when a query fails. Even after the browse and agents
namespaces
- """
+ '''
addr = get_agent_address(result.jid)
# Call callbacks
@@ -452,10 +452,10 @@ class ServicesCache:
del self._cbs[cbkey]
def _disco_items_received(self, task):
- """
+ '''
Callback for when we receive an agent's items
array is (agent, node, items)
- """
+ '''
try:
result = task.finish()
@@ -482,10 +482,10 @@ class ServicesCache:
del self._cbs[cbkey]
def _disco_items_error(self, result):
- """
+ '''
Callback for when a query fails. Even after the browse and agents
namespaces
- """
+ '''
addr = get_agent_address(result.jid)
# Call callbacks
@@ -499,9 +499,9 @@ class ServicesCache:
class ServiceDiscoveryWindow:
- """
+ '''
Class that represents the Services Discovery window
- """
+ '''
def __init__(self, account, jid='', node=None, address_entry=False,
parent=None, initial_identities=None):
self._account = account
@@ -602,10 +602,10 @@ class ServiceDiscoveryWindow:
self.reload()
def _initial_state(self):
- """
+ '''
Set some initial state on the window. Separated in a method because it's
handy to use within browser's cleanup method
- """
+ '''
self.progressbar.hide()
title_text = _('Service Discovery using account %s') % self.account
self.window.set_title(title_text)
@@ -622,11 +622,11 @@ class ServiceDiscoveryWindow:
self.banner_subheader.hide()
def _destroy(self, chain=False):
- """
+ '''
Close the browser. This can optionally close its children and propagate
to the parent. This should happen on actions like register, or join to
kill off the entire browser chain
- """
+ '''
if self.dying:
return
self.dying = True
@@ -663,9 +663,9 @@ class ServiceDiscoveryWindow:
self.travel(self.jid, self.node)
def travel(self, jid, node):
- """
+ '''
Travel to an agent within the current services window
- """
+ '''
if self.browser:
self.browser.cleanup()
self.browser = None
@@ -682,9 +682,9 @@ class ServiceDiscoveryWindow:
self.cache.get_info(jid, node, self._travel, force=self.reloading)
def _travel(self, jid, node, identities, features, data):
- """
+ '''
Continuation of travel
- """
+ '''
if self.dying or jid != self.jid or node != self.node:
return
if not identities:
@@ -712,9 +712,9 @@ class ServiceDiscoveryWindow:
self.reloading = False
def open(self, jid, node):
- """
+ '''
Open an agent. By default, this happens in a new window
- """
+ '''
try:
win = app.interface.instances[
self.account]['disco'][get_agent_address(jid, node)]
@@ -780,12 +780,12 @@ class ServiceDiscoveryWindow:
class AgentBrowser:
- """
+ '''
Class that deals with browsing agents and appearance of the browser window.
This class and subclasses should basically be treated as "part" of the
ServiceDiscoveryWindow class, but had to be separated because this part is
dynamic
- """
+ '''
def __init__(self, account, jid, node):
self.account = account
@@ -797,15 +797,15 @@ class AgentBrowser:
self.active = False
def _get_agent_address(self):
- """
+ '''
Get the agent's address for displaying in the GUI
- """
+ '''
return get_agent_address(self.jid, self.node)
def _set_initial_title(self):
- """
+ '''
Set the initial window title based on agent address
- """
+ '''
self.window.window.set_title(
_('Browsing %(address)s using account %(account)s') % {
'address': self._get_agent_address(),
@@ -813,11 +813,11 @@ class AgentBrowser:
self.window._set_window_banner_text(self._get_agent_address())
def _create_treemodel(self):
- """
+ '''
Create the treemodel for the services treeview. When subclassing, note
that the first two columns should ALWAYS be of type string and contain
the JID and node of the item respectively
- """
+ '''
# JID, node, name, address
self.model = Gtk.ListStore(str, str, str, str)
self.model.set_sort_column_id(3, Gtk.SortType.ASCENDING)
@@ -845,10 +845,10 @@ class AgentBrowser:
self.window.services_treeview.set_headers_visible(False)
def _add_actions(self):
- """
+ '''
Add the action buttons to the buttonbox for actions the browser can
perform
- """
+ '''
self.browse_button = Gtk.Button()
self.browse_button.connect('clicked', self.on_browse_button_clicked)
self.window.action_buttonbox.add(self.browse_button)
@@ -856,17 +856,17 @@ class AgentBrowser:
self.browse_button.show_all()
def _clean_actions(self):
- """
+ '''
Remove the action buttons specific to this browser
- """
+ '''
if self.browse_button:
self.browse_button.destroy()
self.browse_button = None
def _set_title(self, jid, node, identities, features, data):
- """
+ '''
Set the window title based on agent info
- """
+ '''
# Set the banner and window title
name = ''
if len(identities) > 1:
@@ -894,10 +894,10 @@ class AgentBrowser:
pass
def prepare_window(self, window):
- """
+ '''
Prepare the service discovery window. Called when a browser is hooked up
with a ServiceDiscoveryWindow instance
- """
+ '''
self.window = window
self.cache = window.cache
@@ -911,9 +911,9 @@ class AgentBrowser:
self.cache.get_info(self.jid, self.node, self._set_title)
def cleanup(self):
- """
+ '''
Cleanup when the window intends to switch browsers
- """
+ '''
self.active = False
self._clean_actions()
@@ -923,15 +923,15 @@ class AgentBrowser:
self.window._initial_state()
def update_theme(self):
- """
+ '''
Called when the default theme is changed
- """
+ '''
def on_browse_button_clicked(self, widget=None):
- """
+ '''
When we want to browse an agent: open a new services window with a
browser for the agent type
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if not iter_:
@@ -942,9 +942,9 @@ class AgentBrowser:
self.window.open(jid, node)
def update_actions(self):
- """
+ '''
When we select a row: activate action buttons based on the agent's info
- """
+ '''
if self.browse_button:
self.browse_button.set_sensitive(False)
model, iter_ = \
@@ -957,9 +957,9 @@ class AgentBrowser:
self.cache.get_info(jid, node, self._update_actions, nofetch=True)
def _update_actions(self, jid, node, identities, features, data):
- """
+ '''
Continuation of update_actions
- """
+ '''
if not identities or not self.browse_button:
return
klass = self.cache.get_browser(identities, features)
@@ -967,10 +967,10 @@ class AgentBrowser:
self.browse_button.set_sensitive(True)
def default_action(self):
- """
+ '''
When we double-click a row: perform the default action on the selected
item
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if not iter_:
@@ -981,9 +981,9 @@ class AgentBrowser:
self.cache.get_info(jid, node, self._default_action, nofetch=True)
def _default_action(self, jid, node, identities, features, data):
- """
+ '''
Continuation of default_action
- """
+ '''
if self.cache.get_browser(identities, features):
# Browse if we can
self.on_browse_button_clicked()
@@ -991,9 +991,9 @@ class AgentBrowser:
return False
def browse(self, force=False):
- """
+ '''
Fill the treeview with agents, fetching the info if necessary
- """
+ '''
self.model.clear()
self._total_items = self._progress = 0
self.window.progressbar.show()
@@ -1002,19 +1002,19 @@ class AgentBrowser:
force=force, args=(force,))
def _pulse_timeout_cb(self, *args):
- """
+ '''
Simple callback to keep the progressbar pulsing
- """
+ '''
if not self.active:
return False
self.window.progressbar.pulse()
return True
def _find_item(self, jid, node):
- """
+ '''
Check if an item is already in the treeview. Return an iter to it if so,
None otherwise
- """
+ '''
iter_ = self.model.get_iter_first()
while iter_:
cjid = self.model.get_value(iter_, 0)
@@ -1030,9 +1030,9 @@ class AgentBrowser:
pass
def _agent_items(self, jid, node, items, force):
- """
+ '''
Callback for when we receive a list of agent items
- """
+ '''
self.model.clear()
self.add_self_line()
self._total_items = 0
@@ -1074,9 +1074,9 @@ class AgentBrowser:
GLib.idle_add(next, loader)
def _agent_info(self, jid, node, identities, features, data):
- """
+ '''
Callback for when we receive info about an agent's item
- """
+ '''
iter_ = self._find_item(jid, node)
if not iter_:
# Not in the treeview, stop
@@ -1090,27 +1090,27 @@ class AgentBrowser:
self.update_actions()
def _add_item(self, jid, node, parent_node, item, force):
- """
+ '''
Called when an item should be added to the model. The result of a
disco#items query
- """
+ '''
self.model.append((jid, node, item.get('name', ''),
get_agent_address(jid, node)))
self.cache.get_info(jid, node, self._agent_info, force=force)
def _update_item(self, iter_, jid, node, item):
- """
+ '''
Called when an item should be updated in the model. The result of a
disco#items query
- """
+ '''
if 'name' in item:
self.model[iter_][2] = item['name']
def _update_info(self, iter_, jid, node, identities, features, data):
- """
+ '''
Called when an item should be updated in the model with further info.
The result of a disco#info query
- """
+ '''
name = identities[0].name or ''
if name:
self.model[iter_][2] = name
@@ -1120,10 +1120,10 @@ class AgentBrowser:
class ToplevelAgentBrowser(AgentBrowser):
- """
+ '''
This browser is used at the top level of a jabber server to browse services
such as transports, conference servers, etc
- """
+ '''
def __init__(self, *args):
AgentBrowser.__init__(self, *args)
@@ -1158,9 +1158,9 @@ class ToplevelAgentBrowser(AgentBrowser):
self.cache.get_info(self.jid, self.node, self._agent_info, force=False)
def _pixbuf_renderer_data_func(self, col, cell, model, iter_, data=None):
- """
+ '''
Callback for setting the pixbuf renderer's properties
- """
+ '''
jid = model.get_value(iter_, 0)
if jid:
icon_name = model.get_value(iter_, 2)
@@ -1170,9 +1170,9 @@ class ToplevelAgentBrowser(AgentBrowser):
cell.set_property('visible', False)
def _text_renderer_data_func(self, col, cell, model, iter_, data=None):
- """
+ '''
Callback for setting the text renderer's properties
- """
+ '''
jid = model.get_value(iter_, 0)
markup = model.get_value(iter_, 3)
state = model.get_value(iter_, 4)
@@ -1193,9 +1193,9 @@ class ToplevelAgentBrowser(AgentBrowser):
cell.set_property('foreground_set', False)
def _treemodel_sort_func(self, model, iter1, iter2, data=None):
- """
+ '''
Sort function for our treemode
- """
+ '''
# Compare state
state1 = model.get_value(iter1, 4)
state2 = model.get_value(iter2, 4)
@@ -1303,9 +1303,9 @@ class ToplevelAgentBrowser(AgentBrowser):
AgentBrowser._clean_actions(self)
def on_search_button_clicked(self, widget=None):
- """
+ '''
When we want to search something: open search window
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if not iter_:
@@ -1324,9 +1324,9 @@ class ToplevelAgentBrowser(AgentBrowser):
self.window.services_treeview.queue_draw()
def _on_execute_button_clicked(self, widget=None):
- """
+ '''
When we want to execute a command: open adhoc command window
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if not iter_:
@@ -1335,10 +1335,10 @@ class ToplevelAgentBrowser(AgentBrowser):
open_window('AdHocCommands', account=self.account, jid=service)
def _on_register_button_clicked(self, widget=None):
- """
+ '''
When we want to register an agent: request information about registering
with the agent and close the window
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if not iter_:
@@ -1349,10 +1349,10 @@ class ToplevelAgentBrowser(AgentBrowser):
'ServiceRegistration', account=self.account, address=jid)
def _on_join_button_clicked(self, widget):
- """
+ '''
When we want to join an IRC room or create a new MUC room: Opens the
join_groupchat_window
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if not iter_:
@@ -1441,15 +1441,15 @@ class ToplevelAgentBrowser(AgentBrowser):
AgentBrowser.browse(self, force=force)
def _expand_all(self):
- """
+ '''
Expand all items in the treeview
- """
+ '''
self.window.services_treeview.expand_all()
def _update_progressbar(self):
- """
+ '''
Update the progressbar
- """
+ '''
# Refresh this every update
if self._progressbar_sourceid:
GLib.source_remove(self._progressbar_sourceid)
@@ -1473,17 +1473,17 @@ class ToplevelAgentBrowser(AgentBrowser):
self.window.progressbar.set_fraction(fraction)
def _hide_progressbar_cb(self, *args):
- """
+ '''
Simple callback to hide the progressbar a second after we finish
- """
+ '''
if self.active:
self.window.progressbar.hide()
return False
def _friendly_category(self, category, type_=None):
- """
+ '''
Get the friendly category name
- """
+ '''
cat = None
if type_:
# Try type-specific override
@@ -1499,16 +1499,16 @@ class ToplevelAgentBrowser(AgentBrowser):
return cat
def _create_category(self, cat, type_=None):
- """
+ '''
Creates a category row
- """
+ '''
cat = self._friendly_category(cat, type_)
return self.model.append(None, ('', '', None, cat, None))
def _find_category(self, cat, type_=None):
- """
+ '''
Looks up a category row and returns the iterator to it, or None
- """
+ '''
cat = self._friendly_category(cat, type_)
iter_ = self.model.get_iter_first()
while iter_:
@@ -1544,9 +1544,9 @@ class ToplevelAgentBrowser(AgentBrowser):
# Row text
addr = get_agent_address(jid, node)
if 'name' in item:
- descr = "<b>%s</b>\n%s" % (item['name'], addr)
+ descr = '<b>%s</b>\n%s' % (item['name'], addr)
else:
- descr = "<b>%s</b>" % addr
+ descr = '<b>%s</b>' % addr
# Guess which kind of service this is
identities = []
type_ = app.get_transport_name_from_jid(
@@ -1573,21 +1573,21 @@ class ToplevelAgentBrowser(AgentBrowser):
def _update_item(self, iter_, jid, node, item):
addr = get_agent_address(jid, node)
if 'name' in item:
- descr = "<b>%s</b>\n%s" % (item['name'], addr)
+ descr = '<b>%s</b>\n%s' % (item['name'], addr)
else:
- descr = "<b>%s</b>" % addr
+ descr = '<b>%s</b>' % addr
self.model[iter_][3] = descr
def _update_info(self, iter_, jid, node, identities, features, data):
addr = get_agent_address(jid, node)
if not identities:
- descr = "<b>%s</b>" % addr
+ descr = '<b>%s</b>' % addr
else:
name = identities[0].name or ''
if name:
- descr = "<b>%s</b>\n%s" % (name, addr)
+ descr = '<b>%s</b>\n%s' % (name, addr)
else:
- descr = "<b>%s</b>" % addr
+ descr = '<b>%s</b>' % addr
# Update progress
self._progress += 1
@@ -1713,10 +1713,10 @@ class MucBrowser(AgentBrowser):
self.join_button = None
def _on_join_button_clicked(self, *args):
- """
+ '''
When we want to join a conference: ask specific information about the
selected agent and close the window
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if not iter_:
@@ -1734,24 +1734,24 @@ class MucBrowser(AgentBrowser):
self._on_join_button_clicked()
def _start_info_query(self):
- """
+ '''
Idle callback to start checking for visible rows
- """
+ '''
self._fetch_source = None
self._query_visible()
return False
def on_scroll(self, *args):
- """
+ '''
Scrollwindow callback to trigger new queries on scrolling
- """
+ '''
# This apparently happens when inactive sometimes
self._query_visible()
def _query_visible(self):
- """
+ '''
Query the next visible row for info
- """
+ '''
if self._fetch_source:
# We're already fetching
return
@@ -1778,11 +1778,11 @@ class MucBrowser(AgentBrowser):
self._fetch_source = None
def _channel_altinfo(self, jid, node, items, name=None):
- """
+ '''
Callback for the alternate disco#items query. We try to at least get
the amount of users in the room if the service does not support MUC
dataforms
- """
+ '''
if items == 0:
# The server returned an error
self._broken += 1
@@ -1846,20 +1846,20 @@ class MucBrowser(AgentBrowser):
def PubSubBrowser(account, jid, node):
- """
+ '''
Return an AgentBrowser subclass that will display service discovery for
particular pubsub service. Different pubsub services may need to present
different data during browsing
- """
+ '''
# For now, only discussion groups are supported...
# TODO: check if it has appropriate features to be such kind of service
return DiscussionGroupsBrowser(account, jid, node)
class DiscussionGroupsBrowser(AgentBrowser):
- """
+ '''
For browsing pubsub-based discussion groups service
- """
+ '''
def __init__(self, account, jid, node):
AgentBrowser.__init__(self, account, jid, node)
@@ -1878,9 +1878,9 @@ class DiscussionGroupsBrowser(AgentBrowser):
jid, self._on_pep_subscriptions)
def _create_treemodel(self):
- """
+ '''
Create treemodel for the window
- """
+ '''
# JID, node, name (with description) - pango markup,
# don't have info?, subscribed?
self.model = Gtk.TreeStore(str, str, str, bool, bool)
@@ -1933,10 +1933,10 @@ class DiscussionGroupsBrowser(AgentBrowser):
return self.in_list
def _add_item(self, jid, node, parent_node, item, force):
- """
+ '''
Called when we got basic information about new node from query. Show the
item
- """
+ '''
name = item['name'] or ''
@@ -2018,10 +2018,10 @@ class DiscussionGroupsBrowser(AgentBrowser):
self.unsubscribe_button = None
def update_actions(self):
- """
+ '''
Called when user selected a row. Make subscribe/unsubscribe buttons
sensitive appropriately
- """
+ '''
# We have nothing to do if we don't have buttons...
if self.subscribe_button is None:
return
@@ -2041,9 +2041,9 @@ class DiscussionGroupsBrowser(AgentBrowser):
self.unsubscribe_button.set_sensitive(subscribed)
def _on_post_button_clicked(self, widget):
- """
+ '''
Called when 'post' button is pressed. Open window to create post
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if iter_ is None:
@@ -2054,9 +2054,9 @@ class DiscussionGroupsBrowser(AgentBrowser):
GroupsPostWindow(self.account, self.jid, groupnode)
def _on_subscribe_button_clicked(self, widget):
- """
+ '''
Called when 'subscribe' button is pressed. Send subscribtion request
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if iter_ is None:
@@ -2069,9 +2069,9 @@ class DiscussionGroupsBrowser(AgentBrowser):
self.jid, node, self._on_pep_subscribe, groupnode=node)
def _on_unsubscribe_button_clicked(self, widget):
- """
+ '''
Called when 'unsubscribe' button is pressed. Send unsubscription request
- """
+ '''
model, iter_ = \
self.window.services_treeview.get_selection().get_selected()
if iter_ is None:
@@ -2084,10 +2084,10 @@ class DiscussionGroupsBrowser(AgentBrowser):
self.jid, node, self._on_pep_unsubscribe, groupnode=node)
def _on_pep_subscriptions(self, _nbxmpp_client, request):
- """
+ '''
We got the subscribed groups list stanza. Now, if we already have items
on the list, we should actualize them
- """
+ '''
try:
subscriptions = request.getTag('pubsub').getTag('subscriptions')
except Exception:
@@ -2113,9 +2113,9 @@ class DiscussionGroupsBrowser(AgentBrowser):
self.update_actions()
def _on_pep_subscribe(self, _nbxmpp_client, request, groupnode):
- """
+ '''
We have just subscribed to a node. Update UI
- """
+ '''
self.subscriptions.add(groupnode)
model = self.window.services_treeview.get_model()
@@ -2127,9 +2127,9 @@ class DiscussionGroupsBrowser(AgentBrowser):
self.update_actions()
def _on_pep_unsubscribe(self, _nbxmpp_client, request, groupnode):
- """
+ '''
We have just unsubscribed from a node. Update UI
- """
+ '''
self.subscriptions.remove(groupnode)
model = self.window.services_treeview.get_model()
@@ -2147,10 +2147,10 @@ _agent_type_info = _gen_agent_type_info()
class GroupsPostWindow:
def __init__(self, account, servicejid, groupid):
- """
+ '''
Open new 'create post' window to create message for groupid on
servicejid service
- """
+ '''
assert isinstance(servicejid, str)
assert isinstance(groupid, str)
@@ -2169,9 +2169,9 @@ class GroupsPostWindow:
self.window.destroy()
def _on_send_button_clicked(self, w):
- """
+ '''
Gather info from widgets and send it as a message
- """
+ '''
# Constructing item to publish... that's atom:entry element
item = nbxmpp.Node('entry', {'xmlns': 'http://www.w3.org/2005/Atom'})
author = item.addChild('author')
diff --git a/gajim/gtk/features.py b/gajim/gtk/features.py
index e2fea2d2a..6625a672c 100644
--- a/gajim/gtk/features.py
+++ b/gajim/gtk/features.py
@@ -114,7 +114,7 @@ class Features(Gtk.ApplicationWindow):
None),
Feature(_('Automatic Status'),
self._idle_available(),
- _('Enables Gajim to measure your computer\'s idle time in '
+ _("Enables Gajim to measure your computer's idle time in "
'order to set your Status automatically'),
_('Requires: libxss'),
_('No additional requirements'),
diff --git a/gajim/gtk/filetransfer.py b/gajim/gtk/filetransfer.py
index 6c1b16215..30f67da08 100644
--- a/gajim/gtk/filetransfer.py
+++ b/gajim/gtk/filetransfer.py
@@ -327,9 +327,9 @@ class FileTransfersWindow:
return value
def find_transfer_by_jid(self, account, jid):
- """
+ '''
Find all transfers with peer 'jid' that belong to 'account'
- """
+ '''
active_transfers = [[], []] # ['senders', 'receivers']
allfp = FilesProp.getAllFileProp()
for file_props in allfp:
@@ -417,9 +417,9 @@ class FileTransfersWindow:
file_path: str,
file_desc: str = ''
) -> bool:
- """
+ '''
Start the real transfer(upload) of the file
- """
+ '''
if file_is_locked(file_path):
pritext = _('Gajim can not read this file')
sextext = _('Another process is using this file.')
@@ -482,7 +482,7 @@ class FileTransfersWindow:
file_name = GLib.markup_escape_text(
os.path.basename(file_path))
ErrorDialog(
- _('Cannot overwrite existing file \'%s\'') % file_name,
+ _('Cannot overwrite existing file "%s"') % file_name,
_('A file with this name already exists and you do '
'not have permission to overwrite it.'))
return
@@ -494,7 +494,7 @@ class FileTransfersWindow:
# windows, not to mark that a folder is read-only.
# See ticket #3587
ErrorDialog(
- _('Directory \'%s\' is not writable') % dirname,
+ _('Directory "%s" is not writable') % dirname,
_('You do not have permissions to create files '
'in this directory.'))
return
@@ -511,9 +511,9 @@ class FileTransfersWindow:
file_name=file_props.name)
def set_status(self, file_props, status):
- """
+ '''
Change the status of a transfer to state 'status'
- """
+ '''
iter_ = self.get_iter_by_sid(file_props.type_, file_props.sid)
if iter_ is None:
return
@@ -558,10 +558,10 @@ class FileTransfersWindow:
self._select_func(path)
def _format_percent(self, percent):
- """
+ '''
Add extra spaces from both sides of the percent, so that progress
string has always a fixed size
- """
+ '''
_str = ' '
if percent != 100.:
_str += ' '
@@ -616,9 +616,9 @@ class FileTransfersWindow:
event.file_props.received_len)
def set_progress(self, typ, sid, transfered_size, iter_=None):
- """
+ '''
Change the progress of a transfer with new transfered size
- """
+ '''
if time.time() - self._last_progress_update < 0.5:
# Update window every 500ms only
return
@@ -697,10 +697,10 @@ class FileTransfersWindow:
self._select_func(path)
def get_iter_by_sid(self, typ, sid):
- """
+ '''
Return iter to the row, which holds file transfer, identified by the
session id
- """
+ '''
iter_ = self.model.get_iter_first()
while iter_:
if typ + sid == self.model[iter_][Column.SID]:
@@ -720,10 +720,10 @@ class FileTransfersWindow:
file_name: str,
file_desc: str = ''
) -> Optional[FileProp]:
- """
+ '''
Create new file_props object and set initial file transfer
properties in it
- """
+ '''
if os.path.isfile(file_path):
stat = os.stat(file_path)
else:
@@ -755,9 +755,9 @@ class FileTransfersWindow:
return file_props
def add_transfer(self, account, contact, file_props):
- """
+ '''
Add new transfer to FT window and show the FT window
- """
+ '''
if file_props is None:
return
@@ -799,19 +799,19 @@ class FileTransfersWindow:
self._on_open_folder_menuitem_activate(widget)
def _set_cleanup_sensitivity(self):
- """
+ '''
Check if there are transfer rows and set cleanup_button sensitive, or
insensitive if model is empty
- """
+ '''
if not self.model:
self._ui.cleanup_button.set_sensitive(False)
else:
self._ui.cleanup_button.set_sensitive(True)
def _set_all_insensitive(self):
- """
+ '''
Make all buttons/menuitems insensitive
- """
+ '''
self._ui.pause_resume_button.set_sensitive(False)
self._ui.pause_resume_menuitem.set_sensitive(False)
self._ui.remove_menuitem.set_sensitive(False)
@@ -821,10 +821,10 @@ class FileTransfersWindow:
self._set_cleanup_sensitivity()
def _set_buttons_sensitive(self, path, is_row_selected):
- """
+ '''
Make buttons/menuitems sensitive as appropriate to the state of file
transfer located at path 'path'
- """
+ '''
if path is None:
self._set_all_insensitive()
return
@@ -861,9 +861,9 @@ class FileTransfersWindow:
return True
def _selection_changed(self, args):
- """
+ '''
Selection has changed - change the sensitivity of the buttons/menuitems
- """
+ '''
selection = args
selected = selection.get_selected_rows()
if selected[1] != []:
@@ -974,9 +974,9 @@ class FileTransfersWindow:
event.time)
def _on_transfers_list_key_press_event(self, widget, event):
- """
+ '''
When a key is pressed in the treeviews
- """
+ '''
iter_ = None
try:
iter_ = self._ui.transfers_list.get_selection().get_selected()[1]
diff --git a/gajim/gtk/groupchat_nick_completion.py b/gajim/gtk/groupchat_nick_completion.py
index 7475739b2..fdb309539 100644
--- a/gajim/gtk/groupchat_nick_completion.py
+++ b/gajim/gtk/groupchat_nick_completion.py
@@ -104,12 +104,12 @@ class GroupChatNickCompletion:
nicks: list[str],
beginning: str
) -> list[str]:
- """
+ '''
Generate the order of suggested MUC autocompletions
`nicks` is the list of contacts currently participating in a MUC
`beginning` is the text already typed by the user
- """
+ '''
def _nick_matching(nick: str) -> bool:
return (nick != self._contact.nickname and
nick.lower().startswith(beginning.lower()))
diff --git a/gajim/gtk/groupchat_roster.py b/gajim/gtk/groupchat_roster.py
index 0c1978b52..171db7f71 100644
--- a/gajim/gtk/groupchat_roster.py
+++ b/gajim/gtk/groupchat_roster.py
@@ -397,9 +397,9 @@ class GroupchatRoster(Gtk.ScrolledWindow, EventHelper):
iter2: Gtk.TreeIter,
_user_data: Optional[object]
) -> int:
- """
+ '''
Compare two iterators to sort them
- """
+ '''
is_contact = model.iter_parent(iter1)
if is_contact:
# Sort contacts with pending events to top
diff --git a/gajim/gtk/message_input.py b/gajim/gtk/message_input.py
index 797470611..0251c8cbc 100644
--- a/gajim/gtk/message_input.py
+++ b/gajim/gtk/message_input.py
@@ -49,9 +49,9 @@ FORMAT_CHARS: dict[str, str] = {
class MessageInputTextView(Gtk.TextView):
- """
+ '''
A Gtk.Textview for chat message input
- """
+ '''
def __init__(self, account: str, contact: ChatContactT) -> None:
Gtk.TextView.__init__(self)
self.account = account
diff --git a/gajim/gtk/preferences.py b/gajim/gtk/preferences.py
index e43612800..0b07e1414 100644
--- a/gajim/gtk/preferences.py
+++ b/gajim/gtk/preferences.py
@@ -587,14 +587,14 @@ class AutomaticStatus(PreferenceBox):
Setting(SettingKind.AUTO_AWAY,
_('Auto Away'),
SettingType.DIALOG,
- desc=_('Change your status to \'Away\' after a certain '
+ desc=_('Change your status to "Away" after a certain '
'amount of time'),
props={'dialog': AutoAwayDialog}),
Setting(SettingKind.AUTO_EXTENDED_AWAY,
_('Auto Not Available'),
SettingType.DIALOG,
- desc=_('Change your status to \'Not Available\' after a '
+ desc=_('Change your status to "Not Available" after a '
'certain amount of time'),
props={'dialog': AutoExtendedAwayDialog}),
diff --git a/gajim/gtk/preview.py b/gajim/gtk/preview.py
index 00d0bba3f..dd5e17773 100644
--- a/gajim/gtk/preview.py
+++ b/gajim/gtk/preview.py
@@ -251,7 +251,7 @@ class PreviewWidget(Gtk.Box):
dirname = target_path.parent
if not os.access(dirname, os.W_OK):
ErrorDialog(
- _('Directory \'%s\' is not writable') % dirname,
+ _('Directory "%s" is not writable') % dirname,
_('You do not have the proper permissions to '
'create files in this directory.'),
transient_for=app.app.get_active_window())
diff --git a/gajim/gtk/roster.py b/gajim/gtk/roster.py
index 49780fcf5..e91de30f8 100644
--- a/gajim/gtk/roster.py
+++ b/gajim/gtk/roster.py
@@ -368,7 +368,7 @@ class Roster(Gtk.ScrolledWindow, EventHelper):
if has_transport_contacts:
ConfirmationDialog(
_('Remove Transport'),
- _('Transport \'%s\' will be '
+ _('Transport "%s" will be '
'removed') % selected_contact.name,
_('You will no longer be able to send and receive '
'messages from and to contacts using this transport.'),
@@ -746,9 +746,9 @@ class Roster(Gtk.ScrolledWindow, EventHelper):
iter1: Gtk.TreeIter,
iter2: Gtk.TreeIter,
_user_data: Literal[None]):
- """
+ '''
Compare two iterators to sort them
- """
+ '''
is_contact = model.iter_parent(iter1)
if is_contact:
diff --git a/gajim/gtk/roster_item_exchange.py b/gajim/gtk/roster_item_exchange.py
index 4cb27121b..bebd75d7f 100644
--- a/gajim/gtk/roster_item_exchange.py
+++ b/gajim/gtk/roster_item_exchange.py
@@ -27,9 +27,9 @@ from .builder import get_builder
class RosterItemExchange(Gtk.ApplicationWindow):
- """
+ '''
Used when someone sends a Roster Item Exchange suggestion (XEP-0144)
- """
+ '''
def __init__(self,
account: str,
action: str,
diff --git a/gajim/gtk/ssl_error_dialog.py b/gajim/gtk/ssl_error_dialog.py
index 94a338393..d82d6de55 100644
--- a/gajim/gtk/ssl_error_dialog.py
+++ b/gajim/gtk/ssl_error_dialog.py
@@ -60,7 +60,7 @@ class SSLErrorDialog(Gtk.ApplicationWindow):
_('There was an error while attempting to verify the SSL '
'certificate of your XMPP server (%s).') % self._server)
- unknown_error = _('Unknown SSL error \'%s\'') % self._error
+ unknown_error = _('Unknown SSL error "%s"') % self._error
ssl_error = GIO_TLS_ERRORS.get(self._error, unknown_error)
self._ui.ssl_error.set_text(ssl_error)
diff --git a/gajim/gtk/synchronize_accounts.py b/gajim/gtk/synchronize_accounts.py
index 068ff5d75..35eabc6cc 100644
--- a/gajim/gtk/synchronize_accounts.py
+++ b/gajim/gtk/synchronize_accounts.py
@@ -87,9 +87,9 @@ class SynchronizeAccounts(Gtk.ApplicationWindow):
self.destroy()
def _init_accounts(self) -> None:
- """
+ '''
Initialize listStore with existing accounts
- """
+ '''
model = self._ui.accounts_treeview.get_model()
assert isinstance(model, Gtk.ListStore)
model.clear()
diff --git a/gajim/gtk/tooltips.py b/gajim/gtk/tooltips.py
index 13c011904..6e223f95b 100644
--- a/gajim/gtk/tooltips.py
+++ b/gajim/gtk/tooltips.py
@@ -75,16 +75,16 @@ class GCTooltip:
return False, self._ui.tooltip_grid
def _hide_grid_children(self) -> None:
- """
+ '''
Hide all Elements of the Tooltip Grid
- """
+ '''
for child in self._ui.tooltip_grid.get_children():
child.hide()
def _populate_grid(self, contact: types.GroupchatParticipant) -> None:
- """
+ '''
Populate the Tooltip Grid with data of from the contact
- """
+ '''
self._hide_grid_children()
self._ui.nick.set_text(contact.name)
diff --git a/gajim/gtk/util.py b/gajim/gtk/util.py
index 9789d8a1d..73c822857 100644
--- a/gajim/gtk/util.py
+++ b/gajim/gtk/util.py
@@ -174,9 +174,9 @@ def get_total_screen_geometry() -> tuple[int, int]:
def resize_window(window: Gtk.Window, width: int, height: int) -> None:
- """
+ '''
Resize window, but also checks if huge window or negative values
- """
+ '''
screen_w, screen_h = get_total_screen_geometry()
if not width or not height:
return
@@ -187,9 +187,9 @@ def resize_window(window: Gtk.Window, width: int, height: int) -> None:
def move_window(window: Gtk.Window, pos_x: int, pos_y: int) -> None:
- """
+ '''
Move the window, but also check if out of screen
- """
+ '''
screen_w, screen_h = get_total_screen_geometry()
pos_x = max(pos_x, 0)
pos_y = max(pos_y, 0)
@@ -224,10 +224,10 @@ def restore_main_window_position() -> None:
def get_completion_liststore(entry: Gtk.Entry) -> Gtk.ListStore:
- """
+ '''
Create a completion model for entry widget completion list consists of
(Pixbuf, Text) rows
- """
+ '''
completion = Gtk.EntryCompletion()
liststore = Gtk.ListStore(str, str)
@@ -254,14 +254,14 @@ def get_cursor(name: str) -> Gdk.Cursor:
def scroll_to_end(widget: Gtk.ScrolledWindow) -> bool:
- """Scrolls to the end of a GtkScrolledWindow.
+ '''Scrolls to the end of a GtkScrolledWindow.
Args:
widget (GtkScrolledWindow)
Returns:
bool: The return value is False so it can be used with GLib.idle_add.
- """
+ '''
adj_v = widget.get_vadjustment()
if adj_v is None:
# This can happen when the Widget is already destroyed when called
@@ -276,14 +276,14 @@ def scroll_to_end(widget: Gtk.ScrolledWindow) -> bool:
def at_the_end(widget: Gtk.ScrolledWindow) -> bool:
- """Determines if a Scrollbar in a GtkScrolledWindow is at the end.
+ '''Determines if a Scrollbar in a GtkScrolledWindow is at the end.
Args:
widget (GtkScrolledWindow)
Returns:
bool: The return value is True if at the end, False if not.
- """
+ '''
adj_v = widget.get_vadjustment()
max_scroll_pos = adj_v.get_upper() - adj_v.get_page_size()
return adj_v.get_value() == max_scroll_pos
@@ -351,11 +351,11 @@ def get_monitor_scale_factor() -> int:
def get_primary_accel_mod() -> Optional[Gdk.ModifierType]:
- """
+ '''
Returns the primary Gdk.ModifierType modifier.
cmd on osx, ctrl everywhere else.
- """
- return Gtk.accelerator_parse("<Primary>")[1]
+ '''
+ return Gtk.accelerator_parse('<Primary>')[1]
def get_hardware_key_codes(keyval: int) -> list[int]:
@@ -515,9 +515,9 @@ def add_css_to_widget(widget: Any, css: str) -> None:
def get_pixbuf_from_data(file_data: bytes) -> Optional[GdkPixbuf.Pixbuf]:
# TODO: This already exists in preview_helpery pixbuf_from_data
- """
+ '''
Get image data and returns GdkPixbuf.Pixbuf
- """
+ '''
pixbufloader = GdkPixbuf.PixbufLoader()
try:
pixbufloader.write(file_data)
@@ -529,7 +529,7 @@ def get_pixbuf_from_data(file_data: bytes) -> Optional[GdkPixbuf.Pixbuf]:
log.warning('loading avatar using pixbufloader failed, trying to '
'convert avatar image using pillow')
try:
- avatar = Image.open(BytesIO(file_data)).convert("RGBA")
+ avatar = Image.open(BytesIO(file_data)).convert('RGBA')
array = GLib.Bytes.new(avatar.tobytes()) # type: ignore
width, height = avatar.size
pixbuf = GdkPixbuf.Pixbuf.new_from_bytes(
@@ -584,7 +584,7 @@ def load_pixbuf(path: Union[str, Path],
try:
with open(path, 'rb') as im_handle:
img = Image.open(im_handle)
- avatar = img.convert("RGBA")
+ avatar = img.convert('RGBA')
except (NameError, OSError):
log.warning('Pillow convert failed: %s', path)
log.debug('Error', exc_info=True)
@@ -711,21 +711,21 @@ def _connect_destroy(sender: Any,
handler: Any,
*args: Any,
**kwargs: Any) -> int:
- """Connect a bound method to a foreign object signal and disconnect
+ '''Connect a bound method to a foreign object signal and disconnect
if the object the method is bound to emits destroy (Gtk.Widget subclass).
Also works if the handler is a nested function in a method and
references the method's bound object.
This solves the problem that the sender holds a strong reference
to the bound method and the bound to object doesn't get GCed.
- """
+ '''
- if hasattr(handler, "__self__"):
+ if hasattr(handler, '__self__'):
obj = handler.__self__
else:
# XXX: get the "self" var of the enclosing scope.
# Used for nested functions which ref the object but aren't methods.
# In case they don't ref "self" normal connect() should be used anyway.
- index = handler.__code__.co_freevars.index("self")
+ index = handler.__code__.co_freevars.index('self')
obj = handler.__closure__[index].cell_contents
assert obj is not sender
diff --git a/gajim/gtk/xml_console.py b/gajim/gtk/xml_console.py
index a1fdbdf81..047a86c25 100644
--- a/gajim/gtk/xml_console.py
+++ b/gajim/gtk/xml_console.py
@@ -214,7 +214,7 @@ class XMLConsoleWindow(Gtk.ApplicationWindow, EventHelper):
# If offline or connecting
ErrorDialog(
_('Connection not available'),
- _('Please make sure you are connected with \'%s\'.') %
+ _('Please make sure you are connected with "%s".') %
self._selected_send_account)
return
buffer_ = self._ui.input_entry.get_buffer()
diff --git a/gajim/gui_interface.py b/gajim/gui_interface.py
index 2e9becad8..cc0841bae 100644
--- a/gajim/gui_interface.py
+++ b/gajim/gui_interface.py
@@ -132,11 +132,11 @@ class Interface:
# pylint: enable=line-too-long
def _register_core_handlers(self) -> None:
- """
+ '''
Register core handlers in Global Events Dispatcher (GED).
This is part of rewriting whole events handling system to use GED.
- """
+ '''
for event_name, event_handlers in self.handlers.items():
for event_handler in event_handlers:
prio = ged.GUI1
@@ -150,9 +150,9 @@ class Interface:
@staticmethod
def handle_event_signed_in(event):
- """
+ '''
SIGNED_IN event is emitted when we sign in, so handle it
- """
+ '''
# ('SIGNED_IN', account, ())
# block signed in notifications for 30 seconds
@@ -540,9 +540,9 @@ class Interface:
window.remove_account(account)
def autoconnect(self) -> None:
- """
+ '''
Auto connect at startup
- """
+ '''
for account, con in app.connections.items():
if not app.settings.get_account_setting(account, 'autoconnect'):
@@ -592,9 +592,9 @@ class Interface:
client.change_status(status, message)
def process_connections(self) -> bool:
- """
+ '''
Called each foo (200) milliseconds. Check for idlequeue timeouts
- """
+ '''
try:
app.idlequeue.process()
except Exception:
@@ -707,9 +707,9 @@ class Interface:
class ThreadInterface:
def __init__(self, func, func_args=(), callback=None, callback_args=()):
- """
+ '''
Call a function in a thread
- """
+ '''
def thread_function(func, func_args, callback, callback_args):
output = func(*func_args)
if callback:
diff --git a/gajim/plugins/repository.py b/gajim/plugins/repository.py
index b097541f3..8a5477aa2 100644
--- a/gajim/plugins/repository.py
+++ b/gajim/plugins/repository.py
@@ -39,14 +39,14 @@ UPDATE_CHECK_INTERVAL = 68400
class PluginRepository(Observable):
- """Signals
+ '''Signals
- donwload-started
- download-finished
- download-failed
- plugin-updates-available
- auto-update-finished
- """
+ '''
def __init__(self) -> None:
Observable.__init__(self)
self._manifests: dict[str, PluginManifest] = {}
diff --git a/mac/makebundle.py b/mac/makebundle.py
index 87726dfaf..246cbc6aa 100755
--- a/mac/makebundle.py
+++ b/mac/makebundle.py
@@ -7,8 +7,8 @@ from subprocess import run, check_output, CalledProcessError
if __name__ == '__main__':
if not os.path.isdir('mac'):
- sys.exit("can't find the 'mac' directory. make sure you run "
- "this script from the project root")
+ sys.exit('Unable to find "mac" directory. make sure you run '
+ 'this script from the project root')
parser = ArgumentParser(description='Create a macOS .app bundle. '
'Requires PyInstaller and hdiutil (macOS).')
diff --git a/scripts/bump_version.py b/scripts/bump_version.py
index 9df9538a3..84ea3fae8 100755
--- a/scripts/bump_version.py
+++ b/scripts/bump_version.py
@@ -14,7 +14,7 @@ FLATPAK = REPO_DIR / 'flatpak' / 'org.gajim.Gajim.yaml'
APPDATA = REPO_DIR / 'data' / 'org.gajim.Gajim.appdata.xml.in'
CHANGELOG = REPO_DIR / 'ChangeLog'
-VERSION_RX = r"\d+\.\d+\.\d+"
+VERSION_RX = r'\d+\.\d+\.\d+'
def get_current_version() -> str:
diff --git a/setup.py b/setup.py
index f1b6b143d..e07533486 100644
--- a/setup.py
+++ b/setup.py
@@ -40,7 +40,7 @@ ALL_LINGUAS = sorted([lang.stem for lang in TRANS_DIR.glob('*.po')])
def newer(source: Path, target: Path) -> bool:
if not source.exists():
- raise ValueError("file '%s' does not exist" % source.resolve())
+ raise ValueError('file "%s" does not exist' % source.resolve())
if not target.exists():
return True
@@ -172,10 +172,10 @@ class install(_install):
# only install subdirectories of data
data_files_app_icon = [
- ("share/icons/hicolor/scalable/apps",
- ["gajim/data/icons/hicolor/scalable/apps/org.gajim.Gajim.svg"]),
- ("share/icons/hicolor/scalable/apps",
- ["gajim/data/icons/hicolor/scalable/apps/org.gajim.Gajim-symbolic.svg"])
+ ('share/icons/hicolor/scalable/apps',
+ ['gajim/data/icons/hicolor/scalable/apps/org.gajim.Gajim.svg']),
+ ('share/icons/hicolor/scalable/apps',
+ ['gajim/data/icons/hicolor/scalable/apps/org.gajim.Gajim-symbolic.svg'])
]
data_files: DataFilesT = data_files_app_icon
diff --git a/win/misc/depcheck.py b/win/misc/depcheck.py
index 5d5fafe43..a835079fa 100644
--- a/win/misc/depcheck.py
+++ b/win/misc/depcheck.py
@@ -5,9 +5,9 @@
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
-"""
-Deletes unneeded DLLs and checks DLL dependencies.
-"""
+
+# Deletes unneeded DLLs and checks DLL dependencies.
+
import subprocess
import os
@@ -15,7 +15,7 @@ import sys
from typing import Optional
import gi
-gi.require_version("GIRepository", "2.0")
+gi.require_version('GIRepository', '2.0')
from gi.repository import GIRepository # noqa: E402
@@ -23,44 +23,44 @@ def get_required_by_typelibs() -> set[str]:
deps: set[str] = set()
repo = GIRepository.Repository()
for tl in os.listdir(repo.get_search_path()[0]):
- namespace, version = os.path.splitext(tl)[0].split("-", 1)
+ namespace, version = os.path.splitext(tl)[0].split('-', 1)
repo.require(namespace, version, 0)
lib = repo.get_shared_library(namespace)
if lib:
- deps.update(lib.split(","))
+ deps.update(lib.split(','))
return deps
-EXTENSIONS = [".exe", ".pyd", ".dll"]
+EXTENSIONS = ['.exe', '.pyd', '.dll']
SYSTEM_LIBS = [
- "advapi32.dll",
- "cabinet.dll", "comctl32.dll", "comdlg32.dll", "crypt32.dll", "d3d9.dll",
- "dnsapi.dll", "dsound.dll", "dwmapi.dll", "gdi32.dll", "imm32.dll",
- "iphlpapi.dll", "kernel32.dll", "ksuser.dll", "msi.dll", "msimg32.dll",
- "msvcr71.dll", "msvcr80.dll", "msvcrt.dll", "ole32.dll", "oleaut32.dll",
- "opengl32.dll", "rpcrt4.dll", "setupapi.dll", "shell32.dll", "user32.dll",
- "usp10.dll", "winmm.dll", "winspool.drv", "wldap32.dll", "ws2_32.dll",
- "wsock32.dll", "shlwapi.dll"
+ 'advapi32.dll',
+ 'cabinet.dll', 'comctl32.dll', 'comdlg32.dll', 'crypt32.dll', 'd3d9.dll',
+ 'dnsapi.dll', 'dsound.dll', 'dwmapi.dll', 'gdi32.dll', 'imm32.dll',
+ 'iphlpapi.dll', 'kernel32.dll', 'ksuser.dll', 'msi.dll', 'msimg32.dll',
+ 'msvcr71.dll', 'msvcr80.dll', 'msvcrt.dll', 'ole32.dll', 'oleaut32.dll',
+ 'opengl32.dll', 'rpcrt4.dll', 'setupapi.dll', 'shell32.dll', 'user32.dll',
+ 'usp10.dll', 'winmm.dll', 'winspool.drv', 'wldap32.dll', 'ws2_32.dll',
+ 'wsock32.dll', 'shlwapi.dll'
]
def get_dependencies(filename: str) -> list[str]:
deps: list[str] = []
try:
- data = subprocess.getoutput("objdump -p %s" % filename)
+ data = subprocess.getoutput('objdump -p %s' % filename)
except Exception as error:
print(error)
return deps
for line in data.splitlines():
line = line.strip()
- if line.startswith("DLL Name:"):
- deps.append(line.split(":", 1)[-1].strip().lower())
+ if line.startswith('DLL Name:'):
+ deps.append(line.split(':', 1)[-1].strip().lower())
return deps
def find_lib(root: str, name: str) -> Optional[str]:
- search_path = os.path.join(root, "bin")
+ search_path = os.path.join(root, 'bin')
if os.path.exists(os.path.join(search_path, name)):
return os.path.join(search_path, name)
elif name in SYSTEM_LIBS:
@@ -79,18 +79,18 @@ def get_things_to_delete(root: str) -> list[str]:
all_libs.add(lib)
needed.add(lib)
if find_lib(root, lib) is None:
- print("MISSING:", path, lib)
+ print('MISSING:', path, lib)
for lib in get_required_by_typelibs():
needed.add(lib)
if find_lib(root, lib) is None:
- print("MISSING:", lib)
+ print('MISSING:', lib)
result: list[str] = []
libs = all_libs - needed
for lib in libs:
_, ext = os.path.splitext(lib)
- if ext == ".exe":
+ if ext == '.exe':
continue
name = find_lib(root, lib)
@@ -106,10 +106,10 @@ def main() -> None:
libs = get_things_to_delete(sys.prefix)
while libs:
for lib in libs:
- print("DELETE:", lib)
+ print('DELETE:', lib)
os.unlink(lib)
libs = get_things_to_delete(sys.prefix)
-if __name__ == "__main__":
+if __name__ == '__main__':
main()