Пример #1
0
def strip_soundfile_path(file_, dirs=None, abs_=True):
    """
    Remove knowns paths from a sound file

    Filechooser returns an absolute path.
    If path is a known fallback path, we remove it.
    So config has no hardcoded path to DATA_DIR and text in textfield is
    shorther.
    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

    if dirs is None:
        dirs = [configpaths.get('MY_DATA'),
                configpaths.get('DATA')]

    file_ = Path(file_)
    name = file_.name
    for dir_ in dirs:
        dir_ = dir_ / 'sounds' / name
        if abs_:
            dir_ = dir_.absolute()
        if file_ == dir_:
            return name
    return file_
Пример #2
0
    def get_theme_path(self, theme, user=True):
        if theme == 'default' and self.prefer_dark:
            theme = 'default-dark'

        if user:
            return configpaths.get('MY_THEME') / f'{theme}.css'
        return configpaths.get('STYLE') / f'{theme}.css'
Пример #3
0
    def get_theme_path(self, theme, user=True):
        if theme == 'default' and self.prefer_dark:
            theme = 'default-dark'

        if user:
            return os.path.join(configpaths.get('MY_THEME'), '%s.css' % theme)
        return os.path.join(configpaths.get('STYLE'), '%s.css' % theme)
Пример #4
0
    def get_theme_path(cls, theme, user=True):
        if theme == 'default' and PREFER_DARK:
            theme = 'default-dark'

        if user:
            return os.path.join(configpaths.get('MY_THEME'), '%s.css' % theme)
        return os.path.join(configpaths.get('STYLE'), '%s.css' % theme)
Пример #5
0
    def _get_emoji_theme_path(theme):
        if theme == 'font':
            return 'font'
        emoticons_data_path = os.path.join(configpaths.get('EMOTICONS'), theme,
                                           '%s.png' % theme)
        if os.path.exists(emoticons_data_path):
            return emoticons_data_path

        emoticons_user_path = os.path.join(configpaths.get('MY_EMOTS'),
                                           '%s.png' % theme)
        if os.path.exists(emoticons_user_path):
            return emoticons_user_path

        log.warning('Could not find emoji theme: %s', theme)
Пример #6
0
def get_available_emoticon_themes():
    files = []
    for folder in configpaths.get('EMOTICONS').iterdir():
        if not folder.is_dir():
            continue
        files += [theme for theme in folder.iterdir() if theme.is_file()]

    my_emots = configpaths.get('MY_EMOTS')
    if my_emots.is_dir():
        files += list(my_emots.iterdir())

    emoticons_themes = ['font']
    emoticons_themes += [file.stem for file in files if file.suffix == '.png']
    return sorted(emoticons_themes)
Пример #7
0
    def __init__(self, plugin, textview):
        self.plugin = plugin
        self.textview = textview
        self.handlers = {}

        self.directory = os.path.join(configpaths.get('MY_DATA'), 'downloads')
        self.thumbpath = os.path.join(configpaths.get('MY_CACHE'),
                                      'downloads.thumb')

        try:
            self._create_path(self.directory)
            self._create_path(self.thumbpath)
        except Exception:
            log.error('Error creating download and/or thumbnail folder!')
            raise
Пример #8
0
    def _get_emoji_theme_path(theme):
        if theme == 'font':
            return 'font'

        base_path = configpaths.get('EMOTICONS')
        emoticons_data_path = base_path / theme / f'{theme}.png'
        if emoticons_data_path.exists():
            return emoticons_data_path

        emoticons_user_path = configpaths.get('MY_EMOTS') / f'{theme}.png'
        if emoticons_user_path.exists():
            return emoticons_user_path

        log.warning('Could not find emoji theme: %s', theme)
        return None
Пример #9
0
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)
    ctx.set_options(flags)
    ctx.set_cipher_list(b'HIGH:!aNULL:!3DES')

    if fingerprint == 'server':  # for testing purposes only
        ctx.set_verify(SSL.VERIFY_NONE | SSL.VERIFY_FAIL_IF_NO_PEER_CERT,
                       verify_cb or default_callback)
    elif fingerprint == 'client':
        ctx.set_verify(SSL.VERIFY_PEER, verify_cb or default_callback)

    cert_name = os.path.join(configpaths.get('MY_CERT'),
                             SELF_SIGNED_CERTIFICATE)
    ctx.use_privatekey_file((cert_name + '.pkey').encode('utf-8'))
    ctx.use_certificate_file((cert_name + '.cert').encode('utf-8'))

    # Try to load Diffie-Hellman parameters.
    # First try user DH parameters, if this fails load the default DH parameters
    dh_params_name = os.path.join(configpaths.get('MY_CERT'), DH_PARAMS)
    try:
        with open(dh_params_name, "r"):
            ctx.load_tmp_dh(dh_params_name.encode('utf-8'))
    except FileNotFoundError as err:
        default_dh_params_name = os.path.join(configpaths.get('DATA'), 'other',
                                              DEFAULT_DH_PARAMS)
        try:
            with open(default_dh_params_name, "r"):
                ctx.load_tmp_dh(default_dh_params_name.encode('utf-8'))
        except FileNotFoundError as err:
            log.error('Unable to load default DH parameter file: %s, %s',
                      default_dh_params_name, err)
            raise

    if remote_jid:
        store = ctx.get_cert_store()
        path = os.path.join(
            os.path.expanduser(configpaths.get('MY_PEER_CERTS')),
            remote_jid) + '.cert'
        if os.path.exists(path):
            load_cert_file(path, cert_store=store)
            log.debug('certificate file %s loaded fingerprint %s', path,
                      fingerprint)
    return ctx
Пример #10
0
def get_gtk_builder(file_name, widget=None):
    file_path = os.path.join(configpaths.get('GUI'), file_name)

    builder = Gtk.Builder()
    builder.set_translation_domain(i18n.DOMAIN)

    if sys.platform == "win32":
        # This is a workaround for non working translation on Windows
        tree = ET.parse(file_path)
        for node in tree.iter():
            if 'translatable' in node.attrib:
                node.text = _(node.text)
        xml_text = ET.tostring(tree.getroot(),
                               encoding='unicode',
                               method='xml')

        if widget is not None:
            builder.add_objects_from_string(xml_text, [widget])
        else:
            builder.add_from_string(xml_text)
    else:
        if widget is not None:
            builder.add_objects_from_file(file_path, [widget])
        else:
            builder.add_from_file(file_path)
    return builder
Пример #11
0
    def __init__(self):
        log_db_path = configpaths.get('LOG_DB')
        if not os.path.exists(log_db_path):
            ErrorDialog(_('Cannot find history logs database'),
                        _('%s does not exist.') % log_db_path)
            sys.exit()

        self._ui = get_builder('history_manager.ui')
        Gtk.Window.set_default_icon_list(
            get_app_icon_list(self._ui.history_manager_window))

        self.jids_already_in = []  # holds jids that we already have in DB
        self.AT_LEAST_ONE_DELETION_DONE = False

        self.con = sqlite3.connect(log_db_path,
                                   timeout=20.0,
                                   isolation_level='IMMEDIATE')
        self.con.execute("PRAGMA secure_delete=1")
        self.cur = self.con.cursor()

        self._init_jids_listview()
        self._init_logs_listview()
        self._init_search_results_listview()

        self._fill_jids_listview()

        self._ui.search_entry.grab_focus()

        self._ui.history_manager_window.show_all()

        self._ui.connect_signals(self)
Пример #12
0
    def _self_update_received(self, properties):
        jid = properties.jid.getBare()
        if properties.avatar_state == AvatarState.EMPTY:
            # Empty <photo/> tag, means no avatar is advertised
            self._log.info('%s has no avatar published', properties.jid)
            app.config.set_per('accounts', self._account, 'avatar_sha', '')
            app.contacts.set_avatar(self._account, jid, None)
            app.interface.update_avatar(self._account, jid)
            return

        self._log.info('Update: %s %s', jid, properties.avatar_sha)
        current_sha = app.config.get_per('accounts', self._account,
                                         'avatar_sha')

        if properties.avatar_sha != current_sha:
            path = Path(configpaths.get('AVATAR')) / properties.avatar_sha
            if path.exists():
                app.config.set_per('accounts', self._account, 'avatar_sha',
                                   properties.avatar_sha)
                app.contacts.set_avatar(self._account, jid,
                                        properties.avatar_sha)
                app.interface.update_avatar(self._account, jid)
            else:
                self._log.info('Request : %s', jid)
                self._con.get_module('VCardTemp').request_vcard(
                    RequestAvatar.SELF)
        else:
            self._log.info('Avatar already known: %s %s', jid,
                           properties.avatar_sha)
Пример #13
0
 def _load_birthdays(self):
     path = os.path.join(configpaths.get('MY_DATA'), 'birthdays.json')
     if os.path.exists(path):
         with open(path, 'r', encoding='utf-8') as file:
             content = file.read()
             if content:
                 self._birthdays = json.loads(content)
Пример #14
0
    def _on_own_avatar_received(self, jid, resource, room, vcard, *args):
        avatar_sha, photo_decoded = self._get_vcard_photo(vcard, jid)

        log.info('Received own vcard, avatar sha is: %s', avatar_sha)

        self._own_vcard = vcard
        self.own_vcard_received = True
        if avatar_sha is None:
            log.info('No avatar found')
            app.config.set_per('accounts', self._account, 'avatar_sha', '')
            self._con.get_module('VCardAvatars').send_avatar_presence(
                force=True)
            return

        current_sha = app.config.get_per('accounts', self._account,
                                         'avatar_sha')
        if current_sha == avatar_sha:
            path = os.path.join(configpaths.get('AVATAR'), current_sha)
            if not os.path.isfile(path):
                log.info('Caching: %s', current_sha)
                app.interface.save_avatar(photo_decoded)
            self._con.get_module('VCardAvatars').send_avatar_presence()
        else:
            app.interface.save_avatar(photo_decoded)

        app.config.set_per('accounts', self._account, 'avatar_sha', avatar_sha)
        if app.is_invisible(self._account):
            log.info('We are invisible, not advertising avatar')
            return

        self._con.get_module('VCardAvatars').send_avatar_presence(force=True)
Пример #15
0
    def _on_connect_clicked(self, _button):
        # Ignore this error
        if self._ui.ignore_error_checkbutton.get_active():
            ignore_ssl_errors = app.config.get_per(
                'accounts', self.account, 'ignore_ssl_errors').split()
            ignore_ssl_errors.append(str(self._error_num))
            app.config.set_per('accounts', self.account, 'ignore_ssl_errors',
                               ' '.join(ignore_ssl_errors))

        if self._ui.add_certificate_checkbutton.get_active():
            pem = crypto.dump_certificate(crypto.FILETYPE_PEM,
                                          self._cert).decode('utf-8')

            # Check if cert is already in file
            certs = ''
            my_ca_certs = configpaths.get('MY_CACERTS')
            if os.path.isfile(my_ca_certs):
                with open(my_ca_certs, encoding='utf-8') as file_:
                    certs = file_.read()
            if pem not in certs:
                with open(my_ca_certs, 'a', encoding='utf-8') as file_:
                    file_.write(self._server + '\n')
                    file_.write(pem + '\n\n')

        self.destroy()
        self._con.process_ssl_errors()
Пример #16
0
    def __init__(self):
        SqliteStorage.__init__(self, log, configpaths.get('CACHE_DB'),
                               CACHE_SQL_STATEMENT)

        self._entity_caps_cache = {}
        self._disco_info_cache = {}
        self._muc_avatar_sha_cache = {}
Пример #17
0
 def _fill_content(self, content):
     description_node = nbxmpp.simplexml.Node(
         tag=nbxmpp.NS_JINGLE_FILE_TRANSFER_5 + ' description')
     file_tag = description_node.setTag('file')
     if self.file_props.name:
         node = nbxmpp.simplexml.Node(tag='name')
         node.addData(self.file_props.name)
         file_tag.addChild(node=node)
     if self.file_props.date:
         node = nbxmpp.simplexml.Node(tag='date')
         node.addData(self.file_props.date)
         file_tag.addChild(node=node)
     if self.file_props.size:
         node = nbxmpp.simplexml.Node(tag='size')
         node.addData(self.file_props.size)
         file_tag.addChild(node=node)
     if self.file_props.type_ == 'r':
         if self.file_props.hash_:
             file_tag.addChild('hash',
                               attrs={'algo': self.file_props.algo},
                               namespace=nbxmpp.NS_HASHES_2,
                               payload=self.file_props.hash_)
     else:
         # if the file is less than 10 mb, then it is small
         # lets calculate it right away
         if self.file_props.size < 10000000 and not self.file_props.hash_:
             hash_data = self._compute_hash()
             if hash_data:
                 file_tag.addChild(node=hash_data)
             pjid = app.get_jid_without_resource(self.session.peerjid)
             file_info = {
                 'name': self.file_props.name,
                 'file-name': self.file_props.file_name,
                 'hash': self.file_props.hash_,
                 'size': self.file_props.size,
                 'date': self.file_props.date,
                 'peerjid': pjid
             }
             self.session.connection.get_module('Jingle').set_file_info(
                 file_info)
     desc = file_tag.setTag('desc')
     if self.file_props.desc:
         desc.setData(self.file_props.desc)
     if self.use_security:
         security = nbxmpp.simplexml.Node(tag=nbxmpp.NS_JINGLE_XTLS +
                                          ' security')
         certpath = os.path.join(configpaths.get('MY_CERT'),
                                 SELF_SIGNED_CERTIFICATE) + '.cert'
         cert = load_cert_file(certpath)
         if cert:
             digest_algo = (cert.get_signature_algorithm().decode(
                 'utf-8').split('With')[0])
             security.addChild('fingerprint').addData(
                 cert.digest(digest_algo).decode('utf-8'))
             for m in ('x509', ):  # supported authentication methods
                 method = nbxmpp.simplexml.Node(tag='method')
                 method.setAttr('name', m)
                 security.addChild(node=method)
             content.addChild(node=security)
     content.addChild(node=description_node)
Пример #18
0
def get_local_version(plugin_manifest):
    name = plugin_manifest['name']
    short_name = plugin_manifest['short_name']

    for plugin in app.plugin_manager.plugins:
        if plugin.name == name:
            return plugin.version

    # Fallback:
    # If the plugin has errors and is not loaded by the
    # PluginManager. Look in the Gajim config if the plugin is
    # known and active, if yes load the manifest from the Plugin
    # dir and parse the version
    active = app.config.get_per('plugins', short_name, 'active')
    if not active:
        return
    manifest_path = os.path.join(configpaths.get('PLUGINS_USER'), short_name,
                                 'manifest.ini')
    if not os.path.exists(manifest_path):
        return
    conf = configparser.ConfigParser()
    with open(manifest_path, encoding='utf-8') as conf_file:
        try:
            conf.read_file(conf_file)
        except configparser.Error:
            log.warning('Cant parse version for %s from manifest', short_name)
            return

    version = conf.get('info', 'version', fallback=None)
    return version
Пример #19
0
 def init(self):
     self.description = _('This plugin contains translation files '
                          'for Gajim plugins')
     self.config_dialog = None
     self.config_default_values = {'last_version': '0'}
     self.locale_dir = os.path.join(
         configpaths.get('PLUGINS_USER'), 'locale')
Пример #20
0
    def init(self):
        self.description = _('Adds Moov support to Gajim')
        self.config_dialog = partial(MoovConfigDialog, self)
        self.config_default_values = {
            'DB_ENABLED': (True, ''),
            'VIDEO_DIR': (None, 'Directory for local video search'),
            'preferred_maximum_stream_quality':
            ('best', _('Preferred maximum quality for internet videos')),
            'USER_FG_COLOR':
            ('rgba(255, 255, 191, 100)', 'Foreground color for your messages'),
            'USER_BG_COLOR': ('rgba(0, 0, 0, 80)',
                              'Background color for your messages'),
            'PARTNER_FG_COLOR':
            ('rgba(191, 255, 255, 100)',
             'Foreground color for your partner\'s messages'),
            'PARTNER_BG_COLOR':
            ('rgba(0, 0, 0, 80)',
             'Background color for your partner\'s messages'),
        }
        for p in color_properties:
            self.config_default_values[p] = (color_properties[p][0],
                                             color_properties[p][2])

        self.events_handlers = {
            'decrypted-message-received':
            (ged.PREGUI, self._on_message_received),
            'message-sent': (ged.PREGUI, self._on_message_sent),
        }
        if self.config['DB_ENABLED']:
            db_path = Path(
                configpaths.get('PLUGINS_DATA')) / 'moov' / 'db.json'
            self.db = moovdb.MoovDB(db_path)
Пример #21
0
    def __init__(self):
        self.xml = get_builder('account_creation_wizard_window.ui')
        self.window = self.xml.get_object('account_creation_wizard_window')
        active_window = app.app.get_active_window()
        self.window.set_transient_for(active_window)

        # Connect events from comboboxtext_entry
        server_comboboxtext = self.xml.get_object('server_comboboxtext')
        entry = self.xml.get_object('server_comboboxtext_entry')
        entry.connect('key_press_event',
                      self.on_entry_key_press_event, server_comboboxtext)

        server_comboboxtext1 = self.xml.get_object('server_comboboxtext1')

        self.update_proxy_list()

        # parse servers.json
        server_file_path = os.path.join(
            configpaths.get('DATA'), 'other', 'servers.json')
        servers = helpers.load_json(server_file_path, 'servers', [])

        servers_model = self.xml.get_object('server_liststore')
        for server in servers:
            servers_model.append((server,))

        server_comboboxtext.set_model(servers_model)
        server_comboboxtext1.set_model(servers_model)

        # Generic widgets
        self.notebook = self.xml.get_object('notebook')
        self.cancel_button = self.xml.get_object('cancel_button')
        self.back_button = self.xml.get_object('back_button')
        self.forward_button = self.xml.get_object('forward_button')
        self.finish_button = self.xml.get_object('finish_button')
        self.advanced_button = self.xml.get_object('advanced_button')
        self.finish_label = self.xml.get_object('finish_label')
        self.go_online_checkbutton = self.xml.get_object(
            'go_online_checkbutton')
        self.show_vcard_checkbutton = self.xml.get_object(
            'show_vcard_checkbutton')
        self.progressbar = self.xml.get_object('progressbar')

        # some vars
        self.update_progressbar_timeout_id = None

        self.notebook.set_current_page(0)
        self.xml.connect_signals(self)
        self.window.show_all()
        app.ged.register_event_handler(
            'new-account-connected', ged.GUI1,
            self._nec_new_acc_connected)
        app.ged.register_event_handler(
            'new-account-not-connected', ged.GUI1,
            self._nec_new_acc_not_connected)
        app.ged.register_event_handler(
            'account-created', ged.GUI1,
            self._nec_acc_is_ok)
        app.ged.register_event_handler(
            'account-not-created', ged.GUI1,
            self._nec_acc_is_not_ok)
Пример #22
0
 def _cleanup_debug_logs():
     debug_folder = Path(configpaths.get('DEBUG'))
     debug_files = list(debug_folder.glob('*-debug.log*'))
     now = time.time()
     for file in debug_files:
         # Delete everything older than 3 days
         if file.stat().st_ctime < now - 259200:
             file.unlink()
Пример #23
0
 def _find_own_avatar(self):
     sha = app.config.get_per('accounts', self._account, 'avatar_sha')
     if not sha:
         return
     path = Path(configpaths.get('AVATAR')) / sha
     if not path.exists():
         self._log.info('Missing own avatar, reset sha')
         app.config.set_per('accounts', self._account, 'avatar_sha', '')
Пример #24
0
def set_debug_mode(enable: bool) -> None:
    debug_folder = configpaths.get('DEBUG')
    debug_enabled = debug_folder / 'debug-enabled'
    if enable:
        debug_enabled.touch()
    else:
        if debug_enabled.exists():
            debug_enabled.unlink()
Пример #25
0
def get_gtk_builder(file_name, widget=None):
    file_path = os.path.join(configpaths.get('GUI'), file_name)
    builder = Gtk.Builder()
    builder.set_translation_domain(i18n.APP)
    if widget:
        builder.add_objects_from_file(file_path, [widget])
    else:
        builder.add_from_file(file_path)
    return builder
Пример #26
0
 def _load_css_from_file(self, filename, priority):
     path = configpaths.get('STYLE') / filename
     try:
         with open(path, "r") as file_:
             css = file_.read()
     except Exception as exc:
         log.error('Error loading css: %s', exc)
         return
     self._activate_css(css, priority)
Пример #27
0
def load_user_iconsets():
    iconsets_path = Path(configpaths.get('MY_ICONSETS'))
    if not iconsets_path.exists():
        return

    for path in iconsets_path.iterdir():
        if not path.is_dir():
            continue
        log.info('Found iconset: %s', path.stem)
        _icon_theme.append_search_path(str(path))
Пример #28
0
def check_cert(jid, fingerprint):
    certpath = configpaths.get('MY_PEER_CERTS').expanduser() / (jid + '.cert')
    if certpath.exists():
        cert = load_cert_file(certpath)
        if cert:
            digest_algo = cert.get_signature_algorithm().decode('utf-8')\
                    .split('With')[0]
            if cert.digest(digest_algo) == fingerprint:
                return True
    return False
Пример #29
0
def get_stored_bob_data(algo_hash: str) -> Optional[bytes]:
    try:
        return bob_cache[algo_hash]
    except KeyError:
        filepath = configpaths.get('BOB') / algo_hash
        if filepath.exists():
            with open(str(filepath), 'r+b') as file:
                data = file.read()
            return data
    return None
Пример #30
0
 def init(self):
     self.description = _('Adds Moov support to Gajim')
     self.config_dialog = None
     self.events_handlers = {
         'decrypted-message-received':
         (ged.PREGUI, self._on_message_received),
         'message-sent': (ged.PREGUI, self._on_message_sent),
     }
     db_path = Path(configpaths.get('PLUGINS_DATA')) / 'moov' / 'db.json'
     self.db = moovdb.MoovDB(db_path)