Exemple #1
0
    def export_csv(self, fname, fields, data, paths, popup=True):
        encoding = self.csv_enc.get_active_text() or 'utf_8_sig'
        locale_format = self.csv_locale.get_active()

        try:
            writer = csv.writer(open(fname, 'w', encoding=encoding,
                                     newline=''),
                                quotechar=self.get_quotechar(),
                                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for row, path in zip_longest(data, paths or []):
                indent = len(path) - 1 if path else 0
                if row:
                    writer.writerow(
                        self.format_row(row,
                                        indent=indent,
                                        locale_format=locale_format))
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except (IOError, UnicodeEncodeError, csv.Error) as exception:
            common.warning(str(exception), _('Export failed'))
            return False
Exemple #2
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or 'UTF-8'

        try:
            writer = csv.writer(open(fname, 'w+', encoding=encoding),
                                quotechar=self.get_quotechar(),
                                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for line in data:
                row = []
                for val in line:
                    row.append(val)
                writer.writerow(row)
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except IOError as exception:
            common.warning(
                _("Operation failed.\nError message:\n%s") % exception,
                _('Error'))
            return False
Exemple #3
0
 def export_csv(self, fname, fields, result, write_title=False, popup=True):
     try:
         file_p = open(fname, 'wb+')
         writer = csv.writer(file_p)
         if write_title:
             writer.writerow(fields)
         for data in result:
             row = []
             for val in data:
                 if isinstance(type(val), types.StringType):
                     row.append(val.replace('\n', ' ').replace('\t', ' '))
                 else:
                     row.append(val)
             writer.writerow(row)
         file_p.close()
         if popup:
             if len(result) == 1:
                 common.message(_('%d record saved!') % len(result))
             else:
                 common.message(_('%d records saved!') % len(result))
         return True
     except IOError, exception:
         common.warning(
             _("Operation failed!\nError message:\n%s") %
             (exception.faultCode, ), _('Error'))
         return False
Exemple #4
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or 'UTF-8'

        try:
            writer = csv.writer(open(fname, 'wb+'),
                                quotechar=self.get_quotechar(),
                                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for line in data:
                row = []
                for val in line:
                    if isinstance(type(val), types.StringType):
                        val = val.replace('\n', ' ').replace('\t', ' ')
                        val = val.encode(encoding)
                    row.append(val)
                writer.writerow(row)
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except IOError, exception:
            common.warning(
                _("Operation failed.\nError message:\n%s") % exception,
                _('Error'))
            return False
Exemple #5
0
 def export_csv(self, fname, fields, result, write_title=False, popup=True):
     try:
         file_p = open(fname, 'wb+')
         writer = csv.writer(file_p)
         if write_title:
             writer.writerow(fields)
         for data in result:
             row = []
             for val in data:
                 if isinstance(type(val), types.StringType):
                     row.append(val.replace('\n', ' ').replace('\t', ' '))
                 else:
                     row.append(val)
             writer.writerow(row)
         file_p.close()
         if popup:
             if len(result) == 1:
                 common.message(_('%d record saved!') % len(result))
             else:
                 common.message(_('%d records saved!') % len(result))
         return True
     except IOError, exception:
         common.warning(_("Operation failed!\nError message:\n%s")
             % (exception.faultCode,), _('Error'))
         return False
Exemple #6
0
    def sig_autodetect(self, widget=None):
        fname = self.import_csv_file.get_filename()
        if not fname:
            common.message(_('You must select an import file first.'))
            return True

        encoding = self.get_encoding()
        self.csv_skip.set_value(1)
        try:
            data = csv.reader(open(fname, 'r', encoding=encoding, newline=''),
                              quotechar=self.get_quotechar(),
                              delimiter=self.get_delimiter())
        except (IOError, UnicodeDecodeError, csv.Error) as exception:
            common.warning(str(exception), _("Detection failed"))
            return True
        self.sig_unsel_all()
        word = ''
        for line in data:
            for word in line:
                if word not in self.fields_invert and word not in self.fields:
                    iter = self.model1.get_iter_first()
                    prefix = ''
                    for parent in word.split('/')[:-1]:
                        while iter:
                            if self.model1.get_value(iter, 0) == parent or \
                                    self.model1.get_value(iter, 1) == \
                                    (prefix + parent):
                                self.on_row_expanded(
                                    self.view1, iter,
                                    self.model1.get_path(iter))
                                iter = self.model1.iter_children(iter)
                                prefix = parent + '/'
                                break
                            else:
                                iter = self.model1.iter_next(iter)

                if word in self.fields_invert:
                    name = word
                    field = self.fields_invert[word]
                elif word in self.fields:
                    name = self.fields[word][0]
                    field = word
                else:
                    common.warning(
                        _('Error processing the file at field %s.') % word,
                        _('Error'))
                    return True
                num = self.model2.append()
                self.model2.set(num, 0, name, 1, field)
            break
        return True
Exemple #7
0
    def sig_autodetect(self, widget=None):
        fname = self.import_csv_file.get_filename()
        if not fname:
            common.message(_('You must select an import file first!'))
            return True
        csvsep = self.import_csv_sep.get_text() or None
        csvdel = self.import_csv_del.get_text() or None
        csvcode = self.import_csv_enc.get_active_text() or 'UTF-8'

        self.import_csv_skip.set_value(1)
        try:
            data = csv.reader(open(fname, 'rb'),
                              quotechar=csvdel,
                              delimiter=csvsep)
        except IOError:
            common.warning(_('Error opening CSV file'), _('Error'))
            return True
        self.sig_unsel_all()
        word = ''
        for line in data:
            for word in line:
                word = word.decode(csvcode)
                if word not in self.fields_invert and word not in self.fields:
                    iter = self.model1.get_iter_first()
                    prefix = ''
                    for parent in word.split('/')[:-1]:
                        while iter:
                            if self.model1.get_value(iter, 0) == parent or \
                                    self.model1.get_value(iter, 1) == \
                                    (prefix + parent):
                                self.on_row_expanded(
                                    self.view1, iter,
                                    self.model1.get_path(iter))
                                break
                            iter = self.model1.iter_next(iter)
                        prefix = parent + '/'
                if word in self.fields_invert:
                    name = word
                    field = self.fields_invert[word]
                elif word in self.fields:
                    name = self.fields[word][0]
                    field = word
                else:
                    common.warning(
                        _('Error processing the file at field %s.') % word,
                        _('Error'))
                    return True
                num = self.model2.append()
                self.model2.set(num, 0, name, 1, field)
            break
        return True
    def sig_autodetect(self, widget=None):
        fname = self.import_csv_file.get_filename()
        if not fname:
            common.message(_('You must select an import file first!'))
            return True
        csvsep = self.import_csv_sep.get_text()
        csvdel = self.import_csv_del.get_text()
        csvcode = self.import_csv_enc.get_active_text() \
                or 'UTF-8'

        self.import_csv_skip.set_value(1)
        try:
            data = csv.reader(open(fname, 'rb'), quotechar=csvdel,
                    delimiter=csvsep)
        except IOError:
            common.warning(_('Error opening CSV file'), _('Error'))
            return True
        self.sig_unsel_all()
        word = ''
        for line in data:
            for word in line:
                word = word.decode(csvcode)
                if word not in self.fields_invert and word not in self.fields:
                    iter = self.model1.get_iter_first()
                    prefix = ''
                    for parent in word.split('/')[:-1]:
                        while iter:
                            if self.model1.get_value(iter, 0) == parent or \
                                    self.model1.get_value(iter, 1) == \
                                    (prefix + parent):
                                self.on_row_expanded(self.view1, iter,
                                        self.model1.get_path(iter))
                                break
                            iter = self.model1.iter_next(iter)
                        prefix = parent + '/'
                if word in self.fields_invert:
                    name = word
                    field = self.fields_invert[word]
                elif word in self.fields:
                    name = self.fields[word][0]
                    field = word
                else:
                    common.warning(_('Error processing the file at field %s.')
                        % word, _('Error'))
                    return True
                num = self.model2.append()
                self.model2.set(num, 0, name, 1, field)
            break
        return True
Exemple #9
0
 def import_csv(self, fname, fields):
     # TODO: make it works with references
     skip = self.csv_skip.get_value_as_int()
     encoding = self.get_encoding()
     locale_format = self.csv_locale.get_active()
     try:
         reader = csv.reader(open(fname, 'r', encoding=encoding),
                             quotechar=self.get_quotechar(),
                             delimiter=self.get_delimiter())
         data = []
         for i, line in enumerate(reader):
             if i < skip or not line:
                 continue
             row = []
             for field, val in zip(fields, line):
                 if locale_format and val:
                     type_ = self.fields_data[field]['type']
                     if type_ in ['integer', 'biginteger']:
                         val = locale.atoi(val)
                     elif type_ == 'float':
                         val = locale.atof(val)
                     elif type_ == 'numeric':
                         val = Decimal(locale.delocalize(val))
                     elif type_ in ['date', 'datetime']:
                         val = date_parse(val, common.date_format())
                     elif type_ == 'binary':
                         val = base64.b64decode(val)
                 row.append(val)
             data.append(row)
     except (IOError, UnicodeDecodeError, csv.Error) as exception:
         common.warning(str(exception), _("Import failed"))
         return
     try:
         count = RPCExecute('model',
                            self.model,
                            'import_data',
                            fields,
                            data,
                            context=self.context)
     except RPCException:
         return
     if count == 1:
         common.message(_('%d record imported.') % count)
     else:
         common.message(_('%d records imported.') % count)
Exemple #10
0
def verify_document(data):
    """ Verify the digital signature of the document """

    gpg = gnupg.GPG()
    gpg.encoding = 'utf-8'

    document_model = data['model']
    """ Verify that the document handles digital signatures """

    try:
        record_vals = rpc.execute('model', document_model, 'read', data['ids'],
                                  ['document_digest', 'digital_signature'],
                                  rpc.CONTEXT)

    except:
        warning(
            _('Please enable the model for digital signature'),
            _('No Digest or Digital Signature fields found !'),
        )
        return

    # Verify signature
    digital_signature = record_vals[0]['digital_signature']

    # Check that the document has a digital signature associated to it

    if not digital_signature:
        warning(
            _('Unsigned document'),
            _('This document has not been signed yet'),
        )
        return

    # Signature verification
    try:
        verify_signature = gpg.verify(digital_signature)

    except:
        warning(
            _('Error when verifying Digital Signature'),
            _('Please check your GNU Privacy Guard Settings'),
        )

    else:
        # Show message of warning boxes depending on the verification
        if (verify_signature.valid):
            message(_("Valid Signature !\n\n" + verify_signature.stderr))
        else:
            warning(
                _(str(verify_signature.stderr)),
                _(str("Error !")),
            )
Exemple #11
0
 def button(self, button):
     'Execute button on the selected records'
     self.current_view.set_value()
     fields = self.current_view.get_fields()
     for record in self.selected_records:
         domain = record.expr_eval(button.get('states',
                                              {})).get('pre_validate', [])
         if not record.validate(fields, pre_validate=domain):
             warning(self.invalid_message(record), _('Pre-validation'))
             self.display(set_cursor=True)
             if domain:
                 # Reset valid state with normal domain
                 record.validate(fields)
             return
     if button.get('confirm', False) and not sur(button['confirm']):
         return
     if button.get('type', 'class') == 'class':
         if not self.current_record.save(force_reload=False):
             return
     if button.get('type', 'class') == 'class':
         self._button_class(button)
     else:
         self._button_instance(button)
Exemple #12
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or 'UTF-8'
        locale_format = self.csv_locale.get_active()

        try:
            writer = csv.writer(
                open(fname, 'w', encoding=encoding, newline=''),
                quotechar=self.get_quotechar(),
                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for row in data:
                writer.writerow(self.format_row(row, locale_format))
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except IOError as exception:
            common.warning(_("Operation failed.\nError message:\n%s")
                % exception, _('Error'))
            return False
Exemple #13
0
 def button(self, button):
     'Execute button on the selected records'
     self.current_view.set_value()
     fields = self.current_view.get_fields()
     for record in self.selected_records:
         domain = record.expr_eval(
             button.get('states', {})).get('pre_validate', [])
         if not record.validate(fields, pre_validate=domain):
             warning(self.invalid_message(record), _('Pre-validation'))
             self.display(set_cursor=True)
             if domain:
                 # Reset valid state with normal domain
                 record.validate(fields)
             return
     if button.get('confirm', False) and not sur(button['confirm']):
         return
     if button.get('type', 'class') == 'class':
         if not self.current_record.save(force_reload=False):
             return
     if button.get('type', 'class') == 'class':
         self._button_class(button)
     else:
         self._button_instance(button)
Exemple #14
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or 'UTF-8'
        locale_format = self.csv_locale.get_active()

        try:
            writer = csv.writer(open(fname, 'w', encoding=encoding,
                                     newline=''),
                                quotechar=self.get_quotechar(),
                                delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for line in data:
                row = []
                for val in line:
                    if locale_format:
                        if isinstance(val, Number):
                            val = locale.str(val)
                        elif isinstance(val, datetime.datetime):
                            val = val.strftime(common.date_format() + ' %X')
                        elif isinstance(val, datetime.date):
                            val = val.strftime(common.date_format())
                    elif isinstance(val, bool):
                        val = int(val)
                    row.append(val)
                writer.writerow(row)
            if popup:
                if len(data) == 1:
                    common.message(_('%d record saved.') % len(data))
                else:
                    common.message(_('%d records saved.') % len(data))
            return True
        except IOError as exception:
            common.warning(
                _("Operation failed.\nError message:\n%s") % exception,
                _('Error'))
            return False
Exemple #15
0
    def export_csv(self, fname, fields, data, popup=True):
        encoding = self.csv_enc.get_active_text() or "UTF-8"

        try:
            writer = csv.writer(open(fname, "wb+"), quotechar=self.get_quotechar(), delimiter=self.get_delimiter())
            if self.add_field_names.get_active():
                writer.writerow(fields)
            for line in data:
                row = []
                for val in line:
                    if isinstance(type(val), types.StringType):
                        val = val.replace("\n", " ").replace("\t", " ")
                        val = val.encode(encoding)
                    row.append(val)
                writer.writerow(row)
            if popup:
                if len(data) == 1:
                    common.message(_("%d record saved!") % len(data))
                else:
                    common.message(_("%d records saved!") % len(data))
            return True
        except IOError, exception:
            common.warning(_("Operation failed!\nError message:\n%s") % exception, _("Error"))
            return False
Exemple #16
0
    def run(self):
        parent = common.get_toplevel_window()
        self.dialog.set_default_response(gtk.RESPONSE_OK)
        self.dialog.set_transient_for(parent)
        self.dialog.show_all()

        pass_widget = self.entry_serverpasswd
        change_button = self.button_server_change
        admin_passwd = self.entry_adminpasswd
        admin_passwd2 = self.entry_adminpasswd2
        change_button.connect_after('clicked', self.server_change)

        if self.host and self.port:
            url = '%s:%d' % (self.host, self.port)
        else:
            url = ''
        self.entry_server_connection.set_text(url)

        liststore = gtk.ListStore(str, str)
        self.combo_language.set_model(liststore)
        try:
            common.refresh_langlist(self.combo_language, self.host, self.port)
        except TrytonServerError:
            self.button_create.set_sensitive(False)

        while True:
            self.dialog.props.sensitive = True
            res = self.dialog.run()
            dbname = self.entry_dbname.get_text()
            url = self.entry_server_connection.get_text()
            url_m = re.match('^([\w.\-]+):(\d{1,5})', url or '')
            langidx = self.combo_language.get_active_iter()
            langreal = langidx \
                and self.combo_language.get_model().get_value(langidx, 1)
            passwd = pass_widget.get_text()
            if res == gtk.RESPONSE_OK:
                if (not dbname or not re.match('^[a-zA-Z0-9_]+$', dbname)):
                    common.warning(
                        _('The database name is restricted to '
                          'alpha-nummerical characters '
                          'and "_" (underscore). '
                          'Avoid all accents, space '
                          'and any other special characters.'),
                        _('Wrong characters in database name!'))
                    continue
                elif admin_passwd.get_text() != admin_passwd2.get_text():
                    common.warning(
                        _("The new admin password "
                          "doesn't match the confirmation field.\n"),
                        _("Passwords doesn't match!"))
                    continue
                elif not admin_passwd.get_text():
                    common.warning(
                        _("Admin password and confirmation are "
                          "required to create a new database."),
                        _('Missing admin password!'))
                    continue
                elif url_m.group(1) \
                        and int(url_m.group(2)) \
                        and dbname \
                        and langreal \
                        and passwd \
                        and admin_passwd.get_text():
                    try:
                        exist = rpc.db_exec(url_m.group(1),
                                            int(url_m.group(2)), 'db_exist',
                                            dbname)
                    except TrytonServerError, exception:
                        common.process_exception(exception)
                        continue
                    if exist:
                        common.warning(
                            _("A database with the same name "
                              "already exists.\n"
                              "Try another database name."),
                            _("This database name already exist!"))
                        self.entry_dbname.set_text("")
                        self.entry_dbname.grab_focus()
                        continue
                    else:  # Everything runs fine, break the block here
                        host = url_m.group(1)
                        port = url_m.group(2)
                        self.dialog.props.sensitive = False
                        try:
                            rpcprogress = common.RPCProgress(
                                'db_exec',
                                (host, int(port), 'create', dbname, passwd,
                                 langreal, admin_passwd.get_text()))
                            rpcprogress.run(False)
                        except TrytonServerError, exception:
                            if str(exception.faultCode) == "AccessDenied":
                                common.warning(
                                    _("Sorry, wrong password for "
                                      "the Tryton server. "
                                      "Please try again."),
                                    _("Access denied!"))
                                self.entry_serverpasswd.set_text("")
                                self.entry_serverpasswd.grab_focus()
                                continue
                            else:  # Unclassified error
                                common.warning(
                                    _("Can't create the "
                                      "database, caused by an unknown reason.\n"
                                      "If there is a database created, it could "
                                      "be broken. Maybe drop this database! "
                                      "Please check the error message for "
                                      "possible informations.\n"
                                      "Error message:\n") +
                                    str(exception.faultCode),
                                    _("Error creating database!"))
                            parent.present()
                            self.dialog.destroy()
                            rpc.logout()
                            break
                        parent.present()
                        self.dialog.destroy()
                        if self.sig_login:
                            CONFIG['login.server'] = host
                            CONFIG['login.port'] = port
                            CONFIG['login.db'] = dbname
                            CONFIG['login.login'] = '******'
                            self.sig_login()
                        break
Exemple #17
0
def sign_document(data):
    """ Retrieve the hash value of the serialized document and
        generates a clearsign signature using the user's private key
        on the client side via GNU Privacy Guard - GPG -"""

    gpg = gnupg.GPG()

    gpg.encoding = 'utf-8'

    document_model = data['model']
    """ Don't allow signing more than one document at a time
        To avoid signing unwanted / unread documents
    """

    if (len(data['ids']) > 1):
        warning(
            _('For security reasons, Please sign one document at a time'),
            _('Multiple records selected !'),
        )
        return
    """ Verify that the document handles digital signatures """

    try:
        record_vals = rpc.execute('model', document_model, 'read', data['ids'],
                                  ['document_digest', 'digital_signature'],
                                  rpc.CONTEXT)

    except:
        warning(
            _('Please enable the model for digital signature'),
            _('No Digest or Digital Signature fields found !'),
        )
        return

    digest = record_vals[0]['document_digest']
    """ Check that the document hasn't been signed already """

    if record_vals[0]['digital_signature']:
        warning(
            _('Document already signed'),
            _('This record has been already signed'),
        )
        return

    # Check that the document has the digest before trying to
    # to sign it.
    if digest:

        try:
            gpg_signature = gpg.sign(digest, clearsign=True)

        except:
            warning(
                _('Error when signing the document'),
                _('Please check your encryption settings'),
            )

    else:
        warning(
            _('No Digest found for this document'),
            _('You need generate the digest'),
        )
        return
    """
    Set the clearsigned digest
    """
    try:
        RPCExecute('model', document_model, 'set_signature', data,
                   str(gpg_signature))

    except:
        warning(
            _('Error when saving the digital signature'),
            _('The signature was generated but NOT saved !'),
        )

    else:
        message(_('Document digitally signed'))
Exemple #18
0
def main(data):

    # Allow only one record

    if (len(data['ids']) == 0):
        warning(
            _('Please choose one record associated to this picture / video'),
            _('You need to select a record !'),
        )
        return

    if (len(data['ids']) > 1):
        warning(
            _('Please choose only one record for this picture / video'),
            _('Multiple records selectd !'),
        )
        return

    document_model = data['model']

    # Open the webcam device
    cap = cv2.VideoCapture(0)

    preview = False

    while (True):
        # Grab the frames
        try:
            rc, frame = cap.read()
        except:
            cleanup()

        # Display the resulting frame

        cv2.imshow('== GNU Health Camera ==', frame)

        keypressed = cv2.waitKey(1)

        if keypressed == ord(' '):
            cv2.imshow("Preview", frame)

            # Make a backup copy
            cv2.imwrite('/tmp/gnuhealth_snapshot_preview.png', frame)

            # call set media
            set_media(data, frame)
            preview = True

        if keypressed == ord('a'):
            cv2.imshow("Preview", frame)
            # Make a backup copy
            cv2.imwrite('/tmp/gnuhealth_snapshot_preview.png', frame)

            # call set media
            set_attachment(data, frame)
            break

        # Cleanup / Destroy window when q key is pressed or when closing
        # the window via alt+f4
        if (keypressed == ord('q')):
            break

        if (cv2.getWindowProperty('== GNU Health Camera ==',
                                  cv2.WND_PROP_VISIBLE) < 1):
            break

        if keypressed == ord('h'):
            get_help()

    cleanup(cap)

    # Reload the form
    a = Form(document_model, res_id=data['ids'][0])
    a.sig_reload(test_modified=False)
Exemple #19
0
#
##############################################################################

import tryton.rpc as rpc
from tryton.common import RPCExecute, warning, message
from tryton.gui.window.form import Form
import gettext
import numpy as np
from datetime import datetime
import base64
try:
    import cv2
except:
    warning(
        ('Install CV2 libraries for the Camera'
         '\nPlease install the CV2 libraries '),
        ('No CV2 library found !'),
    )

_ = gettext.gettext


def set_attachment(data, frame):
    #Store the frame in a container
    rc, container = cv2.imencode(".png", frame)
    container = container.tostring()
    document_model = data['model']
    ref = document_model + ',' + str(data['ids'][0])
    timestamp = str(datetime.now())
    attach_name = "GNU Health media " + timestamp
Exemple #20
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.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())
Exemple #21
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,)
Exemple #22
0
    def run(self):
        profile_name = CONFIG['login.profile']
        can_use_profile = self.profiles.has_section(profile_name)
        if can_use_profile:
            for (configname, option) in [
                ('login.host', 'host'),
                ('login.db', 'database'),
            ]:
                try:
                    value = self.profiles.get(profile_name, option)
                except configparser.NoOptionError:
                    value = None
                if value != 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()

        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.ResponseType.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('',
                                   _('Incompatible version of the server'),
                                   parent=self.dialog)
                else:
                    common.warning('',
                                   _('Could not connect to the server'),
                                   parent=self.dialog)
                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']:
            CONFIG['login.date'] = self.entry_date.props.value
        self.dialog.destroy()
        self._window.destroy()
        return response == Gtk.ResponseType.OK
    def run(self):
        parent = common.get_toplevel_window()
        self.dialog.set_default_response(gtk.RESPONSE_OK)
        self.dialog.set_transient_for(parent)
        self.dialog.show_all()

        pass_widget = self.entry_serverpasswd
        change_button = self.button_server_change
        admin_passwd = self.entry_adminpasswd
        admin_passwd2 = self.entry_adminpasswd2
        change_button.connect_after('clicked', self.server_change)

        if self.host and self.port:
            url = '%s:%d' % (self.host, self.port)
        else:
            url = ''
        self.entry_server_connection.set_text(url)

        liststore = gtk.ListStore(str, str)
        self.combo_language.set_model(liststore)
        try:
            common.refresh_langlist(self.combo_language, self.host, self.port)
        except TrytonServerError:
            self.button_create.set_sensitive(False)

        while True:
            res = self.dialog.run()
            dbname = self.entry_dbname.get_text()
            url = self.entry_server_connection.get_text()
            url_m = re.match('^([\w.\-]+):(\d{1,5})', \
                url or '')
            langidx = self.combo_language.get_active_iter()
            langreal = langidx \
                and self.combo_language.get_model().get_value(langidx, 1)
            passwd = pass_widget.get_text()
            if res == gtk.RESPONSE_OK:
                if (not dbname) \
                    or (not re.match('^[a-zA-Z0-9_]+$', dbname)):
                    common.warning(_('The database name is restricted to ' \
                        'alpha-nummerical characters and "_" (underscore). ' \
                        'Avoid all accents, space ' \
                        'and any other special characters.'),
                        _('Wrong characters in database name!'))
                    continue
                elif admin_passwd.get_text() != admin_passwd2.get_text():
                    common.warning(
                        _("The new admin password " \
                              "doesn't match the confirmation field.\n"),
                        _("Passwords doesn't match!"))
                    continue
                elif not admin_passwd.get_text():
                    common.warning(_("Admin password and confirmation are " \
                        "required to create a new database."), \
                        _('Missing admin password!'))
                    continue
                elif url_m.group(1) \
                        and int(url_m.group(2)) \
                        and dbname \
                        and langreal \
                        and passwd \
                        and admin_passwd.get_text():
                    try:
                        exist = rpc.db_exec(url_m.group(1),
                                int(url_m.group(2)), 'db_exist', dbname)
                    except TrytonServerError, exception:
                        common.process_exception(exception)
                        continue
                    if exist:
                        common.warning(_("A database with the same name "
                                "already exists.\n"
                                "Try another database name."),
                            _("This database name already exist!"))
                        self.entry_dbname.set_text("")
                        self.entry_dbname.grab_focus()
                        continue
                    else:  # Everything runs fine, break the block here
                        host = url_m.group(1)
                        port = url_m.group(2)
                        try:
                            rpcprogress = common.RPCProgress('db_exec',
                                    (host, int(port), 'create', dbname, passwd,
                                        langreal, admin_passwd.get_text()))
                            rpcprogress.run(False)
                        except TrytonServerError, exception:
                            if str(exception.faultCode) == "AccessDenied":
                                common.warning(_("Sorry, wrong password for " \
                                    "the Tryton server. Please try again."),
                                    _("Access denied!"))
                                self.entry_serverpasswd.set_text("")
                                self.entry_serverpasswd.grab_focus()
                                continue
                            else:  # Unclassified error
                                common.warning(_("Can't create the "
                                    "database, caused by an unknown reason.\n"
                                    "If there is a database created, it could "
                                    "be broken. Maybe drop this database! "
                                    "Please check the error message for "
                                    "possible informations.\n"
                                    "Error message:\n")
                                    + str(exception.faultCode),
                                    _("Error creating database!"))
                            parent.present()
                            self.dialog.destroy()
                            rpc.logout()
                            from tryton.gui.main import Main
                            Main.get_main().refresh_ssl()
                            break
                        from tryton.gui.main import Main
                        Main.get_main().refresh_ssl()
                        parent.present()
                        self.dialog.destroy()
                        if self.sig_login:
                            CONFIG['login.server'] = host
                            CONFIG['login.port'] = port
                            CONFIG['login.db'] = dbname
                            CONFIG['login.login'] = '******'
                            self.sig_login()
                        break
Exemple #24
0
    def run(self):
        parent = common.get_toplevel_window()
        self.dialog.set_default_response(gtk.RESPONSE_OK)
        self.dialog.set_transient_for(parent)
        self.dialog.show_all()

        pass_widget = self.entry_serverpasswd
        change_button = self.button_server_change
        admin_passwd = self.entry_adminpasswd
        admin_passwd2 = self.entry_adminpasswd2
        change_button.connect_after('clicked', self.server_change)

        if self.host and self.port:
            url = '%s:%d' % (self.host, self.port)
        else:
            url = ''
        self.entry_server_connection.set_text(url)

        liststore = gtk.ListStore(str, str)
        self.combo_language.set_model(liststore)
        try:
            common.refresh_langlist(self.combo_language, self.host, self.port)
        except TrytonServerError:
            self.button_create.set_sensitive(False)

        while True:
            self.dialog.props.sensitive = True
            res = self.dialog.run()
            dbname = self.entry_dbname.get_text()
            netloc = self.entry_server_connection.get_text()
            host = common.get_hostname(netloc)
            port = common.get_port(netloc)
            langidx = self.combo_language.get_active_iter()
            langreal = langidx \
                and self.combo_language.get_model().get_value(langidx, 1)
            passwd = pass_widget.get_text()
            if res == gtk.RESPONSE_OK:
                if admin_passwd.get_text() != admin_passwd2.get_text():
                    common.warning(
                        _("The new admin password "
                            "doesn't match the confirmation field.\n"),
                        _("Passwords doesn't match!"))
                    continue
                try:
                    exist = rpc.db_exec(host, port, 'db_exist', dbname)
                except TrytonServerError, exception:
                    common.process_exception(exception)
                    continue
                if exist:
                    common.warning(_("A database with the same name "
                            "already exists.\n"
                            "Try another database name."),
                        _("This database name already exist!"))
                    self.entry_dbname.set_text("")
                    self.entry_dbname.grab_focus()
                    continue
                else:  # Everything runs fine, break the block here
                    self.dialog.props.sensitive = False
                    try:
                        rpcprogress = common.RPCProgress('db_exec',
                            (host, port, 'create', dbname, passwd, langreal,
                                admin_passwd.get_text()))
                        rpcprogress.run(False)
                    except TrytonServerError, exception:
                        if str(exception.faultCode) == "AccessDenied":
                            common.warning(_("Sorry, wrong password for "
                                    "the Tryton server. "
                                    "Please try again."),
                                _("Access denied!"))
                            self.entry_serverpasswd.set_text("")
                            self.entry_serverpasswd.grab_focus()
                            continue
                        else:  # Unclassified error
                            common.warning(_("Can't create the "
                                "database, caused by an unknown reason.\n"
                                "If there is a database created, it could "
                                "be broken. Maybe drop this database! "
                                "Please check the error message for "
                                "possible informations.\n"
                                "Error message:\n")
                                + str(exception.faultCode),
                                _("Error creating database!"))
                        parent.present()
                        self.dialog.destroy()
                        rpc.logout()
                        break
                    parent.present()
                    self.dialog.destroy()
                    if self.sig_login:
                        CONFIG['login.server'] = host
                        CONFIG['login.port'] = str(port)
                        CONFIG['login.db'] = dbname
                        CONFIG['login.login'] = '******'
                        self.sig_login()
                    break
Exemple #25
0
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

import tryton.rpc as rpc
from tryton.common import RPCExecute, warning, message
from tryton.gui.window.form import Form
import gettext

try:
    import gnupg
except:
    warning(
        ('Document Encryption / Signing disabled'
         '\nPlease install the gnupg library '),
        ('No GNU Privacy Guard library found !'),
    )

_ = gettext.gettext


def sign_document(data):
    """ Retrieve the hash value of the serialized document and
        generates a clearsign signature using the user's private key
        on the client side via GNU Privacy Guard - GPG -"""

    gpg = gnupg.GPG()

    gpg.encoding = 'utf-8'
Exemple #26
0
    def run(self):
        parent = common.get_toplevel_window()
        self.dialog.set_default_response(gtk.RESPONSE_OK)
        self.dialog.set_transient_for(parent)
        self.dialog.show_all()

        pass_widget = self.entry_serverpasswd
        change_button = self.button_server_change
        admin_passwd = self.entry_adminpasswd
        admin_passwd2 = self.entry_adminpasswd2
        change_button.connect_after('clicked', self.server_change)

        if self.host and self.port:
            url = '%s:%d' % (self.host, self.port)
        else:
            url = ''
        self.entry_server_connection.set_text(url)

        liststore = gtk.ListStore(str, str)
        self.combo_language.set_model(liststore)
        try:
            common.refresh_langlist(self.combo_language, self.host, self.port)
        except TrytonServerError:
            self.button_create.set_sensitive(False)

        while True:
            self.dialog.props.sensitive = True
            res = self.dialog.run()
            dbname = self.entry_dbname.get_text()
            netloc = self.entry_server_connection.get_text()
            host = common.get_hostname(netloc)
            port = common.get_port(netloc)
            langidx = self.combo_language.get_active_iter()
            langreal = langidx \
                and self.combo_language.get_model().get_value(langidx, 1)
            passwd = pass_widget.get_text()
            if res == gtk.RESPONSE_OK:
                if admin_passwd.get_text() != admin_passwd2.get_text():
                    common.warning(
                        _("The new admin password "
                          "doesn't match the confirmation field.\n"),
                        _("Passwords doesn't match!"))
                    continue
                try:
                    exist = rpc.db_exec(host, port, 'db_exist', dbname)
                except TrytonServerError, exception:
                    common.process_exception(exception)
                    continue
                if exist:
                    common.warning(
                        _("A database with the same name "
                          "already exists.\n"
                          "Try another database name."),
                        _("This database name already exist!"))
                    self.entry_dbname.set_text("")
                    self.entry_dbname.grab_focus()
                    continue
                else:  # Everything runs fine, break the block here
                    self.dialog.props.sensitive = False
                    try:
                        rpcprogress = common.RPCProgress(
                            'db_exec',
                            (host, port, 'create', dbname, passwd, langreal,
                             admin_passwd.get_text()))
                        rpcprogress.run(False)
                    except TrytonServerError, exception:
                        if str(exception.faultCode) == "AccessDenied":
                            common.warning(
                                _("Sorry, wrong password for "
                                  "the Tryton server. "
                                  "Please try again."), _("Access denied!"))
                            self.entry_serverpasswd.set_text("")
                            self.entry_serverpasswd.grab_focus()
                            continue
                        else:  # Unclassified error
                            common.warning(
                                _("Can't create the "
                                  "database, caused by an unknown reason.\n"
                                  "If there is a database created, it could "
                                  "be broken. Maybe drop this database! "
                                  "Please check the error message for "
                                  "possible informations.\n"
                                  "Error message:\n") +
                                str(exception.faultCode),
                                _("Error creating database!"))
                        parent.present()
                        self.dialog.destroy()
                        rpc.logout()
                        break
                    parent.present()
                    self.dialog.destroy()
                    if self.sig_login:
                        CONFIG['login.server'] = host
                        CONFIG['login.port'] = str(port)
                        CONFIG['login.db'] = dbname
                        CONFIG['login.login'] = '******'
                        self.sig_login()
                    break
Exemple #27
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.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()

        if not self.entry_login.get_text():
            self.entry_login.grab_focus()
        else:
            self.entry_password.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)

        res, result = None, ('', '', '', '', '', '')
        while not all(result):
            res = self.dialog.run()
            if res != 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:
                if not common.test_server_version(host, port):
                    common.warning('',
                        _(u'Incompatible version of 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 = (self.entry_login.get_text(),
                self.entry_password.get_text(), host, port, database)