Esempio n. 1
0
    def parse(self):
        parser = optparse.OptionParser(version=("Tryton %s" % __version__),
                usage="Usage: %prog [options] [url]")
        parser.add_option("-c", "--config", dest="config",
                help=_("specify alternate config file"))
        parser.add_option("-d", "--dev", action="store_true",
                default=False, dest="dev",
                help=_("development mode"))
        parser.add_option("-v", "--verbose", action="store_true",
                default=False, dest="verbose",
                help=_("logging everything at INFO level"))
        parser.add_option("-l", "--log-level", dest="log_level",
                help=_("specify the log level: "
                "DEBUG, INFO, WARNING, ERROR, CRITICAL"))
        parser.add_option("-u", "--user", dest="login",
                help=_("specify the login user"))
        parser.add_option("-p", "--port", dest="port",
                help=_("specify the server port"))
        parser.add_option("-s", "--server", dest="server",
                help=_("specify the server hostname"))
        opt, self.arguments = parser.parse_args()

        if len(self.arguments) > 1:
            raise TrytonError(_('Too much arguments'))

        if opt.config and not os.path.isfile(opt.config):
            raise TrytonError(_('File "%s" not found') % (opt.config,))
        self.rcfile = opt.config or os.path.join(
            get_config_dir(), 'tryton.conf')
        self.load()

        self.options['dev'] = opt.dev
        logging.basicConfig()
        loglevels = {
            'DEBUG': logging.DEBUG,
            'INFO': logging.INFO,
            'WARNING': logging.WARNING,
            'ERROR': logging.ERROR,
            'CRITICAL': logging.CRITICAL,
            }
        if not opt.log_level:
            if opt.verbose:
                opt.log_level = 'INFO'
            else:
                opt.log_level = 'ERROR'
        logging.getLogger().setLevel(loglevels[opt.log_level.upper()])

        for arg in ('login', 'port', 'server'):
            if getattr(opt, arg):
                self.options['login.' + arg] = getattr(opt, arg)
Esempio n. 2
0
 def __init__(self, func=rpc.login):
     parameters = {}
     while True:
         try:
             func(parameters)
         except TrytonServerError as exception:
             if exception.faultCode == str(int(HTTPStatus.UNAUTHORIZED)):
                 parameters.clear()
                 continue
             if (exception.faultCode
                     == str(int(HTTPStatus.TOO_MANY_REQUESTS))):
                 message(
                     _('Too many requests. Try again later.'),
                     msg_type=Gtk.MessageType.ERROR)
                 continue
             if exception.faultCode != 'LoginException':
                 raise
             name, msg, type = exception.args
             value = getattr(self, 'get_%s' % type)(msg)
             if value is None:
                 raise TrytonError('QueryCanceled')
             parameters[name] = value
             continue
         else:
             return
Esempio n. 3
0
 def parse(self, screen, root_node, fields, children_field=None):
     for node in root_node.childNodes:
         if not node.nodeType == node.ELEMENT_NODE:
             continue
         if node.localName in PARSERS:
             widget = PARSERS[node.localName](self.parent, self.attrs,
                                              screen, children_field)
             (wid, child, state_widgets, on_write, notebooks,
              cursor_widget) = widget.parse(screen.model_name, node, fields)
             screen.set_on_write(on_write)
             res = PARSERS2[node.localName](screen, wid, child,
                                            state_widgets, notebooks,
                                            cursor_widget, children_field)
             res.title = widget.title
             return res
         else:
             raise TrytonError('Unknow view mode: %s' % node.localName)
Esempio n. 4
0
 def __init__(self, func=rpc.login):
     parameters = {}
     while True:
         try:
             func(parameters)
         except TrytonServerError as exception:
             if exception.faultCode == str(HTTPStatus.UNAUTHORIZED.value):
                 parameters.clear()
                 continue
             if exception.faultCode != 'LoginException':
                 raise
             name, message, type = exception.args
             value = getattr(self, 'get_%s' % type)(message)
             if value is None:
                 raise TrytonError('QueryCanceled')
             parameters[name] = value
             continue
         else:
             return
Esempio n. 5
0
 def __init__(self, func):
     parameters = {}
     while True:
         try:
             func(parameters)
         except TrytonServerError, exception:
             if exception.faultCode.startswith('403'):
                 parameters.clear()
                 continue
             if exception.faultCode != 'LoginException':
                 raise
             name, message, type = exception.args
             value = getattr(self, 'get_%s' % type)(message)
             if value is None:
                 raise TrytonError('QueryCanceled')
             parameters[name] = value
             continue
         else:
             return
Esempio n. 6
0
class DBLogin(object):
    def __init__(self):
        # GTK Stuffs
        self.parent = common.get_toplevel_window()
        self.dialog = gtk.Dialog(title=_('Login'), parent=self.parent,
            flags=gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT)
        self.dialog.set_position(gtk.WIN_POS_CENTER_ON_PARENT)
        self.dialog.set_icon(GNUHEALTH_ICON)

        tooltips = common.Tooltips()
        button_cancel = gtk.Button(_('_Cancel'), use_underline=True)
        img_cancel = gtk.Image()
        img_cancel.set_from_stock('gtk-cancel', gtk.ICON_SIZE_BUTTON)
        button_cancel.set_image(img_cancel)
        tooltips.set_tip(button_cancel,
            _('Cancel connection to the GNU Health server'))
        self.dialog.add_action_widget(button_cancel, gtk.RESPONSE_CANCEL)
        self.button_connect = gtk.Button(_('C_onnect'), use_underline=True)
        img_connect = gtk.Image()
        img_connect.set_from_stock('tryton-connect', gtk.ICON_SIZE_BUTTON)
        self.button_connect.set_image(img_connect)
        self.button_connect.set_can_default(True)
        tooltips.set_tip(self.button_connect, _('Connect the GNU Health server'))
        self.dialog.add_action_widget(self.button_connect, gtk.RESPONSE_OK)
        self.dialog.set_default_response(gtk.RESPONSE_OK)
        alignment = gtk.Alignment(yalign=0, yscale=0, xscale=1)
        self.table_main = gtk.Table(3, 3, False)
        self.table_main.set_border_width(0)
        self.table_main.set_row_spacings(3)
        self.table_main.set_col_spacings(3)
        alignment.add(self.table_main)
        self.dialog.vbox.pack_start(alignment, True, True, 0)

        image = gtk.Image()
        # Use custom banner if set in the custom_banner param
        if (CONFIG['client.banner']):
            image.set_from_file(CONFIG['client.banner'])
        else:
            image.set_from_file(os.path.join(PIXMAPS_DIR, BANNER))
        image.set_alignment(0.5, 1)
        ebox = gtk.EventBox()
        ebox.modify_bg(gtk.STATE_NORMAL, gtk.gdk.color_parse("#1b2019"))
        ebox.add(image)
        self.table_main.attach(ebox, 0, 3, 0, 1, ypadding=2)

        self.profile_store = gtk.ListStore(gobject.TYPE_STRING,
            gobject.TYPE_BOOLEAN)
        self.combo_profile = gtk.ComboBox()
        cell = gtk.CellRendererText()
        self.combo_profile.pack_start(cell, True)
        self.combo_profile.add_attribute(cell, 'text', 0)
        self.combo_profile.add_attribute(cell, 'sensitive', 1)
        self.combo_profile.set_model(self.profile_store)
        self.combo_profile.connect('changed', self.profile_changed)
        self.profile_label = gtk.Label(_(u'Profile:'))
        self.profile_label.set_justify(gtk.JUSTIFY_RIGHT)
        self.profile_label.set_alignment(1, 0.5)
        self.profile_label.set_padding(3, 3)
        self.profile_button = gtk.Button(_('_Manage profiles'),
            use_underline=True)
        self.profile_button.connect('clicked', self.profile_manage)
        self.table_main.attach(self.profile_label, 0, 1, 1, 2,
            xoptions=gtk.FILL)
        self.table_main.attach(self.combo_profile, 1, 2, 1, 2)
        self.table_main.attach(self.profile_button, 2, 3, 1, 2,
            xoptions=gtk.FILL)
        image = gtk.Image()
        image.set_from_stock('gtk-edit', gtk.ICON_SIZE_BUTTON)
        self.profile_button.set_image(image)
        self.expander = gtk.Expander()
        self.expander.set_label(_('Host / Database information'))
        self.expander.connect('notify::expanded', self.expand_hostspec)
        self.table_main.attach(self.expander, 0, 3, 3, 4)
        self.label_host = gtk.Label(_('Host:'))
        self.label_host.set_justify(gtk.JUSTIFY_RIGHT)
        self.label_host.set_alignment(1, 0.5)
        self.label_host.set_padding(3, 3)
        self.entry_host = gtk.Entry()
        self.entry_host.connect_after('focus-out-event',
            self.clear_profile_combo)
        self.entry_host.set_activates_default(True)
        self.label_host.set_mnemonic_widget(self.entry_host)
        self.table_main.attach(self.label_host, 0, 1, 4, 5, xoptions=gtk.FILL)
        self.table_main.attach(self.entry_host, 1, 3, 4, 5)
        self.label_database = gtk.Label(_('Database:'))
        self.label_database.set_justify(gtk.JUSTIFY_RIGHT)
        self.label_database.set_alignment(1, 0.5)
        self.label_database.set_padding(3, 3)
        self.entry_database = gtk.Entry()
        self.entry_database.connect_after('focus-out-event',
            self.clear_profile_combo)
        self.entry_database.set_activates_default(True)
        self.label_database.set_mnemonic_widget(self.entry_database)
        self.table_main.attach(self.label_database, 0, 1, 5, 6,
            xoptions=gtk.FILL)
        self.table_main.attach(self.entry_database, 1, 3, 5, 6)
        self.entry_login = gtk.Entry()
        self.entry_login.set_activates_default(True)
        self.table_main.attach(self.entry_login, 1, 3, 6, 7)
        label_username = gtk.Label(_("User name:"))
        label_username.set_alignment(1, 0.5)
        label_username.set_padding(3, 3)
        label_username.set_mnemonic_widget(self.entry_login)
        self.table_main.attach(label_username, 0, 1, 6, 7, xoptions=gtk.FILL)

        # Profile informations
        self.profile_cfg = os.path.join(get_config_dir(), 'profiles.cfg')
        self.profiles = ConfigParser.SafeConfigParser({'port': '8000'})
        if not os.path.exists(self.profile_cfg):
            short_version = '.'.join(__version__.split('.', 2)[:2])
            name = 'health.gnusolidario.org'
            self.profiles.add_section(name)
            self.profiles.set(name, 'host', name)
            self.profiles.set(name, 'port', '8000')
            self.profiles.set(name, 'database', 'health32')
            self.profiles.set(name, 'username', 'admin')
        else:
            self.profiles.read(self.profile_cfg)
        for section in self.profiles.sections():
            active = all(self.profiles.has_option(section, option)
                for option in ('host', 'port', 'database'))
            self.profile_store.append([section, active])

    def profile_manage(self, widget):
        def callback(profile_name):
            with open(self.profile_cfg, 'wb') as configfile:
                self.profiles.write(configfile)

            for idx, row in enumerate(self.profile_store):
                if row[0] == profile_name and row[1]:
                    self.combo_profile.set_active(idx)
                    self.profile_changed(self.combo_profile)
                    break

        dia = DBListEditor(self.dialog, self.profile_store, self.profiles,
            callback)
        active_profile = self.combo_profile.get_active()
        profile_name = None
        if active_profile != -1:
            profile_name = self.profile_store[active_profile][0]
        dia.run(profile_name)

    def profile_changed(self, combobox):
        position = combobox.get_active()
        if position == -1:
            return
        profile = self.profile_store[position][0]
        try:
            username = self.profiles.get(profile, 'username')
        except ConfigParser.NoOptionError:
            username = ''
        host = self.profiles.get(profile, 'host')
        self.entry_host.set_text('%s' % host)
        self.entry_database.set_text(self.profiles.get(profile, 'database'))
        if username:
            self.entry_login.set_text(username)
        else:
            self.entry_login.set_text('')

    def clear_profile_combo(self, entry, event):
        netloc = self.entry_host.get_text()
        host = common.get_hostname(netloc)
        port = common.get_port(netloc)
        database = self.entry_database.get_text().strip()
        for idx, profile_info in enumerate(self.profile_store):
            if not profile_info[1]:
                continue
            profile = profile_info[0]
            profile_host = self.profiles.get(profile, 'host')
            profile_db = self.profiles.get(profile, 'database')
            if (host == common.get_hostname(profile_host)
                    and port == common.get_port(profile_host)
                    and database == profile_db):
                break
        else:
            idx = -1
        self.combo_profile.set_active(idx)
        return False

    def expand_hostspec(self, expander, *args):
        visibility = expander.props.expanded
        self.entry_host.props.visible = visibility
        self.label_host.props.visible = visibility
        self.entry_database.props.visible = visibility
        self.label_database.props.visible = visibility

    def run(self):
        profile_name = CONFIG['login.profile']
        can_use_profile = self.profiles.has_section(profile_name)
        if can_use_profile:
            for (configname, sectionname) in (('login.server', 'host'),
                    ('login.port', 'port'), ('login.db', 'database')):
                if (self.profiles.get(profile_name, sectionname)
                        != CONFIG[configname]):
                    can_use_profile = False
                    break

        if can_use_profile:
            for idx, row in enumerate(self.profile_store):
                if row[0] == profile_name:
                    self.combo_profile.set_active(idx)
                    break
        else:
            self.combo_profile.set_active(-1)
            if ':' in CONFIG['login.server']:
                host = '[%s]' % CONFIG['login.server']
            else:
                host = CONFIG['login.server']
            self.entry_host.set_text('%s:%s' % (host,
                CONFIG['login.port']))
            db = CONFIG['login.db'] if CONFIG['login.db'] else ''
            self.entry_database.set_text(db)
            self.entry_login.set_text(CONFIG['login.login'])
        self.dialog.show_all()

        self.entry_login.grab_focus()

        # Reshow dialog for gtk-quarks
        self.dialog.reshow_with_initial_size()
        self.expander.set_expanded(CONFIG['login.expanded'])
        # The previous action did not called expand_hostspec
        self.expand_hostspec(self.expander)

        response, result = None, ('', '', '', '')
        while not all(result):
            response = self.dialog.run()
            if response != gtk.RESPONSE_OK:
                break
            active_profile = self.combo_profile.get_active()
            if active_profile != -1:
                profile = self.profile_store[active_profile][0]
                CONFIG['login.profile'] = profile
            netloc = self.entry_host.get_text()
            host = common.get_hostname(netloc)
            port = common.get_port(netloc)
            try:
                test = DBListEditor.test_server_version(host, port)
                if not test:
                    if test is False:
                        common.warning('',
                            _(u'Incompatible version of the server'))
                    else:
                        common.warning('',
                            _(u'Could not connect to the server'))
                    continue
            except Exception, exception:
                common.process_exception(exception)
                continue
            database = self.entry_database.get_text()
            login = self.entry_login.get_text()
            CONFIG['login.server'] = host
            CONFIG['login.port'] = port
            CONFIG['login.db'] = database
            CONFIG['login.expanded'] = self.expander.props.expanded
            CONFIG['login.login'] = login
            result = (
                host, port, database, self.entry_login.get_text())

        self.parent.present()
        self.dialog.destroy()
        if response != gtk.RESPONSE_OK:
            rpc.logout()
            raise TrytonError('QueryCanceled')
        return result
Esempio n. 7
0
    def run(self):
        profile_name = CONFIG['login.profile']
        can_use_profile = self.profiles.has_section(profile_name)
        if can_use_profile:
            for (configname, sectionname) in [
                    ('login.host', 'host'),
                    ('login.db', 'database'),
                    ]:
                if (self.profiles.get(profile_name, sectionname)
                        != CONFIG[configname]):
                    can_use_profile = False
                    break

        if can_use_profile:
            for idx, row in enumerate(self.profile_store):
                if row[0] == profile_name:
                    self.combo_profile.set_active(idx)
                    break
        else:
            self.combo_profile.set_active(-1)
            host = CONFIG['login.host'] if CONFIG['login.host'] else ''
            self.entry_host.set_text(host)
            db = CONFIG['login.db'] if CONFIG['login.db'] else ''
            self.entry_database.set_text(db)
            self.entry_login.set_text(CONFIG['login.login'])
            self.clear_profile_combo()
        self.dialog.show_all()

        self.entry_login.grab_focus()

        # Reshow dialog for gtk-quarks
        self.dialog.reshow_with_initial_size()
        self.expander.set_expanded(CONFIG['login.expanded'])
        # The previous action did not called expand_hostspec
        self.expand_hostspec(self.expander)

        response, result = None, ('', '', '', '')
        while not all(result):
            response = self.dialog.run()
            if response != gtk.RESPONSE_OK:
                break
            self.clear_profile_combo()
            active_profile = self.combo_profile.get_active()
            if active_profile != -1:
                profile = self.profile_store[active_profile][0]
            else:
                profile = ''
            host = self.entry_host.get_text()
            hostname = common.get_hostname(host)
            port = common.get_port(host)
            test = DBListEditor.test_server_version(hostname, port)
            if not test:
                if test is False:
                    common.warning('',
                        _(u'Incompatible version of the server'))
                else:
                    common.warning('',
                        _(u'Could not connect to the server'))
                continue
            database = self.entry_database.get_text()
            login = self.entry_login.get_text()
            CONFIG['login.profile'] = profile
            CONFIG['login.host'] = host
            CONFIG['login.db'] = database
            CONFIG['login.expanded'] = self.expander.props.expanded
            CONFIG['login.login'] = login
            result = (
                hostname, port, database, self.entry_login.get_text())

        if CONFIG['login.date']:
            date = self.entry_date.props.value
        else:
            date = None
        self.parent.present()
        self.dialog.destroy()
        if response != gtk.RESPONSE_OK:
            rpc.logout()
            raise TrytonError('QueryCanceled')
        return result + (date,)