Philipp Hörist pushed to branch master at gajim / gajim
Commits: 0f72e168 by lovetox at 2022-03-20T21:10:55+01:00 Format helpers.py
- - - - - e10a4814 by lovetox at 2022-03-20T21:14:37+01:00 Remove unused methods
- - - - - 33722790 by lovetox at 2022-03-20T21:17:22+01:00 Simplify import
- - - - - d2b56ae9 by lovetox at 2022-03-20T21:18:23+01:00 Remove unused method
- - - - - 1cf2bf41 by lovetox at 2022-03-20T21:24:38+01:00 Helpers: Add type annotations
- - - - - d9762a40 by lovetox at 2022-03-20T21:26:08+01:00 Remove unused import
- - - - -
1 changed file:
- gajim/common/helpers.py
Changes:
===================================== gajim/common/helpers.py ===================================== @@ -54,7 +54,6 @@ import string import webbrowser from string import Template -import urllib from datetime import datetime from datetime import timedelta from urllib.parse import unquote @@ -129,6 +128,7 @@ def parse_jid(jidstring: str) -> str: except Exception as error: raise InvalidFormat(error)
+ def idn_to_ascii(host: str) -> str: """ Convert IDN (Internationalized Domain Names) to ACE (ASCII-compatible @@ -144,6 +144,7 @@ def idn_to_ascii(host: str) -> str: converted_labels.append('') return ".".join(converted_labels)
+ def ascii_to_idn(host: str) -> str: """ Convert ACE (ASCII-compatible encoding) to IDN (Internationalized Domain @@ -156,17 +157,6 @@ def ascii_to_idn(host: str) -> str: converted_labels.append(idna.ToUnicode(label)) return ".".join(converted_labels)
-def puny_encode_url(url: str) -> Optional[str]: - _url = url - if '//' not in _url: - _url = '//' + _url - try: - o = urllib.parse.urlparse(_url) - p_loc = idn_to_ascii(o.hostname) - except Exception: - log.debug('urlparse failed: %s', url) - return None - return url.replace(o.hostname, p_loc)
def parse_resource(resource: str) -> Optional[str]: """ @@ -180,16 +170,13 @@ def parse_resource(resource: str) -> Optional[str]: except UnicodeError: raise InvalidFormat('Invalid character in resource.')
-def windowsify(word: str) -> str: - if os.name == 'nt': - return word.capitalize() - return word
def get_uf_show(show: str, use_mnemonic: bool = False) -> str: if use_mnemonic: return SHOW_STRING_MNEMONIC[show] return SHOW_STRING[show]
+ def get_uf_sub(sub: str) -> str: if sub == 'none': uf_sub = Q_('?Subscription we already have:None') @@ -204,6 +191,7 @@ def get_uf_sub(sub: str) -> str:
return uf_sub
+ def get_uf_ask(ask: Union[str, None]) -> str: if ask is None: uf_ask = Q_('?Ask (for Subscription):None') @@ -214,6 +202,7 @@ def get_uf_ask(ask: Union[str, None]) -> str:
return uf_ask
+ def get_uf_role(role: Union[Role, str], plural: bool = False) -> str: ''' plural determines if you get Moderators or Moderator''' if not isinstance(role, str): @@ -235,6 +224,7 @@ def get_uf_role(role: Union[Role, str], plural: bool = False) -> str: return _('Visitor') return ''
+ def get_uf_affiliation(affiliation: Union[Affiliation, str], plural: bool = False ) -> str: @@ -258,6 +248,7 @@ def get_uf_affiliation(affiliation: Union[Affiliation, str], return _('Member') return ''
+ def get_uf_relative_time(timestamp: float) -> str: date_time = datetime.fromtimestamp(timestamp) now = datetime.now() @@ -282,9 +273,6 @@ def get_uf_relative_time(timestamp: float) -> str: minutes) return _('Just now')
-def get_sorted_keys(adict): - keys = sorted(adict.keys()) - return keys
def to_one_line(msg: str) -> str: msg = msg.replace('\', '\\') @@ -296,6 +284,7 @@ def to_one_line(msg: str) -> str: # 'test\ntest\\ntest' return msg
+ def from_one_line(msg: str) -> str: # (?<!\) is a lookbehind assertion which asks anything but '' # to match the regexp that follows it @@ -311,6 +300,7 @@ def from_one_line(msg: str) -> str: # 'test\ntest\ntest' return msg
+ def get_uf_chatstate(chatstate: str) -> str: """ Remove chatstate jargon and returns user friendly messages @@ -322,12 +312,13 @@ def get_uf_chatstate(chatstate: str) -> str: if chatstate == 'composing': return _('is composing a message…') if chatstate == 'paused': - #paused means he or she was composing but has stopped for a while + # paused means he or she was composing but has stopped for a while return _('paused composing a message') if chatstate == 'gone': return _('has closed the chat window or tab') return ''
+ def exec_command(command: str, use_shell: bool = False, posix: bool = True @@ -344,6 +335,7 @@ def exec_command(command: str, process = subprocess.Popen(args) app.thread_interface(process.wait)
+ def build_command(executable: str, parameter: str) -> str: # we add to the parameter (can hold path with spaces) # "" so we have good parsing from shell @@ -351,8 +343,9 @@ def build_command(executable: str, parameter: str) -> str: command = f'{executable} "{parameter}"' return command
+ def get_file_path_from_dnd_dropped_uri(uri: str) -> str: - path = urllib.parse.unquote(uri) # escape special chars + path = unquote(uri) # escape special chars path = path.strip('\r\n\x00') # remove \r\n and NULL # get the path to file if re.match('^file:///[a-zA-Z]:/', path): # windows @@ -363,6 +356,7 @@ def get_file_path_from_dnd_dropped_uri(uri: str) -> str: path = path[5:] # 5 is len('file:') return path
+ def sanitize_filename(filename: str) -> str: """ Make sure the filename we will write does contain only acceptable and latin @@ -383,6 +377,7 @@ def sanitize_filename(filename: str) -> str:
return filename
+ def reduce_chars_newlines(text: str, max_chars: int = 0, max_lines: int = 0) -> str: """ @@ -464,7 +459,10 @@ def check_soundfile_path(file_: str, return dir_ return None
-def strip_soundfile_path(file_, dirs=None, abs_=True): + +def strip_soundfile_path(file_: Union[Path, str], + dirs: Optional[list[Path]] = None, + abs_: bool = True): """ Remove knowns paths from a sound file
@@ -494,6 +492,7 @@ def strip_soundfile_path(file_, dirs=None, abs_=True): return name return file_
+ def play_sound_file(str_path_to_soundfile: str, loop: bool = False) -> None: path_to_soundfile = check_soundfile_path(str_path_to_soundfile) if path_to_soundfile is None: @@ -502,6 +501,7 @@ def play_sound_file(str_path_to_soundfile: str, loop: bool = False) -> None: from gajim.common import sound sound.play(path_to_soundfile, loop)
+ def get_client_status(account: str) -> str: client = app.get_client(account) if client.state.is_disconnected: @@ -514,6 +514,7 @@ def get_client_status(account: str) -> str:
return client.status
+ def get_global_show() -> str: maxi = 0 for account in app.connections: @@ -526,6 +527,7 @@ def get_global_show() -> str: maxi = index return SHOW_LIST[maxi]
+ def get_global_status_message() -> str: maxi = 0 status_message = '' @@ -539,6 +541,7 @@ def get_global_status_message() -> str: status_message = con.status_message return status_message
+ def statuses_unified() -> bool: """ Test if all statuses are the same @@ -566,6 +569,7 @@ def get_full_jid_from_iq(iq_obj: Iq) -> Optional[str]: return None return parse_jid(str(iq_obj.getFrom()))
+ def get_jid_from_iq(iq_obj: Iq) -> Optional[str]: """ Return the jid (without resource) from an iq @@ -575,6 +579,7 @@ def get_jid_from_iq(iq_obj: Iq) -> Optional[str]: return None return app.get_jid_without_resource(jid)
+ def get_auth_sha(sid: str, initiator: str, target: str) -> str: """ Return sha of sid + initiator + target used for proxy auth @@ -582,11 +587,13 @@ def get_auth_sha(sid: str, initiator: str, target: str) -> str: return hashlib.sha1( (f'{sid}{initiator}{target}').encode('utf-8')).hexdigest()
+ def remove_invalid_xml_chars(string_: str) -> str: if string_: string_ = re.sub(INVALID_XML_CHARS_REGEX, '', string_) return string_
+ def get_random_string(count: int = 16) -> str: """ Create random string of count length @@ -661,7 +668,7 @@ def allow_sound_notification(account: str, sound_event: str) -> bool: return False
-def get_optional_features(account: str) -> list[Namespace]: +def get_optional_features(account: str) -> list[str]: features: list[str] = []
if app.settings.get_account_setting(account, 'request_user_data'): @@ -684,10 +691,12 @@ def get_optional_features(account: str) -> list[Namespace]: app.plugin_manager.extension_point('update_caps', account, features) return features
+ def jid_is_blocked(account: str, jid: str) -> bool: con = app.connections[account] return jid in con.get_module('Blocking').blocked
+ def get_subscription_request_msg(account: Optional[str] = None) -> str: message = _('I would like to add you to my contact list.') if account is None: @@ -701,8 +710,11 @@ def get_subscription_request_msg(account: Optional[str] = None) -> str: message = _('Hello, I am $name. %s') % message return Template(message).safe_substitute({'name': app.nicks[account]})
-def get_retraction_text(account: str, moderator_jid: str, + +def get_retraction_text(account: str, + moderator_jid: str, reason: Optional[str]) -> str: + client = app.get_client(account) contact = client.get_module('Contacts').get_contact( moderator_jid, groupchat=True) @@ -711,12 +723,14 @@ def get_retraction_text(account: str, moderator_jid: str, text += ' ' + _('Reason: %s') % reason return text
+ def get_global_proxy() -> Optional[ProxyData]: proxy_name = app.settings.get('global_proxy') if not proxy_name: return None return get_proxy(proxy_name)
+ def get_account_proxy(account: str, fallback=True) -> Optional[ProxyData]: proxy_name = app.settings.get_account_setting(account, 'proxy') if proxy_name: @@ -726,6 +740,7 @@ def get_account_proxy(account: str, fallback=True) -> Optional[ProxyData]: return get_global_proxy() return None
+ def get_proxy(proxy_name: str) -> Optional[ProxyData]: try: settings = app.settings.get_proxy_settings(proxy_name) @@ -741,11 +756,13 @@ def get_proxy(proxy_name: str) -> Optional[ProxyData]: username=username, password=password)
+ def version_condition(current_version: str, required_version: str) -> bool: if V(current_version) < V(required_version): return False return True
+ def get_available_emoticon_themes() -> list[str]: files: list[Path] = [] for folder in configpaths.get('EMOTICONS').iterdir(): @@ -761,6 +778,7 @@ def get_available_emoticon_themes() -> list[str]: emoticons_themes += [file.stem for file in files if file.suffix == '.png'] return sorted(emoticons_themes)
+ def call_counter(func): def helper(self, restart=False): if restart: @@ -769,6 +787,7 @@ def helper(self, restart=False): return func(self) return helper
+ def load_json(path: Path, key: Optional[str] = None, default: Optional[Any] = None) -> Any:
View it on GitLab: https://dev.gajim.org/gajim/gajim/-/compare/24900985f9342d6fc81844685e174698...