[MERGE] Sync with trunk.
[odoo/odoo.git] / addons / mail / mail_group.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2010-today OpenERP SA (<http://www.openerp.com>)
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>
19 #
20 ##############################################################################
21
22 import openerp
23 import openerp.tools as tools
24 from osv import osv
25 from osv import fields
26 from openerp import SUPERUSER_ID
27
28
29 class mail_group(osv.Model):
30     """ A mail_group is a collection of users sharing messages in a discussion
31         group. The group mechanics are based on the followers. """
32     _description = 'Discussion group'
33     _name = 'mail.group'
34     _mail_flat_thread = False
35     _inherit = ['mail.thread']
36     _inherits = {'mail.alias': 'alias_id', 'ir.ui.menu': 'menu_id'}
37
38     def _get_image(self, cr, uid, ids, name, args, context=None):
39         result = dict.fromkeys(ids, False)
40         for obj in self.browse(cr, uid, ids, context=context):
41             result[obj.id] = tools.image_get_resized_images(obj.image)
42         return result
43
44     def _set_image(self, cr, uid, id, name, value, args, context=None):
45         return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
46
47     _columns = {
48         'description': fields.text('Description'),
49         'menu_id': fields.many2one('ir.ui.menu', string='Related Menu', required=True, ondelete="cascade"),
50         'public': fields.selection([('public', 'Public'), ('private', 'Private'), ('groups', 'Selected Group Only')], 'Privacy', required=True,
51             help='This group is visible by non members. \
52             Invisible groups can add members through the invite button.'),
53         'group_public_id': fields.many2one('res.groups', string='Authorized Group'),
54         'group_ids': fields.many2many('res.groups', rel='mail_group_res_group_rel',
55             id1='mail_group_id', id2='groups_id', string='Auto Subscription',
56             help="Members of those groups will automatically added as followers. "\
57                  "Note that they will be able to manage their subscription manually "\
58                  "if necessary."),
59         # image: all image fields are base64 encoded and PIL-supported
60         'image': fields.binary("Photo",
61             help="This field holds the image used as photo for the group, limited to 1024x1024px."),
62         'image_medium': fields.function(_get_image, fnct_inv=_set_image,
63             string="Medium-sized photo", type="binary", multi="_get_image",
64             store={
65                 'mail.group': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
66             },
67             help="Medium-sized photo of the group. It is automatically "\
68                  "resized as a 128x128px image, with aspect ratio preserved. "\
69                  "Use this field in form views or some kanban views."),
70         'image_small': fields.function(_get_image, fnct_inv=_set_image,
71             string="Small-sized photo", type="binary", multi="_get_image",
72             store={
73                 'mail.group': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
74             },
75             help="Small-sized photo of the group. It is automatically "\
76                  "resized as a 64x64px image, with aspect ratio preserved. "\
77                  "Use this field anywhere a small image is required."),
78         'alias_id': fields.many2one('mail.alias', 'Alias', ondelete="cascade", required=True,
79             help="The email address associated with this group. New emails received will automatically "
80                  "create new topics."),
81     }
82
83     def _get_default_employee_group(self, cr, uid, context=None):
84         ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'base', 'group_user')
85         return ref and ref[1] or False
86
87     def _get_default_image(self, cr, uid, context=None):
88         image_path = openerp.modules.get_module_resource('mail', 'static/src/img', 'groupdefault.png')
89         return tools.image_resize_image_big(open(image_path, 'rb').read().encode('base64'))
90
91     def _get_menu_parent(self, cr, uid, context=None):
92         ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mail', 'mail_group_root')
93         return ref and ref[1] or False
94
95     _defaults = {
96         'public': 'groups',
97         'group_public_id': _get_default_employee_group,
98         'image': _get_default_image,
99         'parent_id': _get_menu_parent,
100         'alias_domain': False, # always hide alias during creation
101     }
102
103     def _subscribe_users(self, cr, uid, ids, context=None):
104         for mail_group in self.browse(cr, uid, ids, context=context):
105             partner_ids = []
106             for group in mail_group.group_ids:
107                 partner_ids += [user.partner_id.id for user in group.users]
108             self.message_subscribe(cr, uid, ids, partner_ids, context=context)
109
110     def create(self, cr, uid, vals, context=None):
111         mail_alias = self.pool.get('mail.alias')
112         if not vals.get('alias_id'):
113             vals.pop('alias_name', None) # prevent errors during copy()
114             alias_id = mail_alias.create_unique_alias(cr, uid,
115                           # Using '+' allows using subaddressing for those who don't
116                           # have a catchall domain setup.
117                           {'alias_name': "group+" + vals['name']},
118                           model_name=self._name, context=context)
119             vals['alias_id'] = alias_id
120
121         #check access rights for the current user, then create as SUPERUSER because the object inherits
122         #ir.ui.menu (for which normal users do not have creation rights)
123         self.check_access_rights(cr, uid, 'create')
124         mail_group_id = super(mail_group, self).create(cr, SUPERUSER_ID, vals, context=context)
125
126         # Create client action for this group and link the menu to it
127         ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mail', 'action_mail_group_feeds')
128         if ref:
129             search_ref = self.pool.get('ir.model.data').get_object_reference(cr, uid, 'mail', 'view_message_search')
130             params = {
131                 'search_view_id': search_ref and search_ref[1] or False,
132                 'domain': [('model', '=', 'mail.group'), ('res_id', '=', mail_group_id)],
133                 'context': {'default_model': 'mail.group', 'default_res_id': mail_group_id, 'search_default_message_unread': True},
134                 'res_model': 'mail.message',
135                 'thread_level': 1,
136                 'header_description': vals.get('description'),
137             }
138             cobj = self.pool.get('ir.actions.client')
139             newref = cobj.copy(cr, SUPERUSER_ID, ref[1], default={'params': str(params), 'name': vals['name']}, context=context)
140             self.write(cr, SUPERUSER_ID, [mail_group_id], {'action': 'ir.actions.client,' + str(newref), 'mail_group_id': mail_group_id}, context=context)
141
142         mail_alias.write(cr, uid, [vals['alias_id']], {"alias_force_thread_id": mail_group_id}, context)
143
144         if vals.get('group_ids'):
145             self._subscribe_users(cr, uid, [mail_group_id], context=context)
146         return mail_group_id
147
148     def unlink(self, cr, uid, ids, context=None):
149         groups = self.browse(cr, uid, ids, context=context)
150         # Cascade-delete mail aliases as well, as they should not exist without the mail group.
151         mail_alias = self.pool.get('mail.alias')
152         alias_ids = [group.alias_id.id for group in groups if group.alias_id]
153         # Cascade-delete menu entries as well
154         self.pool.get('ir.ui.menu').unlink(cr, uid, [group.menu_id.id for group in groups if group.menu_id], context=context)
155         # Delete mail_group
156         res = super(mail_group, self).unlink(cr, uid, ids, context=context)
157         mail_alias.unlink(cr, uid, alias_ids, context=context)
158         return res
159
160     def write(self, cr, uid, ids, vals, context=None):
161         result = super(mail_group, self).write(cr, uid, ids, vals, context=context)
162         if vals.get('group_ids'):
163             self._subscribe_users(cr, uid, ids, context=context)
164         # if description is changed: update client action
165         if vals.get('description'):
166             cobj = self.pool.get('ir.actions.client')
167             for action in [group.action for group in self.browse(cr, SUPERUSER_ID, ids, context=context) if group.action]:
168                 new_params = action.params
169                 new_params['header_description'] = vals.get('description')
170                 cobj.write(cr, SUPERUSER_ID, [action.id], {'params': str(new_params)}, context=context)
171         return result
172
173     def action_follow(self, cr, uid, ids, context=None):
174         """ Wrapper because message_subscribe_users take a user_ids=None
175             that receive the context without the wrapper. """
176         return self.message_subscribe_users(cr, uid, ids, context=context)
177
178     def action_unfollow(self, cr, uid, ids, context=None):
179         """ Wrapper because message_unsubscribe_users take a user_ids=None
180             that receive the context without the wrapper. """
181         return self.message_unsubscribe_users(cr, uid, ids, context=context)