Example #1
0
 def is_valid(self):
     if self.value:
         try:
             helpers.parse_jid(self.value)
             return True
         except:
             return False
     if self.required:
         return False
     return True
Example #2
0
 def is_valid(self):
     if len(self.values):
         for value in self.values:
             try:
                 helpers.parse_jid(value)
             except:
                 return False
         return True
     if self.required:
         return False
     return True
Example #3
0
 def on_room_entry_changed(self, widget):
     if self.ignore_events:
         return
     (model, iter_) = self.selection.get_selected()
     if not iter_:
         return
     room = widget.get_text()
     if not room:
         return
     if '@' in room:
         room, server = room.split('@', 1)
         widget.set_text(room)
         if server:
             self.server_entry.set_text(server)
         self.server_entry.grab_focus()
     server = self.server_entry.get_text().strip()
     if not server:
         return
     room_jid = room.strip() + '@' + server
     try:
         room_jid = helpers.parse_jid(room_jid)
     except helpers.InvalidFormat:
         ErrorDialog(_('Invalid room'),
                     _('Character not allowed'),
                     transient_for=self.window)
         return True
     model[iter_][2] = room_jid
Example #4
0
    def _affiliation_received(self, stanza):
        if not nbxmpp.isResultNode(stanza):
            log.info('Error: %s', stanza.getError())
            return

        room_jid = stanza.getFrom().getStripped()
        query = stanza.getTag('query', namespace=nbxmpp.NS_MUC_ADMIN)
        items = query.getTags('item')
        users_dict = {}
        for item in items:
            try:
                jid = helpers.parse_jid(item.getAttr('jid'))
            except helpers.InvalidFormat:
                log.warning('Invalid JID: %s, ignoring it',
                            item.getAttr('jid'))
                continue
            affiliation = item.getAttr('affiliation')
            users_dict[jid] = {'affiliation': affiliation}
            if item.has_attr('nick'):
                users_dict[jid]['nick'] = item.getAttr('nick')
            if item.has_attr('role'):
                users_dict[jid]['role'] = item.getAttr('role')
            reason = item.getTagData('reason')
            if reason:
                users_dict[jid]['reason'] = reason
        log.info('Affiliations received from %s: %s', room_jid, users_dict)
        app.nec.push_incoming_event(
            MucAdminReceivedEvent(None,
                                  conn=self._con,
                                  room_jid=room_jid,
                                  users_dict=users_dict))
Example #5
0
    def _direct_invite(self, con, stanza):
        direct = stanza.getTag('x', namespace=nbxmpp.NS_CONFERENCE)
        if direct is None:
            return

        from_ = stanza.getFrom()

        try:
            room_jid = helpers.parse_jid(direct.getAttr('jid'))
        except helpers.InvalidFormat:
            log.warning('Invalid JID on invite: %s, ignoring it',
                        direct.getAttr('jid'))
            raise nbxmpp.NodeProcessed

        reason = direct.getAttr('reason')
        password = direct.getAttr('password')
        is_continued = direct.getAttr('continue') == 'true'

        log.info('Direct invite: continued: %s, reason: %s, from: %s',
                 is_continued, reason, from_)

        app.nec.push_incoming_event(
            GcInvitationReceived(None,
                                 account=self._account,
                                 from_=from_,
                                 room_jid=room_jid,
                                 reason=reason,
                                 password=password,
                                 is_continued=is_continued))
        raise nbxmpp.NodeProcessed
Example #6
0
    def on_server_entry_focus_out(self, widget, event):
        if self.ignore_events:
            return
        (model, iter_) = self.selection.get_selected()
        if not iter_:
            return
        server = widget.get_text()
        if not server:
            return
        if '@' in server:
            ErrorDialog(_('Invalid server'),
                        _('Character not allowed'),
                        transient_for=self.window)
            widget.set_text(server.replace('@', ''))

        room = self.room_entry.get_text().strip()
        if not room:
            return
        room_jid = room + '@' + server.strip()
        try:
            room_jid = helpers.parse_jid(room_jid)
        except helpers.InvalidFormat as e:
            ErrorDialog(_('Invalid server'),
                        _('Character not allowed'),
                        transient_for=self.window)
            self.server_entry.set_text(model[iter_][2].split('@')[1])
            return True
        model[iter_][2] = room_jid
Example #7
0
    def open_chat(self, jid, account, message):
        """
        Shows the tabbed window for new message to 'jid', using account (optional)
        'account'
        """
        if not jid:
            raise ValueError('jid is missing')
        jid = self._get_real_jid(jid, account)
        try:
            jid = helpers.parse_jid(jid)
        except Exception:
            # Jid is not conform, ignore it
            return False

        minimized_control = None
        if account:
            accounts = [account]
        else:
            accounts = app.connections.keys()
            if len(accounts) == 1:
                account = accounts[0]
        connected_account = None
        first_connected_acct = None
        for acct in accounts:
            if app.account_is_available(acct):  # account is  online
                contact = app.contacts.get_first_contact_from_jid(acct, jid)
                if app.interface.msg_win_mgr.has_window(jid, acct):
                    connected_account = acct
                    break
                # jid is in roster
                if contact:
                    minimized_control = \
                        jid in app.interface.minimized_controls[acct]
                    connected_account = acct
                    break
                # we send the message to jid not in roster, because account is
                # specified, or there is only one account
                if account:
                    connected_account = acct
                elif first_connected_acct is None:
                    first_connected_acct = acct

        # if jid is not a contact, open-chat with first connected account
        if connected_account is None and first_connected_acct:
            connected_account = first_connected_acct

        if minimized_control:
            app.interface.roster.on_groupchat_maximized(
                None, jid, connected_account)

        if connected_account:
            app.interface.new_chat_from_jid(connected_account, jid, message)
            # preserve the 'steal focus preservation'
            win = app.interface.msg_win_mgr.get_window(
                jid, connected_account).window
            if win.get_property('visible'):
                win.window.present()
            return True
        return False
Example #8
0
    def _start_new_chat(self, row):
        if row.new:
            if not app.account_is_connected(row.account):
                app.interface.raise_dialog('start-chat-not-connected')
                return
            try:
                helpers.parse_jid(row.jid)
            except helpers.InvalidFormat as e:
                app.interface.raise_dialog('invalid-jid-with-error', str(e))
                return

        if row.groupchat:
            app.interface.join_gc_minimal(row.account, row.jid)
        else:
            app.interface.new_chat_from_jid(row.account, row.jid)

        self.ready_to_destroy = True
Example #9
0
    def received_item(self, con, stanza):
        # stanza can be a message or a iq

        log.info('Received roster items from %s', stanza.getFrom())

        exchange_items_list = {}
        items_list = stanza.getTag('x',
                                   namespace=nbxmpp.NS_ROSTERX).getChildren()
        if items_list is None:
            raise nbxmpp.NodeProcessed

        action = items_list[0].getAttr('action')
        if not action:
            action = 'add'

        for item in items_list:
            try:
                jid = helpers.parse_jid(item.getAttr('jid'))
            except helpers.InvalidFormat:
                log.warning('Invalid JID: %s, ignoring it',
                            item.getAttr('jid'))
                continue
            name = item.getAttr('name')
            contact = app.contacts.get_contact(self._account, jid)
            groups = []
            same_groups = True
            for group in item.getTags('group'):
                groups.append(group.getData())
                # check that all suggested groups are in the groups we have for
                # this contact
                if not contact or group not in contact.groups:
                    same_groups = False
            if contact:
                # check that all groups we have for this contact are in the
                # suggested groups
                for group in contact.groups:
                    if group not in groups:
                        same_groups = False
                if contact.sub in ('both', 'to') and same_groups:
                    continue
            exchange_items_list[jid] = [name, groups]

        if not exchange_items_list:
            raise nbxmpp.NodeProcessed

        log.info('Items: %s', exchange_items_list)

        app.nec.push_incoming_event(
            RosterItemExchangeEvent(None,
                                    conn=self._con,
                                    fjid=str(stanza.getFrom()),
                                    exchange_items_list=exchange_items_list,
                                    action=action))

        raise nbxmpp.NodeProcessed
Example #10
0
    def _send_single_message(self):
        if not app.account_is_available(self.account):
            # if offline or connecting
            ErrorDialog(_('Connection not available'),
                        _('Please make sure you are connected with "%s".') %
                        self.account)
            return True
        if isinstance(self._to, list):
            sender_list = []
            for i in self._to:
                if i[0].resource:
                    sender_list.append(i[0].jid + '/' + i[0].resource)
                else:
                    sender_list.append(i[0].jid)
        else:
            sender_list = [j.strip() for j
                           in self._ui.to_entry.get_text().split(',')]

        subject = self._ui.subject_entry.get_text()
        begin, end = self._message_tv_buffer.get_bounds()
        message = self._message_tv_buffer.get_text(begin, end, True)

        recipient_list = []

        for to_whom_jid in sender_list:
            if to_whom_jid in self._completion_dict:
                to_whom_jid = self._completion_dict[to_whom_jid].jid
            try:
                to_whom_jid = helpers.parse_jid(to_whom_jid)
            except helpers.InvalidFormat:
                ErrorDialog(
                    _('Invalid XMPP Address'),
                    _('It is not possible to send a message to %s, this '
                      'XMPP Address is not valid.') % to_whom_jid)
                return True

            if '/announce/' in to_whom_jid:
                con = app.connections[self.account]
                con.get_module('Announce').set_announce(
                    to_whom_jid, subject, message)
                continue

            recipient_list.append(to_whom_jid)

        message = OutgoingMessage(account=self.account,
                                  contact=None,
                                  message=message,
                                  type_='normal',
                                  subject=subject)
        con = app.connections[self.account]
        con.send_messages(recipient_list, message)

        self._ui.subject_entry.set_text('') # we sent ok, clear the subject
        self._message_tv_buffer.set_text('') # we sent ok, clear the textview
        return False
Example #11
0
    def send_single_message(self):
        if app.connections[self.account].connected <= 1:
            # if offline or connecting
            ErrorDialog(_('Connection not available'),
                _('Please make sure you are connected with "%s".') % self.account)
            return True
        if isinstance(self.to, list):
            sender_list = []
            for i in self.to:
                if i[0].resource:
                    sender_list.append(i[0].jid + '/' + i[0].resource)
                else:
                    sender_list.append(i[0].jid)
        else:
            sender_list = [j.strip() for j in self.to_entry.get_text().split(
                ',')]

        subject = self.subject_entry.get_text()
        begin, end = self.message_tv_buffer.get_bounds()
        message = self.message_tv_buffer.get_text(begin, end, True)

        if self.form_widget:
            form_node = self.form_widget.data_form
        else:
            form_node = None

        recipient_list = []

        for to_whom_jid in sender_list:
            if to_whom_jid in self.completion_dict:
                to_whom_jid = self.completion_dict[to_whom_jid].jid
            try:
                to_whom_jid = helpers.parse_jid(to_whom_jid)
            except helpers.InvalidFormat:
                ErrorDialog(_('Invalid JID'),
                    _('It is not possible to send a message to %s, this JID is not '
                    'valid.') % to_whom_jid)
                return True

            if '/announce/' in to_whom_jid:
                app.connections[self.account].send_motd(to_whom_jid, subject,
                    message)
                continue

            recipient_list.append(to_whom_jid)

        app.nec.push_outgoing_event(MessageOutgoingEvent(None,
            account=self.account, jid=recipient_list, message=message,
            type_='normal', subject=subject, form_node=form_node))

        self.subject_entry.set_text('') # we sent ok, clear the subject
        self.message_tv_buffer.set_text('') # we sent ok, clear the textview
Example #12
0
    def _parse_bookmarks(self, stanza, check_merge=False):
        merged = False
        storage = self._get_storage_node(stanza)
        if storage is None:
            return

        NS_GAJIM_BM = 'xmpp:gajim.org/bookmarks'
        confs = storage.getTags('conference')
        for conf in confs:
            autojoin_val = conf.getAttr('autojoin')
            if not autojoin_val:  # not there (it's optional)
                autojoin_val = False
            minimize_val = conf.getTag('minimize', namespace=NS_GAJIM_BM)
            if not minimize_val:  # not there, try old Gajim behaviour
                minimize_val = conf.getAttr('minimize')
                if not minimize_val:  # not there (it's optional)
                    minimize_val = False
            else:
                minimize_val = minimize_val.getData()

            print_status = conf.getTag('print_status', namespace=NS_GAJIM_BM)
            if not print_status:  # not there, try old Gajim behaviour
                print_status = conf.getTagData('print_status')
                if not print_status:  # not there, try old Gajim behaviour
                    print_status = conf.getTagData('show_status')
            else:
                print_status = print_status.getData()

            try:
                jid = helpers.parse_jid(conf.getAttr('jid'))
            except helpers.InvalidFormat:
                log.warning('Invalid JID: %s, ignoring it' %
                            conf.getAttr('jid'))
                continue

            if check_merge:
                if jid in self.bookmarks:
                    continue
                merged = True

            log.debug('Found Bookmark: %s', jid)
            self.bookmarks[jid] = {
                'name': conf.getAttr('name'),
                'autojoin': autojoin_val,
                'minimize': minimize_val,
                'password': conf.getTagData('password'),
                'nick': conf.getTagData('nick'),
                'print_status': print_status
            }

        return merged
 def discover_ft_proxies(self):
     cfg_proxies = app.config.get_per('accounts', self.name,
                                      'file_transfer_proxies')
     our_jid = helpers.parse_jid(app.get_jid_from_account(self.name) + \
         '/' + self.server_resource)
     testit = app.config.get_per('accounts', self.name,
                                 'test_ft_proxies_on_startup')
     if cfg_proxies:
         proxies = [e.strip() for e in cfg_proxies.split(',')]
         for proxy in proxies:
             app.proxy65_manager.resolve(proxy,
                                         self.connection,
                                         our_jid,
                                         testit=testit)
Example #14
0
    def _get_from(self, room_jid, stanza):
        try:
            from_ = nbxmpp.JID(helpers.parse_jid(stanza.getAttr('from')))
        except helpers.InvalidFormat:
            log.warning('Invalid JID on invite: %s, ignoring it',
                        stanza.getAttr('from'))
            raise nbxmpp.NodeProcessed

        known_contact = app.contacts.get_contacts(self._account, room_jid)
        ignore = app.config.get_per('accounts', self._account,
                                    'ignore_unknown_contacts')
        if ignore and not known_contact:
            log.info('Ignore invite from unknown contact %s', from_)
            raise nbxmpp.NodeProcessed

        return from_
Example #15
0
 def parse_items_response(cls, stanza):
     payload = stanza.getQueryPayload()
     items = []
     for item in payload:
         # CDATA payload is not processed, only nodes
         if not isinstance(item, nbxmpp.simplexml.Node):
             continue
         attr = item.getAttrs()
         if 'jid' not in attr:
             log.warning('No jid attr in disco items: %s', stanza)
             continue
         try:
             attr['jid'] = helpers.parse_jid(attr['jid'])
         except helpers.InvalidFormat:
             log.warning('Invalid jid attr in disco items: %s', stanza)
             continue
         items.append(attr)
     return items
Example #16
0
    def on_jid_multi_cellrenderertext_edited(self, cell, path, newtext, treeview,
    model, field):
        old = model[path][0]
        if old == newtext:
            return
        try:
            newtext = helpers.parse_jid(newtext)
        except helpers.InvalidFormat as s:
            app.interface.raise_dialog('invalid-jid-with-error', str(s))    
            return
        if newtext in field.values:
            app.interface.raise_dialog('jid-in-list')
            GLib.idle_add(treeview.set_cursor, path)
            return
        model[path][0]=newtext

        values = field.values
        values[values.index(old)]=newtext
        field.values = values
Example #17
0
    def on_jid_multi_cellrenderertext_edited(self, cell, path, newtext,
                                             treeview, model, field):
        old = model[path][0]
        if old == newtext:
            return
        try:
            newtext = helpers.parse_jid(newtext)
        except helpers.InvalidFormat as s:
            dialogs.ErrorDialog(_('Invalid JID'), str(s))
            return
        if newtext in field.values:
            dialogs.ErrorDialog(
                _('JID already in list'),
                _('The JID you entered is already in the list. Choose another one.'
                  ))
            GLib.idle_add(treeview.set_cursor, path)
            return
        model[path][0] = newtext

        values = field.values
        values[values.index(old)] = newtext
        field.values = values
Example #18
0
    def _result_received(self, stanza):
        if not nbxmpp.isResultNode(stanza):
            log.info('Error: %s', stanza.getError())
            return

        log.info('Received annotations from %s', self._server)
        self.annotations = {}
        query = stanza.getTag('query')
        storage_node = query.getTag('storage')
        if storage_node is None:
            return

        notes = storage_node.getTags('note')
        if notes is None:
            return

        for note in notes:
            try:
                jid = helpers.parse_jid(note.getAttr('jid'))
            except helpers.InvalidFormat:
                log.warning('Invalid JID: %s, ignoring it',
                            note.getAttr('jid'))
                continue
            self.annotations[jid] = note.getData()
Example #19
0
 def _parse_metacontacts(stanza):
     meta_list = {}
     query = stanza.getQuery()
     storage = query.getTag('storage')
     metas = storage.getTags('meta')
     for meta in metas:
         try:
             jid = helpers.parse_jid(meta.getAttr('jid'))
         except helpers.InvalidFormat:
             continue
         tag = meta.getAttr('tag')
         data = {'jid': jid}
         order = meta.getAttr('order')
         try:
             order = int(order)
         except Exception:
             order = 0
         if order is not None:
             data['order'] = order
         if tag in meta_list:
             meta_list[tag].append(data)
         else:
             meta_list[tag] = [data]
     return meta_list
Example #20
0
    def on_forward_button_clicked(self, widget):
        cur_page = self.notebook.get_current_page()

        if cur_page == 0:
            widget = self.xml.get_object('use_existing_account_radiobutton')
            if widget.get_active():
                self.modify = True
                self.notebook.set_current_page(1)
            else:
                self.modify = False
                self.notebook.set_current_page(2)
            self.back_button.set_sensitive(True)
            return

        if cur_page == 1:
            # We are adding an existing account
            anonymous = self.xml.get_object('anonymous_checkbutton1').\
                get_active()
            username = self.xml.get_object('username_entry').get_text().strip()
            if not username and not anonymous:
                pritext = _('Invalid username')
                sectext = _(
                    'You must provide a username to configure this account.')
                ErrorDialog(pritext, sectext)
                return
            server = self.xml.get_object('server_comboboxtext_entry').\
                get_text().strip()
            savepass = self.xml.get_object('save_password_checkbutton').\
                get_active()
            password = self.xml.get_object('password_entry').get_text()

            if anonymous:
                jid = ''
            else:
                jid = username + '@'
            jid += server
            # check if jid is conform to RFC and stringprep it
            try:
                jid = helpers.parse_jid(jid)
            except helpers.InvalidFormat as s:
                pritext = _('Invalid XMPP Address')
                ErrorDialog(pritext, str(s))
                return

            self.account = server
            i = 1
            while self.account in app.config.get_per('accounts'):
                self.account = server + str(i)
                i += 1

            username, server = app.get_name_and_server_from_jid(jid)
            if self.xml.get_object('anonymous_checkbutton1').get_active():
                self.save_account('', server, False, '', anonymous=True)
            else:
                self.save_account(username, server, savepass, password)
            self.show_finish_page()
        elif cur_page == 2:
            # We are creating a new account
            server = self.xml.get_object('server_comboboxtext_entry1').\
                get_text()

            if not server:
                ErrorDialog(
                    _('Invalid server'),
                    _('Please provide a server on which you want to register.'))
                return
            self.account = server
            i = 1
            while self.account in app.config.get_per('accounts'):
                self.account = server + str(i)
                i += 1

            config = self.get_config('', server, '', '')
            # Get advanced options
            proxies_combobox = self.xml.get_object('proxies_combobox')
            active = proxies_combobox.get_active()
            proxy = proxies_combobox.get_model()[active][0]
            if proxy == _('None'):
                proxy = ''
            config['proxy'] = proxy

            config['use_custom_host'] = self.xml.get_object(
                'custom_host_port_checkbutton').get_active()
            custom_port = self.xml.get_object('custom_port_entry').get_text()
            try:
                custom_port = int(custom_port)
            except Exception:
                ErrorDialog(
                    _('Invalid entry'),
                    _('Custom port must be a port number.'))
                return
            config['custom_port'] = custom_port
            config['custom_host'] = self.xml.get_object(
                'custom_host_entry').get_text()

            if self.xml.get_object('anonymous_checkbutton2').get_active():
                self.modify = True
                self.save_account('', server, False, '', anonymous=True)
                self.show_finish_page()
            else:
                self.notebook.set_current_page(5)  # show creating page
                self.back_button.hide()
                self.forward_button.hide()
                self.update_progressbar_timeout_id = GLib.timeout_add(
                    100, self.update_progressbar)
                # Get form from serveur
                con = connection.Connection(self.account)
                app.connections[self.account] = con
                con.new_account(self.account, config)
        elif cur_page == 3:
            checked = self.xml.get_object('ssl_checkbutton').get_active()
            if checked:
                hostname = app.connections[self.account].new_account_info[
                    'hostname']
                # 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) as f:
                        certs = f.read()
                if self.ssl_cert in certs:
                    ErrorDialog(
                        _('Certificate Already in File'),
                        _('This certificate is already in file %s, so it\'s '
                          'not added again.') % my_ca_certs)
                else:
                    with open(my_ca_certs, 'a') as f:
                        f.write(hostname + '\n')
                        f.write(self.ssl_cert + '\n\n')
                    app.connections[self.account].new_account_info[
                        'ssl_fingerprint_sha1'] = self.ssl_fingerprint_sha1
                    app.connections[self.account].new_account_info[
                        'ssl_fingerprint_sha256'] = self.ssl_fingerprint_sha256
            self.notebook.set_current_page(4)  # show fom page
        elif cur_page == 4:
            if self.is_form:
                form = self.data_form_widget.data_form
            else:
                form = self.data_form_widget.get_submit_form()
            app.connections[self.account].send_new_account_infos(
                form, self.is_form)
            self.xml.get_object('form_vbox').remove(self.data_form_widget)
            self.xml.get_object('progressbar_label').set_markup(
                '<b>Account is being created</b>\n\nPlease wait…')
            self.notebook.set_current_page(5)  # show creating page
            self.back_button.hide()
            self.forward_button.hide()
            self.update_progressbar_timeout_id = GLib.timeout_add(
                100, self.update_progressbar)
Example #21
0
    def _message_received(self, con, stanza):
        # https://tools.ietf.org/html/rfc6120#section-8.1.1.1
        # If the stanza does not include a 'to' address then the client MUST
        # treat it as if the 'to' address were included with a value of the
        # client's full JID.
        #
        # Implementation Note: However, if the client does
        # check the 'to' address then it is suggested to check at most the
        # bare JID portion (not the full JID)

        own_jid = self._con.get_own_jid().getStripped()
        to = stanza.getTo()
        if to is None:
            stanza.setTo(own_jid)
        elif not to.bareMatch(own_jid):
            log.warning('Message addressed to someone else: %s', stanza)
            raise nbxmpp.NodeProcessed

        # Check if a child of the message contains any
        # namespaces that we handle in other modules.
        # nbxmpp executes less common handlers last
        if self._message_namespaces & set(stanza.getProperties()):
            return

        muc_user = stanza.getTag('x', namespace=nbxmpp.NS_MUC_USER)
        if muc_user is not None:
            if muc_user.getChildren():
                # Not a PM, handled by MUC module
                return

        log.info('Received from %s', stanza.getFrom())

        app.nec.push_incoming_event(
            NetworkEvent('raw-message-received',
                         conn=self._con,
                         stanza=stanza,
                         account=self._account))

        if stanza.getFrom() == self._con.get_own_jid(warn=True):
            # Drop messages sent from our own full jid
            # It can happen that when we sent message to our own bare jid
            # that the server routes that message back to us
            log.info('Received message from self: %s, message is dropped',
                     stanza.getFrom())
            return

        stanza, sent, forwarded = parse_carbon(self._con, stanza)

        from_ = stanza.getFrom()
        type_ = stanza.getType()
        if type_ is None:
            type_ = 'normal'
        self_message = is_self_message(stanza, type_ == 'groupchat')
        muc_pm = is_muc_pm(stanza, from_, type_ == 'groupchat')

        id_ = stanza.getID()

        fjid = None
        if from_ is not None:
            try:
                fjid = helpers.parse_jid(str(from_))
            except helpers.InvalidFormat:
                log.warning('Invalid JID: %s, ignoring it', stanza.getFrom())
                return

        jid, resource = app.get_room_and_nick_from_fjid(fjid)

        # Check for duplicates
        stanza_id, origin_id = self._get_unique_id(stanza, forwarded, sent,
                                                   self_message, muc_pm)

        # Check groupchat messages for duplicates,
        # We do this because of MUC History messages
        if type_ == 'groupchat' or self_message or muc_pm:
            if type_ == 'groupchat':
                archive_jid = stanza.getFrom().getStripped()
            else:
                archive_jid = own_jid
            if app.logger.find_stanza_id(self._account, archive_jid, stanza_id,
                                         origin_id, type_ == 'groupchat'):
                return

        thread_id = stanza.getThread()
        msgtxt = stanza.getBody()

        # TODO: remove all control UI stuff
        gc_control = app.interface.msg_win_mgr.get_gc_control(
            jid, self._account)
        if not gc_control:
            minimized = app.interface.minimized_controls[self._account]
            gc_control = minimized.get(jid)

        if gc_control and jid == fjid:
            if type_ == 'error':
                msgtxt = _('error while sending %(message)s ( %(error)s )') % {
                    'message': msgtxt,
                    'error': stanza.getErrorMsg()
                }
                # TODO: why is this here?
                if stanza.getTag('html'):
                    stanza.delChild('html')

        session = None
        if type_ != 'groupchat':
            if muc_pm and type_ == 'error':
                session = self._con.find_session(fjid, thread_id)
                if not session:
                    session = self._con.get_latest_session(fjid)
                if not session:
                    session = self._con.make_new_session(fjid,
                                                         thread_id,
                                                         type_='pm')
            else:
                session = self._con.get_or_create_session(fjid, thread_id)

            if thread_id and not session.received_thread_id:
                session.received_thread_id = True

            session.last_receive = time.time()

        timestamp = parse_delay(stanza)
        if timestamp is None:
            timestamp = time.time()

        event_attr = {
            'conn': self._con,
            'stanza': stanza,
            'account': self._account,
            'id_': id_,
            'encrypted': False,
            'additional_data': {},
            'forwarded': forwarded,
            'sent': sent,
            'timestamp': timestamp,
            'fjid': fjid,
            'jid': jid,
            'resource': resource,
            'stanza_id': stanza_id,
            'unique_id': stanza_id or origin_id,
            'mtype': type_,
            'msgtxt': msgtxt,
            'thread_id': thread_id,
            'session': session,
            'self_message': self_message,
            'muc_pm': muc_pm,
            'gc_control': gc_control
        }

        event = MessageReceivedEvent(None, **event_attr)
        app.nec.push_incoming_event(event)

        app.plugin_manager.extension_point('decrypt', self._con, event,
                                           self._on_message_decrypted)
        if not event.encrypted:
            eme = parse_eme(event.stanza)
            if eme is not None:
                event.msgtxt = eme
            self._on_message_decrypted(event)
Example #22
0
    def _add_jid(self, jid, type_):
        # check if jid is conform to RFC and stringprep it
        try:
            jid = helpers.parse_jid(jid)
        except helpers.InvalidFormat as s:
            pritext = _('Invalid User ID')
            ErrorDialog(pritext, str(s))
            return

        # No resource in jid
        if jid.find('/') >= 0:
            pritext = _('Invalid User ID')
            ErrorDialog(pritext, _('The user ID must not contain a resource.'))
            return

        if jid == app.get_jid_from_account(self.account):
            pritext = _('Invalid User ID')
            ErrorDialog(pritext,
                        _('You cannot add yourself to your contact list.'))
            return

        if not app.account_is_connected(self.account):
            ErrorDialog(_('Account Offline'),
                        _('Your account must be online to add new contacts.'))
            return

        nickname = self.nickname_entry.get_text() or ''
        # get value of account combobox, if account was not specified
        if not self.account:
            model = self.account_combobox.get_model()
            index = self.account_combobox.get_active()
            self.account = model[index][1]

        # Check if jid is already in roster
        if jid in app.contacts.get_jid_list(self.account):
            c = app.contacts.get_first_contact_from_jid(self.account, jid)
            if _('Not in contact list') not in c.groups and c.sub in ('both',
                                                                      'to'):
                ErrorDialog(_('Contact Already in Contact List'),
                            _('This contact is already in your contact list.'))
                return

        if type_ == 'jabber':
            message_buffer = self.message_textview.get_buffer()
            start_iter = message_buffer.get_start_iter()
            end_iter = message_buffer.get_end_iter()
            message = message_buffer.get_text(start_iter, end_iter, True)
            if self.save_message_checkbutton.get_active():
                msg = helpers.to_one_line(message)
                app.config.set_per('accounts', self.account,
                                   'subscription_request_msg', msg)
        else:
            message = ''
        group = self.group_comboboxentry.get_child().get_text()
        groups = []
        if group:
            groups = [group]
        auto_auth = self.auto_authorize_checkbutton.get_active()
        app.interface.roster.req_sub(self,
                                     jid,
                                     message,
                                     self.account,
                                     groups=groups,
                                     nickname=nickname,
                                     auto_auth=auto_auth)
        self.destroy()
Example #23
0
    def generate(self):
        self.ptype = self.presence_obj.ptype
        self.fjid = self.presence_obj.fjid
        self.jid = self.presence_obj.jid
        self.room_jid = self.presence_obj.jid
        self.nick = self.presence_obj.resource
        self.show = self.presence_obj.show
        self.status = self.presence_obj.status
        self.avatar_sha = self.presence_obj.avatar_sha
        self.errcode = self.presence_obj.errcode
        self.errmsg = self.presence_obj.errmsg
        self.errcon = self.stanza.getError()
        self.get_gc_control()
        self.gc_contact = app.contacts.get_gc_contact(self.conn.name,
            self.room_jid, self.nick)

        if self.ptype == 'error':
            return True

        if self.ptype and self.ptype != 'unavailable':
            return
        if app.config.get('log_contact_status_changes') and \
        app.config.should_log(self.conn.name, self.room_jid):
            if self.gc_contact:
                jid = self.gc_contact.jid
            else:
                jid = self.stanza.getJid()
            st = self.status
            if jid:
                # we know real jid, save it in db
                st += ' (%s)' % jid
            show = app.logger.convert_show_values_to_db_api_values(self.show)
            if show is not None:
                fjid = nbxmpp.JID(self.fjid)
                app.logger.insert_into_logs(self.conn.name,
                                            fjid.getStripped(),
                                            time_time(),
                                            KindConstant.GCSTATUS,
                                            contact_name=fjid.getResource(),
                                            message=st,
                                            show=show)


        # NOTE: if it's a gc presence, don't ask vcard here.
        # We may ask it to real jid in gui part.
        self.status_code = []
        ns_muc_user_x = self.stanza.getTag('x', namespace=nbxmpp.NS_MUC_USER)
        if ns_muc_user_x:
            destroy = ns_muc_user_x.getTag('destroy')
        else:
            destroy = None
        if ns_muc_user_x and destroy:
            # Room has been destroyed. see
            # http://www.xmpp.org/extensions/xep-0045.html#destroyroom
            self.reason = _('Room has been destroyed')
            r = destroy.getTagData('reason')
            if r:
                self.reason += ' (%s)' % r
            if destroy.getAttr('jid'):
                try:
                    jid = helpers.parse_jid(destroy.getAttr('jid'))
                    self.reason += '\n' + \
                        _('You can join this room instead: %s') % jid
                except helpers.InvalidFormat:
                    pass
            self.status_code = ['destroyed']
        else:
            self.reason = self.stanza.getReason()
            conditions = self.stanza.getStatusConditions()
            if conditions:
                self.status_code = []
                for condition in conditions:
                    if condition in CONDITION_TO_CODE:
                        self.status_code.append(CONDITION_TO_CODE[condition])
            else:
                self.status_code = self.stanza.getStatusCode()

        self.role = self.stanza.getRole()
        self.affiliation = self.stanza.getAffiliation()
        self.real_jid = self.stanza.getJid()
        self.actor = self.stanza.getActor()
        self.new_nick = self.stanza.getNewNick()
        return True
Example #24
0
 def _ft_get_streamhost_jid_attr(self, streamhost):
     return helpers.parse_jid(streamhost.getAttr('jid'))
Example #25
0
 def _ft_get_streamhost_jid_attr(self, streamhost):
     if self._account == 'Local':
         return streamhost.getAttr('jid')
     return helpers.parse_jid(streamhost.getAttr('jid'))
Example #26
0
    def _on_join_clicked(self, *args):
        account = self.account_combo.get_active_id()
        nickname = self.nick_entry.get_text()

        if app.is_invisible(account):
            app.interface.raise_dialog('join-while-invisible')
            return

        server = self.server_combo.get_active_text()
        room = self.room_entry.get_text()

        if room == '':
            ErrorDialog(_('Invalid Group Chat'),
                        _('Please choose a group chat'),
                        transient_for=self)
            return

        self.room_jid = '%s@%s' % (room, server)

        try:
            self.room_jid = helpers.parse_jid(self.room_jid)
        except helpers.InvalidFormat as error:
            ErrorDialog(_('Invalid XMPP Address'),
                        str(error),
                        transient_for=self)
            return

        if app.in_groupchat(account, self.room_jid):
            # If we already in the groupchat, join_gc_room will bring
            # it to front
            app.interface.join_gc_room(account, self.room_jid, nickname, '')
            self.destroy()
            return

        if nickname == '':
            ErrorDialog(_('Invalid Nickname'),
                        _('Please choose a nickname'),
                        transient_for=self)
            return

        try:
            helpers.parse_resource(nickname)
        except helpers.InvalidFormat as error:
            ErrorDialog(_('Invalid Nickname'), str(error), transient_for=self)
            return

        if not app.account_is_connected(account):
            ErrorDialog(
                _('You are not connected to the server'),
                _('You can not join a group chat unless you are connected.'),
                transient_for=self)
            return

        password = self.password_entry.get_text()
        self._add_bookmark(account, nickname, password)
        app.add_recent_groupchat(account, self.room_jid, nickname)

        if self.automatic:
            app.automatic_rooms[self.account][self.room_jid] = self.automatic

        app.interface.join_gc_room(account, self.room_jid, nickname, password)
        self.destroy()