[MERGE] Merged with main addons.
[odoo/odoo.git] / addons / mail / static / src / js / mail.js
1 openerp.mail = function(session) {
2     var _t = session.web._t,
3        _lt = session.web._lt;
4
5     var mail = session.mail = {};
6
7     /**
8      * Add records to sorted_comments array
9      * @param {Array} records records from mail.message sorted by date desc
10      * @returns {Object} cs comments_structure: dict
11      *                      cs.model_to_root_ids = {model: [root_ids], }
12      *                      cs.new_root_ids = [new_root_ids]
13      *                      cs.root_ids = [root_ids]
14      *                      cs.msgs = {record.id: record,}
15      *                      cs.tree_struct = {record.id: {
16      *                          'level': record_level in hierarchy, 0 is root,
17      *                          'msg_nbr': number of childs,
18      *                          'direct_childs': [msg_ids],
19      *                          'all_childs': [msg_ids],
20      *                          'for_thread_msgs': [records],
21      *                          'ancestors': [msg_ids], } }
22      */
23     function tools_sort_comments(cs, records, parent_id) {
24         var cur_iter = 0; var max_iter = 10; var modif = true;
25         while ( modif && (cur_iter++) < max_iter) {
26             modif = false;
27             _(records).each(function (record) {
28                 // root and not yet recorded
29                 if ( (record.parent_id == false || record.parent_id[0] == parent_id) && ! cs['msgs'][record.id]) {
30                     // add to model -> root_list ids
31                     if (! cs['model_to_root_ids'][record.model]) cs['model_to_root_ids'][record.model] = [record.id];
32                     else cs['model_to_root_ids'][record.model].push(record.id);
33                     // add root data
34                     cs['new_root_ids'].push(record.id);
35                     // add record
36                     cs['tree_struct'][record.id] = {'level': 0, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [record], 'msg_nbr': -1, 'ancestors': []};
37                     cs['msgs'][record.id] = record;
38                     modif = true;
39                 }
40                 // not yet recorded, but parent is recorded
41                 else if (! cs['msgs'][record.id] && cs['msgs'][record.parent_id[0]]) {
42                     var parent_level = cs['tree_struct'][record.parent_id[0]]['level'];
43                     // update parent structure
44                     cs['tree_struct'][record.parent_id[0]]['direct_childs'].push(record.id);
45                     cs['tree_struct'][record.parent_id[0]]['for_thread_msgs'].push(record);
46                     // update ancestors structure
47                     for (ancestor_id in cs['tree_struct'][record.parent_id[0]]['ancestors']) {
48                         cs['tree_struct'][ancestor_id]['all_childs'].push(record.id);
49                     }
50                     // add record
51                     cs['tree_struct'][record.id] = {'level': parent_level+1, 'direct_childs': [], 'all_childs': [], 'for_thread_msgs': [], 'msg_nbr': -1, 'ancestors': []};
52                     cs['msgs'][record.id] = record;
53                     modif = true;
54                 }
55             });
56         }
57         return cs;
58     }
59
60     /** 
61      * ThreadDisplay widget: this widget handles the display of a thread of
62      * messages. The [thread_level] parameter sets the thread level number:
63      * - root message
64      * - - sub message (parent_id = root message)
65      * - - - sub sub message (parent id = sub message)
66      * - - sub message (parent_id = root message)
67      * This widget has 2 ways of initialization, either you give records to be rendered,
68      * either it will fetch [limit] messages related to [res_model]:[res_id].
69      */
70     mail.Thread = session.web.Widget.extend({
71         template: 'mail.Thread',
72
73         /**
74          * @param {Object} parent parent
75          * @param {Object} [params]
76          * @param {String} [params.res_model] res_model of mail.thread object
77          * @param {Number} [params.res_id] res_id of record
78          * @param {Number} [params.parent_id=false] parent_id of message
79          * @param {Number} [params.uid] user id
80          * @param {Number} [params.thread_level=0] number of levels in the thread (only 0 or 1 currently)
81          * @param {Number} [params.msg_more_limit=100] number of character to display before having a "show more" link;
82          *                                             note that the text will not be truncated if it does not have 110% of
83          *                                             the parameter (ex: 110 characters needed to be truncated and be displayed
84          *                                             as a 100-characters message)
85          * @param {Number} [params.limit=10] maximum number of messages to fetch
86          * @param {Number} [params.offset=0] offset for fetching messages
87          * @param {Number} [params.records=null] records to show instead of fetching messages
88          */
89         init: function(parent, params) {
90             this._super(parent);
91             this.params = params;
92             this.params.parent_id = this.params.parent_id || false;
93             this.params.thread_level = this.params.thread_level || 0;
94             this.params.msg_more_limit = this.params.msg_more_limit || 100;
95             this.params.limit = this.params.limit || 100;
96             this.params.offset = this.params.offset || 0;
97             this.params.records = this.params.records || null;
98             // datasets and internal vars
99             this.ds = new session.web.DataSet(this, this.params.res_model);
100             this.ds_users = new session.web.DataSet(this, 'res.users');
101             this.ds_msg = new session.web.DataSet(this, 'mail.message');
102             this.sorted_comments = {'root_ids': [], 'root_id_msg_list': {}};
103             this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
104             // display customization vars
105             this.display = {};
106             this.display.show_post_comment = this.params.show_post_comment || false;
107             this.display.show_reply = (this.params.thread_level > 0);
108             this.display.show_delete = true;
109             this.display.show_hide = this.params.show_hide || false;
110             this.display.show_more = (this.params.thread_level == 0);
111             // not used currently
112             this.intlinks_mapping = {};
113         },
114         
115         start: function() {
116             var self = this;
117             
118             this._super.apply(this, arguments);
119             // customize display
120             if (! this.display.show_post_comment) {
121                 this.$element.find('div.oe_mail_thread_action').hide();
122             }
123             // add events
124             this.add_events();
125             
126             // display user, fetch comments
127             this.display_current_user();
128             
129             if (this.params.records) {
130                 var display_done = this.display_comments_from_parameters(this.params.records);
131             } else {
132                 var display_done = this.init_comments();
133             }
134             return display_done
135         },
136         
137         add_events: function() {
138             var self = this;
139             // event: click on 'more' at bottom of thread
140             this.$element.find('button.oe_mail_button_more').click(function () {
141                 self.do_more();
142             });
143             // event: writing in textarea
144             this.$element.find('textarea.oe_mail_action_textarea').keyup(function (event) {
145                 var charCode = (event.which) ? event.which : window.event.keyCode;
146                 if (event.shiftKey && charCode == 13) { this.value = this.value+"\n"; }
147                 else if (charCode == 13) { return self.do_comment(); }
148             });
149             // event: click on 'reply' in msg
150             this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_reply', 'click', function (event) {
151                 var act_dom = $(this).parents('div.oe_mail_thread_display').find('div.oe_mail_thread_action:first');
152                 act_dom.toggle();
153                 event.preventDefault();
154             });
155             // event: click on 'delete' in msg
156             this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_delete', 'click', function (event) {
157                 //console.log('deleting');
158                 if (! confirm(_t("Do you really want to delete this message?"))) { return false; }
159                 var msg_id = event.srcElement.dataset.id;
160                 if (! msg_id) return false;
161                 var call_defer = self.ds_msg.unlink([parseInt(msg_id)]);
162                 $(event.srcElement).parents('.oe_mail_thread_msg').eq(0).hide();
163                 if (self.params.thread_level > 0) {
164                     $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
165                 }
166                 return false;
167             });
168             // event: click on 'hide' in msg
169             this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_msg_hide', 'click', function (event) {
170                 //console.log('hiding');
171                 if (! confirm(_t("Do you really want to hide this thread ?"))) { return false; }
172                 var msg_id = event.srcElement.dataset.id;
173                 if (! msg_id) return false;
174                 //console.log(msg_id);
175                 var call_defer = self.ds.call('message_remove_pushed_notifications', [[self.params.res_id], [parseInt(msg_id)], true]);
176                 $(event.srcElement).parents('.oe_mail_thread_msg').eq(0).hide();
177                 if (self.params.thread_level > 0) {
178                     $(event.srcElement).parents('.oe_mail_thread').eq(0).hide();
179                 }
180                 return false;
181             });
182             // event: click on an internal link
183             this.$element.find('div.oe_mail_thread_display').delegate('a.oe_mail_internal_link', 'click', function (event) {
184                 // lazy implementation: fetch data and try to redirect
185                 if (! event.srcElement.dataset.resModel) return false;
186                 else var res_model = event.srcElement.dataset.resModel;
187                 var res_login = event.srcElement.dataset.resLogin;
188                 var res_id = event.srcElement.dataset.resId;
189                 if ((! res_login) && (! res_id)) return false;
190                 if (! res_id) {
191                     var ds = new session.web.DataSet(self, res_model);
192                     var defer = ds.call('search', [[['login', '=', res_login]]]).then(function (records) {
193                         if (records[0]) {
194                             self.do_action({ type: 'ir.actions.act_window', res_model: res_model, res_id: parseInt(records[0]), views: [[false, 'form']]});
195                         }
196                         else return false;
197                     });
198                 }
199                 else self.do_action({ type: 'ir.actions.act_window', res_model: res_model, res_id: parseInt(res_id), views: [[false, 'form']]});
200             });
201             // event: click on 'attachment(s)' in msg
202             this.$element.delegate('a.oe_mail_msg_view_attachments', 'click', function (event) {
203                 var act_dom = $(this).parent().parent().parent().find('.oe_mail_msg_attachments');
204                 act_dom.toggle();
205                 return false;
206             });
207             // see more
208             this.$element.on('click','a.oe_mail_msg_more', function (event) {
209                 $(this).siblings('.oe_mail_msg_tail').show();
210                 $(this).hide();
211                 return false;
212             });
213         },
214         
215         destroy: function () {
216             this._super.apply(this, arguments);
217         },
218         
219         init_comments: function() {
220             var self = this;
221             this.params.offset = 0;
222             this.sorted_comments = {'root_ids': [], 'root_id_msg_list': {}};
223             this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
224             this.$element.find('div.oe_mail_thread_display').empty();
225             domain = this.get_fetch_domain(this.sorted_comments);
226             return this.fetch_comments(this.params.limit, this.params.offset, domain).then();
227         },
228         
229         fetch_comments: function (limit, offset, domain) {
230             var self = this;
231             var defer = this.ds.call('message_load', [[this.params.res_id], ( (limit+1)||(this.params.limit+1) ), (offset||this.params.offset), (domain||[]), (this.params.thread_level > 0), (this.sorted_comments['root_ids'])]);
232             $.when(defer).then(function (records) {
233                 if (records.length <= self.params.limit) self.display.show_more = false;
234                 else { self.display.show_more = true; records.pop(); }
235                 
236                 self.display_comments(records);
237                 if (self.display.show_more == true) self.$element.find('div.oe_mail_thread_more:last').show();
238                 else  self.$element.find('div.oe_mail_thread_more:last').hide();
239             });
240             
241             return defer;
242         },
243
244         display_comments_from_parameters: function (records) {
245             if (records.length > 0 && records.length < (records[0].child_ids.length+1) ) this.display.show_more = true;
246             else this.display.show_more = false;
247             var defer = this.display_comments(records);
248             if (this.display.show_more == true) $('div.oe_mail_thread_more').eq(-2).show();
249             else $('div.oe_mail_thread_more').eq(-2).hide();
250             return defer;
251         },
252         
253         display_comments: function (records) {
254             var self = this;
255             
256             //build attachments download urls and compute time-relative from dates
257             for (var k in records) {
258                 records[k].timerelative = $.timeago(records[k].date);
259                 if (records[k].attachments) {
260                     for (var l in records[k].attachments) {
261                         var url = self.session.origin + '/web/binary/saveas?session_id=' + self.session.session_id + '&model=ir.attachment&field=datas&filename_field=datas_fname&id='+records[k].attachments[l].id;
262                         records[k].attachments[l].url = url;
263                     }
264                 }
265             }
266             this.cs = this.sort_comments_tmp(records);
267             _(records).each(function (record) {
268                 var sub_msgs = [];
269                 if ((record.parent_id == false || record.parent_id[0] == self.params.parent_id) && self.params.thread_level > 0 ) {
270                     var sub_list = self.cs['tree_struct'][record.id]['direct_childs'];
271                     _(records).each(function (record) {
272                         //if (record.parent_id == false || record.parent_id[0] == self.params.parent_id) return;
273                         if (_.indexOf(sub_list, record.id) != -1) {
274                             sub_msgs.push(record);
275                         }
276                     });
277                     self.display_comment(record);
278                     self.thread = new mail.Thread(self, {'res_model': self.params.res_model, 'res_id': self.params.res_id, 'uid': self.params.uid,
279                                                             'records': sub_msgs, 'thread_level': (self.params.thread_level-1), 'parent_id': record.id});
280                     self.$element.find('.oe_mail_thread_msg:last').append('<div class="oe_mail_thread_subthread"/>');
281                     self.thread.appendTo(self.$element.find('div.oe_mail_thread_subthread:last'));
282                 }
283                 else if (self.params.thread_level == 0) {
284                     self.display_comment(record);
285                 }
286             });
287             // update offset for "More" buttons
288             if (this.params.thread_level == 0) this.params.offset += records.length;
289         },
290
291         /**
292          * Display a record
293          */
294         display_comment: function (record) {
295             record.body = this.do_text_nl2br(record.body, true);
296             if (record.type == 'email') {
297                 record.mini_url = ('/mail/static/src/img/email_icon.png');
298             } else { 
299                 record.mini_url = this.thread_get_avatar('res.users', 'image_small', record.user_id[0]);
300             }
301             // body text manipulation
302             record.body = this.do_clean_text(record.body);
303             record.body = this.do_replace_internal_links(record.body);
304
305             // split for see more
306             var split = this.do_truncate_string(record.body, this.params.msg_more_limit);
307             record.body_head = split[0];
308             record.body_tail = split[1];
309
310             // format date according to the user timezone
311             record.date = session.web.format_value(record.date, {type:"datetime"});
312
313
314             var rendered = session.web.qweb.render('mail.Thread.message', {'record': record, 'thread': this, 'params': this.params, 'display': this.display});
315             $( rendered).appendTo(this.$element.children('div.oe_mail_thread_display:first'));
316         },
317        
318         /**
319          * Add records to sorted_comments array
320          * @param {Array} records records from mail.message sorted by date desc
321          * @returns {Object} sc sorted_comments: dict {
322          *                          'root_id_list': list or root_ids
323          *                          'root_id_msg_list': {'record_id': [ancestor_ids]}, still sorted by date desc
324          *                          'id_to_root': {'root_id': [records]}, still sorted by date desc
325          *                          }
326          */
327         sort_comments: function (records) {
328             var self = this;
329             sc = {'root_id_list': [], 'root_id_msg_list': {}, 'id_to_root': {}}
330             var cur_iter = 0; var max_iter = 10; var modif = true;
331             /* step1: get roots */
332             while ( modif && (cur_iter++) < max_iter) {
333                 modif = false;
334                 _(records).each(function (record) {
335                     if ( (record.parent_id == false || record.parent_id[0] == self.params.parent_id) && (_.indexOf(sc['root_id_list'], record.id) == -1)) {
336                         sc['root_id_list'].push(record.id);
337                         sc['root_id_msg_list'][record.id] = [];
338                         self.sorted_comments['root_ids'].push(record.id);
339                         modif = true;
340                     } 
341                     else {
342                         if (_.indexOf(sc['root_id_list'], record.parent_id[0]) != -1) {
343                              sc['id_to_root'][record.id] = record.parent_id[0];
344                              modif = true;
345                         }
346                         else if ( sc['id_to_root'][record.parent_id[0]] ) {
347                              sc['id_to_root'][record.id] = sc['id_to_root'][record.parent_id[0]];
348                              modif = true;
349                         }
350                     }
351                 });
352             }
353             /* step2: add records */
354             _(records).each(function (record) {
355                 var root_id = sc['id_to_root'][record.id];
356                 if (! root_id) return;
357                 sc['root_id_msg_list'][root_id].push(record);
358                 //self.sorted_comments['root_id_msg_list'][root_id].push(record.id);
359             });
360             return sc;
361         },
362         
363         /**
364          * Add records to comments_structure object: see function for details
365          */
366         sort_comments_tmp: function(records) {
367             return tools_sort_comments(this.comments_structure, records, this.params.parent_id);
368         },
369         
370         display_current_user: function () {
371             return this.$element.find('img.oe_mail_msg_image').attr('src', this.thread_get_avatar('res.users', 'image_small', this.params.uid));
372         },
373         
374         do_comment: function () {
375             var comment_node = this.$element.find('textarea');
376             var body_text = comment_node.val();
377             comment_node.val('');
378             return this.ds.call('message_append_note', [[this.params.res_id], 'Reply', body_text, this.params.parent_id, 'comment', 'html']).then(
379                 this.proxy('init_comments'));
380         },
381         
382         /**
383          * Create a domain to fetch new comments according to
384          * comment already present in sorted_comments
385          * @param {Object} sorted_comments (see sort_comments)
386          * @returns {Array} fetch_domain (OpenERP domain style)
387          */
388         get_fetch_domain: function (sorted_comments) {
389             var domain = [];
390             var ids = sorted_comments.root_ids.slice();
391             var ids2 = [];
392             // must be child of current parent
393             if (this.params.parent_id) { domain.push(['id', 'child_of', this.params.parent_id]); }
394             _(sorted_comments.root_ids).each(function (id) { // each record
395                 ids.push(id);
396                 ids2.push(id);
397             });
398             if (this.params.parent_id != false) {
399                 ids2.push(this.params.parent_id);
400             }
401             // must not be children of already fetched messages
402             if (ids.length > 0) {
403                 domain.push('&');
404                 domain.push('!');
405                 domain.push(['id', 'child_of', ids]);
406             }
407             if (ids2.length > 0) {
408                 domain.push(['id', 'not in', ids2]);
409             }
410             return domain;
411         },
412         
413         do_more: function () {
414             domain = this.get_fetch_domain(this.sorted_comments);
415             return this.fetch_comments(this.params.limit, this.params.offset, domain);
416         },
417         
418         /**
419          *
420          * var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
421          * var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
422          */
423         do_replace_internal_links: function (string) {
424             var self = this;
425             var icon_list = ['al', 'pinky']
426             /* shortcut to user: @login */
427             var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
428             var regex_res = regex_login.exec(string);
429             while (regex_res != null) {
430                 var login = regex_res[2];
431                 string = string.replace(regex_res[0], regex_res[1] + '<a href="#" class="oe_mail_internal_link" data-res-model="res.users" data-res-login = ' + login + '>@' + login + '</a>');
432                 regex_res = regex_login.exec(string);
433             }
434             /* special shortcut: :name, try to find an icon if in list */
435             var regex_login = new RegExp(/(^|\s):((\w)*)/g);
436             var regex_res = regex_login.exec(string);
437             while (regex_res != null) {
438                 var icon_name = regex_res[2];
439                 if (_.include(icon_list, icon_name))
440                     string = string.replace(regex_res[0], regex_res[1] + '<img src="/mail/static/src/img/_' + icon_name + '.png" width="22px" height="22px" alt="' + icon_name + '"/>');
441                 regex_res = regex_login.exec(string);
442             }
443             return string;
444         },
445         
446         thread_get_avatar: function(model, field, id) {
447             return this.session.prefix + '/web/binary/image?session_id=' + this.session.session_id + '&model=' + model + '&field=' + field + '&id=' + (id || '');
448         },
449         
450         /**
451          * @param {String} string to truncate
452          * @param {Number} max number of chars to display 
453          * @returns {String} truncated string
454          */
455         do_truncate_string: function(string, max_length) {
456             // multiply by 1.2: prevent truncating an just too little long string
457             if (string.length <= (max_length * 1.2)) {
458                 return [string, ""];
459             } else {
460                 return [string.slice(0, max_length), string.slice(max_length)];
461             }
462         },
463         
464         /** Removes html tags, except b, em, br */
465         do_clean_text: function (string) {
466             var html = $('<div/>').text(string.replace(/\s+/g, ' ')).html().replace(new RegExp('&lt;(/)?(b|em|br|br /)\\s*&gt;', 'gi'), '<$1$2>');
467             return html;
468         },
469         
470         /** Replaces line bracks by html line breaks (br) */
471         do_text_nl2br: function (str, is_xhtml) {   
472             var break_tag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';    
473             return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1'+ break_tag +'$2');
474         },
475         
476         /**
477          *
478          * var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
479          * var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
480          */
481         do_check_internal_links: function(string) {
482             /* shortcut to user: @login */
483             var regex_login = new RegExp(/(^|\s)@((\w|@|\.)*)/g);
484             var regex_res = regex_login.exec(string);
485             while (regex_res != null) {
486                 var login = regex_res[2];
487                 if (! ('res.users' in this.map_hash)) { this.map_hash['res.users']['name'] = []; }
488                 this.map_hash['res.users']['login'].push(login);
489                 regex_res = regex_login.exec(string);
490             }
491             /* internal links: #res.model,name */
492             var regex_intlink = new RegExp(/(^|\s)#(\w*[a-zA-Z_]+\w*)\.(\w+[a-zA-Z_]+\w*),(\w+)/g);
493             regex_res = regex_intlink.exec(string);
494             while (regex_res != null) {
495                 var res_model = regex_res[2] + '.' + regex_res[3];
496                 var res_name = regex_res[4];
497                 if (! (res_model in this.map_hash)) { this.map_hash[res_model]['name'] = []; }
498                 this.map_hash[res_model]['name'].push(res_name);
499                 regex_res = regex_intlink.exec(string);
500             }
501         },
502         
503         /** checks if tue current user is the message author */
504         _is_author: function (id) {
505             return (this.session.uid == id);
506         },
507
508     });
509     session.web.form.widgets.add( 'Thread', 'openerp.mail.Thread');
510
511     /** ThreadView widget: thread of comments */
512     mail.RecordThread = session.web.form.AbstractField.extend({
513         template: 'mail.RecordThread',
514
515        init: function() {
516             this._super.apply(this, arguments);
517             this.see_subscribers = true;
518             this.thread = null;
519             this.params = this.get_definition_options();
520             this.params.thread_level = this.params.thread_level || 0;
521             // datasets
522             this.ds = new session.web.DataSet(this, this.view.model);
523             this.ds_users = new session.web.DataSet(this, 'res.users');
524         },
525
526         start: function() {
527             this._super.apply(this, arguments);
528             var self = this;
529             // bind buttons
530             this.$element.find('button.oe_mail_button_followers').click(function () { self.do_toggle_followers(); }).hide();
531             this.$element.find('button.oe_mail_button_follow').click(function () { self.do_follow(); })
532                 .mouseover(function () { $(this).html('Follow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
533                 .mouseleave(function () { $(this).html('Not following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
534             this.$element.find('button.oe_mail_button_unfollow').click(function () { self.do_unfollow(); })
535                 .mouseover(function () { $(this).html('Unfollow').removeClass('oe_mail_button_mouseout').addClass('oe_mail_button_mouseover'); })
536                 .mouseleave(function () { $(this).html('Following').removeClass('oe_mail_button_mouseover').addClass('oe_mail_button_mouseout'); });
537             this.reinit();
538         },
539
540         destroy: function () {
541             this._super.apply(this, arguments);
542         },
543         
544         reinit: function() {
545             this.see_subscribers = true;
546             this.$element.find('button.oe_mail_button_followers').html('Hide followers')
547             this.$element.find('button.oe_mail_button_follow').hide();
548             this.$element.find('button.oe_mail_button_unfollow').hide();
549         },
550         
551         set_value: function() {
552             this._super.apply(this, arguments);
553             var self = this;
554             this.reinit();
555             if (! this.view.datarecord.id) { this.$element.find('.oe_mail_thread').hide(); return; }
556             // fetch followers
557             var fetch_sub_done = this.fetch_subscribers();
558             // create and render Thread widget
559             this.$element.find('div.oe_mail_recthread_left').empty();
560             if (this.thread) this.thread.destroy();
561             this.thread = new mail.Thread(this, {'res_model': this.view.model, 'res_id': this.view.datarecord.id, 'uid': this.session.uid,
562                                                     'thread_level': this.params.thread_level, 'show_post_comment': true, 'limit': 15});
563             var thread_done = this.thread.appendTo(this.$element.find('div.oe_mail_recthread_left'));
564             return fetch_sub_done && thread_done;
565         },
566         
567         fetch_subscribers: function () {
568             return this.ds.call('message_get_subscribers', [[this.view.datarecord.id]]).then(this.proxy('display_subscribers'));
569         },
570         
571         display_subscribers: function (records) {
572             var self = this;
573             this.is_subscriber = false;
574             var user_list = this.$element.find('ul.oe_mail_followers_display').empty();
575             this.$element.find('div.oe_mail_recthread_followers h4').html('Followers (' + records.length + ')');
576             _(records).each(function (record) {
577                 if (record.id == self.session.uid) { self.is_subscriber = true; }
578                 var mini_url = self.thread_get_avatar('res.users', 'image_small', record.id);
579                 $('<li><img class="oe_mail_oe_left oe_mail_msg_image" src="' + mini_url + '"/>' +
580                   '<a href="#" class="oe_mail_internal_link" data-res-model="res.users" data-res-id="' + record.id + '">' + record.name + '</a></li>').appendTo(user_list);
581             });
582             if (self.is_subscriber) {
583                 self.$element.find('button.oe_mail_button_follow').hide();
584                 self.$element.find('button.oe_mail_button_unfollow').show(); }
585             else {
586                 self.$element.find('button.oe_mail_button_follow').show();
587                 self.$element.find('button.oe_mail_button_unfollow').hide(); }
588         },
589         
590         do_follow: function () {
591             return this.ds.call('message_subscribe', [[this.view.datarecord.id]]).pipe(this.proxy('fetch_subscribers'));
592         },
593         
594         do_unfollow: function () {
595             var self = this;
596             return this.ds.call('message_unsubscribe', [[this.view.datarecord.id]]).then(function (record) {
597                 if (record == false) self.do_notify("Impossible to unsubscribe", "You are automatically subscribed to this record. You cannot unsubscribe.");
598                 }).pipe(this.proxy('fetch_subscribers'));
599         },
600         
601         do_toggle_followers: function () {
602             this.see_subscribers = ! this.see_subscribers;
603             if (this.see_subscribers) { this.$element.find('button.oe_mail_button_followers').html('Hide followers'); }
604             else { this.$element.find('button.oe_mail_button_followers').html('Display followers'); }
605             this.$element.find('div.oe_mail_recthread_followers').toggle();
606         },
607         
608         thread_get_avatar: function(model, field, id) {
609             return this.session.prefix + '/web/binary/image?session_id=' + this.session.session_id + '&model=' + model + '&field=' + field + '&id=' + (id || '');
610         },
611     });
612     session.web.form.widgets.add( 'ThreadView', 'openerp.mail.RecordThread');
613
614     /** WallView widget: a wall of messages */
615     mail.WallView = session.web.Widget.extend({
616         template: 'mail.Wall',
617
618         /**
619          * @param {Object} parent parent
620          * @param {Object} [params]
621          * @param {Number} [params.limit=20] number of messages to show and fetch
622          * @param {Number} [params.search_view_id=false] search view id for messages
623          * @var {Array} sorted_comments records sorted by res_model and res_id
624          *                  records.res_model = {res_ids}
625          *                  records.res_model.res_id = [records]
626          */
627         init: function (parent, params) {
628             this._super(parent);
629             this.params = {};
630             this.params.limit = params.limit || 25;
631             this.params.domain = params.domain || [];
632             this.params.context = params.context || {};
633             this.params.search_view_id = params.search_view_id || false;
634             this.params.thread_level = params.thread_level || 1;
635             this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
636             this.display_show_more = true;
637             this.thread_list = [];
638             this.search = {'domain': [], 'context': {}, 'groupby': {}}
639             this.search_results = {'domain': [], 'context': {}, 'groupby': {}}
640             // datasets
641             this.ds_msg = new session.web.DataSet(this, 'mail.message');
642             this.ds_thread = new session.web.DataSet(this, 'mail.thread');
643             this.ds_users = new session.web.DataSet(this, 'res.users');
644         },
645
646         start: function () {
647             this._super.apply(this, arguments);
648             var self = this;
649             // add events
650             this.add_event_handlers();
651             // load mail.message search view
652             var search_view_ready = this.load_search_view(this.params.search_view_id, {}, false);
653             // fetch first threads
654             var comments_ready = this.init_and_fetch_comments(this.params.limit, 0);
655             return (search_view_ready && comments_ready);
656         },
657         
658         stop: function () {
659             this._super.apply(this, arguments);
660         },
661         
662         /** Add events */
663         add_event_handlers: function () {
664             var self = this;
665             // post a comment
666             this.$element.find('.oe_mail_wall_action button').click(function () { return self.do_comment(); });
667             // display more threads
668             this.$element.find('button.oe_mail_wall_button_more').click(function () { return self.do_more(); });
669         },
670
671         /**
672          * Loads the mail.message search view
673          * @param {Number} view_id id of the search view to load
674          * @param {Object} defaults ??
675          * @param {Boolean} hidden some kind of trick we do not care here
676          */
677         load_search_view: function (view_id, defaults, hidden) {
678             var self = this;
679             this.searchview = new session.web.SearchView(this, this.ds_msg, view_id || false, defaults || {}, hidden || false);
680             var search_view_loaded = this.searchview.appendTo(this.$element.find('.oe_view_manager_view_search'));
681             return $.when(search_view_loaded).then(function () {
682                 self.searchview.on_search.add(self.do_searchview_search);
683             });
684         },
685
686         /**
687          * Aggregate the domains, contexts and groupbys in parameter
688          * with those from search form, and then calls fetch_comments
689          * to actually fetch comments
690          * @param {Array} domains
691          * @param {Array} contexts
692          * @param {Array} groupbys
693          */
694         do_searchview_search: function(domains, contexts, groupbys) {
695             var self = this;
696             this.rpc('/web/session/eval_domain_and_context', {
697                 domains: domains || [],
698                 contexts: contexts || [],
699                 group_by_seq: groupbys || []
700             }, function (results) {
701                 self.search_results['context'] = results.context;
702                 self.search_results['domain'] = results.domain;
703                 self.search_results['groupby'] = results.group_by;
704                 return self.init_and_fetch_comments();
705             });
706         },
707
708         /**
709          * Initializes the wall and calls fetch_comments
710          * @param {Number} limit: number of notifications to fetch
711          * @param {Number} offset: offset in notifications search
712          * @param {Array} domain
713          * @param {Array} context
714          */
715         init_and_fetch_comments: function() {
716             this.search['domain'] = _.union(this.params.domain, this.search_results.domain);
717             this.search['context'] = _.extend(this.params.context, this.search_results.context);
718             this.display_show_more = true;
719             this.comments_structure = {'root_ids': [], 'new_root_ids': [], 'msgs': {}, 'tree_struct': {}, 'model_to_root_ids': {}};
720             this.$element.find('ul.oe_mail_wall_threads').empty();
721             return this.fetch_comments(this.params.limit, 0);
722         },
723
724         /**
725          * Fetches wall messages
726          * @param {Number} limit: number of notifications to fetch
727          * @param {Number} offset: offset in notifications search
728          * @param {Array} domain
729          * @param {Array} context
730          */
731         fetch_comments: function (limit, offset, additional_domain, additional_context) {
732             var self = this;
733             if (additional_domain) var fetch_domain = this.search['domain'].concat(additional_domain);
734             else var fetch_domain = this.search['domain'];
735             if (additional_context) var fetch_context = _.extend(this.search['context'], additional_context);
736             else var fetch_context = this.search['context'];
737             return this.ds_thread.call('get_pushed_messages', 
738                 [[this.session.uid], (limit || 0), (offset || 0), fetch_domain, true, [], fetch_context]).then(this.proxy('display_comments'));
739         },
740
741         /**
742          * @param {Array} records records to show in threads
743          */
744         display_comments: function (records) {
745             var self = this;
746             this.do_update_show_more(records.length >= self.params.limit);
747             this.sort_comments(records);
748             _(this.comments_structure['new_root_ids']).each(function (root_id) {
749                 var records = self.comments_structure.tree_struct[root_id]['for_thread_msgs'];
750                 var model_name = self.comments_structure.msgs[root_id]['model'];
751                 var res_id = self.comments_structure.msgs[root_id]['res_id'];
752                 var render_res = session.web.qweb.render('mail.WallThreadContainer', {});
753                 $('<li class="oe_mail_wall_thread">').html(render_res).appendTo(self.$element.find('ul.oe_mail_wall_threads'));
754                 var thread = new mail.Thread(self, {
755                     'res_model': model_name, 'res_id': res_id, 'uid': self.session.uid, 'records': records,
756                     'parent_id': false, 'thread_level': self.params.thread_level, 'show_hide': true}
757                     );
758                 self.thread_list.push(thread);
759                 return thread.appendTo(self.$element.find('li.oe_mail_wall_thread:last'));
760             });
761             // update TODO
762             this.comments_structure['root_ids'] = _.union(this.comments_structure['root_ids'], this.comments_structure['new_root_ids']);
763             this.comments_structure['new_root_ids'] = [];
764         },
765
766         /**
767          * Add records to comments_structure object: see function for details
768          */
769         sort_comments: function(records) {
770             tools_sort_comments(this.comments_structure, records, false);
771         },
772
773         /**
774          * Create a domain to fetch new comments according to
775          * comments already present in sorted_comments
776          * - for each model:
777          * -- should not be child of already displayed ids
778          * @param {Object} sorted_comments (see sort_comments)
779          * @returns {Array} fetch_domain (OpenERP domain style)
780          */
781         get_fetch_domain: function () {
782             var self = this;
783             var model_to_root = {};
784             var fetch_domain = [];
785             _(this.comments_structure['model_to_root_ids']).each(function (sc_model, model_name) {
786                 fetch_domain.push('|', ['model', '!=', model_name], '!', ['id', 'child_of', sc_model]);
787             });
788             return fetch_domain;
789         },
790         
791         /** Display update: show more button */
792         do_update_show_more: function (new_value) {
793             if (new_value != undefined) this.display_show_more = new_value;
794             if (this.display_show_more) this.$element.find('div.oe_mail_wall_more:last').show();
795             else this.$element.find('div.oe_mail_wall_more:last').hide();
796         },
797         
798         /** Action: Shows more discussions */
799         do_more: function () {
800             var domain = this.get_fetch_domain();
801             return this.fetch_comments(this.params.limit, 0, domain);
802         },
803         
804         /** Action: Posts a comment */
805         do_comment: function () {
806             var comment_node = this.$element.find('.oe_mail_wall_action textarea');
807             var body_text = comment_node.val();
808             comment_node.val('');
809             var call_done = this.ds_users.call('message_append_note', [[this.session.uid], 'Tweet', body_text, false, 'comment', 'html']).then(this.proxy('init_and_fetch_comments'));
810         },
811     });
812     session.web.client_actions.add('mail.all_feeds', 'session.mail.WallView');
813
814 };
815
816 // vim:et fdc=0 fdl=0 foldnestmax=3 fdm=syntax: