[MIG] website_mail: code migration to new api

No functional changes, only rewrite the code with
the api.v8 which more pythonic and smooth.
This commit is contained in:
Keyur Gajjar
2016-04-13 11:20:53 +02:00
committed by Jérome Maes
parent d672d8aa86
commit 30f48eb6b6
10 changed files with 120 additions and 147 deletions
+1 -1
View File
@@ -13,7 +13,7 @@
'data/mail_channel_data.xml',
],
'qweb': [
'static/src/xml/website_mail.xml'
'static/src/xml/chatter_message.xml'
],
'installable': True,
'auto_install': True,
@@ -1 +1,4 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import main
+53 -76
View File
@@ -4,9 +4,8 @@ from hashlib import sha1
from time import time
from werkzeug.exceptions import NotFound
from openerp import SUPERUSER_ID
from openerp.addons.web import http
from openerp.addons.web.http import request
from odoo import http
from odoo.http import request
def object_shasign(record=False, res_model='', res_id=None, **kw):
@@ -47,127 +46,105 @@ def _message_post_helper(res_model='', res_id=None, message='', token='', token_
The rest of the kwargs are passed on to message_post()
"""
res = request.env[res_model].browse(res_id)
author_id = request.env.user.partner_id.id
if token and res and token == getattr(res.sudo(), token_field, None):
res = res.sudo()
if request.env.user == request.env['ir.model.data'].xmlid_to_object('base.public_user'):
author_id = (res.partner_id and res.partner_id.id) if hasattr(res, 'partner_id') else author_id
record = request.env[res_model].browse(res_id)
author_id = request.env.user.partner_id.id if request.env.user.partner_id else False
if token and record and token == getattr(record.sudo(), token_field, None):
record = record.sudo()
if request.env.user == request.env.ref('base.public_user'):
author_id = record.partner_id.id if hasattr(record, 'partner_id') else author_id
else:
author_id = request.env.user.partner_id and request.env.user.partner_id.id
if not author_id:
raise NotFound()
elif sha_in:
timestamp = int(sha_time)
secret = request.env['ir.config_parameter'].sudo().get_param('database.secret')
shasign = sha1('%s%s%s%s' % (res_model, res_id, secret, timestamp))
secret_sudo = request.env['ir.config_parameter'].sudo().get_param('database.secret')
shasign = sha1('%s%s%s%s' % (res_model, res_id, secret_sudo, timestamp))
if sha_in == shasign.hexdigest() and int(time()) < timestamp + 3600 * 24:
res = res.sudo()
record = record.sudo()
else:
raise NotFound()
return res.with_context({'mail_create_nosubscribe': nosubscribe}).message_post(body=message,
message_type=kw.pop('message_type', False) or "comment",
subtype=kw.pop('subtype', False) or "mt_comment",
return record.with_context(mail_create_nosubscribe=nosubscribe).message_post(body=message,
message_type=kw.pop('message_type', "comment"),
subtype=kw.pop('subtype', "mt_comment"),
author_id=author_id,
**kw)
class WebsiteMail(http.Controller):
@http.route(['/website_mail/follow'], type='json', auth="public", website=True)
def website_message_subscribe(self, id=0, object=None, message_is_follower="on", email=False, **post):
# TDE FIXME: check this method with new followers
cr, uid, context = request.cr, request.uid, request.context
partner_obj = request.registry['res.partner']
user_obj = request.registry['res.users']
_id = int(id)
_message_is_follower = message_is_follower == 'on'
_object = request.registry[object]
res_id = int(id)
is_follower = message_is_follower == 'on'
record = request.env[object].browse(res_id)
# search partner_id
public_id = request.website.user_id.id
if uid != public_id:
partner_ids = [user_obj.browse(cr, uid, uid, context).partner_id.id]
if request.env.user != request.website.user_id:
partner_ids = request.env.user.partner_id.ids
else:
# mail_thread method
partner_ids = _object._find_partner_from_emails(
cr, SUPERUSER_ID, [_id], [email], context=context, check_followers=True)
partner_ids = record.sudo()._find_partner_from_emails([email], check_followers=True)
if not partner_ids or not partner_ids[0]:
name = email.split('@')[0]
partner_ids = [partner_obj.create(cr, SUPERUSER_ID, {'name': name, 'email': email}, context=context)]
partner_ids = request.env['res.partner'].sudo().create({'name': name, 'email': email}).ids
# add or remove follower
if _message_is_follower:
_object.check_access_rule(cr, uid, [_id], 'read', context)
_object.message_unsubscribe(cr, SUPERUSER_ID, [_id], partner_ids, context=context)
if is_follower:
record.check_access_rule('read')
record.sudo().message_unsubscribe(partner_ids)
return False
else:
_object.check_access_rule(cr, uid, [_id], 'read', context)
record.check_access_rule('read')
# add partner to session
request.session['partner_id'] = partner_ids[0]
_object.message_subscribe(cr, SUPERUSER_ID, [_id], partner_ids, context=context)
record.sudo().message_subscribe(partner_ids)
return True
@http.route(['/website_mail/is_follower'], type='json', auth="public", website=True)
def call(self, model, id, **post):
id = int(id)
cr, uid, context = request.cr, request.uid, request.context
partner_obj = request.registry.get('res.partner')
users_obj = request.registry.get('res.users')
obj = request.registry.get(model)
partner_id = None
public_id = request.website.user_id.id
if uid != public_id:
partner_id = users_obj.browse(cr, SUPERUSER_ID, uid, context).partner_id
def is_follower(self, model, res_id, **post):
user = request.env.user
partner = None
public_user = request.website.user_id
if user != public_user:
partner = request.env.user.partner_id
elif request.session.get('partner_id'):
partner_id = partner_obj.browse(cr, SUPERUSER_ID, request.session.get('partner_id'), context)
email = partner_id and partner_id.email or ""
partner = request.env['res.partner'].sudo().browse(request.session.get('partner_id'))
values = {
'is_user': uid != public_id,
'email': email,
'is_user': user != public_user,
'email': partner.email if partner else "",
'is_follower': False,
'alias_name': False,
}
if not obj:
return values
obj_ids = obj.exists(cr, SUPERUSER_ID, [id], context=context)
if obj_ids:
if partner_id:
values['is_follower'] = len(
request.registry['mail.followers'].search(
cr, SUPERUSER_ID, [
('res_model', '=', model),
('res_id', '=', obj_ids[0]),
('partner_id', '=', partner_id.id)
], context=context)) == 1
record = request.env[model].sudo().browse(int(res_id))
if record and partner:
values['is_follower'] = bool(request.env['mail.followers'].search_count([
('res_model', '=', model),
('res_id', '=', record.id),
('partner_id', '=', partner.id)
]))
return values
@http.route(['/website_mail/post/json'], type='json', auth='public', website=True)
def chatter_json(self, res_model='', res_id=None, message='', **kw):
res_id = int(res_id)
try:
msg = _message_post_helper(res_model, res_id, message, **kw)
data = {
'id': msg.id,
'body': msg.body,
'date': msg.date,
'author': msg.author_id.name,
'image_url': '/mail/%s/%s/avatar/%s' % (msg.model, msg.res_id, msg.author_id.id)
}
return data
msg = _message_post_helper(res_model, int(res_id), message, **kw)
except Exception:
return False
data = {
'id': msg.id,
'body': msg.body,
'date': msg.date,
'author': msg.author_id.name,
'image_url': '/mail/%s/%s/avatar/%s' % (msg.model, msg.res_id, msg.author_id.id)
}
return data
@http.route(['/website_mail/post/post'], type='http', methods=['POST'], auth='public', website=True)
def chatter_post(self, res_model='', res_id=None, message='', redirect=None, **kw):
res_id = int(res_id)
url = request.httprequest.referrer
if message:
message = _message_post_helper(res_model, res_id, message, **kw)
message = _message_post_helper(res_model, int(res_id), message, **kw)
url = url + "#message-%s" % (message.id,)
return request.redirect(url)
@@ -1,8 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<odoo>
<data noupdate="1">
<record model="mail.channel" id="channel_public">
<record id="channel_public" model="mail.channel">
<field name="name">Discussion Group</field>
<field name="public">public</field>
<field name="description">Public Discussion Group</field>
@@ -127,9 +127,10 @@
<data noupdate="1">
<function
id="mail_template_function_module_install_website_mail"
model="mail.template"
model="mail.template"
name="send_mail"
eval="[ref('mail_template_data_module_install_website_mail'), ref('base.module_website_mail')]"/>
</data>
</openerp>
</odoo>
+3
View File
@@ -1,3 +1,6 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import mail_message
import mail_thread
import update
+36 -45
View File
@@ -1,37 +1,18 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp import SUPERUSER_ID
from openerp.tools import html2plaintext
from openerp.tools.translate import _
from openerp.osv import osv, fields, expression
from openerp.exceptions import AccessError
from odoo import api, fields, models, SUPERUSER_ID, _
from odoo.osv import expression
from odoo.tools import html2plaintext
from odoo.exceptions import AccessError
class MailMessage(osv.Model):
class MailMessage(models.Model):
_inherit = 'mail.message'
def _get_description_short(self, cr, uid, ids, name, arg, context=None):
res = dict.fromkeys(ids, False)
for message in self.browse(cr, uid, ids, context=context):
if message.subject:
res[message.id] = message.subject
else:
plaintext_ct = '' if not message.body else html2plaintext(message.body)
res[message.id] = plaintext_ct[:30] + '%s' % (' [...]' if len(plaintext_ct) >= 30 else '')
return res
_columns = {
'description': fields.function(
_get_description_short, type='char',
help='Message description: either the subject, or the beginning of the body'
),
'website_published': fields.boolean(
'Published', help="Visible on the website as a comment", copy=False,
),
}
def default_get(self, cr, uid, fields_list, context=None):
defaults = super(MailMessage, self).default_get(cr, uid, fields_list, context=context)
@api.model
def default_get(self, fields_list):
defaults = super(MailMessage, self).default_get(fields_list)
# Note: explicitly implemented in default_get() instead of _defaults,
# to avoid setting to True for all existing messages during upgrades.
@@ -42,30 +23,40 @@ class MailMessage(osv.Model):
return defaults
def _search(self, cr, uid, args, offset=0, limit=None, order=None,
context=None, count=False, access_rights_uid=None):
description = fields.Char(compute="_compute_description", help='Message description: either the subject, or the beginning of the body')
website_published = fields.Boolean(string='Published', help="Visible on the website as a comment", copy=False)
@api.multi
def _compute_description(self):
for message in self:
if message.subject:
message.description = message.subject
else:
plaintext_ct = '' if not message.body else html2plaintext(message.body)
message.description = plaintext_ct[:30] + '%s' % (' [...]' if len(plaintext_ct) >= 30 else '')
@api.model
def _search(self, args, offset=0, limit=None, order=None, count=False, access_rights_uid=None):
""" Override that adds specific access rights of mail.message, to restrict
messages to published messages for public users. """
if uid != SUPERUSER_ID:
group_ids = self.pool.get('res.users').browse(cr, uid, uid, context=context).groups_id
group_user_id = self.pool.get("ir.model.data").get_object_reference(cr, uid, 'base', 'group_public')[1]
if group_user_id in [group.id for group in group_ids]:
if self.env.uid != SUPERUSER_ID:
group_user = self.env.ref('base.group_public')
if group_user in self.env.user.groups_id:
args = expression.AND([[('website_published', '=', True)], list(args)])
return super(MailMessage, self)._search(cr, uid, args, offset=offset, limit=limit, order=order,
context=context, count=count, access_rights_uid=access_rights_uid)
return super(MailMessage, self)._search(args, offset=offset, limit=limit, order=order,
count=count, access_rights_uid=access_rights_uid)
def check_access_rule(self, cr, uid, ids, operation, context=None):
@api.multi
def check_access_rule(self, operation):
""" Add Access rules of mail.message for non-employee user:
- read:
- raise if the type is comment and subtype NULL (internal note)
"""
if uid != SUPERUSER_ID:
group_ids = self.pool.get('res.users').browse(cr, uid, uid, context=context).groups_id
group_user_id = self.pool.get("ir.model.data").get_object_reference(cr, uid, 'base', 'group_public')[1]
if group_user_id in [group.id for group in group_ids]:
cr.execute('SELECT id FROM "%s" WHERE website_published IS FALSE AND id = ANY (%%s)' % (self._table), (ids,))
if cr.fetchall():
if self.env.uid != SUPERUSER_ID:
group_user = self.env.ref('base.group_public')
if group_user in self.env.user.groups_id:
self.env.cr.execute('SELECT id FROM "%s" WHERE website_published IS FALSE AND id = ANY (%%s)' % (self._table), (self.ids,))
if self.env.cr.fetchall():
raise AccessError(_('The requested operation cannot be completed due to security restrictions. Please contact your system administrator.\n\n(Document type: %s, Operation: %s)') % (self._description, operation))
return super(MailMessage, self).check_access_rule(cr, uid, ids=ids, operation=operation, context=context)
return super(MailMessage, self).check_access_rule(operation=operation)
+6 -12
View File
@@ -1,19 +1,13 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp.osv import osv, fields
from odoo import fields, models
# TODO for trunk, remove me
class MailThread(osv.AbstractModel):
class MailThread(models.AbstractModel):
_inherit = 'mail.thread'
_columns = {
'website_message_ids': fields.one2many(
'mail.message', 'res_id',
domain=lambda self: [
'&', ('model', '=', self._name), ('message_type', '=', 'comment')
],
string='Website Messages',
help="Website communication history",
),
}
website_message_ids = fields.One2many('mail.message', 'res_id',
domain=lambda self: ['&', ('model', '=', self._name), ('message_type', '=', 'comment')],
string='Website Messages', help="Website communication history")
+8 -4
View File
@@ -1,10 +1,14 @@
# -*- coding: utf-8 -*-
from openerp.models import AbstractModel
# Part of Odoo. See LICENSE file for full copyright and licensing details.
class publisher_warranty_contract(AbstractModel):
from odoo import api, models
class PublisherWarrantyContract(models.AbstractModel):
_inherit = "publisher_warranty.contract"
def _get_message(self, cr, uid):
msg = super(publisher_warranty_contract, self)._get_message(cr, uid)
@api.model
def _get_message(self):
msg = super(PublisherWarrantyContract, self)._get_message()
msg['website'] = True
return msg
+1 -1
View File
@@ -11,7 +11,7 @@ animation.registry.follow = animation.Class.extend({
this.is_user = false;
ajax.jsonRpc('/website_mail/is_follower', 'call', {
model: this.$target.data('object'),
id: this.$target.data('id'),
res_id: this.$target.data('id'),
}).always(function (data) {
self.is_user = data.is_user;
self.email = data.email;
@@ -1,15 +1,15 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from openerp.addons.mail.tests.common import TestMail
from openerp.addons.website_mail.controllers.main import WebsiteMail
from openerp.tools import mute_logger, email_split
from odoo.addons.mail.tests.common import TestMail
from odoo.addons.website_mail.controllers.main import WebsiteMail
from odoo.tools import mute_logger, email_split
class TestControllers(TestMail):
def test_00_subscribe(self):
# from openerp.addons.web.http import request
# from odoo.addons.web.http import request
# print request
cr, uid = self.cr, self.uid