app.py 21 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
# Copyright (C) 2003-2014 Yann Leboulanger <asterix AT lagaule.org>
# Copyright (C) 2005-2006 Dimitur Kirov <dkirov AT gmail.com>
#                         Travis Shirk <travis AT pobox.com>
#                         Nikos Kouremenos <kourem AT gmail.com>
# Copyright (C) 2006 Junglecow J <junglecow AT gmail.com>
#                    Stefan Bethge <stefan AT lanpartei.de>
# Copyright (C) 2006-2008 Jean-Marie Traissard <jim AT lapin.org>
# Copyright (C) 2007-2008 Brendan Taylor <whateley AT gmail.com>
#                         Stephan Erb <steve-e AT h3c.de>
# Copyright (C) 2008 Jonathan Schleifer <js-gajim AT webkeks.org>
# Copyright (C) 2018 Philipp Hörist <philipp @ hoerist.com>
#
# This file is part of Gajim.
#
# Gajim is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published
# by the Free Software Foundation; version 3 only.
#
# Gajim is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Gajim. If not, see <http://www.gnu.org/licenses/>.

from typing import Any  # pylint: disable=unused-import
from typing import Dict  # pylint: disable=unused-import
from typing import List  # pylint: disable=unused-import
from typing import Optional  # pylint: disable=unused-import
from typing import cast
Tanguy Ortolo's avatar
Tanguy Ortolo committed
32

33
import os
34
import sys
Tanguy Ortolo's avatar
Tanguy Ortolo committed
35
import logging
36
import uuid
37
from pathlib import Path
38
from distutils.version import LooseVersion as V
39 40
from collections import namedtuple

41
import nbxmpp
42

43
import gajim
44 45 46 47 48
from gajim.common import config as c_config
from gajim.common import configpaths
from gajim.common import ged as ged_module
from gajim.common.contacts import LegacyContactsAPI
from gajim.common.events import Events
49 50 51 52
from gajim.common.types import NetworkEventsControllerT  # pylint: disable=unused-import
from gajim.common.types import InterfaceT  # pylint: disable=unused-import
from gajim.common.types import LoggerT  # pylint: disable=unused-import
from gajim.common.types import ConnectionT  # pylint: disable=unused-import
Tanguy Ortolo's avatar
Tanguy Ortolo committed
53

54
interface = cast(InterfaceT, None)
55 56
thread_interface = lambda *args: None # Interface to run a thread and then a callback
config = c_config.Config()
57
version = gajim.__version__
58 59
connections = {}  # type: Dict[str, ConnectionT]
avatar_cache = {}  # type: Dict[str, Dict[str, Any]]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
60
ipython_window = None
61
app = None  # Gtk.Application
Tanguy Ortolo's avatar
Tanguy Ortolo committed
62

63
ged = ged_module.GlobalEventsDispatcher() # Global Events Dispatcher
64
nec = cast(NetworkEventsControllerT, None)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
65 66
plugin_manager = None # Plugins Manager

67
logger = cast(LoggerT, None)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
68

69 70
# For backwards compatibility needed
# some plugins use that
Tanguy Ortolo's avatar
Tanguy Ortolo committed
71 72 73
gajimpaths = configpaths.gajimpaths


74 75
RecentGroupchat = namedtuple('RecentGroupchat', ['room', 'server', 'nickname'])

76
css_config = None
Tanguy Ortolo's avatar
Tanguy Ortolo committed
77 78 79

os_info = None # used to cache os information

80
transport_type = {}  # type: Dict[str, str]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
81

82 83 84
# dict of time of the latest incoming message per jid
# {acct1: {jid1: time1, jid2: time2}, }
last_message_time = {}  # type: Dict[str, Dict[str, float]]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
85 86

contacts = LegacyContactsAPI()
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108

# tell if we are connected to the room or not
# {acct: {room_jid: True}}
gc_connected = {}  # type: Dict[str, Dict[str, bool]]

# dict of the pass required to enter a room
# {room_jid: password}
gc_passwords = {}  # type: Dict[str, str]

# dict of rooms that must be automaticaly configured
# and for which we have a list of invities
# {account: {room_jid: {'invities': []}}}
automatic_rooms = {}  # type: Dict[str, Dict[str, Dict[str, List[str]]]]

 # dict of groups, holds if they are expanded or not
groups = {}  # type: Dict[str, Dict[str, Dict[str, bool]]]

# list of contacts that has just signed in
newly_added = {}  # type: Dict[str, List[str]]

# list of contacts that has just signed out
to_be_removed = {}  # type: Dict[str, List[str]]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
109 110 111

events = Events()

Tanguy Ortolo's avatar
Tanguy Ortolo committed
112 113
notification = None

114 115 116
# list of our nick names in each account
nicks = {}  # type: Dict[str, str]

Tanguy Ortolo's avatar
Tanguy Ortolo committed
117 118 119 120 121
# should we block 'contact signed in' notifications for this account?
# this is only for the first 30 seconds after we change our show
# to something else than offline
# can also contain account/transport_jid to block notifications for contacts
# from this transport
122 123 124 125
block_signed_in_notifications = {}  # type: Dict[str, bool]

 # type of each connection (ssl, tls, tcp, ...)
con_types = {}  # type: Dict[str, Optional[str]]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
126

127
# whether we pass auto away / xa or not
Tanguy Ortolo's avatar
Tanguy Ortolo committed
128 129 130 131
#'off': don't use sleeper for this account
#'online': online and use sleeper
#'autoaway': autoaway and use sleeper
#'autoxa': autoxa and use sleeper
132
sleeper_state = {}  # type: Dict[str, str]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
133

134
status_before_autoaway = {}  # type: Dict[str, str]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
135 136 137 138

# Is Gnome configured to activate on single click ?
single_click = False
SHOW_LIST = ['offline', 'connecting', 'online', 'chat', 'away', 'xa', 'dnd',
139
             'invisible', 'error']
Tanguy Ortolo's avatar
Tanguy Ortolo committed
140 141 142 143

# zeroconf account name
ZEROCONF_ACC_NAME = 'Local'

144
# These will be set in app.gui_interface.
145
idlequeue = None  # type: nbxmpp.idlequeue.IdleQueue
146 147
socks5queue = None

Martin's avatar
Martin committed
148 149
gupnp_igd = None

Tanguy Ortolo's avatar
Tanguy Ortolo committed
150
gajim_identity = {'type': 'pc', 'category': 'client', 'name': 'Gajim'}
151 152 153 154 155 156 157
gajim_common_features = [nbxmpp.NS_BYTESTREAM, nbxmpp.NS_SI, nbxmpp.NS_FILE,
    nbxmpp.NS_MUC, nbxmpp.NS_MUC_USER, nbxmpp.NS_MUC_ADMIN, nbxmpp.NS_MUC_OWNER,
    nbxmpp.NS_MUC_CONFIG, nbxmpp.NS_COMMANDS, nbxmpp.NS_DISCO_INFO, 'ipv6',
    'jabber:iq:gateway', nbxmpp.NS_LAST, nbxmpp.NS_PRIVACY, nbxmpp.NS_PRIVATE,
    nbxmpp.NS_REGISTER, nbxmpp.NS_VERSION, nbxmpp.NS_DATA, nbxmpp.NS_ENCRYPTED,
    'msglog', 'sslc2s', 'stringprep', nbxmpp.NS_PING, nbxmpp.NS_TIME_REVISED,
    nbxmpp.NS_SSN, nbxmpp.NS_MOOD, nbxmpp.NS_ACTIVITY, nbxmpp.NS_NICK,
158
    nbxmpp.NS_ROSTERX, nbxmpp.NS_SECLABEL, nbxmpp.NS_HASHES_2,
159
    nbxmpp.NS_HASHES_MD5, nbxmpp.NS_HASHES_SHA1, nbxmpp.NS_HASHES_SHA256,
160 161
    nbxmpp.NS_HASHES_SHA512, nbxmpp.NS_CONFERENCE, nbxmpp.NS_CORRECT,
    nbxmpp.NS_EME, 'urn:xmpp:avatar:metadata+notify']
Tanguy Ortolo's avatar
Tanguy Ortolo committed
162 163

# Optional features gajim supports per account
164
gajim_optional_features = {}  # type: Dict[str, List[str]]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
165 166

# Capabilities hash per account
167
caps_hash = {}  # type: Dict[str, List[str]]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
168

169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
_dependencies = {
    'PYTHON-DBUS': False,
    'PYBONJOUR': False,
    'PYGPG': False,
    'GPG_BINARY': False,
    'FARSTREAM': False,
    'GEOCLUE': False,
    'UPNP': False,
    'PYCURL': False,
    'GSPELL': False,
    'IDLE': False,
}


def is_installed(dependency):
    if dependency == 'GPG':
        # Alias for checking python-gnupg and the GPG binary
        return _dependencies['PYGPG'] and _dependencies['GPG_BINARY']
    if dependency == 'ZEROCONF':
        # Alias for checking zeroconf libs
        return _dependencies['PYTHON-DBUS'] or _dependencies['PYBONJOUR']
    return _dependencies[dependency]

def is_flatpak():
    return gajim.IS_FLATPAK

def disable_dependency(dependency):
    _dependencies[dependency] = False

def detect_dependencies():
    import gi

    # ZEROCONF
    try:
Martin's avatar
Martin committed
203 204 205 206 207 208 209 210
        import pybonjour  # pylint: disable=unused-variable
        _dependencies['PYBONJOUR'] = True
    except Exception:
        pass

    try:
        import dbus  # pylint: disable=unused-variable
        _dependencies['PYTHON-DBUS'] = True
211 212 213 214 215 216
    except Exception:
        pass

    # python-gnupg
    try:
        import gnupg
217 218 219 220 221 222
        # We need https://pypi.python.org/pypi/python-gnupg
        # but https://pypi.python.org/pypi/gnupg shares the same package name.
        # It cannot be used as a drop-in replacement.
        # We test with a version check if python-gnupg is installed as it is
        # on a much lower version number than gnupg
        # Also we need at least python-gnupg 0.3.8
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
        v_gnupg = gnupg.__version__
        if V(v_gnupg) < V('0.3.8') or V(v_gnupg) > V('1.0.0'):
            log('gajim').info('Gajim needs python-gnupg >= 0.3.8')
            raise ImportError
        _dependencies['PYGPG'] = True
    except ImportError:
        pass

    # GPG BINARY
    import subprocess

    def test_gpg(binary='gpg'):
        if os.name == 'nt':
            gpg_cmd = binary + ' -h >nul 2>&1'
        else:
            gpg_cmd = binary + ' -h >/dev/null 2>&1'
        if subprocess.call(gpg_cmd, shell=True):
            return False
        return True

    if test_gpg(binary='gpg2'):
        _dependencies['GPG_BINARY'] = 'gpg2'
    elif test_gpg(binary='gpg'):
        _dependencies['GPG_BINARY'] = 'gpg'

    # FARSTREAM
    try:
        if os.name == 'nt':
251 252 253 254 255
            root_path = Path(sys.executable).parents[1]
            fs_plugin_path = str(root_path / 'lib' / 'farstream-0.2')
            gst_plugin_path = str(root_path / 'lib' / 'gstreamer-1.0')
            os.environ['FS_PLUGIN_PATH'] = fs_plugin_path
            os.environ['GST_PLUGIN_PATH'] = gst_plugin_path
256 257 258 259 260 261 262
        gi.require_version('Farstream', '0.2')
        from gi.repository import Farstream
        gi.require_version('Gst', '1.0')
        from gi.repository import Gst
        try:
            Gst.init(None)
            conference = Gst.ElementFactory.make('fsrtpconference', None)
263
            conference.new_session(Farstream.MediaType.AUDIO)
264 265 266 267 268 269 270 271 272
        except Exception as error:
            log('gajim').info(error)
        _dependencies['FARSTREAM'] = True
    except (ImportError, ValueError):
        pass

    # GEOCLUE
    try:
        gi.require_version('Geoclue', '2.0')
273
        from gi.repository import Geoclue  # pylint: disable=unused-variable
274 275 276 277 278 279 280 281
        _dependencies['GEOCLUE'] = True
    except (ImportError, ValueError):
        pass

    # UPNP
    try:
        gi.require_version('GUPnPIgd', '1.0')
        from gi.repository import GUPnPIgd
Martin's avatar
Martin committed
282 283
        global gupnp_igd
        gupnp_igd = GUPnPIgd.SimpleIgd()
284 285 286 287 288 289
        _dependencies['UPNP'] = True
    except ValueError:
        pass

    # PYCURL
    try:
290
        import pycurl  # pylint: disable=unused-variable
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
        _dependencies['PYCURL'] = True
    except ImportError:
        pass

    # IDLE
    try:
        from gajim.common import idle
        if idle.Monitor.is_available():
            _dependencies['IDLE'] = True
    except Exception:
        pass

    # GSPELL
    try:
        gi.require_version('Gspell', '1')
        from gi.repository import Gspell
        langs = Gspell.language_get_available()
        for lang in langs:
            log('gajim').info('%s (%s) dict available',
                              lang.get_name(), lang.get_code())
        if langs:
            _dependencies['GSPELL'] = True
    except (ImportError, ValueError):
        pass

    # Print results
    for dep, val in _dependencies.items():
        log('gajim').info('%-13s %s', dep, val)

def get_gpg_binary():
    return _dependencies['GPG_BINARY']

323
def get_an_id():
324
    return str(uuid.uuid4())
325

Tanguy Ortolo's avatar
Tanguy Ortolo committed
326
def get_nick_from_jid(jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
327 328
    pos = jid.find('@')
    return jid[:pos]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
329 330

def get_server_from_jid(jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
331 332
    pos = jid.find('@') + 1 # after @
    return jid[pos:]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
333 334

def get_name_and_server_from_jid(jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
335 336 337
    name = get_nick_from_jid(jid)
    server = get_server_from_jid(jid)
    return name, server
Tanguy Ortolo's avatar
Tanguy Ortolo committed
338 339

def get_room_and_nick_from_fjid(jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
340 341 342 343 344 345 346
    # fake jid is the jid for a contact in a room
    # gaim@conference.jabber.no/nick/nick-continued
    # return ('gaim@conference.jabber.no', 'nick/nick-continued')
    l = jid.split('/', 1)
    if len(l) == 1: # No nick
        l.append('')
    return l
Tanguy Ortolo's avatar
Tanguy Ortolo committed
347 348

def get_real_jid_from_fjid(account, fjid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    """
    Return real jid or returns None, if we don't know the real jid
    """
    room_jid, nick = get_room_and_nick_from_fjid(fjid)
    if not nick: # It's not a fake_jid, it is a real jid
        return fjid # we return the real jid
    real_jid = fjid
    if interface.msg_win_mgr.get_gc_control(room_jid, account):
        # It's a pm, so if we have real jid it's in contact.jid
        gc_contact = contacts.get_gc_contact(account, room_jid, nick)
        if not gc_contact:
            return
        # gc_contact.jid is None when it's not a real jid (we don't know real jid)
        real_jid = gc_contact.jid
    return real_jid
Tanguy Ortolo's avatar
Tanguy Ortolo committed
364 365

def get_room_from_fjid(jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
366
    return get_room_and_nick_from_fjid(jid)[0]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
367 368

def get_contact_name_from_jid(account, jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
369 370
    c = contacts.get_first_contact_from_jid(account, jid)
    return c.name
Tanguy Ortolo's avatar
Tanguy Ortolo committed
371 372

def get_jid_without_resource(jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
373
    return jid.split('/')[0]
Tanguy Ortolo's avatar
Tanguy Ortolo committed
374 375

def construct_fjid(room_jid, nick):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
376 377 378
    # fake jid is the jid for a contact in a room
    # gaim@conference.jabber.org/nick
    return room_jid + '/' + nick
Tanguy Ortolo's avatar
Tanguy Ortolo committed
379 380

def get_resource_from_jid(jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
381 382 383
    jids = jid.split('/', 1)
    if len(jids) > 1:
        return jids[1] # abc@doremi.org/res/res-continued
384
    return ''
Tanguy Ortolo's avatar
Tanguy Ortolo committed
385 386

def get_number_of_accounts():
Tanguy Ortolo's avatar
Tanguy Ortolo committed
387 388 389 390
    """
    Return the number of ALL accounts
    """
    return len(connections.keys())
Tanguy Ortolo's avatar
Tanguy Ortolo committed
391

392
def get_number_of_connected_accounts(accounts_list=None):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
393 394 395 396 397 398 399 400 401 402 403 404 405
    """
    Returns the number of CONNECTED accounts. Uou 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()
    else:
        accounts = accounts_list
    for account in accounts:
        if account_is_connected(account):
            connected_accounts = connected_accounts + 1
    return connected_accounts
Tanguy Ortolo's avatar
Tanguy Ortolo committed
406

407 408 409 410 411 412 413 414 415 416
def get_connected_accounts():
    """
    Returns a list of CONNECTED accounts
    """
    account_list = []
    for account in connections:
        if account_is_connected(account):
            account_list.append(account)
    return account_list

417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
def get_enabled_accounts_with_labels(exclude_local=True, connected_only=False,
                                     private_storage_only=False):
    """
    Returns a list with [account, account_label] entries.
    Order by account_label
    """
    accounts = []
    for acc in connections:
        if exclude_local and account_is_zeroconf(acc):
            continue
        if connected_only and not account_is_connected(acc):
            continue
        if private_storage_only and not account_supports_private_storage(acc):
            continue

432
        accounts.append([acc, get_account_label(acc)])
433 434 435 436

    accounts.sort(key=lambda xs: str.lower(xs[1]))
    return accounts

437 438 439
def get_account_label(account):
    return config.get_per('accounts', account, 'account_label') or account

440 441 442 443 444 445 446 447
def account_is_zeroconf(account):
    return connections[account].is_zeroconf

def account_supports_private_storage(account):
    # If Delimiter module is not available we can assume
    # Private Storage is not available
    return connections[account].get_module('Delimiter').available

Tanguy Ortolo's avatar
Tanguy Ortolo committed
448
def account_is_connected(account):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
449 450
    if account not in connections:
        return False
451 452
    # 0 is offline, 1 is connecting
    return connections[account].connected > 1
Tanguy Ortolo's avatar
Tanguy Ortolo committed
453

454 455 456
def is_invisible(account):
    return SHOW_LIST[connections[account].connected] == 'invisible'

Tanguy Ortolo's avatar
Tanguy Ortolo committed
457
def account_is_disconnected(account):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
458
    return not account_is_connected(account)
Tanguy Ortolo's avatar
Tanguy Ortolo committed
459 460

def zeroconf_is_connected():
Tanguy Ortolo's avatar
Tanguy Ortolo committed
461 462
    return account_is_connected(ZEROCONF_ACC_NAME) and \
            config.get_per('accounts', ZEROCONF_ACC_NAME, 'is_zeroconf')
Tanguy Ortolo's avatar
Tanguy Ortolo committed
463

464 465 466 467 468
def in_groupchat(account, room_jid):
    if room_jid not in gc_connected[account]:
        return False
    return gc_connected[account][room_jid]

Tanguy Ortolo's avatar
Tanguy Ortolo committed
469
def get_number_of_securely_connected_accounts():
Tanguy Ortolo's avatar
Tanguy Ortolo committed
470 471 472 473
    """
    Return the number of the accounts that are SSL/TLS connected
    """
    num_of_secured = 0
474
    for account in connections:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
475 476 477
        if account_is_securely_connected(account):
            num_of_secured += 1
    return num_of_secured
Tanguy Ortolo's avatar
Tanguy Ortolo committed
478 479

def account_is_securely_connected(account):
480
    if not account_is_connected(account):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
481
        return False
482
    return con_types.get(account) in ('tls', 'ssl')
Tanguy Ortolo's avatar
Tanguy Ortolo committed
483

484
def get_transport_name_from_jid(jid, use_config_setting=True):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
485
    """
486
    Returns 'gg', 'irc' etc
Tanguy Ortolo's avatar
Tanguy Ortolo committed
487 488 489 490 491 492 493 494 495 496 497 498 499 500 501

    If JID is not from transport returns None.
    """
    #FIXME: jid can be None! one TB I saw had this problem:
    # in the code block # it is a groupchat presence in handle_event_notify
    # jid was None. Yann why?
    if not jid or (use_config_setting and not config.get('use_transports_iconsets')):
        return

    host = get_server_from_jid(jid)
    if host in transport_type:
        return transport_type[host]

    # host is now f.e. icq.foo.org or just icq (sometimes on hacky transports)
    host_splitted = host.split('.')
502
    if host_splitted:
Tanguy Ortolo's avatar
Tanguy Ortolo committed
503 504 505
        # now we support both 'icq.' and 'icq' but not icqsucks.org
        host = host_splitted[0]

506
    if host in ('irc', 'icq', 'sms', 'weather', 'mrim', 'facebook'):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
507
        return host
508
    if host == 'gg':
Tanguy Ortolo's avatar
Tanguy Ortolo committed
509
        return 'gadu-gadu'
510
    if host == 'jit':
Tanguy Ortolo's avatar
Tanguy Ortolo committed
511
        return 'icq'
512
    if host == 'facebook':
Tanguy Ortolo's avatar
Tanguy Ortolo committed
513
        return 'facebook'
514
    return None
Tanguy Ortolo's avatar
Tanguy Ortolo committed
515 516

def jid_is_transport(jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
517 518 519 520
    # if not '@' or '@' starts the jid then it is transport
    if jid.find('@') <= 0:
        return True
    return False
Tanguy Ortolo's avatar
Tanguy Ortolo committed
521

522
def get_jid_from_account(account_name):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
523 524 525 526 527 528 529
    """
    Return the jid we use in the given account
    """
    name = config.get_per('accounts', account_name, 'name')
    hostname = config.get_per('accounts', account_name, 'hostname')
    jid = name + '@' + hostname
    return jid
Tanguy Ortolo's avatar
Tanguy Ortolo committed
530

531 532 533 534 535
def get_account_from_jid(jid):
    for account in config.get_per('accounts'):
        if jid == get_jid_from_account(account):
            return account

Tanguy Ortolo's avatar
Tanguy Ortolo committed
536
def get_our_jids():
Tanguy Ortolo's avatar
Tanguy Ortolo committed
537 538 539 540 541 542 543
    """
    Returns a list of the jids we use in our accounts
    """
    our_jids = list()
    for account in contacts.get_accounts():
        our_jids.append(get_jid_from_account(account))
    return our_jids
Tanguy Ortolo's avatar
Tanguy Ortolo committed
544

545
def get_hostname_from_account(account_name, use_srv=False):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
546 547 548 549 550 551 552 553
    """
    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 config.get_per('accounts', account_name, 'use_custom_host'):
        return config.get_per('accounts', account_name, 'custom_host')
    return config.get_per('accounts', account_name, 'hostname')
Tanguy Ortolo's avatar
Tanguy Ortolo committed
554 555

def get_notification_image_prefix(jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
556 557 558 559
    """
    Returns the prefix for the notification images
    """
    transport_name = get_transport_name_from_jid(jid)
560
    if transport_name in ('icq', 'facebook'):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
561 562 563 564
        prefix = transport_name
    else:
        prefix = 'jabber'
    return prefix
Tanguy Ortolo's avatar
Tanguy Ortolo committed
565 566

def get_name_from_jid(account, jid):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
567 568 569 570 571 572 573 574 575
    """
    Return from JID's shown name and if no contact returns jids
    """
    contact = contacts.get_first_contact_from_jid(account, jid)
    if contact:
        actor = contact.get_shown_name()
    else:
        actor = jid
    return actor
Tanguy Ortolo's avatar
Tanguy Ortolo committed
576

577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604
def get_muc_domain(account):
    return connections[account].muc_jid.get('jabber', None)

def get_recent_groupchats(account):
    recent_groupchats = config.get_per(
        'accounts', account, 'recent_groupchats').split()

    recent_list = []
    for groupchat in recent_groupchats:
        jid = nbxmpp.JID(groupchat)
        recent = RecentGroupchat(
            jid.getNode(), jid.getDomain(), jid.getResource())
        recent_list.append(recent)
    return recent_list

def add_recent_groupchat(account, room_jid, nickname):
    recent = config.get_per(
        'accounts', account, 'recent_groupchats').split()
    full_jid = room_jid + '/' + nickname
    if full_jid in recent:
        recent.remove(full_jid)
    recent.insert(0, full_jid)
    if len(recent) > 10:
        recent = recent[0:9]
    config_value = ' '.join(recent)
    config.set_per(
        'accounts', account, 'recent_groupchats', config_value)

Tanguy Ortolo's avatar
Tanguy Ortolo committed
605
def get_priority(account, show):
Tanguy Ortolo's avatar
Tanguy Ortolo committed
606 607 608 609 610 611 612 613
    """
    Return the priority an account must have
    """
    if not show:
        show = 'online'

    if show in ('online', 'chat', 'away', 'xa', 'dnd', 'invisible') and \
    config.get_per('accounts', account, 'adjust_priority_with_status'):
614 615 616 617 618 619 620 621 622 623
        prio = config.get_per('accounts', account, 'autopriority_' + show)
    else:
        prio = config.get_per('accounts', account, 'priority')
    if prio < -128:
        prio = -128
    elif prio > 127:
        prio = 127
    return prio

def log(domain):
624 625 626
    if domain != 'gajim':
        domain = 'gajim.%s' % domain
    return logging.getLogger(domain)
627 628 629 630 631 632 633

def prefers_app_menu():
    if sys.platform == 'darwin':
        return True
    if sys.platform == 'win32':
        return False
    return app.prefers_app_menu()
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651

def get_app_window(cls, account=None):
    for win in app.get_windows():
        if isinstance(cls, str):
            if type(win).__name__ == cls:
                if account is not None:
                    if account != win.account:
                        continue
                return win
        elif isinstance(win, cls):
            if account is not None:
                if account != win.account:
                    continue
            return win
    return None

def load_css_config():
    global css_config
652
    from gajim.gtk.css_config import CSSConfig
653
    css_config = CSSConfig()
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669

def set_win_debug_mode(enable: bool) -> None:
    debug_folder = Path(configpaths.get('DEBUG'))
    debug_enabled = debug_folder / 'debug-enabled'
    if enable:
        debug_enabled.touch()
    else:
        if debug_enabled.exists():
            debug_enabled.unlink()

def get_win_debug_mode() -> bool:
    if sys.platform != 'win32':
        return False
    debug_folder = Path(configpaths.get('DEBUG'))
    debug_enabled = debug_folder / 'debug-enabled'
    return debug_enabled.exists()