Beispiel #1
0
 def on_ok(widget):
     target_path = dialog.get_filename()
     if os.path.exists(target_path):
         # check if we have write permissions
         if not os.access(target_path, os.W_OK):
             file_name = os.path.basename(target_path)
             dialogs.ErrorDialog(
                 _('Cannot overwrite existing file "%s"') % file_name,
                 _('A file with this name already exists and you do '
                   'not have permission to overwrite it.'))
             return
         dialog2 = dialogs.FTOverwriteConfirmationDialog(
             _('This file already exists'),
             _('What do you want to do?'),
             propose_resume=False,
             on_response=(on_continue, target_path),
             transient_for=dialog)
         dialog2.set_destroy_with_parent(True)
     else:
         dirname = os.path.dirname(target_path)
         if not os.access(dirname, os.W_OK):
             dialogs.ErrorDialog(
                 _('Directory "%s" is not writable') % dirname,
                 _('You do not have permission to '
                   'create files in this directory.'))
             return
         on_continue(0, target_path)
Beispiel #2
0
 def get_send_file_props(self, account, contact, file_path, file_name,
 file_desc=''):
     """
     Create new file_props object and set initial file transfer
     properties in it
     """
     if os.path.isfile(file_path):
         stat = os.stat(file_path)
     else:
         dialogs.ErrorDialog(_('Invalid File'), _('File: ') + file_path)
         return None
     if stat[6] == 0:
         dialogs.ErrorDialog(_('Invalid File'),
         _('It is not possible to send empty files'))
         return None
     file_props = FilesProp.getNewFileProp(account,
                                 sid=helpers.get_random_string_16())
     mod_date = os.path.getmtime(file_path)
     file_props.file_name = file_path
     file_props.name = file_name
     file_props.date = self.__convert_date(mod_date)
     file_props.type_ = 's'
     file_props.desc = file_desc
     file_props.elapsed_time = 0
     file_props.size = stat[6]
     file_props.sender = account
     file_props.receiver = contact
     file_props.tt_account = account
     return file_props
Beispiel #3
0
    def on_ok(widget):
        def on_ok2(file_path, pixbuf):
            pixbuf.save(file_path, 'jpeg')
            dialog.destroy()

        file_path = dialog.get_filename()
        file_path = decode_filechooser_file_paths((file_path, ))[0]
        if os.path.exists(file_path):
            # check if we have write permissions
            if not os.access(file_path, os.W_OK):
                file_name = os.path.basename(file_path)
                dialogs.ErrorDialog(
                    _('Cannot overwrite existing file "%s"' % file_name),
                    _('A file with this name already exists and you do not have '
                      'permission to overwrite it.'))
                return
            dialog2 = dialogs.FTOverwriteConfirmationDialog(
                _('This file already exists'),
                _('What do you want to do?'),
                propose_resume=False,
                on_response=(on_continue, file_path))
            dialog2.set_transient_for(dialog)
            dialog2.set_destroy_with_parent(True)
        else:
            dirname = os.path.dirname(file_path)
            if not os.access(dirname, os.W_OK):
                dialogs.ErrorDialog(_('Directory "%s" is not writable') % \
                dirname, _('You do not have permission to create files in this'
                ' directory.'))
                return

        on_continue(0, file_path)
Beispiel #4
0
	def get_send_file_props(self, account, contact, file_path, file_name,
	file_desc=''):
		''' create new file_props dict and set initial file transfer 
		properties in it'''
		file_props = {'file-name' : file_path, 'name' : file_name, 
			'type' : 's', 'desc' : file_desc}
		if os.path.isfile(file_path):
			stat = os.stat(file_path)
		else:
			dialogs.ErrorDialog(_('Invalid File'), _('File: ')  + file_path)
			return None
		if stat[6] == 0:
			dialogs.ErrorDialog(_('Invalid File'), 
			_('It is not possible to send empty files'))
			return None
		file_props['elapsed-time'] = 0
		file_props['size'] = unicode(stat[6])
		file_props['sid'] = helpers.get_random_string_16()
		file_props['completed'] = False
		file_props['started'] = False
		file_props['sender'] = account
		file_props['receiver'] = contact
		file_props['tt_account'] = account
		# keep the last time: transfered_size to compute transfer speed
		file_props['transfered_size'] = []
		return file_props
Beispiel #5
0
    def on_set_avatar_button_clicked(self, widget):
        def on_ok(widget, path_to_file):
            must_delete = False
            filesize = os.path.getsize(path_to_file)  # in bytes
            invalid_file = False
            msg = ''
            if os.path.isfile(path_to_file):
                stat = os.stat(path_to_file)
                if stat[6] == 0:
                    invalid_file = True
                    msg = _('File is empty')
            else:
                invalid_file = True
                msg = _('File does not exist')
            if not invalid_file and filesize > 16384:  # 16 kb
                try:
                    pixbuf = gtk.gdk.pixbuf_new_from_file(path_to_file)
                    # get the image at 'notification size'
                    # and hope that user did not specify in ACE crazy size
                    scaled_pixbuf = gtkgui_helpers.get_scaled_pixbuf(
                        pixbuf, 'tooltip')
                except gobject.GError, msg:  # unknown format
                    # msg should be string, not object instance
                    msg = str(msg)
                    invalid_file = True
            if invalid_file:
                if True:  # keep identation
                    dialogs.ErrorDialog(_('Could not load image'), msg)
                    return
            if filesize > 16384:
                if scaled_pixbuf:
                    path_to_file = os.path.join(gajim.TMP, 'avatar_scaled.png')
                    scaled_pixbuf.save(path_to_file, 'png')
                    must_delete = True

            fd = open(path_to_file, 'rb')
            data = fd.read()
            pixbuf = gtkgui_helpers.get_pixbuf_from_data(data)
            try:
                # rescale it
                pixbuf = gtkgui_helpers.get_scaled_pixbuf(pixbuf, 'vcard')
            except AttributeError:  # unknown format
                dialogs.ErrorDialog(_('Could not load image'))
                return
            self.dialog.destroy()
            self.dialog = None
            button = self.xml.get_widget('PHOTO_button')
            image = button.get_image()
            image.set_from_pixbuf(pixbuf)
            button.show()
            text_button = self.xml.get_widget('NOPHOTO_button')
            text_button.hide()
            self.avatar_encoded = base64.encodestring(data)
            # returns None if unknown type
            self.avatar_mime_type = mimetypes.guess_type(path_to_file)[0]
            if must_delete:
                try:
                    os.remove(path_to_file)
                except OSError:
                    gajim.log.debug('Cannot remove %s' % path_to_file)
    def initialize_interfaces(self):
        """Initialize interfaces.

        Find devices, populate GUI, show all widgets and destroy loading widget,
        set the appropriate method to each device and
        if subnet has change alert message,
        which define devices with different subnet.
        """
        self.settings = Settings()
        device_paths = self.netman.get_devices()
        if len(device_paths) == 0:
            dialogs.ErrorDialog(MSG_NO_DEVICES, TITLE_ERROR).showup()
            return
        for device_path in device_paths:
            device = Device(device_path)
            ip4config_path, interface, driver, device_type, managed = device.get_properties()
            if device_type == 1 and managed:
                devicewired = DeviceWired(device_path)
                mac, speed, carrier = devicewired.get_properties()
                interface = Interface(ip4config_path, device_path, interface, \
                                        driver, device_type, mac, speed, carrier)
                self.interfaces.append(interface)
        if len(self.interfaces) == 0:
            dialogs.ErrorDialog(MSG_NO_WIRED_DEVICES, TITLE_ERROR).showup()
            return
        self.interfaces.sort(key=lambda interface: interface.interface)

        # Populate GUI
        for interface in self.interfaces:
            if interface.dhcp_request_info.subnet and interface.existing_info.subnet and \
                            interface.dhcp_request_info.subnet != interface.existing_info.subnet:
                self.interfaces_diff_subnet.append(interface)
            self.populate_pages(interface)

        # Show all widgets and destroy loading widget. Dialog is ready
        self.main_dlg.set_deletable(True)
        self.main_dlg.show_all()
        self.loading_box.destroy()

        # Set the appropriate method to each device
        self.set_default()

        # If subnet has change alert message which define devices with different subnet
        if len(self.interfaces_diff_subnet) > 0:
            if len(self.interfaces_diff_subnet) > 1:
                msg = MSG_SUBNET_PLURAL.format(', '.join([str(interface.interface)
                                                          for interface in self.interfaces_diff_subnet]))
            else:
                msg = MSG_SUBNET.format(', '.join([str(interface.interface)
                                                   for interface in self.interfaces_diff_subnet]))
            info_dialog = dialogs.InfoDialog(MSG_TITLE_SUBNET, TITLE_INFO)
            info_dialog.format_secondary_markup(msg)
            info_dialog.set_transient_for(self.main_dlg)
            info_dialog.showup()
    def __init__(self, parent):
        # Init some values
        self.parent = parent
        self.interfaces = []
        self.interfaces_diff_subnet = []
        self.timeout = 0
        self.settings = None
        self.ts_dns = ['127.0.0.1', '194.63.238.4', '8.8.8.8']
        self.ltsp_ips = dict(ip='192.168.67.1', mask='255.255.255.0', route='0.0.0.0')
        self.builder = Gtk.Builder()
        self.builder.add_from_file('ip_dialog.ui')
        self.builder.connect_signals(self)
        self.main_dlg = self.builder.get_object('main_dlg')
        self.main_dlg_grid = self.builder.get_object('main_dlg_grid')
        self.main_dlg_action_area = self.builder.get_object('main_dlg_action_area')
        self.main_dlg_notebook = self.builder.get_object('main_dlg_notebook')
        self.loading_box = self.builder.get_object('loading_box')
        self.main_dlg.set_transient_for(parent)

        # Connect to NetworkManager
        try:
            self.netman = NetworkManager()
        except dbus.exceptions.DBusException:
            error_dialog = dialogs.ErrorDialog(MSG_ERROR_CONNECT_NM, TITLE_ERROR)
            error_dialog.set_transient_for(self.main_dlg)
            error_dialog.showup()
            return

        # Hide some widget and show loading widget until dhcp request finished
        self.main_dlg_action_area.hide()
        self.main_dlg_grid.attach(self.loading_box, 0, 1, 2, 1)
        self.main_dlg.show()

        GObject.idle_add(self.initialize_interfaces)
Beispiel #8
0
    def send_file(self, account, contact, file_path, file_desc=''):
        """
        Start the real transfer(upload) of the file
        """
        if gtkgui_helpers.file_is_locked(file_path):
            pritext = _('Gajim can not read this file')
            sextext = _('Another process is using this file.')
            dialogs.ErrorDialog(pritext, sextext)
            return

        if isinstance(contact, str):
            if contact.find('/') == -1:
                return
            (jid, resource) = contact.split('/', 1)
            contact = gajim.contacts.create_contact(jid=jid, account=account,
                resource=resource)
        file_name = os.path.split(file_path)[1]
        file_props = self.get_send_file_props(account, contact,
                        file_path, file_name, file_desc)
        if file_props is None:
            return False
        if contact.supports(NS_JINGLE_FILE_TRANSFER):
            log.info("contact %s supports jingle file transfer"%(contact.get_full_jid()))
            gajim.connections[account].start_file_transfer(contact.get_full_jid(),
                                                           file_props)
            self.add_transfer(account, contact, file_props)
        else:
            log.info("contact does not support jingle file transfer")
            gajim.connections[account].send_file_request(file_props)
            self.add_transfer(account, contact, file_props)
        return True
    def on_mi_import_csv_activate(cls, _widget):
        """Import csv file.

        If the file is empty return false.
        """
        chooser = Gtk.FileChooserDialog(title="Επιλέξτε το αρχείο CSV προς εισαγωγή",
                                        action=Gtk.FileChooserAction.OPEN,
                                        buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                                 Gtk.STOCK_OK, Gtk.ResponseType.OK))

        chooser.set_icon_from_file('/usr/share/pixmaps/sch-scripts.svg')
        chooser.set_default_response(Gtk.ResponseType.OK)
        homepath = os.path.expanduser('~')
        chooser.set_current_folder(homepath)
        resp = chooser.run()
        if resp == Gtk.ResponseType.OK:
            fname = chooser.get_filename()
            new_users = parsers.CSV().parse(fname)
            if len(new_users.users) == 0:
                text = "Το αρχείο '%s' δεν περιέχει δεδομένα." % fname
                dialogs.ErrorDialog(text, "Σφάλμα").showup()
                return False
            chooser.destroy()
            import_dialog.ImportDialog(new_users)
        else:
            chooser.destroy()
    def on_mi_import_passwd_activate(cls, _widget):
        """Import password file dialog."""
        chooser = Gtk.FileChooserDialog(title="Επιλέξτε το αρχείο passwd προς εισαγωγή",
                                        action=Gtk.FileChooserAction.OPEN,
                                        buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL,
                                                 Gtk.STOCK_OK, Gtk.ResponseType.OK))

        chooser.set_icon_from_file('/usr/share/pixmaps/sch-scripts.svg')
        chooser.set_default_response(Gtk.ResponseType.OK)
        homepath = os.path.expanduser('~')
        chooser.set_current_folder(homepath)
        resp = chooser.run()
        if resp == Gtk.ResponseType.OK:
            passwd = chooser.get_filename()
            path = os.path.dirname(passwd)
            shadow = os.path.join(path, 'shadow')
            group = os.path.join(path, 'group')
            if not os.path.isfile(shadow):
                shadow = None
            if not os.path.isfile(group):
                group = None
            new_users = parsers.Passwd().parse(passwd, shadow, group)
            if len(new_users.users) == 0:
                text = "Το αρχείο '%s' δεν περιέχει δεδομένα." % passwd
                dialogs.ErrorDialog(text, "Σφάλμα").showup()
                return False
            chooser.destroy()
            import_dialog.ImportDialog(new_users)
        else:
            chooser.destroy()
Beispiel #11
0
 def on_mi_import_passwd_activate(self, widget):
     chooser = Gtk.FileChooserDialog(
         title=_("Select the passwd file to import"),
         action=Gtk.FileChooserAction.OPEN,
         buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_OK,
                  Gtk.ResponseType.OK))
     chooser.set_transient_for(self.main_window)
     chooser.set_icon(self.icontheme.load_icon('ltsp-manager', 128, 0))
     chooser.set_default_response(Gtk.ResponseType.OK)
     homepath = os.path.expanduser('~')
     chooser.set_current_folder(homepath)
     resp = chooser.run()
     if resp == Gtk.ResponseType.OK:
         passwd = chooser.get_filename()
         path = os.path.dirname(passwd)
         shadow = os.path.join(path, 'shadow')
         group = os.path.join(path, 'group')
         if not os.path.isfile(shadow):
             shadow = None
         if not os.path.isfile(group):
             group = None
         new_users = parsers.passwd().parse(passwd, shadow, group)
         if len(new_users.users) == 0:
             text = _("The file \"%s\" contains no data.") % passwd
             dialogs.ErrorDialog(text, _("Error")).showup()
             return False
         chooser.destroy()
         import_dialog.ImportDialog(new_users, parent=self.main_window)
     else:
         chooser.destroy()
Beispiel #12
0
 def on_ok_button_clicked(self, widget):
     if self.update_progressbar_timeout_id:
         # Operation in progress
         return
     if gajim.connections[self.account].connected < 2:
         dialogs.ErrorDialog(
             _('You are not connected to the server'),
             _('Without a connection you can not publish your contact '
               'information.'))
         return
     vcard_ = self.make_vcard()
     nick = ''
     if 'NICKNAME' in vcard_:
         nick = vcard_['NICKNAME']
         from common import pep
         pep.user_send_nickname(self.account, nick)
     if nick == '':
         nick = gajim.config.get_per('accounts', self.account, 'name')
     gajim.nicks[self.account] = nick
     gajim.connections[self.account].send_vcard(vcard_)
     self.message_id = self.statusbar.push(self.context_id,
                                           _('Sending profile...'))
     self.progressbar.show()
     self.update_progressbar_timeout_id = gobject.timeout_add(
         100, self.update_progressbar)
Beispiel #13
0
    def on_calendar_month_changed(self, widget):
        """
        Ask for days in this month, if they have logs it bolds them (marks them)
        """
        if not self.jid:
            return
        year, month, day = widget.get_date()  # integers
        if year < 1900:
            widget.select_month(0, 1900)
            widget.select_day(1)
            return

        # in gtk January is 1, in python January is 0,
        # I want the second
        # first day of month is 1 not 0
        widget.clear_marks()
        month = gtkgui_helpers.make_gtk_month_python_month(month)
        days_in_this_month = calendar.monthrange(year, month)[1]
        try:
            log_days = gajim.logger.get_days_with_logs(self.jid, year, month,
                                                       days_in_this_month,
                                                       self.account)
        except exceptions.PysqliteOperationalError as e:
            dialogs.ErrorDialog(_('Disk Error'), str(e))
            return
        for day in log_days:
            widget.mark_day(day)
Beispiel #14
0
 def on_theme_cell_edited(self, cell, row, new_name):
     model = self.themes_tree.get_model()
     iter_ = model.get_iter_from_string(row)
     old_name = model.get_value(iter_, 0)
     if old_name == new_name:
         return
     if old_name == 'default':
         dialogs.ErrorDialog(
             _('You cannot make changes to the default theme'),
         	_('Please create a new clean theme.'))
         return
     new_config_name = new_name.replace(' ', '_')
     if new_config_name in gajim.config.get_per('themes'):
         return
     gajim.config.add_per('themes', new_config_name)
     # Copy old theme values
     old_config_name = old_name.replace(' ', '_')
     properties = ['textcolor', 'bgcolor', 'font', 'fontattrs']
     gajim.config.add_per('themes', new_config_name)
     for option in self.options:
         for property_ in properties:
             option_name = option + property_
             gajim.config.set_per('themes', new_config_name, option_name,
                     gajim.config.get_per('themes', old_config_name, option_name))
     gajim.config.del_per('themes', old_config_name)
     if old_config_name == gajim.config.get('roster_theme'):
         gajim.config.set('roster_theme', new_config_name)
     model.set_value(iter_, 0, new_name)
     self.current_theme = new_name
Beispiel #15
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, s:
         dialogs.ErrorDialog(_('Invalid Jabber ID'), str(s))
         return
Beispiel #16
0
        def on_ok(widget, account, contact, file_props):
            file_path = dialog2.get_filename()
            if os.path.exists(file_path):
                # check if we have write permissions
                if not os.access(file_path, os.W_OK):
                    file_name = GLib.markup_escape_text(os.path.basename(
                        file_path))
                    dialogs.ErrorDialog(
                        _('Cannot overwrite existing file "%s"' % file_name),
                        _('A file with this name already exists and you do not '
                        'have permission to overwrite it.'))
                    return
                stat = os.stat(file_path)
                dl_size = stat.st_size
                file_size = file_props.size
                dl_finished = dl_size >= file_size

                def on_response(response):
                    if response < 0:
                        return
                    elif response == 100:
                        file_props.offset = dl_size
                    dialog2.destroy()
                    self._start_receive(file_path, account, contact, file_props)

                dialog = dialogs.FTOverwriteConfirmationDialog(
                    _('This file already exists'), _('What do you want to do?'),
                    propose_resume=not dl_finished, on_response=on_response,
                    transient_for=dialog2)
                dialog.set_destroy_with_parent(True)
                return
            else:
                dirname = os.path.dirname(file_path)
                if not os.access(dirname, os.W_OK) and os.name != 'nt':
                    # read-only bit is used to mark special folder under
                    # windows, not to mark that a folder is read-only.
                    # See ticket #3587
                    dialogs.ErrorDialog(_('Directory "%s" is not writable') % \
                        dirname, _('You do not have permission to create files '
                        'in this directory.'))
                    return
            dialog2.destroy()
            self._start_receive(file_path, account, contact, file_props)
Beispiel #17
0
 def on_open_link_in_browser_menuitem_activate(self, menu, data):
     url = data["url"]
     if data["encrypted"]:
         dialogs.ErrorDialog(
             _('Encrypted file'),
             _('You cannot open encrypted files in your '
               'browser directly. Try "Open Downloaded File '
               'in Browser" instead.'),
             transient_for=self.chat_control.parent_win.window)
     else:
         helpers.launch_browser_mailer('url', url)
Beispiel #18
0
 def show_stopped(self, jid, file_props, error_msg=''):
     if file_props.type_ == 'r':
         file_name = os.path.basename(file_props.file_name)
     else:
         file_name = file_props.name
     sectext = '\t' + _('Filename: %s') % GLib.markup_escape_text(file_name)
     sectext += '\n\t' + _('Recipient: %s') % jid
     if error_msg:
         sectext += '\n\t' + _('Error message: %s') % error_msg
     dialogs.ErrorDialog(_('File transfer stopped'), sectext)
     self.tree.get_selection().unselect_all()
Beispiel #19
0
    def watch_nm(self, interest_interfaces, prefered_hostname):
        self.timeout += 1000
        break_bool = True
        for interface in interest_interfaces:
            if interface.carrier != 1:
                continue
            #TODO: Change it (do not create new instances)
            device = Device(interface.device_path)
            ip4config_path, interface, driver, device_type, managed = device.get_properties(
            )
            if ip4config_path == '/':
                break_bool = False

        if break_bool:
            p = common.run_command(
                ['sh', '-c', 'ltsp-config dnsmasq  --enable-dns --overwrite'],
                True)
            while p.poll() is None:
                while Gtk.events_pending():
                    Gtk.main_iteration()

            if p.returncode == 0:
                msg = MSG_DNSMASQ_RESTART_SUCCESS
                if prefered_hostname:
                    msg = MSG_SUGGEST_HOSTNAME.format(prefered_hostname) + msg

                success_dialog = dialogs.InfoDialog(
                    MSG_TITLE_CONNECTIONS_CREATE, TITLE_SUCCESS)
                success_dialog.format_secondary_markup(msg)
                success_dialog.set_transient_for(self.main_dlg)
                success_dialog.showup()
                self.main_dlg.destroy()
            else:
                error_dialog = dialogs.ErrorDialog(
                    MSG_TITLE_DNSMASQ_RESTART_FAIL, TITLE_ERROR)
                error_dialog.format_secondary_markup(MSG_DNSMASQ_RESTART_FAIL)
                error_dialog.set_transient_for(self.main_dlg)
                error_dialog.showup()
                self.main_dlg.destroy()
            return False
        elif not break_bool and self.timeout == 30000:
            msg = MSG_DNSMASQ_RESTART_FAIL_ENABLE
            if prefered_hostname:
                msg = MSG_SUGGEST_HOSTNAME.format(prefered_hostname) + msg

            success_dialog = dialogs.InfoDialog(MSG_TITLE_CONNECTIONS_CREATE,
                                                TITLE_SUCCESS)
            success_dialog.format_secondary_markup(msg)
            success_dialog.set_transient_for(self.main_dlg)
            success_dialog.showup()
            self.main_dlg.destroy()
            return False
        return True
Beispiel #20
0
	def show_stopped(self, jid, file_props, error_msg = ''):
		if file_props['type'] == 'r':
			file_name = os.path.basename(file_props['file-name'])
		else:
			file_name = file_props['name']
		sectext = '\t' + _('Filename: %s') % file_name
		sectext += '\n\t' + _('Recipient: %s') % jid
		if error_msg:
			sectext += '\n\t' + _('Error message: %s') % error_msg
		dialogs.ErrorDialog(_('File transfer stopped by the contact at the other '
			'end'), sectext)
		self.tree.get_selection().unselect_all()
Beispiel #21
0
 def show_progress_error(self, result, message, ignore=True):
     message += '\n\n' + api.SEE_LOG
     errorDlg = dialogs.ErrorDialog(self, message, ignore)
     answer = errorDlg.ShowModal()
     result['stop_for_errors'] = not errorDlg.future_errors.GetValue()
     errorDlg.Destroy()
     if answer == wx.ID_ABORT:
         result['answer'] = _('abort')
         self.show_log()
     elif answer == wx.ID_FORWARD:
         result['answer'] = _('skip')
     else:
         result['answer'] = _('ignore')
Beispiel #22
0
    def __on_connected_failed(self, reason, host_id, host, port, user, passwd,
                              try_counter):
        log.debug("Failed to connect: %s", reason.value)

        if reason.check(AuthenticationRequired, BadLoginError):
            log.debug("PasswordRequired exception")
            dialog = dialogs.AuthenticationDialog(reason.value.message,
                                                  reason.value.username)

            def dialog_finished(response_id, host, port, user):
                if response_id == gtk.RESPONSE_OK:
                    self.__connect(host_id, host, port, user and user
                                   or dialog.get_username(),
                                   dialog.get_password())

            d = dialog.run().addCallback(dialog_finished, host, port, user)
            return d

        elif reason.trap(IncompatibleClient):
            dialog = dialogs.ErrorDialog(_("Incompatible Client"),
                                         reason.value.message)
            return dialog.run()

        if try_counter:
            log.info("Retrying connection.. Retries left: %s", try_counter)
            return reactor.callLater(0.5,
                                     self.__connect,
                                     host_id,
                                     host,
                                     port,
                                     user,
                                     passwd,
                                     try_counter=try_counter - 1)

        msg = str(reason.value)
        if not self.builder.get_object("chk_autostart").get_active():
            msg += '\n' + _("Auto-starting the daemon locally is not enabled. "
                            "See \"Options\" on the \"Connection Manager\".")
        dialogs.ErrorDialog(_("Failed To Connect"), msg).run()
Beispiel #23
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
Beispiel #24
0
 def on_BDAY_entry_focus_out_event(self, widget, event):
     txt = widget.get_text()
     if not txt:
         return
     try:
         time.strptime(txt, '%Y-%m-%d')
     except ValueError:
         if not widget.is_focus():
             pritext = _('Wrong date format')
             dialogs.ErrorDialog(pritext, _('Format of the date must be '
                 'YYYY-MM-DD'), transient_for=self.window)
             GLib.idle_add(lambda: widget.grab_focus())
         return True
Beispiel #25
0
    def __start_non_classic(self):
        # Autoconnect to a host
        if self.config["autoconnect"]:
            for host in self.connectionmanager.config["hosts"]:
                if host[0] == self.config["autoconnect_host_id"]:
                    try_connect = True
                    # Check to see if we need to start the localhost daemon
                    if self.config["autostart_localhost"] and host[1] in (
                            "localhost", "127.0.0.1"):
                        log.debug("Autostarting localhost:%s", host[2])
                        try_connect = client.start_daemon(
                            host[2], deluge.configmanager.get_config_dir())
                        log.debug("Localhost started: %s", try_connect)
                        if not try_connect:
                            dialogs.ErrorDialog(
                                _("Error Starting Daemon"),
                                _("There was an error starting the daemon process.  Try running it from a console to see if there is an error."
                                  )).run()

                    def on_connect(connector):
                        component.start()

                    def on_connect_fail(result, try_counter):
                        log.info("Connection to host failed..")
                        # We failed connecting to the daemon, but lets try again
                        if try_counter:
                            log.info("Retrying connection.. Retries left: %s",
                                     try_counter)
                            try_counter -= 1
                            import time
                            time.sleep(0.5)
                            do_connect(try_counter)
                        return

                    def do_connect(try_counter):
                        client.connect(
                            *host[1:]).addCallback(on_connect).addErrback(
                                on_connect_fail, try_counter)

                    if try_connect:
                        do_connect(6)
                    break

        if self.config["show_connection_manager_on_start"]:
            # XXX: We need to call a simulate() here, but this could be a bug in twisted
            try:
                reactor._simulate()
            except AttributeError:
                # twisted < 12
                reactor.simulate()
            self.connectionmanager.show()
Beispiel #26
0
 def on_remove_button_clicked(self, widget):
     (model, iter_) = self.themes_tree.get_selection().get_selected()
     if not iter_:
         return
     if self.current_theme == gajim.config.get('roster_theme'):
         dialogs.ErrorDialog(
             _('You cannot delete your current theme'),
             _('Pick another theme to use first.'))
         return
     self.theme_options_vbox.set_sensitive(False)
     self.theme_options_table.set_sensitive(False)
     self.xml.get_object('remove_button').set_sensitive(False)
     gajim.config.del_per('themes', self.current_theme)
     model.remove(iter_)
Beispiel #27
0
    def start_daemon(self, port, config):
        """
        Attempts to start a daemon process and will show an ErrorDialog if unable
        to.
        """
        try:
            return client.start_daemon(port, config)
        except OSError, e:
            from errno import ENOENT
            if e.errno == ENOENT:
                dialogs.ErrorDialog(
                    _("Unable to start daemon!"),
                    _("Deluge cannot find the 'deluged' executable, it is likely \
that you forgot to install the deluged package or it's not in your PATH.")).run()
            else:
                raise e
Beispiel #28
0
    def _on_reactor_start(self):
        log.debug("_on_reactor_start")
        self.mainwindow.first_show()

        if self.config["classic_mode"]:

            def on_dialog_response(response):
                if response != gtk.RESPONSE_YES:
                    # The user does not want to turn Classic Mode off, so just quit
                    reactor.stop()
                    return
                # Turning off classic_mode
                self.config["classic_mode"] = False
                self.__start_non_classic()

            try:
                client.start_classic_mode()
            except deluge.error.DaemonRunningError:
                d = dialogs.YesNoDialog(
                    _("Turn off Classic Mode?"),
                    _("It appears that a Deluge daemon process (deluged) is already running.\n\n\
You will either need to stop the daemon or turn off Classic Mode to continue.")
                ).run()

                self.started_in_classic = False
                d.addCallback(on_dialog_response)
            except Exception, e:
                import traceback
                tb = sys.exc_info()
                ed = dialogs.ErrorDialog(
                    _("Error Starting Core"),
                    _("There was an error starting the core component which is required to run Deluge in Classic Mode.\n\n\
Please see the details below for more information."),
                    details=traceback.format_exc(tb[2])).run()

                def on_ed_response(response):
                    d = dialogs.YesNoDialog(
                        _("Turn off Classic Mode?"),
                        _("Since there was an error starting in Classic Mode would you like to continue by turning it off?"
                          )).run()
                    self.started_in_classic = False
                    d.addCallback(on_dialog_response)

                ed.addCallback(on_ed_response)
            else:
                component.start()
                return
Beispiel #29
0
    def __init__(self):
        pixs = []
        for size in (16, 32, 48, 64, 128):
            pix = gtkgui_helpers.get_icon_pixmap('gajim', size)
            if pix:
                pixs.append(pix)
        if pixs:
            # set the icon to all windows
            Gtk.Window.set_default_icon_list(pixs)

        if not os.path.exists(LOG_DB_PATH):
            dialogs.ErrorDialog(_('Cannot find history logs database'),
                                '%s does not exist.' % LOG_DB_PATH)
            sys.exit()

        xml = gtkgui_helpers.get_gtk_builder('history_manager.ui')
        self.window = xml.get_object('history_manager_window')
        self.jids_listview = xml.get_object('jids_listview')
        self.logs_listview = xml.get_object('logs_listview')
        self.search_results_listview = xml.get_object(
            'search_results_listview')
        self.search_entry = xml.get_object('search_entry')
        self.logs_scrolledwindow = xml.get_object('logs_scrolledwindow')
        self.search_results_scrolledwindow = xml.get_object(
            'search_results_scrolledwindow')
        self.welcome_vbox = xml.get_object('welcome_vbox')

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

        self.con = sqlite.connect(LOG_DB_PATH,
                                  timeout=20.0,
                                  isolation_level='IMMEDIATE')
        self.cur = self.con.cursor()

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

        self._fill_jids_listview()

        self.search_entry.grab_focus()

        self.window.show_all()

        xml.connect_signals(self)
    def create_update_connections(self, interest_interfaces, prefered_hostname, dnsmasq_via_carrier,
                                  dnsmasq_via_autoconnect):
        for interface in interest_interfaces:
            # Test if static ip exists in network
            # Case which doesn't work: User had set .10 manual and .10 is owned by another pc,
            # arping always fail so we can't catch the conflict.
            if interface.page.method_entry.get_active() == 2 and \
                            interface.carrier == 1 and self.netman.get_active_connections():
                test_ip = interface.page.ip_entry.get_text()
                if test_ip != interface.existing_info.ip_add:
                    sample = common.run_command(['arping', '-f', '-w1', '-I', interface.interface, test_ip], True)
                    while sample.poll() is None:
                        while Gtk.events_pending():
                            Gtk.main_iteration()
                    if sample.returncode == 0:
                        interface.page.ip_entry.set_icon_from_stock(1, Gtk.STOCK_DIALOG_WARNING)
                        interface.page.ip_entry.set_icon_tooltip_text(1, MSG_PC_CONFLICT_IP.format(test_ip))
                        title = MSG_PC_CONFLICT_IP.format(test_ip)
                        err_dialog = dialogs.ErrorDialog(title, TITLE_ERROR)
                        err_dialog.set_transient_for(self.main_dlg)
                        if err_dialog.showup() != Gtk.ResponseType.OK:
                            self.main_dlg.set_sensitive(True)
                            self.main_dlg.show()
                            return

            if interface.conflict is not None:
                interface.conflict.interface.Update(interface.connection)
                if interface.carrier == 1 and interface.page.auto_checkbutton.get_active():
                    self.netman.interface.ActivateConnection(interface.conflict.object_path, interface.device_path, '/')
            else:
                object_path = self.settings.interface.AddConnection(interface.connection)
                if interface.carrier == 1 and interface.page.auto_checkbutton.get_active():
                    self.netman.interface.ActivateConnection(object_path, interface.device_path, '/')

            for connection_settings in interface.interface_connections:
                settings = connection_settings.get_settings()
                settings['connection'][dbus.String('autoconnect')] = dbus.Boolean('false')
                connection_settings.interface.Update(settings)

        if dnsmasq_via_carrier and dnsmasq_via_autoconnect:
            GObject.timeout_add(1000, self.watch_nm, interest_interfaces, prefered_hostname)
        else:
            success_dialog = dialogs.InfoDialog(MSG_TITLE_CONNECTIONS_CREATE, TITLE_SUCCESS)
            success_dialog.set_transient_for(self.main_dlg)
            success_dialog.showup()
            self.main_dlg.destroy()