Ejemplo n.º 1
0
    def new_dispatch_rpc(service_name, method, params):
        try:

            if service_name == 'metaweblog':
                rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG)
                rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG)
                if rpc_request_flag or rpc_response_flag:
                    start_time = time.time()
                    start_memory = 0
                    if psutil:
                        start_memory = memory_info(psutil.Process(os.getpid()))
                    if rpc_request and rpc_response_flag:
                        netsvc.log(rpc_request, logging.DEBUG,
                                   '%s.%s' % (service_name, method),
                                   http.replace_request_password(params))

                threading.current_thread().uid = None
                threading.current_thread().dbname = None

                dispatch = addons.website_metaweblog.services.metaweblog.dispatch

                result = dispatch(method, params)

                if rpc_request_flag or rpc_response_flag:
                    end_time = time.time()
                    end_memory = 0
                    if psutil:
                        end_memory = memory_info(psutil.Process(os.getpid()))
                    logline = '%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (
                        service_name, method, end_time - start_time,
                        start_memory / 1024, end_memory / 1024,
                        (end_memory - start_memory) / 1024)
                    if rpc_response_flag:
                        netsvc.log(rpc_response, logging.DEBUG, logline,
                                   result)
                    else:
                        netsvc.log(rpc_request,
                                   logging.DEBUG,
                                   logline,
                                   http.replace_request_password(params),
                                   depth=1)

                return result

            else:
                return dispatch_rpc(service_name, method, params)

        except http.NO_POSTMORTEM:
            raise
        except exceptions.DeferredException as e:
            _logger.exception(tools.exception_to_unicode(e))
            tools.debugger.post_mortem(tools.config, e.traceback)
            raise
        except Exception as e:
            _logger.exception(tools.exception_to_unicode(e))
            tools.debugger.post_mortem(tools.config, sys.exc_info())
            raise
Ejemplo n.º 2
0
 def go(id, uid, ids, datas, context):
     with odoo.api.Environment.manage():
         cr = odoo.registry(db).cursor()
         try:
             result, format = odoo.report.render_report(
                 cr, uid, ids, object, datas, context)
             if not result:
                 tb = sys.exc_info()
                 self_reports[id][
                     'exception'] = odoo.exceptions.DeferredException(
                         'RML is not available at specified location or not enough data to print!',
                         tb)
             self_reports[id]['result'] = result
             self_reports[id]['format'] = format
             self_reports[id]['state'] = True
         except Exception as exception:
             _logger.exception('Exception: %s\n', exception)
             if hasattr(exception, 'name') and hasattr(exception, 'value'):
                 self_reports[id][
                     'exception'] = odoo.exceptions.DeferredException(
                         tools.ustr(exception.name),
                         tools.ustr(exception.value))
             else:
                 tb = sys.exc_info()
                 self_reports[id][
                     'exception'] = odoo.exceptions.DeferredException(
                         tools.exception_to_unicode(exception), tb)
             self_reports[id]['state'] = True
         cr.commit()
         cr.close()
     return True
Ejemplo n.º 3
0
def exp_render_report(db, uid, object, ids, datas=None, context=None):
    if not datas:
        datas={}
    if not context:
        context={}

    self_id_protect.acquire()
    global self_id
    self_id += 1
    id = self_id
    self_id_protect.release()

    self_reports[id] = {'uid': uid, 'result': False, 'state': False, 'exception': None}

    cr = odoo.registry(db).cursor()
    try:
        result, format = odoo.report.render_report(cr, uid, ids, object, datas, context)
        if not result:
            tb = sys.exc_info()
            self_reports[id]['exception'] = odoo.exceptions.DeferredException('RML is not available at specified location or not enough data to print!', tb)
        self_reports[id]['result'] = result
        self_reports[id]['format'] = format
        self_reports[id]['state'] = True
    except Exception, exception:

        _logger.exception('Exception: %s\n', exception)
        if hasattr(exception, 'name') and hasattr(exception, 'value'):
            self_reports[id]['exception'] = odoo.exceptions.DeferredException(tools.ustr(exception.name), tools.ustr(exception.value))
        else:
            tb = sys.exc_info()
            self_reports[id]['exception'] = odoo.exceptions.DeferredException(tools.exception_to_unicode(exception), tb)
        self_reports[id]['state'] = True
Ejemplo n.º 4
0
    def import_zipfile(self, module_file, force=False):
        if not module_file:
            raise Exception(_("No file sent."))
        if not zipfile.is_zipfile(module_file):
            raise UserError(_('File is not a zip file!'))

        success = []
        errors = dict()
        module_names = []
        with zipfile.ZipFile(module_file, "r") as z:
            for zf in z.filelist:
                if zf.file_size > MAX_FILE_SIZE:
                    raise UserError(_("File '%s' exceed maximum allowed file size") % zf.filename)

            with tempdir() as module_dir:
                z.extractall(module_dir)
                dirs = [d for d in os.listdir(module_dir) if os.path.isdir(opj(module_dir, d))]
                for mod_name in dirs:
                    module_names.append(mod_name)
                    try:
                        # assert mod_name.startswith('theme_')
                        path = opj(module_dir, mod_name)
                        self.import_module(mod_name, path, force=force)
                        success.append(mod_name)
                    except Exception, e:
                        _logger.exception('Error while importing module')
                        errors[mod_name] = exception_to_unicode(e)
Ejemplo n.º 5
0
    def _warn_template_error(self, scheduler, exception):
        # We warn ~ once by hour ~ instead of every 10 min if the interval unit is more than 'hours'.
        if random.random() < 0.1666 or scheduler.interval_unit in ('now', 'hours'):
            ex_s = exception_to_unicode(exception)
            try:
                event, template = scheduler.event_id, scheduler.template_id
                emails = list(set([event.organizer_id.email, event.user_id.email, template.write_uid.email]))
                subject = _("WARNING: Event Scheduler Error for event: %s" % event.name)
                body = _("""Event Scheduler for:
                              - Event: %s (%s)
                              - Scheduled: %s
                              - Template: %s (%s)

                            Failed with error:
                              - %s

                            You receive this email because you are:
                              - the organizer of the event,
                              - or the responsible of the event,
                              - or the last writer of the template."""
                         % (event.name, event.id, scheduler.scheduled_date, template.name, template.id, ex_s))
                email = self.env['ir.mail_server'].build_email(
                    email_from=self.env.user.email,
                    email_to=emails,
                    subject=subject, body=body,
                )
                self.env['ir.mail_server'].send_email(email)
            except Exception as e:
                _logger.error("Exception while sending traceback by email: %s.\n Original Traceback:\n%s", e, exception)
                pass
 def rest_request_data_token(self, **kwargs):
     _logger.info(_("Requested User Data Token Service..."))
     try:
         access_token = kwargs.get('access_token', None)
         if None in [access_token]:
             error_msg = _(
                 'The following parameters are must: access_token')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['not_acceptable'], error_msg)
         OuthAppToken = request.env['rest.oauth.app.token']
         oauth_app_token = OuthAppToken.check_access_token(access_token)
         if not oauth_app_token:
             error_msg = _(
                 'The access_token is expired or not found or invalid!')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['unauthorized'], error_msg)
         user_vals = oauth_app_token.get_user_vals(access_token)
         oauth_app_token.action_invalid()
         return self.generate_response(http_status_codes['ok'], user_vals)
     except Exception as e:
         if getattr(e, 'args', ()):
             e = [ustr(a) for a in e.args]
             e = e[0]
         error_msg = tools.exception_to_unicode(e)
         _logger.exception(error_msg)
         return self.generate_response(
             http_status_codes['internal_server_error'], error_msg)
Ejemplo n.º 7
0
    def _warn_template_error(self, scheduler, exception):
        # We warn ~ once by hour ~ instead of every 10 min if the interval unit is more than 'hours'.
        if random.random() < 0.1666 or scheduler.interval_unit in ('now', 'hours'):
            ex_s = exception_to_unicode(exception)
            try:
                event, template = scheduler.event_id, scheduler.template_id
                emails = list(set([event.organizer_id.email, event.user_id.email, template.write_uid.email]))
                subject = _("WARNING: Event Scheduler Error for event: %s" % event.name)
                body = _("""Event Scheduler for:
                              - Event: %s (%s)
                              - Scheduled: %s
                              - Template: %s (%s)

                            Failed with error:
                              - %s

                            You receive this email because you are:
                              - the organizer of the event,
                              - or the responsible of the event,
                              - or the last writer of the template."""
                         % (event.name, event.id, scheduler.scheduled_date, template.name, template.id, ex_s))
                email = self.env['ir.mail_server'].build_email(
                    email_from=self.env.user.email,
                    email_to=emails,
                    subject=subject, body=body,
                )
                self.env['ir.mail_server'].send_email(email)
            except Exception as e:
                _logger.error("Exception while sending traceback by email: %s.\n Original Traceback:\n%s", e, exception)
                pass
Ejemplo n.º 8
0
    def synchronize_events_cron(self):
        """ Call by the cron. """
        users = self.env['res.users'].search([
            ('google_calendar_last_sync_date', '!=', False)
        ])
        _logger.info("Calendar Synchro - Started by cron")

        for user_to_sync in users.ids:
            _logger.info(
                "Calendar Synchro - Starting synchronization for a new user [%s]",
                user_to_sync)
            try:
                resp = self.sudo(user_to_sync).synchronize_events(
                    lastSync=True)
                if resp.get("status") == "need_reset":
                    _logger.info(
                        "[%s] Calendar Synchro - Failed - NEED RESET  !",
                        user_to_sync)
                else:
                    _logger.info(
                        "[%s] Calendar Synchro - Done with status : %s  !",
                        user_to_sync, resp.get("status"))
            except Exception, e:
                _logger.info("[%s] Calendar Synchro - Exception : %s !",
                             user_to_sync, exception_to_unicode(e))
Ejemplo n.º 9
0
    def direct_execute(self, cmd: dict, command_id: models.Model = None):
        if command_id:
            pass  # TODO Direct execution of stored commands
        else:
            for ws in self:
                if ws.module_username is False:
                    username = ''
                else:
                    username = str(ws.module_username)

                if ws.module_password is False:
                    password = ''
                else:
                    password = str(ws.module_password)
                # TODO Store command in model as in execution
                try:
                    response = requests.post('http://' + ws.last_ip + '/sdk/cmd.json', auth=(username, password), json=cmd,
                                             timeout=2)
                    if response.status_code != 200:
                        raise exceptions.ValidationError('While trying to send the command to the module, '
                                                         'it returned code ' + str(response.status_code) + ' with body:\n'
                                                         + response.content.decode())
                    return response.json()
                except Exception as e:
                    _logger.exception(tools.exception_to_unicode(e))
                    raise
Ejemplo n.º 10
0
    def import_zipfile(self, module_file, force=False):
        if not module_file:
            raise Exception(_("No file sent."))
        if not zipfile.is_zipfile(module_file):
            raise UserError(_('File is not a zip file!'))

        success = []
        errors = dict()
        module_names = []
        with zipfile.ZipFile(module_file, "r") as z:
            for zf in z.filelist:
                if zf.file_size > MAX_FILE_SIZE:
                    raise UserError(
                        _("File '%s' exceed maximum allowed file size") %
                        zf.filename)

            with tempdir() as module_dir:
                z.extractall(module_dir)
                dirs = [
                    d for d in os.listdir(module_dir)
                    if os.path.isdir(opj(module_dir, d))
                ]
                for mod_name in dirs:
                    module_names.append(mod_name)
                    try:
                        # assert mod_name.startswith('theme_')
                        path = opj(module_dir, mod_name)
                        self.import_module(mod_name, path, force=force)
                        success.append(mod_name)
                    except Exception, e:
                        _logger.exception('Error while importing module')
                        errors[mod_name] = exception_to_unicode(e)
Ejemplo n.º 11
0
 def synchronize_users_events(self, user_ids):
     if user_ids and len(user_ids) > 0:
         users = self.env['res.users'].search([
             ('google_calendar_last_sync_date', '!=', False),
             ('id', 'in', user_ids)
         ])
         for user_id in users.ids:
             try:
                 resp = self.sudo(user_id).synchronize_events(lastSync=True)
             except Exception as e:
                 _logger.error("[%s] Calendar Synchro - Exception : %s !",
                               user_id, exception_to_unicode(e))
Ejemplo n.º 12
0
 def get_exemption(self, **kw):
     exemption_id = kw.get("exemption_id")
     try:
         message = (
             request.env["res.partner.exemption"]
             .sudo()
             .search_exemption_line(exemption_id)
         )
     except Exception as e:
         message = False, exception_to_unicode(e)
     return request.render(
         "account_avatax_exemption.exemption_page", {"message": message}
     )
Ejemplo n.º 13
0
    def get_one_event_synchro(self, google_id):
        token = self.get_token()

        params = {"access_token": token, "maxResults": 1000, "showDeleted": True}

        headers = {"Content-type": "application/json", "Accept": "text/plain"}

        url = "/calendar/v3/calendars/%s/events/%s" % ("primary", google_id)
        try:
            status, content, ask_time = self.env["google.service"]._do_request(url, params, headers, type="GET")
        except Exception, e:
            _logger.info("Calendar Synchro - In except of get_one_event_synchro")
            _logger.info(exception_to_unicode(e))
            return False
Ejemplo n.º 14
0
 def onchange_partner_id_credit_warning(self):
     try:
         if self.partner_id:
             self.check_partner_credit_limit()
             self.hold_delivery_till_payment = self.partner_id.commercial_partner_id.hold_delivery_till_payment
     except Exception as e:
         partner = self.partner_id.commercial_partner_id
         if not partner.credit_hold and partner.override_credit_threshold_limit >= self.amount_total:
             return
         return {
             'warning': {
                 'title': _("Warning!"),
                 'message': exception_to_unicode(e),
             }
         }
Ejemplo n.º 15
0
def exp_render_report(db, uid, object, ids, datas=None, context=None):
    if not datas:
        datas = {}
    if not context:
        context = {}

    self_id_protect.acquire()
    global self_id
    self_id += 1
    id = self_id
    self_id_protect.release()

    self_reports[id] = {
        'uid': uid,
        'result': False,
        'state': False,
        'exception': None
    }

    cr = odoo.registry(db).cursor()
    try:
        result, format = odoo.report.render_report(cr, uid, ids, object, datas,
                                                   context)
        if not result:
            tb = sys.exc_info()
            self_reports[id]['exception'] = odoo.exceptions.DeferredException(
                'RML is not available at specified location or not enough data to print!',
                tb)
        self_reports[id]['result'] = result
        self_reports[id]['format'] = format
        self_reports[id]['state'] = True
    except Exception as exception:

        _logger.exception('Exception: %s\n', exception)
        if hasattr(exception, 'name') and hasattr(exception, 'value'):
            self_reports[id]['exception'] = odoo.exceptions.DeferredException(
                tools.ustr(exception.name), tools.ustr(exception.value))
        else:
            tb = sys.exc_info()
            self_reports[id]['exception'] = odoo.exceptions.DeferredException(
                tools.exception_to_unicode(exception), tb)
        self_reports[id]['state'] = True
    cr.commit()
    cr.close()

    return _check_report(id)
Ejemplo n.º 16
0
    def get_one_event_synchro(self, google_id):
        token = self.get_token()

        params = {
            'access_token': token,
            'maxResults': 1000,
            'showDeleted': True,
        }

        headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}

        url = "/calendar/v3/calendars/%s/events/%s" % ('primary', google_id)
        try:
            status, content, ask_time = self.env['google.service']._do_request(url, params, headers, type='GET')
        except Exception, e:
            _logger.info("Calendar Synchro - In except of get_one_event_synchro")
            _logger.info(exception_to_unicode(e))
            return False
Ejemplo n.º 17
0
    def import_zipfile(self, module_file, force=False):
        if not module_file:
            raise Exception(_("No file sent."))
        if not zipfile.is_zipfile(module_file):
            raise UserError(_('Only zip files are supported.'))

        success = []
        errors = dict()
        module_names = []
        with zipfile.ZipFile(module_file, "r") as z:
            for zf in z.filelist:
                if zf.file_size > MAX_FILE_SIZE:
                    raise UserError(
                        _("File '%s' exceed maximum allowed file size") %
                        zf.filename)

            with tempfile.TemporaryDirectory() as module_dir:
                import odoo.modules.module as module
                try:
                    odoo.addons.__path__.append(module_dir)
                    z.extractall(module_dir)
                    dirs = [
                        d for d in os.listdir(module_dir)
                        if os.path.isdir(opj(module_dir, d))
                    ]
                    for mod_name in dirs:
                        module_names.append(mod_name)
                        try:
                            # assert mod_name.startswith('theme_')
                            path = opj(module_dir, mod_name)
                            if self._import_module(mod_name, path,
                                                   force=force):
                                success.append(mod_name)
                        except Exception as e:
                            _logger.exception('Error while importing module')
                            errors[mod_name] = exception_to_unicode(e)
                finally:
                    odoo.addons.__path__.remove(module_dir)
        r = ["Successfully imported module '%s'" % mod for mod in success]
        for mod, error in errors.items():
            r.append(
                "Error while importing module '%s'.\n\n %s \n Make sure those modules are installed and try again."
                % (mod, error))
        return '\n'.join(r), module_names
 def generate_response(self, status_code, data={}, headers=[]):
     _logger.info(
         _("Generating response with status code %s!") % (str(status_code)))
     try:
         if data:
             try:
                 data = isinstance(data, str) and data or json.dumps(data)
             except ValueError:
                 data = str(data)
         response = request.make_response(data, headers)
         response.status_code = status_code
         return response
     except Exception as e:  #To Do: Is it needed? recursive?
         if getattr(e, 'args', ()):
             e = [ustr(a) for a in e.args]
             e = e[0]
         error_msg = tools.exception_to_unicode(e)
         _logger.exception(error_msg)
         return self.generate_response(
             http_status_codes['internal_server_error'], error_msg)
Ejemplo n.º 19
0
    def generate_report(self, xml_id, ids):
        self_reports = {}
        self_reports = {'result': False, 'state': False, 'exception': None}
        try:
            result, format = request.env.ref(xml_id).sudo().render_qweb_pdf(
                ids)
            if not result:
                tb = sys.exc_info()
                self_reports['exception'] = odoo.exceptions.DeferredException(
                    'RML is not available at specified location or not enough data to print!',
                    tb)
            self_reports['result'] = result
            self_reports['format'] = format
            self_reports['state'] = True
            self_reports.update({'id': ids})
        except Exception as exception:
            if hasattr(exception, 'name') and hasattr(exception, 'value'):
                self_reports['exception'] = odoo.exceptions.DeferredException(
                    tools.ustr(exception.name), tools.ustr(exception.value))
            else:
                tb = sys.exc_info()
                self_reports['exception'] = odoo.exceptions.DeferredException(
                    tools.exception_to_unicode(exception), tb)
            self_reports['state'] = True

        exc = self_reports['exception']
        if exc:
            raise UserError('%s: %s' % (exc.message, exc.traceback))
        if self_reports['state']:
            if tools.config['reportgz']:
                import zlib
                res2 = zlib.compress(result)
            else:
                if isinstance(result, str):
                    res2 = result.encode('latin1', 'replace')
                else:
                    res2 = result
            if res2:
                self_reports['result'] = binascii.b2a_base64(res2).decode(
                    'utf-8')
        return self_reports
Ejemplo n.º 20
0
    def import_zipfile(self, module_file, force=False):
        if not module_file:
            raise Exception(_("No file sent."))
        if not zipfile.is_zipfile(module_file):
            raise UserError(_('File is not a zip file!'))

        success = []
        errors = dict()
        module_names = []
        with zipfile.ZipFile(module_file, "r") as z:
            for zf in z.filelist:
                if zf.file_size > MAX_FILE_SIZE:
                    raise UserError(
                        _("File '%s' exceed maximum allowed file size") %
                        zf.filename)

            with tempdir() as module_dir:
                import odoo.modules as addons
                try:
                    addons.module.ad_paths.append(module_dir)
                    z.extractall(module_dir)
                    dirs = [
                        d for d in os.listdir(module_dir)
                        if os.path.isdir(opj(module_dir, d))
                    ]
                    for mod_name in dirs:
                        module_names.append(mod_name)
                        try:
                            # assert mod_name.startswith('theme_')
                            path = opj(module_dir, mod_name)
                            self._import_module(mod_name, path, force=force)
                            success.append(mod_name)
                        except Exception as e:
                            _logger.exception('Error while importing module')
                            errors[mod_name] = exception_to_unicode(e)
                finally:
                    addons.module.ad_paths.remove(module_dir)
        r = ["Successfully imported module '%s'" % mod for mod in success]
        for mod, error in pycompat.items(errors):
            r.append("Error while importing module '%s': %r" % (mod, error))
        return '\n'.join(r), module_names
Ejemplo n.º 21
0
 def synchronize_events_cron(self, reportType, flag, args):
     """ Call by the cron. """
     today = datetime.today().date()
     print('крон    крон     крон !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
     if args == 'hours':
         print('крон    крон     крон !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
         if reportType == 'reportDetailByPeriod':
             update_date = today - timedelta(4)
             self = self.with_context(date_from=str(update_date),
                                      date_to=str(update_date),
                                      db_cleanup_suffix='hours')
         else:
             yesterday = today - timedelta(1)
             self = self.with_context(date_from=str(yesterday),
                                      db_cleanup_suffix='hours')
     if args == 'months':
         """ if datetime.today().day != 4:
             return """
         if reportType == 'reportDetailByPeriod':
             date_from = today - timedelta(7)
             date_to = today - timedelta(5)
             self = self.with_context(date_from=str(date_from),
                                      date_to=str(date_to),
                                      db_cleanup_suffix='months')
         else:
             date_from = today - timedelta(5)
             self = self.with_context(date_from=str(date_from),
                                      db_cleanup_suffix='months')
     try:
         resp = self.synchronize_events(reportType, flag)
         if resp.get("status") == "need_reset":
             _logger.info("Wildberries Synchro - Failed - NEED RESET  !")
         else:
             _logger.info("Wildberries Synchro - Done with status : %s  !",
                          resp.get("status"))
     except Exception as e:
         _logger.info("Wildberries Synchro - Exception : %s !",
                      exception_to_unicode(e))
     _logger.info("Wildberries Synchro - Ended by cron")
Ejemplo n.º 22
0
    def import_zipfile(self, module_file, force=False):
        if not module_file:
            raise Exception(_("No file sent."))
        if not zipfile.is_zipfile(module_file):
            raise UserError(_('File is not a zip file!'))

        success = []
        errors = dict()
        module_names = []
        with zipfile.ZipFile(module_file, "r") as z:
            for zf in z.filelist:
                if zf.file_size > MAX_FILE_SIZE:
                    raise UserError(_("File '%s' exceed maximum allowed file size") % zf.filename)

            with tempdir() as module_dir:
                import odoo.modules as addons
                try:
                    addons.module.ad_paths.append(module_dir)
                    z.extractall(module_dir)
                    dirs = [d for d in os.listdir(module_dir) if os.path.isdir(opj(module_dir, d))]
                    for mod_name in dirs:
                        module_names.append(mod_name)
                        try:
                            # assert mod_name.startswith('theme_')
                            path = opj(module_dir, mod_name)
                            self._import_module(mod_name, path, force=force)
                            success.append(mod_name)
                        except Exception as e:
                            _logger.exception('Error while importing module')
                            errors[mod_name] = exception_to_unicode(e)
                finally:
                    addons.module.ad_paths.remove(module_dir)
        r = ["Successfully imported module '%s'" % mod for mod in success]
        for mod, error in pycompat.items(errors):
            r.append("Error while importing module '%s': %r" % (mod, error))
        return '\n'.join(r), module_names
 def rest_request_auth_odoo(self, **kwargs):
     #To Do: Need to cjeck can easily be attacked. if then, find another solution
     _logger.info(_("Requested Odoo Auth Service..."))
     try:
         code = kwargs.get('code', None)
         scope = kwargs.get('scope', None)
         state = kwargs.get('state', None)
         redirect_uri = kwargs.get('redirect_uri', None)
         odoo_oauth2client_uri = kwargs.get('odoo_oauth2client_uri', None)
         if None in [code, state, odoo_oauth2client_uri]:
             error_msg = _(
                 'The following parameters are must: code, state, odoo_oauth2client_uri'
             )
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['not_acceptable'], error_msg)
         redirect_uri = unquote(redirect_uri)
         odoo_oauth2client_uri = unquote(odoo_oauth2client_uri)
         OuthAppAuthCode = request.env['rest.oauth.app.auth.code']
         oauth_app = OuthAppAuthCode.get_oauthapp_auth_code(code)
         if not oauth_app:
             error_msg = _(
                 'The auth code is expired or not found or invalid!')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['unauthorized'], error_msg)
         auth_redirect_uri = urljoin(redirect_uri,
                                     urlparse(redirect_uri).path)
         auth_redirect_uri = redirect_uri
         auth_redirect_uris = [
             x.strip() for x in oauth_app.auth_redirect_uri.split(',')
         ]
         if auth_redirect_uri not in auth_redirect_uris:
             error_msg = _('The value of "redirect_uri" is wrong')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['unauthorized'], error_msg)
         odoo_oauth2client_uri = urljoin(
             odoo_oauth2client_uri,
             urlparse(odoo_oauth2client_uri).path)
         odoo_oauth2client_uri = odoo_oauth2client_uri
         if odoo_oauth2client_uri != oauth_app.odoo_oauth2client_uri:
             error_msg = _('The value of "odoo_oauth2client_uri" is wrong')
             _logger.error(error_msg)
             return self.generate_response(http_status_codes['bad_request'],
                                           error_msg)
         client_id = oauth_app.client_id
         client_secret = oauth_app.client_secret
         gen_auth_headers = oauth_app.generate_basic_auth_header(
             client_id, client_secret)
         params = {
             'code': code,
             'grant_type': 'authorization_code',
             'redirect_uri': redirect_uri,
             'scope': scope,
             'state': state,
         }
         encoded_params = urls.url_encode(params)
         base_url = request.env['ir.config_parameter'].sudo().get_param(
             'web.base.url')
         auth_token_uri = urls.url_join(base_url, rest_auth_token_endpoint)
         auth_token_uri = '?'.join([auth_token_uri, encoded_params])
         _logger.info(
             _("Requested auth_code redirected from odoo endpoint to access_token endpoint"
               ))
         res = requests.request('GET',
                                auth_token_uri,
                                data=params,
                                headers=gen_auth_headers)
         status = res.status_code
         try:
             response = res.json()
         except Exception as e:
             response = res.text
             return self.generate_response(status, response)
         oauth_app_token = OuthAppAuthCode.get_token_auth_code(code)
         encoded_params = urls.url_encode(response)
         odoo_oauth2client_uri = '?'.join(
             [odoo_oauth2client_uri, encoded_params])
         _logger.info(
             _("Requested auth_code redirected from access_token endpoint to odoo_oauth2client endpoint"
               ))
         return utils.redirect(odoo_oauth2client_uri)
     except Exception as e:
         if getattr(e, 'args', ()):
             e = [ustr(a) for a in e.args]
             e = e[0]
         error_msg = tools.exception_to_unicode(e)
         _logger.exception(error_msg)
         return self.generate_response(
             http_status_codes['internal_server_error'], error_msg)
 def rest_request_auth_token(self, **kwargs):
     _logger.info(_("Requested Auth Token Service..."))
     try:
         grant_type = kwargs.get('grant_type', None)
         code = kwargs.get('code', None)
         redirect_uri = kwargs.get('redirect_uri', None)
         if grant_type != 'authorization_code':
             error_msg = _('The "grant_type" must be authorization_code')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['not_acceptable'], error_msg)
         if None in [code, redirect_uri]:
             error_msg = _(
                 'The following parameters are must: code, redirect_uri')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['not_acceptable'], error_msg)
         authorization_header = request.httprequest.headers.get(
             'Authorization')
         if not authorization_header:
             authorization_header = request.httprequest.headers.get(
                 'HTTP_AUTHORIZATION')
         if not authorization_header:
             error_msg = _('The "Authorization" header is missing')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['not_acceptable'], error_msg)
         redirect_uri = unquote(redirect_uri)
         OuthAppAuthCode = request.env['rest.oauth.app.auth.code']
         oauth_app = OuthAppAuthCode.get_oauthapp_auth_code(code)
         if not oauth_app:
             error_msg = _(
                 'The auth code is expired or not found or invalid!')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['unauthorized'], error_msg)
         auth_redirect_uri = urljoin(redirect_uri,
                                     urlparse(redirect_uri).path)
         auth_redirect_uri = redirect_uri
         auth_redirect_uris = [
             x.strip() for x in oauth_app.auth_redirect_uri.split(',')
         ]
         if auth_redirect_uri not in auth_redirect_uris:
             error_msg = _('The value of "redirect_uri" is wrong')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['unauthorized'], error_msg)
         client_id = oauth_app.client_id
         client_secret = oauth_app.client_secret
         gen_auth_headers = oauth_app.generate_basic_auth_header(
             client_id, client_secret)
         authorization = gen_auth_headers.get('Authorization')
         if authorization != authorization_header:
             error_msg = _(
                 'Either client_id or client_secret wrong or wrongly encoded!'
             )
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['unauthorized'], error_msg)
         oauth_app_token = OuthAppAuthCode.get_token_auth_code(code)
         oauth_app_token.action_generate_access_token()
         oauth_app_token.action_generate_refresh_token()
         token_vals = oauth_app_token.get_token_vals(oauth_app_token.id)
         OuthAppAuthCode.check_auth_code(code).action_invalid()
         return self.generate_response(http_status_codes['created'],
                                       token_vals)
     except Exception as e:
         if getattr(e, 'args', ()):
             e = [ustr(a) for a in e.args]
             e = e[0]
         error_msg = tools.exception_to_unicode(e)
         _logger.exception(error_msg)
         return self.generate_response(
             http_status_codes['internal_server_error'], error_msg)
Ejemplo n.º 25
0
    def synchronize_events_cron(self):
        """ Call by the cron. """
        domain = [('google_calendar_last_sync_date', '!=', False)]
        if self.env.context.get('last_sync_hours'):
            last_sync_hours = self.env.context['last_sync_hours']
            last_sync_date = datetime.now() - timedelta(hours=last_sync_hours)
            domain = expression.AND([
                domain,
                [('google_calendar_last_sync_date', '<=', fields.Datetime.to_string(last_sync_date))]
            ])
        users = self.env['res.users'].search(domain, order='google_calendar_last_sync_date')
        _logger.info("Calendar Synchro - Started by cron")

        for user_to_sync in users.ids:
            _logger.info("Calendar Synchro - Starting synchronization for a new user [%s]", user_to_sync)
            try:
                resp = self.sudo(user_to_sync).synchronize_events(lastSync=True)
                if resp.get("status") == "need_reset":
                    _logger.info("[%s] Calendar Synchro - Failed - NEED RESET  !", user_to_sync)
                else:
                    _logger.info("[%s] Calendar Synchro - Done with status : %s  !", user_to_sync, resp.get("status"))
            except Exception as e:
                _logger.info("[%s] Calendar Synchro - Exception : %s !", user_to_sync, exception_to_unicode(e))
        _logger.info("Calendar Synchro - Ended by cron")
 def rest_request_auth_code_implicit(self, **kwargs):
     _logger.info(_("Requested Auth Code Service..."))
     try:
         response_type = kwargs.get('response_type', None)
         client_id = kwargs.get('client_id', None)
         return_redirect = kwargs.get('return_redirect', True)
         redirect_uri = kwargs.get('redirect_uri', None)
         odoo_oauth2client_uri = kwargs.get('odoo_oauth2client_uri', None)
         scope = kwargs.get('scope', None)
         state = kwargs.get('state', None)
         user = request.env.user
         if None in [response_type, client_id, redirect_uri, scope, state]:
             error_msg = _(
                 'The following parameters are must: response_type, client_id, redirect_uri, scope.'
             )
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['not_acceptable'], error_msg)
         if response_type not in ['code', 'token']:
             error_msg = _(
                 'The value of "response_type" must be either "code" or "token"'
             )
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['not_acceptable'], error_msg)
         if return_redirect not in [True, False]:
             error_msg = _(
                 'The value of "return_redirect" must be either "True" or "False"'
             )
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['not_acceptable'], error_msg)
         redirect_uri = unquote(redirect_uri)
         OuthApplication = request.env['rest.oauth.app']
         oauth_app = OuthApplication.search([('client_id', '=', client_id)])
         if not oauth_app:
             error_msg = _('The "client_id" is wrong')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['unauthorized'], error_msg)
         auth_redirect_uri = urljoin(redirect_uri,
                                     urlparse(redirect_uri).path)
         auth_redirect_uri = redirect_uri
         auth_redirect_uris = [
             x.strip() for x in oauth_app.auth_redirect_uri.split(',')
         ]
         if auth_redirect_uri not in auth_redirect_uris:
             error_msg = _('The value of "redirect_uri" is wrong')
             _logger.error(error_msg)
             return self.generate_response(
                 http_status_codes['unauthorized'], error_msg)
         OuthAppToken = request.env['rest.oauth.app.token']
         OuthAppAuthCode = request.env['rest.oauth.app.auth.code']
         vals = {
             'oauth_app_id': oauth_app.id,
             'user_id': user.id,
             'location_uri': redirect_uri,
         }
         oauth_app_token = OuthAppToken.create(vals)
         res = {
             'odoo_oauth2client_uri': odoo_oauth2client_uri,
             'scope': scope,
             'state': state,
             'redirect_uri': redirect_uri,
         }
         if response_type == 'code' and oauth_app.type_auth_grant == 'auth_code':
             auth_code_vals = OuthAppAuthCode.generate_auth_vals(
                 oauth_app_token.id)
             auth_code = auth_code_vals.get('auth_code')
             res.update({
                 'code': auth_code,
             })
         elif response_type == 'token' and oauth_app.type_auth_grant == 'implicit':
             oauth_app_token.action_generate_access_token()
             token_vals = oauth_app_token.get_token_vals(oauth_app_token.id)
             res.update(token_vals)
         else:
             error_msg = _('The requested application cant found!')
             _logger.error(error_msg)
             return self.generate_response(http_status_codes['not_found'],
                                           error_msg)
         if return_redirect:
             encoded_params = urls.url_encode(res)
             redirect_uri = '?'.join([redirect_uri, encoded_params])
             _logger.info(
                 _("Requested auth_code redirected to redirect_uri"))
             return utils.redirect(redirect_uri)
         else:
             _logger.info(_("Requested auth_code returned"))
             return self.generate_response(http_status_codes['created'],
                                           res)
     except Exception as e:
         if getattr(e, 'args', ()):
             e = [ustr(a) for a in e.args]
             e = e[0]
         error_msg = tools.exception_to_unicode(e)
         _logger.exception(error_msg)
         #_logger.error(error_msg)
         return self.generate_response(
             http_status_codes['internal_server_error'], error_msg)
Ejemplo n.º 27
0
    def synchronize_events_cron(self):
        """ Call by the cron. """
        users = self.env['res.users'].search([('google_calendar_last_sync_date', '!=', False)])
        _logger.info("Calendar Synchro - Started by cron")

        for user_to_sync in users.ids:
            _logger.info("Calendar Synchro - Starting synchronization for a new user [%s]", user_to_sync)
            try:
                resp = self.sudo(user_to_sync).synchronize_events(lastSync=True)
                if resp.get("status") == "need_reset":
                    _logger.info("[%s] Calendar Synchro - Failed - NEED RESET  !", user_to_sync)
                else:
                    _logger.info("[%s] Calendar Synchro - Done with status : %s  !", user_to_sync, resp.get("status"))
            except Exception as e:
                _logger.info("[%s] Calendar Synchro - Exception : %s !", user_to_sync, exception_to_unicode(e))
        _logger.info("Calendar Synchro - Ended by cron")
Ejemplo n.º 28
0
Archivo: report.py Proyecto: befks/odoo
 def go(id, uid, ids, datas, context):
     with odoo.api.Environment.manage():
         cr = odoo.registry(db).cursor()
         try:
             result, format = odoo.report.render_report(cr, uid, ids, object, datas, context)
             if not result:
                 tb = sys.exc_info()
                 self_reports[id]['exception'] = odoo.exceptions.DeferredException('RML is not available at specified location or not enough data to print!', tb)
             self_reports[id]['result'] = result
             self_reports[id]['format'] = format
             self_reports[id]['state'] = True
         except Exception as exception:
             _logger.exception('Exception: %s\n', exception)
             if hasattr(exception, 'name') and hasattr(exception, 'value'):
                 self_reports[id]['exception'] = odoo.exceptions.DeferredException(tools.ustr(exception.name), tools.ustr(exception.value))
             else:
                 tb = sys.exc_info()
                 self_reports[id]['exception'] = odoo.exceptions.DeferredException(tools.exception_to_unicode(exception), tb)
             self_reports[id]['state'] = True
         cr.commit()
         cr.close()
     return True