def _retrieve_token(self):
     """ Retrieves the token from Connect. """
     client = config.get('connect_client')
     secret = config.get('connect_secret')
     environment = config.get('connect_env', 'core')
     if not client or not secret:
         raise Warning(
             _('Missing configuration'),
             _('Please give connect_client and connect_secret values '
               'in your Odoo configuration file.'))
     api_client_secret = base64.b64encode("{0}:{1}".format(client, secret))
     params_post = 'grant_type=client_credentials&scope=read+write'
     header_post = {
         "Authorization": "Basic " + api_client_secret,
         "Content-type": "application/x-www-form-urlencoded",
         "Content-Length": 46,
         "Expect": "100-continue",
         "Connection": "Keep-Alive"
     }
     conn = httplib.HTTPSConnection('api2.compassion.com')
     auth_path = "/{}/connect/token".format(environment)
     conn.request("POST", auth_path, params_post, header_post)
     response = conn.getresponse()
     try:
         self._token = simplejson.loads(response.read())
         self._token_time = datetime.now()
         self._session.headers.update({
             'Authorization':
             '{token_type} {access_token}'.format(**self._token)
         })
     except (AttributeError, KeyError):
         raise Warning(_('Authentication Error'),
                       _('Token validation failed.'))
    def _push_pictures(self):
        """ Push the new picture into the NAS for GP. """

        # Retrieve configuration
        smb_user = config.get('smb_user')
        smb_pass = config.get('smb_pwd')
        smb_ip = config.get('smb_ip')
        smb_port = int(config.get('smb_port', 0))
        if not (smb_user and smb_pass and smb_ip and smb_port):
            raise Warning('Config Error',
                          'Missing Samba configuration in conf file.')
        child = self.child_id

        date_pic = self.date.replace('-', '')
        gp_pic_path = "{0}{1}/".format(config.get('gp_pictures'),
                                       child.unique_id[:2])
        file_name = "{0}_{1}.jpg".format(child.unique_id, date_pic)
        picture_file = TemporaryFile()
        picture_file.write(base64.b64decode(self.fullshot))
        picture_file.flush()
        picture_file.seek(0)

        # Upload file to shared folder
        smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
        if smb_conn.connect(smb_ip, smb_port):
            try:
                smb_conn.storeFile('GP', gp_pic_path + file_name, picture_file)
            except OperationFailure:
                # Directory may not exist
                smb_conn.createDirectory('GP', gp_pic_path)
                smb_conn.storeFile('GP', gp_pic_path + file_name, picture_file)
Example #3
0
def Lz_read_SQLCa(self):
    # type: (object) -> object
    Lz_read_SQLCa = MSSQL(config.get('lzread_host'),
                  config.get('lzread_user'),
                  config.get('lzread_pass'),
                  config.get('lzread_db'))
    return Lz_read_SQLCa
    def _cornerstone_fetch(self, project_code, api_mess):
        """ Construct the correct URL to call Compassion Cornerstone APIs.
        Returns the JSON object of the response."""
        url = config.get('compass_url')
        api_key = config.get('compass_api_key')
        if not url or not api_key:
            raise exceptions.Warning(
                'ConfigError',
                _('Missing compass_url or compass_api_key in conf file'))
        if url.endswith('/'):
            url = url[:-1]

        url += ('/ci/v1/' + api_mess + '/' + project_code + '?api_key=' +
                api_key)

        # Send the request and retrieve the result.
        r = self.https_get(url)
        json_result = None
        try:
            json_result = json.loads(r)
        except:
            raise exceptions.Warning(
                'Error calling webservice',
                'Error calling %s for project %s' % (api_mess, project_code))

        if 'error' in json_result:
                raise exceptions.Warning(
                    _('Error fetching data for project %s') % (project_code),
                    json_result['error'].get(
                        'message',
                        _('An unexpected answer was returned by GMC')))

        return json_result
    def _transfer_file_on_nas(self, file_name):
        """
        Puts the letter file on the NAS folder for the translation platform.
        :return: None
        """
        self.ensure_one()
        # Retrieve configuration
        smb_user = config.get('smb_user')
        smb_pass = config.get('smb_pwd')
        smb_ip = config.get('smb_ip')
        smb_port = int(config.get('smb_port', 0))
        if not (smb_user and smb_pass and smb_ip and smb_port):
            raise Exception('No config SMB in file .conf')

        # Copy file in the imported letter folder
        smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
        if smb_conn.connect(smb_ip, smb_port):
            file_ = BytesIO(base64.b64decode(
                self.letter_image.with_context(
                    bin_size=False).datas))
            nas_share_name = self.env.ref(
                'sbc_translation.nas_share_name').value

            nas_letters_store_path = self.env.ref(
                'sbc_translation.nas_letters_store_path').value + file_name
            smb_conn.storeFile(nas_share_name,
                               nas_letters_store_path, file_)

            logger.info('File {} store on NAS with success'
                        .format(self.letter_image.name))
        else:
            raise Warning(_('Connection to NAS failed'))
 def test_config_set(self):
     """Test that the config is properly set on the server
     """
     url = config.get('compass_url')
     api_key = config.get('compass_api_key')
     self.assertTrue(url)
     self.assertTrue(api_key)
Example #7
0
def migrate(cr, version):
    if not version:
        return

    ## info di db
    dbname = cr.dbname
    dbUser = config.get("db_user")
    dbPw = config.get("db_password")
    dbPort = config.get("db_port")
    dbHost = config.get("db_host")
    functionName = "triggers"

    _logger.info(
        "____username: %s_____password: %s____porta: %s______host: %s____",
        dbUser, dbPw, str(dbPort), str(dbHost))

    ## info di filesystem
    relativePath = os.path.dirname(os.path.realpath(__file__))
    if (not os.path.isfile(relativePath + "/../../data/" + functionName +
                           ".sql")):
        raise Exception('create function script ' + functionName +
                        '.sql does not exist in data folder of this module')

    subprocess.call([
        "psql", "postgresql://" + dbUser + ":" + dbPw + "@" + str(dbHost) +
        ":" + str(dbPort) + "/" + dbname, "-f",
        relativePath + "/../../data/" + functionName + ".sql"
    ])
Example #8
0
    def _cornerstone_fetch(self, project_code, api_mess):
        """ Construct the correct URL to call Compassion Cornerstone APIs.
        Returns the JSON object of the response."""
        url = config.get('compass_url')
        api_key = config.get('compass_api_key')
        if not url or not api_key:
            raise exceptions.Warning(
                'ConfigError',
                _('Missing compass_url or compass_api_key in conf file'))
        if url.endswith('/'):
            url = url[:-1]

        url += ('/ci/v1/' + api_mess + '/' + project_code + '?api_key=' +
                api_key)

        # Send the request and retrieve the result.
        r = self.https_get(url)
        json_result = None
        try:
            json_result = json.loads(r)
        except:
            raise exceptions.Warning(
                'Error calling webservice',
                'Error calling %s for project %s' % (api_mess, project_code))
        return json_result
Example #9
0
 def _add_magic_fields(cls):
     sup_export_nbr = config.get('supplier_export_nbr', 3) + 1
     sup_qty_export_nbr = config.get('supplier_qty_export_nbr', 3) + 1
     for idx in range(1, sup_export_nbr):
         field_partner_id = fields.Many2one('res.partner',
                                            compute='_compute_supplier',
                                            inverse='_set_supplier')
         field_code = fields.Char(compute='_compute_supplier',
                                  inverse='_set_supplier')
         field_name = fields.Char(compute='_compute_supplier',
                                  inverse='_set_supplier')
         cls._add_field('supplier_%s_product_code' % idx, field_code)
         cls._add_field('supplier_%s_product_name' % idx, field_name)
         cls._add_field('supplier_%s_name' % idx, field_partner_id)
         for qty_idx in range(1, sup_qty_export_nbr):
             field_price = FloatNullEmpty(
                 digits_compute=dp.get_precision('Product Price'),
                 compute='_compute_supplier',
                 inverse='_set_supplier')
             field_qty = FloatNullEmpty(compute='_compute_supplier',
                                        inverse='_set_supplier')
             cls._add_field('supplier_%s_qty_%s' % (idx, qty_idx),
                            field_qty)
             cls._add_field('supplier_%s_price_%s' % (idx, qty_idx),
                            field_price)
     return super(DenormalizedProductSupplier, cls)._add_magic_fields()
 def _retrieve_token(self):
     """ Retrieves the token from Connect. """
     client = config.get('connect_client')
     secret = config.get('connect_secret')
     if not client or not secret:
         raise Warning(
             _('Missing configuration'),
             _('Please give connect_client and connect_secret values '
               'in your Odoo configuration file.'))
     api_client_secret = base64.b64encode("{0}:{1}".format(client, secret))
     params_post = 'grant_type=client_credentials&scope=read+write'
     header_post = {
         "Authorization": "Basic " + api_client_secret,
         "Content-type": "application/x-www-form-urlencoded",
         "Content-Length": 46,
         "Expect": "100-continue",
         "Connection": "Keep-Alive"}
     conn = httplib.HTTPSConnection('api2.compassion.com')
     conn.request("POST", "/pcore/connect/token", params_post, header_post)
     response = conn.getresponse()
     try:
         self._token = simplejson.loads(response.read())
         self._session.headers.update({
             'Authorization': '{token_type} {access_token}'.format(
                 **self._token)})
     except (AttributeError, KeyError):
         raise Warning(
             _('Authentication Error'),
             _('Token validation failed.'))
Example #11
0
    def get_local_alias(self, cr, uid, alias_domain, context=None):
        port = system_base_config.get('xmlrpc_port', False)
        xmlrpc = system_base_config.get('xmlrpc', False)
        mailgate_file = os.path.dirname(
            mail.__file__) + '/static/scripts/openerp_mailgate.py'
        admin_user = self.pool['res.users'].browse(cr,
                                                   uid,
                                                   SUPERUSER_ID,
                                                   context=context)

        if not xmlrpc or not port:
            port = system_base_config.get('xmlrpcs_port', False)
            xmlrpcs = system_base_config.get('xmlrpcs', False)
            if not xmlrpcs or not port:
                print 'errror!!! falta el puerto'
        local_alias = (alias_domain or '')
        local_alias += ': "| '
        # local_alias = cr.dbname + ': "| '
        local_alias += mailgate_file
        local_alias += " --host=localhost"
        local_alias += " --port=" + str(port)
        local_alias += " -u " + str(SUPERUSER_ID)
        local_alias += " -p " + admin_user.password
        local_alias += " -d " + cr.dbname + '"'
        return local_alias
Example #12
0
    def _transfer_file_on_nas(self, file_name):
        """
        Puts the letter file on the NAS folder for the translation platform.
        :return: None
        """
        self.ensure_one()
        # Retrieve configuration
        smb_user = config.get('smb_user')
        smb_pass = config.get('smb_pwd')
        smb_ip = config.get('smb_ip')
        smb_port = int(config.get('smb_port', 0))
        if not (smb_user and smb_pass and smb_ip and smb_port):
            raise Exception('No config SMB in file .conf')

        # Copy file in the imported letter folder
        smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
        if smb_conn.connect(smb_ip, smb_port):
            file_ = BytesIO(
                base64.b64decode(
                    self.letter_image.with_context(bin_size=False).datas))
            nas_share_name = self.env.ref(
                'sbc_translation.nas_share_name').value

            nas_letters_store_path = self.env.ref(
                'sbc_translation.nas_letters_store_path').value + file_name
            smb_conn.storeFile(nas_share_name, nas_letters_store_path, file_)

            logger.info('File {} store on NAS with success'.format(
                self.letter_image.name))
        else:
            raise Warning(_('Connection to NAS failed'))
Example #13
0
    def send_sendgrid(self):
        """ Use sendgrid transactional e-mails : e-mails are sent one by
        one. """
        api_key = config.get('sendgrid_api_key')
        if not api_key:
            raise exceptions.Warning(
                'ConfigError',
                _('Missing sendgrid_api_key in conf file'))

        message = sendgrid.Mail()
        message.set_from(self.email_from)
        message.set_subject(self.subject or ' ')
        html = self.body_html or ' '
        message.set_html(html)

        # Update message body in associated message, which will be shown in
        # message history view for linked odoo object defined through fields
        # model and res_id
        self.mail_message_id.body = html

        p = re.compile(r'<.*?>')  # Remove HTML markers
        text_only = self.body_text or p.sub('', html.replace('<br/>', '\n'))
        message.set_text(text_only)

        test_address = config.get('sendgrid_test_address')
        if not test_address:
            message.add_to(self.email_to)
            for recipient in self.recipient_ids:
                message.add_to(recipient.email)
            if self.email_cc:
                message.add_cc(self.email_cc)
        else:
            _logger.info('Sending email to test address {}'.format(
                         test_address))
            message.add_to(test_address)

        if self.sendgrid_template_id:
            message.add_filter('templates', 'enable', '1')
            message.add_filter('templates', 'template_id',
                               self.sendgrid_template_id.remote_id)

        for substitution in self.substitution_ids:
            message.add_substitution(substitution.key, substitution.value)

        for attachment in self.attachment_ids:
            message.add_attachment_stream(attachment.name,
                                          base64.b64decode(attachment.datas))

        sg = sendgrid.SendGridClient(api_key)
        status, msg = sg.send(message)

        if status == STATUS_OK:
            _logger.info("Email sent!")
            self.write({
                'sent_date': fields.Datetime.now(),
                'state': 'sent'
            })
        else:
            _logger.error("Failed to send email: {}".format(message))
def migrate(cr, v):
    with api.Environment.manage():
        uid = SUPERUSER_ID
        env = api.Environment(cr, uid, {})
        env['printing.server'].create({
            'name': config.get('cups_host', 'localhost'),
            'address': config.get('cups_host', 'localhost'),
            'port': config.get('cups_port', 631),
        })
Example #15
0
 def __init__(self):
     Thread.__init__(self)
     self.queue = Queue()
     self.lock = Lock()
     self.status = {'status': 'connecting', 'messages': []}
     self.device_name = config.get('telium_terminal_device_name',
                                   '/dev/ttyACM0')
     self.device_rate = int(config.get('telium_terminal_device_rate', 9600))
     self.serial = False
Example #16
0
    def add_child_photos(self, head_image, full_image):
        host = config.get('typo3_host')
        username = config.get('typo3_user')
        pwd = config.get('typo3_pwd')
        path = config.get('typo3_images_path')

        with pysftp.Connection(host, username=username, password=pwd) as sftp:
            with sftp.cd(path):
                sftp.put(head_image)
                sftp.put(full_image)
 def test_config_set(self):
     """Test that the config is properly set on the server
     """
     host = config.get('mysql_host')
     user = config.get('mysql_user')
     pw = config.get('mysql_pw')
     db = config.get('mysql_db')
     self.assertTrue(host)
     self.assertTrue(user)
     self.assertTrue(pw)
     self.assertTrue(db)
     self.assertTrue(self.gp_connect.is_alive())
 def __init__(self):
     """Establishes the connection to the MySQL server used by GP."""
     mysql_host = config.get('mysql_host')
     mysql_user = config.get('mysql_user')
     mysql_pw = config.get('mysql_pw')
     mysql_db = config.get('mysql_db')
     self._con = False
     try:
         self._con = mdb.connect(mysql_host, mysql_user, mysql_pw, mysql_db)
         self._cur = self._con.cursor(mdb.cursors.DictCursor)
     except mdb.Error, e:
         logger.debug("Error %d: %s" % (e.args[0], e.args[1]))
Example #19
0
File: main.py Project: x620/pos
 def __init__(self):
     Thread.__init__(self)
     self.queue = Queue()
     self.lock = Lock()
     self.status = {'status': 'connecting', 'messages': []}
     self.device_name = config.get('customer_display_device_name',
                                   '/dev/ttyUSB0')
     self.device_rate = int(config.get('customer_display_device_rate',
                                       9600))
     self.device_timeout = int(
         config.get('customer_display_device_timeout', 2))
     self.serial = False
 def _get_url(self, api_mess, api_value):
     url = config.get('compass_url')
     api_key = config.get('compass_api_key')
     if not url or not api_key:
         raise orm.except_orm('ConfigError',
                              _('Missing compass_url or compass_api_key '
                                'in conf file'))
     if url.endswith('/'):
         url = url[:-1]
     url += ('/ci/v1/countries/' + api_mess + '/' + api_value +
             '?api_key=' + api_key)
     return url
 def _get_url(self, api_mess, api_value):
     url = config.get('compass_url')
     api_key = config.get('compass_api_key')
     if not url or not api_key:
         raise orm.except_orm('ConfigError',
                              _('Missing compass_url or compass_api_key '
                                'in conf file'))
     if url.endswith('/'):
         url = url[:-1]
     url += ('/ci/v1/countries/' + api_mess + '/' + api_value +
             '?api_key=' + api_key)
     return url
    def add_child_photos(self, head_image, full_image):
        host = config.get('typo3_host')
        username = config.get('typo3_user')
        pwd = config.get('typo3_pwd')
        path = config.get('typo3_images_path')

        with pysftp.Connection(
            host, username=username,
                password=pwd) as sftp:
                    with sftp.cd(path):
                        sftp.put(head_image)
                        sftp.put(full_image)
 def get_url(self, child_code, api_mess):
     url = config.get('compass_url')
     api_key = config.get('compass_api_key')
     if not url or not api_key:
         raise exceptions.Warning(
             'ConfigError',
             _('Missing compass_url or compass_api_key in conf file'))
     if url.endswith('/'):
         url = url[:-1]
     url += ('/ci/v1/children/' + child_code + '/' + api_mess +
             '?api_key=' + api_key)
     return url
Example #24
0
 def __init__(self):
     Thread.__init__(self)
     self.queue = Queue()
     self.lock = Lock()
     self.status = {'status': 'connecting', 'messages': []}
     self.device_name = config.get(
         'customer_display_device_name', 'COM2')
     self.device_rate = int(config.get(
         'customer_display_device_rate', 9600))
     self.device_timeout = int(config.get(
         'customer_display_device_timeout', 2))
     self.serial = False
 def test_config_set(self):
     """Test that the config is properly set on the server
     """
     host = config.get('mysql_host')
     user = config.get('mysql_user')
     pw = config.get('mysql_pw')
     db = config.get('mysql_db')
     self.assertTrue(host)
     self.assertTrue(user)
     self.assertTrue(pw)
     self.assertTrue(db)
     self.assertTrue(self.gp_connect.is_alive())
 def get_url(self, child_code, api_mess):
     url = config.get('compass_url')
     api_key = config.get('compass_api_key')
     if not url or not api_key:
         raise orm.except_orm(
             'ConfigError',
             _('Missing compass_url or compass_api_key '
               'in conf file'))
     if url.endswith('/'):
         url = url[:-1]
     url += ('/ci/v1/children/' + child_code + '/' + api_mess +
             '?api_key=' + api_key)
     return url
 def __init__(self):
     """Establishes the connection to the MySQL server used by GP."""
     mysql_host = config.get('mysql_host')
     mysql_user = config.get('mysql_user')
     mysql_pw = config.get('mysql_pw')
     mysql_db = config.get('mysql_db')
     self._con = False
     try:
         self._con = mdb.connect(mysql_host, mysql_user, mysql_pw,
                                 mysql_db)
         self._cur = self._con.cursor(mdb.cursors.DictCursor)
     except mdb.Error, e:
         logger.debug("Error %d: %s" % (e.args[0], e.args[1]))
 def __init__(self, mysql_host='mysql_host', mysql_user='******',
              mysql_pw='mysql_pw', mysql_db='mysql_db'):
     """Establishes the connection to the MySQL server used."""
     mh = config.get(mysql_host)
     mu = config.get(mysql_user)
     mp = config.get(mysql_pw)
     md = config.get(mysql_db)
     self._con = False
     try:
         self._con = mdb.connect(mh, mu, mp,
                                 md, charset='utf8')
         self._cur = self._con.cursor(mdb.cursors.DictCursor)
     except mdb.Error, e:
         logger.debug("Error %d: %s" % (e.args[0], e.args[1]))
 def __init__(self, cr, uid):
     """ Establishes the connection to the MySQL server used by GP.
         Args:
             - cr : a database cursor to the Postgres database of OpenERP.
             - uid : OpenERP user id. """
     mysql_host = config.get('mysql_host')
     mysql_user = config.get('mysql_user')
     mysql_pw = config.get('mysql_pw')
     mysql_db = config.get('mysql_db')
     self._con = False
     try:
         self._con = mdb.connect(mysql_host, mysql_user, mysql_pw, mysql_db)
         self._cur = self._con.cursor(mdb.cursors.DictCursor)
     except mdb.Error, e:
         logging.debug("Error %d: %s" % (e.args[0], e.args[1]))
Example #30
0
    def __init__(self):
        Thread.__init__(self)
        self.setDaemon(True)
        self.queue = Queue()
        self.lock = Lock()
        self.seep5muntes = False;
        self.remaining = 0;

        self.status = {'status': 'connecting', 'messages': []}
        self.device_name = config.get(
            'customer_display_device_name', '0x200')
        self.device_charset = config.get(
            'customer_display_device_charset', '0x35')
        self.holdDevice = Display(0x200)
        self.holdDevice.set_charset(0x35)
 def __init__(self, cr, uid):
     """ Establishes the connection to the MySQL server used by GP.
         Args:
             - cr : a database cursor to the Postgres database of OpenERP.
             - uid : OpenERP user id. """
     mysql_host = config.get('mysql_host')
     mysql_user = config.get('mysql_user')
     mysql_pw = config.get('mysql_pw')
     mysql_db = config.get('mysql_db')
     self._con = False
     try:
         self._con = mdb.connect(mysql_host, mysql_user, mysql_pw,
                                 mysql_db)
         self._cur = self._con.cursor(mdb.cursors.DictCursor)
     except mdb.Error, e:
         logging.debug("Error %d: %s" % (e.args[0], e.args[1]))
Example #32
0
 def _compute_has_valid_language(self):
     """ Detect if text is written in the language corresponding to the
     language_id """
     self.has_valid_language = False
     if self.translated_text is not None and \
             self.translation_language_id is not None:
         s = self.translated_text.strip(' \t\n\r.')
         if s:
             # find the language name of text argument
             detectlanguage.configuration.api_key = config.get(
                 'detect_language_api_key')
             languageName = ""
             langs = detectlanguage.languages()
             try:
                 codeLang = detectlanguage.simple_detect(
                     self.translated_text)
             except IndexError:
                 # Language could not be detected
                 return
             for lang in langs:
                 if lang.get("code") == codeLang:
                     languageName = lang.get("name").lower()
                     break
             supporter_langs = map(
                 lambda lang: lang.lower(),
                 self.supporter_languages_ids.mapped('name'))
             self.has_valid_language = languageName in supporter_langs
 def _compute_has_valid_language(self):
     """ Detect if text is writed in the language corresponding to the
     language_id """
     self.has_valid_language = False
     if self.translated_text is not None and \
             self.translation_language_id is not None:
         s = self.translated_text.strip(' \t\n\r.')
         if s:
             # find the language name of text argument
             detectlanguage.configuration.api_key = config.get(
                 'detect_language_api_key')
             languageName = ""
             langs = detectlanguage.languages()
             try:
                 codeLang = detectlanguage.simple_detect(
                     self.translated_text)
             except IndexError:
                 # Language could not be detected
                 return
             for lang in langs:
                 if lang.get("code") == codeLang:
                     languageName = lang.get("name").lower()
                     break
             supporter_langs = map(
                 lambda lang: lang.lower(),
                 self.supporter_languages_ids.mapped('name'))
             self.has_valid_language = languageName in supporter_langs
    def _perform_outgoing_action(self, cr, uid, message, context=None):
        """ Process an outgoing message by sending it to the middleware.
            Returns : unique id of generated request, or False.
        """
        action = message.action_id
        object_id = message.object_id
        if context is None:
            context = dict()
        if self._validate_outgoing_action(cr, uid, message, context):
            if context.get('test_mode'):
                # Don't send the request when testing.
                return 'test-uid' + str(randint(0, 999))
            server_url = config.get('middleware_url')
            if not server_url:
                raise orm.except_orm(
                    'ConfigError',
                    _('No middleware server url specified in '
                      'conf file'))
            url = server_url + action.type + '/' + \
                action.model + '/' + str(object_id)
            r = requests.get(url)
            if not r.status_code == 200:
                logger.error('Failing url: ' + url)
                raise orm.except_orm(
                    _('NetworkError'),
                    _('An error occured while sending message.'))
            json_data = r.json()
            logger.debug(r.text)
            success = json_data.get('success')
            if success == 'yes':
                return json_data.get('uuid')

        return False
    def _perform_outgoing_action(self, cr, uid, message, context=None):
        """ Process an outgoing message by sending it to the middleware.
            Returns : unique id of generated request, or False.
        """
        action = message.action_id
        object_id = message.object_id
        if context is None:
            context = dict()
        if self._validate_outgoing_action(cr, uid, message, context):
            if context.get('test_mode'):
                # Don't send the request when testing.
                return 'test-uid' + str(randint(0, 999))
            server_url = config.get('middleware_url')
            if not server_url:
                raise orm.except_orm(
                    'ConfigError', _('No middleware server url specified in '
                                     'conf file'))
            url = server_url + action.type + '/' + \
                action.model + '/' + str(object_id)
            r = requests.get(url)
            if not r.status_code == 200:
                logger.error('Failing url: ' + url)
                raise orm.except_orm(
                    _('NetworkError'),
                    _('An error occured while sending message.'))
            json_data = r.json()
            logger.debug(r.text)
            success = json_data.get('success')
            if success == 'yes':
                return json_data.get('uuid')

        return False
    def update(self):
        api_key = config.get('sendgrid_api_key')
        if not api_key:
            raise exceptions.Warning(
                'ConfigError', _('Missing sendgrid_api_key in conf file'))

        client = sendgrid.SendGridAPIClient(api_key)
        template_client = sendgrid_templates.Templates(client)
        status, msg = template_client.get()
        result = json.loads(msg)

        # TODO: handle error if dict does not have expected structure?
        for template in result["templates"]:
            id = template["id"]
            status, msg = template_client.get(id)
            template_versions = json.loads(msg)['versions']
            template_vals = template_versions[0]
            for version in template_versions:
                if version['active']:
                    template_vals = version
            vals = {
                "remote_id": id,
                "name": template["name"],
                "html_content": template_vals["html_content"],
                "plain_content": template_vals["plain_content"],
            }
            record = self.search([('remote_id', '=', id)])
            if record:
                record.write(vals)
            else:
                self.create(vals)
Example #37
0
 def __init__(self,
              mysql_host='mysql_host',
              mysql_user='******',
              mysql_pw='mysql_pw',
              mysql_db='mysql_db'):
     """Establishes the connection to the MySQL server used."""
     mh = config.get(mysql_host)
     mu = config.get(mysql_user)
     mp = config.get(mysql_pw)
     md = config.get(mysql_db)
     self._con = False
     try:
         self._con = mdb.connect(mh, mu, mp, md, charset='utf8')
         self._cur = self._con.cursor(mdb.cursors.DictCursor)
     except mdb.Error, e:
         logger.debug("Error %d: %s" % (e.args[0], e.args[1]))
Example #38
0
 def _set_supplier(self):
     for record in self:
         suppliers = self.env['product.supplierinfo'].browse(False)
         for idx in range(1, config.get('supplier_export_nbr', 3) + 1):
             if not record['supplier_%s_name' % idx]:
                 continue
             suppliers |= record._update_create_supplier({
                 'sequence':
                 self._get_sequence(idx),
                 'name':
                 record['supplier_%s_name' % idx],
                 'product_name':
                 record['supplier_%s_product_name' % idx],
                 'product_code':
                 record['supplier_%s_product_code' % idx],
                 'qty_1':
                 record['supplier_%s_qty_1' % idx],
                 'price_1':
                 record['supplier_%s_price_1' % idx],
                 'qty_2':
                 record['supplier_%s_qty_2' % idx],
                 'price_2':
                 record['supplier_%s_price_2' % idx],
                 'qty_3':
                 record['supplier_%s_qty_3' % idx],
                 'price_3':
                 record['supplier_%s_price_3' % idx],
             })
         for supplier in record._get_specific_supplier():
             if supplier not in suppliers:
                 supplier.unlink()
Example #39
0
    def _perform_outgoing_action(self,
                                 cr,
                                 uid,
                                 action,
                                 object_id,
                                 context=None):
        """ Process an outgoing message by sending it to the middleware. """
        if self._validate_outgoing_action(cr,
                                          uid,
                                          action,
                                          object_id,
                                          context=context):
            session = requests.Session()
            session.verify = False
            server_url = config.get('middleware_url')
            if not server_url:
                raise orm.except_orm(
                    'ConfigError',
                    _('No middleware server url specified in '
                      'conf file'))
            url = server_url + action.type + '/' + \
                action.model + '/' + str(object_id)
            resp = session.get(url)
            content = resp.content

            # TODO : Parse response content to see if the operation succeeded
            logger.info("middleware response : " + content)

            return True

        else:
            return False
    def update(self):
        api_key = config.get('sendgrid_api_key')
        if not api_key:
            raise exceptions.Warning(
                'ConfigError',
                _('Missing sendgrid_api_key in conf file'))

        sg = sendgrid.SendGridAPIClient(apikey=api_key)
        template_client = sg.client.templates
        msg = template_client.get().body
        result = json.loads(msg)

        for template in result.get("templates", list()):
            id = template["id"]
            msg = template_client._(id).get().body
            template_versions = json.loads(msg)['versions']
            for version in template_versions:
                if version['active']:
                    template_vals = version
                    break
            else:
                continue

            vals = {
                "remote_id": id,
                "name": template["name"],
                "html_content": template_vals["html_content"],
                "plain_content": template_vals["plain_content"],
            }
            record = self.search([('remote_id', '=', id)])
            if record:
                record.write(vals)
            else:
                self.create(vals)
        return True
Example #41
0
 def _denormalized_update(self, vals):
     """ update the porudtc.supplierinof and the pricelist.partnerinfo
     if the data have change, if not change have been done skip the write"""
     self.ensure_one()
     pricelist_obj = self.env['pricelist.partnerinfo']
     sup_vals = {}
     for key in ['product_name', 'product_code', 'sequence']:
         if vals[key] != self[key]:
             sup_vals[key] = vals[key]
     if sup_vals:
         self.write(sup_vals)
     pricelists = pricelist_obj.browse(False)
     for idx in range(0, config.get('supplier_qty_export_nbr', 3)):
         qty = vals['qty_%s' % (idx + 1)]
         price = vals['price_%s' % (idx + 1)]
         pvals = {'min_quantity': qty, 'price': price}
         if len(self.pricelist_ids) > idx:
             p = self.pricelist_ids[idx]
             if not price and not qty:
                 continue
             elif p.price != price or p.min_quantity != qty:
                 p.write(pvals)
             pricelists |= p
         elif price and qty:
             pvals['suppinfo_id'] = self.id
             pricelists |= pricelist_obj.create(pvals)
     for p in self.pricelist_ids:
         if p not in pricelists:
             p.unlink()
Example #42
0
    def _perform_outgoing_action(self):
        """ Process an outgoing message by sending it to the middleware.
            Returns : unique id of generated request, or False.
        """
        action = self.action_id
        object_id = self.object_id

        if self._validate_outgoing_action():
            if self.env.context.get("test_mode"):
                # Don't send the request when testing.
                return "test-uid" + str(randint(0, 999))
            server_url = config.get("middleware_url")
            if not server_url:
                raise Warning("ConfigError", _("No middleware server url specified in conf file"))
            url = server_url + action.type + "/" + action.model + "/" + str(object_id)
            r = requests.get(url)
            if not r.status_code == 200:
                logger.error("Failing url: " + url)
                raise Warning(_("NetworkError"), _("An error occured while sending message."))
            json_data = r.json()
            logger.debug(r.text)
            success = json_data.get("success")
            if success == "yes":
                return json_data.get("uuid")

        return False
Example #43
0
 def _prepare_keychain(self):
     env = config.get('running_env')
     return {
         'name': "%s %s" % (self.name, env),
         'technical_name': self._get_technical_name(),
         'namespace': self._backend_name,
         'environment': env,
     }
Example #44
0
 def _compute_l10n_fr_prevent_print(self):
     file_value = config.get('l10n_fr_certification_mode', 'legacy')
     for pos_config in self:
         if file_value == 'legacy':
             pos_config.l10n_fr_prevent_print =\
                 pos_config.l10n_fr_prevent_print_legacy
         else:
             pos_config.l10n_fr_prevent_print = file_value
 def __new__(cls):
     """ Inherit method to ensure a single instance exists. """
     if OnrampConnector.__instance is None:
         OnrampConnector.__instance = object.__new__(cls)
         connect_url = config.get('connect_url')
         api_key = config.get('connect_api_key')
         if connect_url and api_key:
             OnrampConnector.__instance._connect_url = connect_url
             OnrampConnector.__instance._api_key = api_key
             session = requests.Session()
             session.params.update({'api_key': api_key})
             OnrampConnector.__instance._session = session
         else:
             raise Warning(
                 _('Missing configuration'),
                 _('Please give connect_url and connect_api_key values '
                   'in your Odoo configuration file.'))
     return OnrampConnector.__instance
Example #46
0
 def get_local_alias(self, cr, uid, alias_domain, context=None):
     port = system_base_config.get('xmlrpc_port', False)
     xmlrpc = system_base_config.get('xmlrpc', False)
     mailgate_file = os.path.dirname(mail.__file__) + '/static/scripts/openerp_mailgate.py'
     admin_user = self.pool['res.users'].browse(cr, uid, SUPERUSER_ID, context=context)
     
     if not xmlrpc or not port:
         port = system_base_config.get('xmlrpcs_port', False)
         xmlrpcs = system_base_config.get('xmlrpcs', False)
         if not xmlrpcs or not port:
             print 'errror!!! falta el puerto'
     local_alias = (alias_domain or '')
     local_alias += ': "| '
     # local_alias = cr.dbname + ': "| '
     local_alias += mailgate_file
     local_alias += " --host=localhost"
     local_alias += " --port=" + str(port)
     local_alias += " -u " + str(SUPERUSER_ID)
     local_alias += " -p " + admin_user.password
     local_alias += " -d " + cr.dbname + '"'
     return local_alias
    def transfer(self, uid, old_code, new_code):
        """ Sync a child transfer with GP: rename pictures and log a note. """
        # Retrieve configuration
        smb_user = config.get("smb_user")
        smb_pass = config.get("smb_pwd")
        smb_ip = config.get("smb_ip")
        smb_port = int(config.get("smb_port", 0))
        if not (smb_user and smb_pass and smb_ip and smb_port):
            return False

        # Rename files in shared folder
        smb_conn = SMBConnection(smb_user, smb_pass, "openerp", "nas")
        if smb_conn.connect(smb_ip, smb_port):
            gp_old_pic_path = "{0}{1}/".format(config.get("gp_pictures"), old_code[:2])
            gp_new_pic_path = "{0}{1}/".format(config.get("gp_pictures"), new_code[:2])
            pic_files = smb_conn.listPath("GP", gp_old_pic_path)
            for file in pic_files:
                filename = file.filename
                if filename.startswith(old_code):
                    new_name = filename.replace(old_code, new_code)
                    smb_conn.rename("GP", gp_old_pic_path + filename, gp_new_pic_path + new_name)

        # Rename child code in Poles table
        self.query("UPDATE Poles SET CODESPE = %s WHERE CODESPE = %s", [old_code, new_code])
        return True
    def child_remove_from_typo3(self, cr, uid, ids, context=None):
        child_codes = [child.code for child in self.browse(cr, uid, ids,
                                                           context)]
        filename = "upd.sql"
        file_query = open(filename, "wb")
        for code in child_codes:
            file_query.write(
                "delete from tx_drechildpoolmanagement_domain_model_children "
                "where child_key='%s';\n" % code)
        file_query.close()
        host = config.get('typo3_host')
        username = config.get('typo3_user')
        pwd = config.get('typo3_pwd')
        scripts_url = config.get('typo3_scripts_url')
        path = config.get('typo3_scripts_path')
        api_key = config.get('typo3_api_key')
        if not (host and username and pwd and path and scripts_url
                and api_key):
            raise orm.except_orm('ConfigError',
                                 'Missing typo3 settings '
                                 'in conf file')
        with pysftp.Connection(host, username=username, password=pwd) as sftp:
            with sftp.cd(path):
                sftp.put(filename)

        self._typo3_scripts_fetch(scripts_url, api_key, "upd_db")
        self._typo3_scripts_fetch(scripts_url, api_key, "delete_photo",
                                  {"children": ",".join(child_codes)})

        for child in self.browse(cr, uid, ids, context):
            state = 'R' if child.has_been_sponsored else 'N'
            child.write({'state': state})
        return True
    def request_to_typo3(self, request, request_type):
        filename = request_type+".sql"

        host = config.get('typo3_host')
        username = config.get('typo3_user')
        pwd = config.get('typo3_pwd')
        scripts_url = config.get('typo3_scripts_url')
        path = config.get('typo3_scripts_path')
        api_key = config.get('typo3_api_key')

        file_query = open(filename, "wb")
        file_query.write(request)
        file_query.close()

        if not (host and username and pwd and path and
                scripts_url and api_key):
            raise orm.except_orm('ConfigError',
                                 'Missing typo3 settings '
                                 'in conf file')
        with pysftp.Connection(host, username=username, password=pwd) as sftp:
            with sftp.cd(path):
                sftp.put(filename)

        return self._typo3_scripts_fetch(
            scripts_url, api_key, request_type+"_db")
    def attach_pictures(self, cr, uid, ids, pictures_id, context=None):
        """ Push the new picture. """
        res = super(child_property, self).attach_pictures(
            cr, uid, ids, pictures_id, context)

        pictures = self.pool.get('compassion.child.pictures').browse(
            cr, uid, pictures_id, context)

        # Retrieve configuration
        smb_user = config.get('smb_user')
        smb_pass = config.get('smb_pwd')
        smb_ip = config.get('smb_ip')
        smb_port = int(config.get('smb_port', 0))
        if not (smb_user and smb_pass and smb_ip and smb_port):
            raise orm.except_orm(
                'Config Error',
                'Missing Samba configuration in conf file.')
        child = pictures.child_id

        date_pic = pictures.date.replace('-', '')
        gp_pic_path = "{0}{1}/".format(config.get('gp_pictures'),
                                       child.code[:2])
        file_name = "{0}_{1}.jpg".format(child.code, date_pic)
        picture_file = TemporaryFile()
        picture_file.write(base64.b64decode(pictures.fullshot))
        picture_file.flush()
        picture_file.seek(0)

        # Upload file to shared folder
        smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
        if smb_conn.connect(smb_ip, smb_port):
            try:
                smb_conn.storeFile(
                    'GP', gp_pic_path + file_name, picture_file)
            except OperationFailure:
                # Directory may not exist
                smb_conn.createDirectory('GP', gp_pic_path)
                smb_conn.storeFile(
                    'GP', gp_pic_path + file_name, picture_file)
        return res
    def transfer(self, uid, old_code, new_code):
        """ Sync a child transfer with GP: rename pictures and log a note. """
        # Retrieve configuration
        smb_user = config.get('smb_user')
        smb_pass = config.get('smb_pwd')
        smb_ip = config.get('smb_ip')
        smb_port = int(config.get('smb_port', 0))
        if not (smb_user and smb_pass and smb_ip and smb_port):
            return False

        # Rename files in shared folder
        smb_conn = SMBConnection(smb_user, smb_pass, 'openerp', 'nas')
        if smb_conn.connect(smb_ip, smb_port):
            gp_old_pic_path = "{0}{1}/".format(config.get('gp_pictures'),
                                               old_code[:2])
            gp_new_pic_path = "{0}{1}/".format(config.get('gp_pictures'),
                                               new_code[:2])
            pic_files = smb_conn.listPath('GP', gp_old_pic_path)
            for file in pic_files:
                filename = file.filename
                if filename.startswith(old_code):
                    new_name = filename.replace(old_code, new_code)
                    smb_conn.rename('GP', gp_old_pic_path + filename,
                                    gp_new_pic_path + new_name)

        # Rename child code in GP tables
        self.query("UPDATE ENFANTS SET CODE = %s WHERE CODE = %s",
                   [new_code, old_code])
        self.query("UPDATE Poles SET CODESPE = %s WHERE CODESPE = %s",
                   [new_code, old_code])
        self.query("UPDATE Affectat SET CODESPE = %s WHERE CODESPE = %s",
                   [new_code, old_code])
        return True
    def _cornerstone_fetch(self, project_code, api_mess):
        """ Construct the correct URL to call Compassion Cornerstone APIs.
        Returns the JSON object of the response."""
        url = config.get('compass_url')
        api_key = config.get('compass_api_key')
        if not url or not api_key:
            raise orm.except_orm('ConfigError',
                                 _('Missing compass_url or compass_api_key '
                                   'in conf file'))
        if url.endswith('/'):
            url = url[:-1]
        url += ('/ci/v1/' + api_mess + '/' + project_code + '?api_key='
                + api_key)

        # Send the request and retrieve the result.
        r = requests.get(url)
        if not r.status_code == 200:
            raise orm.except_orm(
                _('Error calling Cornerstone Service'),
                r.text)
        json_result = json.loads(r.text)
        return json_result
Example #53
0
    def _prepare_sendgrid_data(self):
        self.ensure_one()
        s_mail = Mail()
        s_mail.set_from(Email(self.email_from))
        s_mail.set_reply_to(Email(self.reply_to))
        s_mail.add_custom_arg(CustomArg('odoo_id', self.message_id))
        html = self.body_html or ' '

        p = re.compile(r'<.*?>')  # Remove HTML markers
        text_only = self.body_text or p.sub('', html.replace('<br/>', '\n'))

        s_mail.add_content(Content("text/plain", text_only))
        s_mail.add_content(Content("text/html", html))

        test_address = config.get('sendgrid_test_address')

        # TODO For now only one personalization (transactional e-mail)
        personalization = Personalization()
        personalization.set_subject(self.subject or ' ')
        if not test_address:
            if self.email_to:
                personalization.add_to(Email(self.email_to))
            for recipient in self.recipient_ids:
                personalization.add_to(Email(recipient.email))
            if self.email_cc:
                personalization.add_cc(Email(self.email_cc))
        else:
            _logger.info('Sending email to test address {}'.format(
                test_address))
            personalization.add_to(Email(test_address))
            self.email_to = test_address

        if self.sendgrid_template_id:
            s_mail.set_template_id(self.sendgrid_template_id.remote_id)

        for substitution in self.substitution_ids:
            personalization.add_substitution(Substitution(
                substitution.key, substitution.value))

        s_mail.add_personalization(personalization)

        for attachment in self.attachment_ids:
            s_attachment = Attachment()
            # Datas are not encoded properly for sendgrid
            s_attachment.set_content(base64.b64encode(base64.b64decode(
                attachment.datas)))
            s_attachment.set_filename(attachment.name)
            s_mail.add_attachment(s_attachment)

        return s_mail.get()
Example #54
0
def get_sys_logs(self, cr, uid):
    """
    Utility method to send a publisher warranty get logs messages.
    """
    pool = pooler.get_pool(cr.dbname)

    dbuuid = pool.get('ir.config_parameter').get_param(cr, uid, 'database.uuid')
    db_create_date = pool.get('ir.config_parameter').get_param(cr, uid, 'database.create_date')
    limit_date = datetime.datetime.now()
    limit_date = limit_date - datetime.timedelta(15)
    limit_date_str = limit_date.strftime(misc.DEFAULT_SERVER_DATETIME_FORMAT)
    nbr_users = pool.get("res.users").search(cr, uid, [], count=True)
    nbr_active_users = pool.get("res.users").search(cr, uid, [("login_date", ">=", limit_date_str)], count=True)
    nbr_share_users = False
    nbr_active_share_users = False
    if "share" in pool.get("res.users")._all_columns:
        nbr_share_users = pool.get("res.users").search(cr, uid, [("share", "=", True)], count=True)
        nbr_active_share_users = pool.get("res.users").search(cr, uid, [("share", "=", True), ("login_date", ">=", limit_date_str)], count=True)
    user = pool.get("res.users").browse(cr, uid, uid)

    web_base_url = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url', 'False')
    msg = {
        "dbuuid": dbuuid,
        "nbr_users": nbr_users,
        "nbr_active_users": nbr_active_users,
        "nbr_share_users": nbr_share_users,
        "nbr_active_share_users": nbr_active_share_users,
        "dbname": cr.dbname,
        "db_create_date": db_create_date,
        "version": release.version,
        "language": user.lang,
        "web_base_url": web_base_url,
    }
    msg.update(pool.get("res.company").read(cr,uid,[1],["name","email","phone"])[0])

    add_arg = {"timeout":30} if sys.version_info >= (2,6) else {}
    arguments = {'arg0': msg, "action": "update",}
    arguments_raw = urllib.urlencode(arguments)

    url = config.get("publisher_warranty_url")

    uo = urllib2.urlopen(url, arguments_raw, **add_arg)
    result = {}
    try:
        submit_result = uo.read()
        result = safe_eval(submit_result)
    finally:
        uo.close()
    return result
Example #55
0
    def _get_sys_logs(self, cr, uid):
        """
        Utility method to send a publisher warranty get logs messages.
        """
        msg = self._get_message(cr, uid)
        arguments = {'arg0': msg, "action": "update"}
        arguments_raw = werkzeug.urls.url_encode(arguments)

        url = config.get("publisher_warranty_url")

        uo = urllib2.urlopen(url, arguments_raw, timeout=30)
        try:
            submit_result = uo.read()
            return literal_eval(submit_result)
        finally:
            uo.close()
    def __init__(self, cr, uid):
        super(ProductPricelistItem, self).__init__(cr, uid)

        if CACHE_TYPE == 'redis':
            try:
                from openerp.addons.core_extended.redis import Redis
                host = config.get('redis_host', 'localhost')

                self._name_get = Redis(host, database=cr.db_name, model=self._name)
            except:
                _logger.error("Unable to import Redis")
                from openerp.addons.core_extended.dict_cache import SimpleCache
                self._name_get = SimpleCache()
        else:
            from openerp.addons.core_extended.dict_cache import SimpleCache
            self._name_get = SimpleCache()
Example #57
0
    def send_sendgrid(self):
        """ Use sendgrid transactional e-mails : e-mails are sent one by
        one. """
        api_key = config.get('sendgrid_api_key')
        if not api_key:
            raise exceptions.Warning(
                'ConfigError',
                _('Missing sendgrid_api_key in conf file'))

        sg = SendGridAPIClient(apikey=api_key)
        for email in self:
            try:
                response = sg.client.mail.send.post(
                    request_body=email._prepare_sendgrid_data())
            except Exception as e:
                _logger.error(e.read())
                continue

            status = response.status_code
            msg = response.body

            if status == STATUS_OK:
                _logger.info(str(msg))
                email._track_sendgrid_emails()
                email.write({
                    'sent_date': fields.Datetime.now(),
                    'state': 'sent'
                })
                # Update message body in associated message, which will be
                # shown in message history view for linked odoo object
                # defined through fields model and res_id. This will allow
                # tracking from the thread.
                message = email.mail_message_id
                message_vals = {
                    'body': email.body_html
                }
                if not message.subtype_id:
                    message_vals['subtype_id'] = self.env.ref(
                        'mail.mt_comment').id
                if not message.notified_partner_ids:
                    message_vals['notified_partner_ids'] = [
                        (6, 0, email.recipient_ids.ids)]
                message.write(message_vals)
                # Commit changes since e-mail was sent
                self.env.cr.commit()
            else:
                _logger.error("Failed to send email: {}".format(str(msg)))