[FIX] change the string 'Reply survey' into 'Answer Survey' in survey form view ...
[odoo/odoo.git] / addons / im_livechat / im_livechat.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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 json
23 import random
24 import jinja2
25
26 import openerp
27 import openerp.addons.im.im as im
28 from openerp.osv import osv, fields
29 from openerp import tools
30 from openerp import http
31 from openerp.http import request
32
33 env = jinja2.Environment(
34     loader=jinja2.PackageLoader('openerp.addons.im_livechat', "."),
35     autoescape=False
36 )
37 env.filters["json"] = json.dumps
38
39 class LiveChatController(http.Controller):
40
41     def _auth(self, db):
42         reg = openerp.modules.registry.RegistryManager.get(db)
43         uid = request.uid
44         return reg, uid
45
46     @http.route('/im_livechat/loader', auth="public")
47     def loader(self, **kwargs):
48         p = json.loads(kwargs["p"])
49         db = p["db"]
50         channel = p["channel"]
51         user_name = p.get("user_name", None)
52
53         reg, uid = self._auth(db)
54         with reg.cursor() as cr:
55             info = reg.get('im_livechat.channel').get_info_for_chat_src(cr, uid, channel)
56             info["db"] = db
57             info["channel"] = channel
58             info["userName"] = user_name
59             return request.make_response(env.get_template("loader.js").render(info),
60                  headers=[('Content-Type', "text/javascript")])
61
62     @http.route('/im_livechat/web_page', auth="public")
63     def web_page(self, **kwargs):
64         p = json.loads(kwargs["p"])
65         db = p["db"]
66         channel = p["channel"]
67         reg, uid = self._auth(db)
68         with reg.cursor() as cr:
69             script = reg.get('im_livechat.channel').read(cr, uid, channel, ["script"])["script"]
70             info = reg.get('im_livechat.channel').get_info_for_chat_src(cr, uid, channel)
71             info["script"] = script
72             return request.make_response(env.get_template("web_page.html").render(info),
73                  headers=[('Content-Type', "text/html")])
74
75     @http.route('/im_livechat/available', type='json', auth="public")
76     def available(self, db, channel):
77         reg, uid = self._auth(db)
78         with reg.cursor() as cr:
79             return len(reg.get('im_livechat.channel').get_available_users(cr, uid, channel)) > 0
80
81 class im_livechat_channel(osv.osv):
82     _name = 'im_livechat.channel'
83
84     def _get_default_image(self, cr, uid, context=None):
85         image_path = openerp.modules.get_module_resource('im_livechat', 'static/src/img', 'default.png')
86         return tools.image_resize_image_big(open(image_path, 'rb').read().encode('base64'))
87     def _get_image(self, cr, uid, ids, name, args, context=None):
88         result = dict.fromkeys(ids, False)
89         for obj in self.browse(cr, uid, ids, context=context):
90             result[obj.id] = tools.image_get_resized_images(obj.image)
91         return result
92     def _set_image(self, cr, uid, id, name, value, args, context=None):
93         return self.write(cr, uid, [id], {'image': tools.image_resize_image_big(value)}, context=context)
94
95
96     def _are_you_inside(self, cr, uid, ids, name, arg, context=None):
97         res = {}
98         for record in self.browse(cr, uid, ids, context=context):
99             res[record.id] = False
100             for user in record.user_ids:
101                 if user.id == uid:
102                     res[record.id] = True
103                     break
104         return res
105
106     def _script(self, cr, uid, ids, name, arg, context=None):
107         res = {}
108         for record in self.browse(cr, uid, ids, context=context):
109             res[record.id] = env.get_template("include.html").render({
110                 "url": self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url'),
111                 "parameters": {"db":cr.dbname, "channel":record.id},
112             })
113         return res
114
115     def _web_page(self, cr, uid, ids, name, arg, context=None):
116         res = {}
117         for record in self.browse(cr, uid, ids, context=context):
118             res[record.id] = self.pool.get('ir.config_parameter').get_param(cr, uid, 'web.base.url') + \
119                 "/im_livechat/web_page?p=" + json.dumps({"db":cr.dbname, "channel":record.id})
120         return res
121
122     _columns = {
123         'name': fields.char(string="Channel Name", size=200, required=True),
124         'user_ids': fields.many2many('res.users', 'im_livechat_channel_im_user', 'channel_id', 'user_id', string="Users"),
125         'are_you_inside': fields.function(_are_you_inside, type='boolean', string='Are you inside the matrix?', store=False),
126         'script': fields.function(_script, type='text', string='Script', store=False),
127         'web_page': fields.function(_web_page, type='url', string='Web Page', store=False, size="200"),
128         'button_text': fields.char(string="Text of the Button", size=200),
129         'input_placeholder': fields.char(string="Chat Input Placeholder", size=200),
130         'default_message': fields.char(string="Welcome Message", size=200, help="This is an automated 'welcome' message that your visitor will see when they initiate a new chat session."),
131         # image: all image fields are base64 encoded and PIL-supported
132         'image': fields.binary("Photo",
133             help="This field holds the image used as photo for the group, limited to 1024x1024px."),
134         'image_medium': fields.function(_get_image, fnct_inv=_set_image,
135             string="Medium-sized photo", type="binary", multi="_get_image",
136             store={
137                 'im_livechat.channel': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
138             },
139             help="Medium-sized photo of the group. It is automatically "\
140                  "resized as a 128x128px image, with aspect ratio preserved. "\
141                  "Use this field in form views or some kanban views."),
142         'image_small': fields.function(_get_image, fnct_inv=_set_image,
143             string="Small-sized photo", type="binary", multi="_get_image",
144             store={
145                 'im_livechat.channel': (lambda self, cr, uid, ids, c={}: ids, ['image'], 10),
146             },
147             help="Small-sized photo of the group. It is automatically "\
148                  "resized as a 64x64px image, with aspect ratio preserved. "\
149                  "Use this field anywhere a small image is required."),
150     }
151
152     def _default_user_ids(self, cr, uid, context=None):
153         return [(6, 0, [uid])]
154
155     _defaults = {
156         'button_text': "Have a Question? Chat with us.",
157         'input_placeholder': "How may I help you?",
158         'default_message': '',
159         'user_ids': _default_user_ids,
160         'image': _get_default_image,
161     }
162
163     def get_available_users(self, cr, uid, channel_id, context=None):
164         channel = self.browse(cr, openerp.SUPERUSER_ID, channel_id, context=context)
165         im_user_ids = self.pool.get("im.user").search(cr, uid, [["user_id", "in", [user.id for user in channel.user_ids]]], context=context)
166         users = []
167         for iuid in im_user_ids:
168             imuser = self.pool.get("im.user").browse(cr, uid, iuid, context=context)
169             if imuser.im_status:
170                 users.append(imuser)
171         return users
172
173     def get_session(self, cr, uid, channel_id, uuid, context=None):
174         self.pool.get("im.user").get_my_id(cr, uid, uuid, context=context)
175         users = self.get_available_users(cr, openerp.SUPERUSER_ID, channel_id, context=context)
176         if len(users) == 0:
177             return False
178         user_id = random.choice(users).id
179         session = self.pool.get("im.session").session_get(cr, uid, [user_id], uuid, context=context)
180         self.pool.get("im.session").write(cr, openerp.SUPERUSER_ID, session.get("id"), {'channel_id': channel_id}, context=context)
181         return session.get("id")
182
183     def test_channel(self, cr, uid, channel, context=None):
184         if not channel:
185             return {}
186         return {
187             'url': self.browse(cr, uid, channel[0], context=context or {}).web_page,
188             'type': 'ir.actions.act_url'
189         }
190
191     def get_info_for_chat_src(self, cr, uid, channel, context=None):
192         url = self.pool.get('ir.config_parameter').get_param(cr, openerp.SUPERUSER_ID, 'web.base.url')
193         chan = self.browse(cr, uid, channel, context=context)
194         return {
195             "url": url,
196             'buttonText': chan.button_text,
197             'inputPlaceholder': chan.input_placeholder,
198             'defaultMessage': chan.default_message,
199             "channelName": chan.name,
200         }
201
202     def join(self, cr, uid, ids, context=None):
203         self.write(cr, uid, ids, {'user_ids': [(4, uid)]})
204         return True
205
206     def quit(self, cr, uid, ids, context=None):
207         self.write(cr, uid, ids, {'user_ids': [(3, uid)]})
208         return True
209
210 class im_session(osv.osv):
211     _inherit = 'im.session'
212
213     _columns = {
214         'channel_id': fields.many2one("im_livechat.channel", "Channel"),
215     }