[MIG] mail: migrate remaining code in old API

This commit is contained in:
Thibault Delavallée
2016-08-10 15:48:07 +02:00
parent c8a313d51e
commit e33435daa9
9 changed files with 74 additions and 83 deletions
+3 -3
View File
@@ -9,7 +9,7 @@ import werkzeug
from operator import itemgetter
from werkzeug import url_encode
from odoo import http, registry, SUPERUSER_ID
from odoo import api, http, registry, SUPERUSER_ID
from odoo.addons.web.controllers.main import binary_content
from odoo.exceptions import AccessError
from odoo.http import request
@@ -32,8 +32,8 @@ class MailController(http.Controller):
try:
db_registry = registry(db)
with db_registry.cursor() as cr:
mail_thread = db_registry['mail.thread']
mail_thread.message_process(cr, SUPERUSER_ID, None, message)
env = api.Environment(cr, SUPERUSER_ID, {})
env['mail.thread'].message_process(None, message)
except psycopg2.Error:
pass
return True
+5 -4
View File
@@ -1,12 +1,13 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
from odoo import api, models
class AutoVacuum(models.AbstractModel):
_inherit = 'ir.autovacuum'
def power_on(self, cr, uid, *args, **kwargs):
self.pool['mail.thread']._garbage_collect_attachments(cr, uid)
return super(AutoVacuum, self).power_on(cr, uid, *args, **kwargs)
@api.model
def power_on(self, *args, **kwargs):
self.env['mail.thread']._garbage_collect_attachments()
return super(AutoVacuum, self).power_on(*args, **kwargs)
+12 -17
View File
@@ -11,43 +11,38 @@ import urlparse
from urllib import urlencode, quote as quote
from odoo import _, api, fields, models, osv, SUPERUSER_ID, tools
from odoo import _, api, fields, models, tools
from odoo import report as odoo_report
from odoo.exceptions import UserError
_logger = logging.getLogger(__name__)
def format_tz(pool, cr, uid, dt, tz=False, format=False, context=None):
context = dict(context or {})
if tz:
context['tz'] = tz or pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz'] or "UTC"
def format_tz(env, dt, tz=False, format=False):
record_user_timestamp = env.user.sudo().with_context(tz=tz or env.user.sudo().tz or 'UTC')
timestamp = datetime.datetime.strptime(dt, tools.DEFAULT_SERVER_DATETIME_FORMAT)
ts = osv.fields.datetime.context_timestamp(cr, uid, timestamp, context)
ts = fields.Datetime.context_timestamp(record_user_timestamp, timestamp)
# Babel allows to format datetime in a specific language without change locale
# So month 1 = January in English, and janvier in French
# Be aware that the default value for format is 'medium', instead of 'short'
# medium: Jan 5, 2016, 10:20:31 PM | 5 janv. 2016 22:20:31
# short: 1/5/16, 10:20 PM | 5/01/16 22:20
if context.get('use_babel'):
if env.context.get('use_babel'):
# Formatting available here : http://babel.pocoo.org/en/latest/dates.html#date-fields
from babel.dates import format_datetime
return format_datetime(ts, format or 'medium', locale=context.get("lang") or 'en_US')
return format_datetime(ts, format or 'medium', locale=env.context.get("lang") or 'en_US')
if format:
return ts.strftime(format)
else:
lang = context.get("lang")
lang_params = {}
lang = env.context.get("lang")
langs = env['res.lang']
if lang:
res_lang = pool.get('res.lang')
ids = res_lang.search(cr, uid, [("code", "=", lang)])
if ids:
lang_params = res_lang.read(cr, uid, ids[0], ["date_format", "time_format"])
format_date = lang_params.get("date_format", '%B-%d-%Y')
format_time = lang_params.get("time_format", '%I-%M %p')
langs = env['res.lang'].search([("code", "=", lang)])
format_date = langs.date_format or '%B-%d-%Y'
format_time = langs.time_format or '%I-%M %p'
fdate = ts.strftime(format_date).decode('utf-8')
ftime = ts.strftime(format_time)
@@ -355,7 +350,7 @@ class MailTemplate(models.Model):
for record in records:
res_to_rec[record.id] = record
variables = {
'format_tz': lambda dt, tz=False, format=False, context=self._context: format_tz(self.pool, self._cr, self._uid, dt, tz, format, context),
'format_tz': lambda dt, tz=False, format=False, context=self._context: format_tz(self.env, dt, tz, format),
'user': self.env.user,
'ctx': self._context, # context kw would clash with mako internals
}
+4 -13
View File
@@ -300,10 +300,10 @@ class MailThread(models.AbstractModel):
).unlink()
return res
def copy_data(self, cr, uid, id, default=None, context=None):
context = dict(context or {}, mail_notrack=True)
@api.multi
def copy_data(self, default=None):
# avoid tracking multiple temporary changes during copy
return super(MailThread, self).copy_data(cr, uid, id, default=default, context=context)
return super(MailThread, self.with_context(mail_notrack=True)).copy_data(default=default)
# ------------------------------------------------------
# Technical methods (to clean / move to controllers ?)
@@ -486,15 +486,6 @@ class MailThread(models.AbstractModel):
# By passing this key, that allows to let the subtype empty and so don't sent email because partners_to_notify from mail_message._notify will be empty
if not self._context.get('mail_track_log_only'):
subtype_xmlid = record._track_subtype(dict((col_name, initial_values[record.id][col_name]) for col_name in changes))
# compatibility: use the deprecated _track dict
if not subtype_xmlid and hasattr(self, '_track'):
for field, track_info in self._track.items():
if field not in changes or subtype_xmlid:
continue
for subtype, method in track_info.items():
if method(self, self._cr, self._uid, record, self._context):
_logger.warning("Model %s still using deprecated _track dict; override _track_subtype method instead" % self._name)
subtype_xmlid = subtype
if subtype_xmlid:
subtype_rec = self.env.ref(subtype_xmlid) # TDE FIXME check for raise if not found
@@ -1098,7 +1089,7 @@ class MailThread(models.AbstractModel):
# that send the email has the right to create or modify a new document
# Fallback on user_id = uid
# Note: recognized partners will be added as followers anyway
# user_id = self._message_find_user_id(cr, uid, message, context=context)
# user_id = self._message_find_user_id(message)
user_id = self._uid
_logger.info('No matching user_id for the alias %s', alias.alias_name)
route = (alias.alias_model_id.model, alias.alias_force_thread_id, eval(alias.alias_defaults), user_id, alias)
+28 -28
View File
@@ -7,9 +7,8 @@ import werkzeug.urls
import urllib2
from ast import literal_eval
from functools import partial
from odoo import release, SUPERUSER_ID
from odoo import api, release, SUPERUSER_ID
from odoo.exceptions import UserError
from odoo.models import AbstractModel
from odoo.tools.translate import _
@@ -22,37 +21,37 @@ _logger = logging.getLogger(__name__)
class PublisherWarrantyContract(AbstractModel):
_name = "publisher_warranty.contract"
def _get_message(self, cr, uid):
Users = self.pool['res.users']
user_count = partial(Users.search_count, cr, uid)
get_param = partial(self.pool['ir.config_parameter'].get_param, cr, SUPERUSER_ID)
@api.model
def _get_message(self):
Users = self.env['res.users']
IrParamSudo = self.env['ir.config_parameter'].sudo()
dbuuid = get_param('database.uuid')
db_create_date = get_param('database.create_date')
dbuuid = IrParamSudo('database.uuid')
db_create_date = IrParamSudo('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 = user_count([])
nbr_active_users = user_count([("login_date", ">=", limit_date_str)])
nbr_users = Users.search_count([])
nbr_active_users = Users.search_count([("login_date", ">=", limit_date_str)])
nbr_share_users = 0
nbr_active_share_users = 0
if "share" in Users._fields:
nbr_share_users = user_count([("share", "=", True)])
nbr_active_share_users = user_count([("share", "=", True), ("login_date", ">=", limit_date_str)])
user = Users.browse(cr, uid, uid)
nbr_share_users = Users.search_count([("share", "=", True)])
nbr_active_share_users = Users.search_count([("share", "=", True), ("login_date", ">=", limit_date_str)])
user = self.env.user
domain = [('application', '=', True), ('state', 'in', ['installed', 'to upgrade', 'to remove'])]
apps = self.pool['ir.module.module'].search_read(cr, SUPERUSER_ID, domain, ['name'])
apps = self.env['ir.module.module'].sudo().search_read(domain, ['name'])
enterprise_code = get_param('database.enterprise_code')
enterprise_code = IrParamSudo('database.enterprise_code')
web_base_url = get_param('web.base.url')
web_base_url = IrParamSudo('web.base.url')
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,
"dbname": self._cr.dbname,
"db_create_date": db_create_date,
"version": release.version,
"language": user.lang,
@@ -62,14 +61,15 @@ class PublisherWarrantyContract(AbstractModel):
}
if user.partner_id.company_id:
company_id = user.partner_id.company_id.id
msg.update(self.pool["res.company"].read(cr, uid, [company_id], ["name", "email", "phone"])[0])
msg.update(company_id.read(["name", "email", "phone"])[0])
return msg
def _get_sys_logs(self, cr, uid):
@api.model
def _get_sys_logs(self):
"""
Utility method to send a publisher warranty get logs messages.
"""
msg = self._get_message(cr, uid)
msg = self._get_message()
arguments = {'arg0': msg, "action": "update"}
arguments_raw = werkzeug.urls.url_encode(arguments)
@@ -82,7 +82,8 @@ class PublisherWarrantyContract(AbstractModel):
finally:
uo.close()
def update_notification(self, cr, uid, ids, cron_mode=True, context=None):
@api.multi
def update_notification(self, cron_mode=True):
"""
Send a message to OpenERP's publisher warranty server to check the
validity of the contracts, get notifications, etc...
@@ -92,16 +93,15 @@ class PublisherWarrantyContract(AbstractModel):
"""
try:
try:
result = self._get_sys_logs(cr, uid)
result = self._get_sys_logs()
except Exception:
if cron_mode: # we don't want to see any stack trace in cron
return False
_logger.debug("Exception while sending a get logs messages", exc_info=1)
raise UserError(_("Error during communication with the publisher warranty server."))
# old behavior based on res.log; now on mail.message, that is not necessarily installed
IMD = self.pool['ir.model.data']
user = self.pool['res.users'].browse(cr, SUPERUSER_ID, SUPERUSER_ID)
poster = IMD.xmlid_to_object(cr, SUPERUSER_ID, 'mail.channel_all_employees', context=context)
user = self.env['res.users'].sudo().browse(SUPERUSER_ID)
poster = self.env.sudo().ref('mail.channel_all_employees')
if not (poster and poster.exists()):
if not user.exists():
return True
@@ -113,9 +113,9 @@ class PublisherWarrantyContract(AbstractModel):
pass
if result.get('enterprise_info'):
# Update expiration date
self.pool['ir.config_parameter'].set_param(cr, SUPERUSER_ID, 'database.expiration_date', result['enterprise_info'].get('expiration_date'), ['base.group_user'])
self.pool['ir.config_parameter'].set_param(cr, SUPERUSER_ID, 'database.expiration_reason', result['enterprise_info'].get('expiration_reason', 'trial'), ['base.group_system'])
self.pool['ir.config_parameter'].set_param(cr, SUPERUSER_ID, 'database.enterprise_code', result['enterprise_info'].get('enterprise_code'), ['base.group_user'])
self.env['ir.config_parameter'].sudo().set_param('database.expiration_date', result['enterprise_info'].get('expiration_date'), ['base.group_user'])
self.env['ir.config_parameter'].sudo().set_param('database.expiration_reason', result['enterprise_info'].get('expiration_reason', 'trial'), ['base.group_system'])
self.env['ir.config_parameter'].sudo().set_param('database.enterprise_code', result['enterprise_info'].get('enterprise_code'), ['base.group_user'])
except Exception:
if cron_mode:
+7 -4
View File
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from openerp.tests import common
from odoo import api
from odoo.tests import common
class TestMail(common.SavepointCase):
@@ -33,11 +34,13 @@ class TestMail(common.SavepointCase):
cls._mails.append(kwargs)
return build_email.origin(self, *args, **kwargs)
def send_email(self, cr, uid, message, *args, **kwargs):
@api.model
def send_email(self, message, *args, **kwargs):
return message['Message-Id']
def mail_group_message_get_recipient_values(self, cr, uid, ids, notif_message=None, recipient_ids=None, context=None):
return self.pool['mail.thread'].message_get_recipient_values(cr, uid, ids, notif_message=notif_message, recipient_ids=recipient_ids, context=context)
@api.multi
def mail_group_message_get_recipient_values(self, notif_message=None, recipient_ids=None):
return self.env['mail.thread'].message_get_recipient_values(notif_message=notif_message, recipient_ids=recipient_ids)
cls.env['ir.mail_server']._patch_method('build_email', build_email)
cls.env['ir.mail_server']._patch_method('send_email', send_email)
+7 -6
View File
@@ -3,9 +3,9 @@
from email.utils import formataddr
from .common import TestMail
from openerp.exceptions import AccessError
from openerp.exceptions import except_orm
from openerp.tools import mute_logger
from odoo import api
from odoo.exceptions import AccessError, except_orm
from odoo.tools import mute_logger
class TestMailGroup(TestMail):
@@ -28,8 +28,9 @@ class TestMailGroup(TestMail):
@classmethod
def tearDownClass(cls):
# set master class behavior back
def mail_group_message_get_recipient_values(self, cr, uid, ids, notif_message=None, recipient_ids=None, context=None):
return self.pool['mail.thread'].message_get_recipient_values(cr, uid, ids, notif_message=notif_message, recipient_ids=recipient_ids, context=context)
@api.multi
def mail_group_message_get_recipient_values(self, notif_message=None, recipient_ids=None):
return self.env['mail.thread'].message_get_recipient_values(notif_message=notif_message, recipient_ids=recipient_ids)
cls.env['mail.channel']._patch_method('message_get_recipient_values', mail_group_message_get_recipient_values)
super(TestMail, cls).tearDownClass()
@@ -105,7 +106,7 @@ class TestMailGroup(TestMail):
def test_mail_group_notification_recipients_grouped(self):
# Data: set alias_domain to see emails with alias
self.registry('ir.config_parameter').set_param(self.cr, self.uid, 'mail.catchall.domain', 'schlouby.fr')
self.env['ir.config_parameter'].set_param('mail.catchall.domain', 'schlouby.fr')
self.group_private.write({'alias_name': 'Test'})
self.group_private.message_subscribe_users([self.user_employee.id, self.user_portal.id])
+8 -7
View File
@@ -1,6 +1,7 @@
# -*- coding: utf-8 -*-
from openerp.addons.mail.tests.common import TestMail
from odoo import api
from odoo.addons.mail.tests.common import TestMail
class TestTracking(TestMail):
@@ -64,15 +65,15 @@ class TestTracking(TestMail):
'res_id': mt_group_public_unset.id
})
def _track_subtype(self, cr, uid, ids, init_values, context=None):
record = self.browse(cr, uid, ids[0], context=context)
if 'public' in init_values and record.public == 'private':
@api.multi
def _track_subtype(self, init_values):
if 'public' in init_values and self.public == 'private':
return 'mail.mt_private'
elif 'name' in init_values and record.name == 'supername':
elif 'name' in init_values and self.name == 'supername':
return 'mail.mt_name_supername'
elif 'group_public_id' in init_values and record.group_public_id:
elif 'group_public_id' in init_values and self.group_public_id:
return 'mail.mt_group_public_set'
elif 'group_public_id' in init_values and not record.group_public_id:
elif 'group_public_id' in init_values and not self.group_public_id:
return 'mail.mt_group_public_unset'
return False
self.registry('mail.channel')._patch_method('_track_subtype', _track_subtype)
@@ -456,7 +456,6 @@ class MassMailing(models.Model):
""" Override read_group to always display all states. """
if groupby and groupby[0] == "state":
# Default result structure
# states = self._get_state_list(cr, uid, context=context)
states = [('draft', _('Draft')), ('in_queue', _('In Queue')), ('sending', _('Sending')), ('done', _('Sent'))]
read_group_all_states = [{
'__context': {'group_by': groupby[1:]},