You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1418 lines
52 KiB

  1. odoo.define('mail_base.base', function (require) {
  2. "use strict";
  3. var bus = require('bus.bus').bus;
  4. var utils = require('mail.utils');
  5. var config = require('web.config');
  6. var Bus = require('web.Bus');
  7. var core = require('web.core');
  8. var session = require('web.session');
  9. var time = require('web.time');
  10. var web_client = require('web.web_client');
  11. var Class = require('web.Class');
  12. var Mixins = require('web.mixins');
  13. var ServicesMixin = require('web.ServicesMixin');
  14. var _t = core._t;
  15. var _lt = core._lt;
  16. var LIMIT = 25;
  17. var preview_msg_max_size = 350; // optimal for native english speakers
  18. var ODOOBOT_ID = "ODOOBOT";
  19. var chat_manager = require('mail.chat_manager');
  20. // Private model
  21. //----------------------------------------------------------------------------------
  22. var messages = [];
  23. var channels = [];
  24. var channels_preview_def;
  25. var channel_defs = {};
  26. var chat_unread_counter = 0;
  27. var unread_conversation_counter = 0;
  28. var emojis = [];
  29. var emoji_substitutions = {};
  30. var emoji_unicodes = {};
  31. var needaction_counter = 0;
  32. var starred_counter = 0;
  33. var mention_partner_suggestions = [];
  34. var canned_responses = [];
  35. var commands = [];
  36. var discuss_menu_id;
  37. var global_unread_counter = 0;
  38. var pinned_dm_partners = []; // partner_ids we have a pinned DM with
  39. var client_action_open = false;
  40. // Global unread counter and notifications
  41. //----------------------------------------------------------------------------------
  42. bus.on("window_focus", null, function() {
  43. global_unread_counter = 0;
  44. web_client.set_title_part("_chat");
  45. });
  46. var ChatAction = core.action_registry.get('mail.chat.instant_messaging');
  47. ChatAction.include({
  48. init: function (parent, action, options) {
  49. this._super.apply(this, arguments);
  50. this.channels_show_send_button = ['channel_inbox'];
  51. this.channels_display_subject = [];
  52. },
  53. start: function () {
  54. var result = this._super.apply(this, arguments);
  55. var search_defaults = {};
  56. var context = this.action ? this.action.context : [];
  57. _.each(context, function (value, key) {
  58. var match = /^search_default_(.*)$/.exec(key);
  59. if (match) {
  60. search_defaults[match[1]] = value;
  61. }
  62. });
  63. this.searchview.defaults = search_defaults;
  64. var self = this;
  65. return $.when(result).done(function () {
  66. $('.oe_leftbar').toggle(false);
  67. self.searchview.do_search();
  68. });
  69. },
  70. destroy: function() {
  71. var result = this._super.apply(this, arguments);
  72. $('.oe_leftbar .oe_secondary_menu').each(function () {
  73. if ($(this).css('display') == 'block'){
  74. if ($(this).children().length > 0) {
  75. $('.oe_leftbar').toggle(true);
  76. }
  77. return false;
  78. }
  79. });
  80. return result;
  81. },
  82. set_channel: function (channel) {
  83. var result = this._super.apply(this, arguments);
  84. var self = this;
  85. return $.when(result).done(function() {
  86. self.$buttons
  87. .find('.o_mail_chat_button_new_message')
  88. .toggle(self.channels_show_send_button.indexOf(channel.id) != -1);
  89. });
  90. },
  91. get_thread_rendering_options: function (messages) {
  92. var options = this._super.apply(this, arguments);
  93. options.display_subject = options.display_subject || this.channels_display_subject.indexOf(this.channel.id) != -1;
  94. return options;
  95. },
  96. update_message_on_current_channel: function (current_channel_id, message) {
  97. var starred = current_channel_id === "channel_starred" && !message.is_starred;
  98. var inbox = current_channel_id === "channel_inbox" && !message.is_needaction;
  99. return starred || inbox;
  100. },
  101. on_update_message: function (message) {
  102. var self = this;
  103. var current_channel_id = this.channel.id;
  104. if (this.update_message_on_current_channel(current_channel_id, message)) {
  105. chat_manager.get_messages({channel_id: this.channel.id, domain: this.domain}).then(function (messages) {
  106. var options = self.get_thread_rendering_options(messages);
  107. self.thread.remove_message_and_render(message.id, messages, options).then(function () {
  108. self.update_button_status(messages.length === 0);
  109. });
  110. });
  111. } else if (_.contains(message.channel_ids, current_channel_id)) {
  112. this.fetch_and_render_thread();
  113. }
  114. }
  115. });
  116. chat_manager.notify_incoming_message = function (msg, options) {
  117. if (bus.is_odoo_focused() && options.is_displayed) {
  118. // no need to notify
  119. return;
  120. }
  121. var title = _t('New message');
  122. if (msg.author_id[1]) {
  123. title = _.escape(msg.author_id[1]);
  124. }
  125. var content = utils.parse_and_transform(msg.body, utils.strip_html).substr(0, preview_msg_max_size);
  126. if (!bus.is_odoo_focused()) {
  127. global_unread_counter++;
  128. var tab_title = _.str.sprintf(_t("%d Messages"), global_unread_counter);
  129. web_client.set_title_part("_chat", tab_title);
  130. }
  131. utils.send_notification(web_client, title, content);
  132. }
  133. // Message and channel manipulation helpers
  134. //----------------------------------------------------------------------------------
  135. // options: channel_id, silent
  136. chat_manager.add_message = function (data, options) {
  137. options = options || {};
  138. var msg = _.findWhere(messages, { id: data.id });
  139. if (!msg) {
  140. msg = chat_manager.make_message(data);
  141. // Keep the array ordered by id when inserting the new message
  142. messages.splice(_.sortedIndex(messages, msg, 'id'), 0, msg);
  143. _.each(msg.channel_ids, function (channel_id) {
  144. var channel = chat_manager.get_channel(channel_id);
  145. if (channel) {
  146. // update the channel's last message (displayed in the channel
  147. // preview, in mobile)
  148. if (!channel.last_message || msg.id > channel.last_message.id) {
  149. channel.last_message = msg;
  150. }
  151. chat_manager.add_to_cache(msg, []);
  152. if (options.domain && options.domain !== []) {
  153. chat_manager.add_to_cache(msg, options.domain);
  154. }
  155. if (channel.hidden) {
  156. channel.hidden = false;
  157. chat_manager.bus.trigger('new_channel', channel);
  158. }
  159. if (channel.type !== 'static' && !msg.is_author && !msg.is_system_notification) {
  160. if (options.increment_unread) {
  161. chat_manager.update_channel_unread_counter(channel, channel.unread_counter+1);
  162. }
  163. if (channel.is_chat && options.show_notification) {
  164. if (!client_action_open && !config.device.isMobile) {
  165. // automatically open chat window
  166. chat_manager.bus.trigger('open_chat', channel, { passively: true });
  167. }
  168. var query = {is_displayed: false};
  169. chat_manager.bus.trigger('anyone_listening', channel, query);
  170. chat_manager.notify_incoming_message(msg, query);
  171. }
  172. }
  173. }
  174. });
  175. if (!options.silent) {
  176. chat_manager.bus.trigger('new_message', msg);
  177. }
  178. } else if (options.domain && options.domain !== []) {
  179. chat_manager.add_to_cache(msg, options.domain);
  180. }
  181. return msg;
  182. }
  183. chat_manager.get_channel_array = function(msg){
  184. return [ msg.channel_ids, 'channel_inbox', 'channel_starred' ];
  185. }
  186. chat_manager.get_properties = function(msg){
  187. return {
  188. is_starred: chat_manager.property_descr("channel_starred", msg, chat_manager),
  189. is_needaction: chat_manager.property_descr("channel_inbox", msg, chat_manager)
  190. };
  191. }
  192. chat_manager.property_descr = function (channel, msg, self) {
  193. return {
  194. enumerable: true,
  195. get: function () {
  196. return _.contains(msg.channel_ids, channel);
  197. },
  198. set: function (bool) {
  199. if (bool) {
  200. chat_manager.add_channel_to_message(msg, channel);
  201. } else {
  202. msg.channel_ids = _.without(msg.channel_ids, channel);
  203. }
  204. }
  205. };
  206. }
  207. chat_manager.set_channel_flags = function (data, msg) {
  208. if (_.contains(data.needaction_partner_ids, session.partner_id)) {
  209. msg.is_needaction = true;
  210. }
  211. if (_.contains(data.starred_partner_ids, session.partner_id)) {
  212. msg.is_starred = true;
  213. }
  214. return msg;
  215. }
  216. chat_manager.make_message = function (data) {
  217. var msg = {
  218. id: data.id,
  219. author_id: data.author_id,
  220. body: data.body || "",
  221. date: moment(time.str_to_datetime(data.date)),
  222. message_type: data.message_type,
  223. subtype_description: data.subtype_description,
  224. is_author: data.author_id && data.author_id[0] === session.partner_id,
  225. is_note: data.is_note,
  226. is_system_notification: (data.message_type === 'notification' && data.model === 'mail.channel')
  227. || data.info === 'transient_message',
  228. attachment_ids: data.attachment_ids || [],
  229. subject: data.subject,
  230. email_from: data.email_from,
  231. customer_email_status: data.customer_email_status,
  232. customer_email_data: data.customer_email_data,
  233. record_name: data.record_name,
  234. tracking_value_ids: data.tracking_value_ids,
  235. channel_ids: data.channel_ids,
  236. model: data.model,
  237. res_id: data.res_id,
  238. url: session.url("/mail/view?message_id=" + data.id),
  239. module_icon:data.module_icon,
  240. };
  241. _.each(_.keys(emoji_substitutions), function (key) {
  242. var escaped_key = String(key).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1');
  243. var regexp = new RegExp("(?:^|\\s|<[a-z]*>)(" + escaped_key + ")(?=\\s|$|</[a-z]*>)", "g");
  244. msg.body = msg.body.replace(regexp, ' <span class="o_mail_emoji">'+emoji_substitutions[key]+'</span> ');
  245. });
  246. Object.defineProperties(msg, chat_manager.get_properties(msg));
  247. msg = chat_manager.set_channel_flags(data, msg);
  248. if (msg.model === 'mail.channel') {
  249. var real_channels = _.without(chat_manager.get_channel_array(msg));
  250. var origin = real_channels.length === 1 ? real_channels[0] : undefined;
  251. var channel = origin && chat_manager.get_channel(origin);
  252. if (channel) {
  253. msg.origin_id = origin;
  254. msg.origin_name = channel.name;
  255. }
  256. }
  257. // Compute displayed author name or email
  258. if ((!msg.author_id || !msg.author_id[0]) && msg.email_from) {
  259. msg.mailto = msg.email_from;
  260. } else {
  261. msg.displayed_author = (msg.author_id === ODOOBOT_ID) && "OdooBot" ||
  262. msg.author_id && msg.author_id[1] ||
  263. msg.email_from || _t('Anonymous');
  264. }
  265. // Don't redirect on author clicked of self-posted or OdooBot messages
  266. msg.author_redirect = !msg.is_author && msg.author_id !== ODOOBOT_ID;
  267. // Compute the avatar_url
  268. if (msg.author_id === ODOOBOT_ID) {
  269. msg.avatar_src = "/mail/static/src/img/odoo_o.png";
  270. } else if (msg.author_id && msg.author_id[0]) {
  271. msg.avatar_src = "/web/image/res.partner/" + msg.author_id[0] + "/image_small";
  272. } else if (msg.message_type === 'email') {
  273. msg.avatar_src = "/mail/static/src/img/email_icon.png";
  274. } else {
  275. msg.avatar_src = "/mail/static/src/img/smiley/avatar.jpg";
  276. }
  277. // add anchor tags to urls
  278. msg.body = utils.parse_and_transform(msg.body, utils.add_link);
  279. // Compute url of attachments
  280. _.each(msg.attachment_ids, function(a) {
  281. a.url = '/web/content/' + a.id + '?download=true';
  282. });
  283. // format date to the local only once by message
  284. // can not be done in preprocess, since it alter the original value
  285. if (msg.tracking_value_ids && msg.tracking_value_ids.length) {
  286. _.each(msg.tracking_value_ids, function(f) {
  287. if (f.field_type === 'datetime') {
  288. var format = 'LLL';
  289. if (f.old_value) {
  290. f.old_value = moment.utc(f.old_value).local().format(format);
  291. }
  292. if (f.new_value) {
  293. f.new_value = moment.utc(f.new_value).local().format(format);
  294. }
  295. } else if (f.field_type === 'date') {
  296. var format = 'LL';
  297. if (f.old_value) {
  298. f.old_value = moment(f.old_value).local().format(format);
  299. }
  300. if (f.new_value) {
  301. f.new_value = moment(f.new_value).local().format(format);
  302. }
  303. }
  304. });
  305. }
  306. return msg;
  307. }
  308. chat_manager.add_channel_to_message = function (message, channel_id) {
  309. message.channel_ids.push(channel_id);
  310. message.channel_ids = _.uniq(message.channel_ids);
  311. }
  312. chat_manager.add_channel = function (data, options) {
  313. options = typeof options === "object" ? options : {};
  314. var channel = chat_manager.get_channel(data.id);
  315. if (channel) {
  316. if (channel.is_folded !== (data.state === "folded")) {
  317. channel.is_folded = (data.state === "folded");
  318. chat_manager.bus.trigger("channel_toggle_fold", channel);
  319. }
  320. } else {
  321. channel = chat_manager.make_channel(data, options);
  322. channels.push(channel);
  323. if (data.last_message) {
  324. channel.last_message = chat_manager.add_message(data.last_message);
  325. }
  326. // In case of a static channel (Inbox, Starred), the name is translated thanks to _lt
  327. // (lazy translate). In this case, channel.name is an object, not a string.
  328. channels = _.sortBy(channels, function (channel) { return _.isString(channel.name) ? channel.name.toLowerCase() : '' });
  329. if (!options.silent) {
  330. chat_manager.bus.trigger("new_channel", channel);
  331. }
  332. if (channel.is_detached) {
  333. chat_manager.bus.trigger("open_chat", channel);
  334. }
  335. }
  336. return channel;
  337. }
  338. chat_manager.make_channel = function (data, options) {
  339. var channel = {
  340. id: data.id,
  341. name: data.name,
  342. server_type: data.channel_type,
  343. type: data.type || data.channel_type,
  344. all_history_loaded: false,
  345. uuid: data.uuid,
  346. is_detached: data.is_minimized,
  347. is_folded: data.state === "folded",
  348. autoswitch: 'autoswitch' in options ? options.autoswitch : true,
  349. hidden: options.hidden,
  350. display_needactions: options.display_needactions,
  351. mass_mailing: data.mass_mailing,
  352. group_based_subscription: data.group_based_subscription,
  353. needaction_counter: data.message_needaction_counter || 0,
  354. unread_counter: 0,
  355. last_seen_message_id: data.seen_message_id,
  356. cache: {'[]': {
  357. all_history_loaded: false,
  358. loaded: false,
  359. messages: [],
  360. }},
  361. };
  362. if (channel.type === "channel") {
  363. channel.type = data.public !== "private" ? "public" : "private";
  364. }
  365. if (_.size(data.direct_partner) > 0) {
  366. channel.type = "dm";
  367. channel.name = data.direct_partner[0].name;
  368. channel.direct_partner_id = data.direct_partner[0].id;
  369. channel.status = data.direct_partner[0].im_status;
  370. pinned_dm_partners.push(channel.direct_partner_id);
  371. bus.update_option('bus_presence_partner_ids', pinned_dm_partners);
  372. } else if ('anonymous_name' in data) {
  373. channel.name = data.anonymous_name;
  374. }
  375. if (data.last_message_date) {
  376. channel.last_message_date = moment(time.str_to_datetime(data.last_message_date));
  377. }
  378. channel.is_chat = !channel.type.match(/^(public|private|static)$/);
  379. if (data.message_unread_counter) {
  380. chat_manager.update_channel_unread_counter(channel, data.message_unread_counter);
  381. }
  382. return channel;
  383. }
  384. chat_manager.remove_channel = function (channel) {
  385. if (!channel) { return; }
  386. if (channel.type === 'dm') {
  387. var index = pinned_dm_partners.indexOf(channel.direct_partner_id);
  388. if (index > -1) {
  389. pinned_dm_partners.splice(index, 1);
  390. bus.update_option('bus_presence_partner_ids', pinned_dm_partners);
  391. }
  392. }
  393. channels = _.without(channels, channel);
  394. delete channel_defs[channel.id];
  395. }
  396. chat_manager.get_channel_cache = function (channel, domain) {
  397. var stringified_domain = JSON.stringify(domain || []);
  398. if (!channel.cache[stringified_domain]) {
  399. channel.cache[stringified_domain] = {
  400. all_history_loaded: false,
  401. loaded: false,
  402. messages: [],
  403. };
  404. }
  405. return channel.cache[stringified_domain];
  406. }
  407. chat_manager.invalidate_caches = function (channel_ids) {
  408. _.each(channel_ids, function (channel_id) {
  409. var channel = chat_manager.get_channel(channel_id);
  410. if (channel) {
  411. channel.cache = { '[]': channel.cache['[]']};
  412. }
  413. });
  414. }
  415. chat_manager.add_to_cache = function (message, domain) {
  416. _.each(message.channel_ids, function (channel_id) {
  417. var channel = chat_manager.get_channel(channel_id);
  418. if (channel) {
  419. var channel_cache = chat_manager.get_channel_cache(channel, domain);
  420. var index = _.sortedIndex(channel_cache.messages, message, 'id');
  421. if (channel_cache.messages[index] !== message) {
  422. channel_cache.messages.splice(index, 0, message);
  423. }
  424. }
  425. });
  426. }
  427. chat_manager.remove_message_from_channel = function (channel_id, message) {
  428. message.channel_ids = _.without(message.channel_ids, channel_id);
  429. var channel = _.findWhere(channels, { id: channel_id });
  430. _.each(channel.cache, function (cache) {
  431. cache.messages = _.without(cache.messages, message);
  432. });
  433. }
  434. chat_manager.update_channel_unread_counter = function (channel, counter) {
  435. if (channel.unread_counter > 0 && counter === 0) {
  436. unread_conversation_counter = Math.max(0, unread_conversation_counter-1);
  437. } else if (channel.unread_counter === 0 && counter > 0) {
  438. unread_conversation_counter++;
  439. }
  440. if (channel.is_chat) {
  441. chat_unread_counter = Math.max(0, chat_unread_counter - channel.unread_counter + counter);
  442. }
  443. channel.unread_counter = counter;
  444. chat_manager.bus.trigger("update_channel_unread_counter", channel);
  445. }
  446. // Notification handlers
  447. // ---------------------------------------------------------------------------------
  448. chat_manager.on_notification = function (notifications) {
  449. // sometimes, the web client receives unsubscribe notification and an extra
  450. // notification on that channel. This is then followed by an attempt to
  451. // rejoin the channel that we just left. The next few lines remove the
  452. // extra notification to prevent that situation to occur.
  453. var unsubscribed_notif = _.find(notifications, function (notif) {
  454. return notif[1].info === "unsubscribe";
  455. });
  456. if (unsubscribed_notif) {
  457. notifications = _.reject(notifications, function (notif) {
  458. return notif[0][1] === "mail.channel" && notif[0][2] === unsubscribed_notif[1].id;
  459. });
  460. }
  461. _.each(notifications, function (notification) {
  462. var model = notification[0][1];
  463. if (model === 'ir.needaction') {
  464. // new message in the inbox
  465. chat_manager.on_needaction_notification(notification[1]);
  466. } else if (model === 'mail.channel') {
  467. // new message in a channel
  468. chat_manager.on_channel_notification(notification[1]);
  469. } else if (model === 'res.partner') {
  470. // channel joined/left, message marked as read/(un)starred, chat open/closed
  471. chat_manager.on_partner_notification(notification[1]);
  472. } else if (model === 'bus.presence') {
  473. // update presence of users
  474. chat_manager.on_presence_notification(notification[1]);
  475. }
  476. });
  477. }
  478. chat_manager.on_needaction_notification = function (message) {
  479. message = chat_manager.add_message(message, {
  480. channel_id: 'channel_inbox',
  481. show_notification: true,
  482. increment_unread: true,
  483. });
  484. chat_manager.invalidate_caches(message.channel_ids);
  485. if (message.channel_ids.length !== 0) {
  486. needaction_counter++;
  487. }
  488. _.each(message.channel_ids, function (channel_id) {
  489. var channel = chat_manager.get_channel(channel_id);
  490. if (channel) {
  491. channel.needaction_counter++;
  492. }
  493. });
  494. chat_manager.bus.trigger('update_needaction', needaction_counter);
  495. }
  496. chat_manager.on_channel_notification = function (message) {
  497. var def;
  498. var channel_already_in_cache = true;
  499. if (message.channel_ids.length === 1) {
  500. channel_already_in_cache = !!chat_manager.get_channel(message.channel_ids[0]);
  501. def = chat_manager.join_channel(message.channel_ids[0], {autoswitch: false});
  502. } else {
  503. def = $.when();
  504. }
  505. def.then(function () {
  506. // don't increment unread if channel wasn't in cache yet as its unread counter has just been fetched
  507. chat_manager.add_message(message, { show_notification: true, increment_unread: channel_already_in_cache });
  508. chat_manager.invalidate_caches(message.channel_ids);
  509. });
  510. }
  511. chat_manager.on_partner_notification = function (data) {
  512. if (data.info === "unsubscribe") {
  513. var channel = chat_manager.get_channel(data.id);
  514. if (channel) {
  515. var msg;
  516. if (_.contains(['public', 'private'], channel.type)) {
  517. msg = _.str.sprintf(_t('You unsubscribed from <b>%s</b>.'), channel.name);
  518. } else {
  519. msg = _.str.sprintf(_t('You unpinned your conversation with <b>%s</b>.'), channel.name);
  520. }
  521. chat_manager.remove_channel(channel);
  522. chat_manager.bus.trigger("unsubscribe_from_channel", data.id);
  523. web_client.do_notify(_("Unsubscribed"), msg);
  524. }
  525. } else if (data.type === 'toggle_star') {
  526. chat_manager.on_toggle_star_notification(data);
  527. } else if (data.type === 'mark_as_read') {
  528. chat_manager.on_mark_as_read_notification(data);
  529. } else if (data.type === 'mark_as_unread') {
  530. chat_manager.on_mark_as_unread_notification(data);
  531. } else if (data.info === 'channel_seen') {
  532. chat_manager.on_channel_seen_notification(data);
  533. } else if (data.info === 'transient_message') {
  534. chat_manager.on_transient_message_notification(data);
  535. } else if (data.type === 'activity_updated') {
  536. chat_manager.onActivityUpdateNodification(data);
  537. } else {
  538. chat_manager.on_chat_session_notification(data);
  539. }
  540. }
  541. chat_manager.on_toggle_star_notification = function (data) {
  542. _.each(data.message_ids, function (msg_id) {
  543. var message = _.findWhere(messages, { id: msg_id });
  544. if (message) {
  545. chat_manager.invalidate_caches(message.channel_ids);
  546. message.is_starred = data.starred;
  547. if (!message.is_starred) {
  548. chat_manager.remove_message_from_channel("channel_starred", message);
  549. starred_counter--;
  550. } else {
  551. chat_manager.add_to_cache(message, []);
  552. var channel_starred = chat_manager.get_channel('channel_starred');
  553. channel_starred.cache = _.pick(channel_starred.cache, "[]");
  554. starred_counter++;
  555. }
  556. chat_manager.bus.trigger('update_message', message);
  557. }
  558. });
  559. chat_manager.bus.trigger('update_starred', starred_counter);
  560. }
  561. chat_manager.on_mark_as_read_notification = function (data) {
  562. _.each(data.message_ids, function (msg_id) {
  563. var message = _.findWhere(messages, { id: msg_id });
  564. if (message) {
  565. chat_manager.invalidate_caches(message.channel_ids);
  566. chat_manager.remove_message_from_channel("channel_inbox", message);
  567. chat_manager.bus.trigger('update_message', message, data.type);
  568. }
  569. });
  570. if (data.channel_ids) {
  571. _.each(data.channel_ids, function (channel_id) {
  572. var channel = chat_manager.get_channel(channel_id);
  573. if (channel) {
  574. channel.needaction_counter = Math.max(channel.needaction_counter - data.message_ids.length, 0);
  575. }
  576. });
  577. } else { // if no channel_ids specified, this is a 'mark all read' in the inbox
  578. _.each(channels, function (channel) {
  579. channel.needaction_counter = 0;
  580. });
  581. }
  582. needaction_counter = Math.max(needaction_counter - data.message_ids.length, 0);
  583. chat_manager.bus.trigger('update_needaction', needaction_counter);
  584. }
  585. chat_manager.on_mark_as_unread_notification = function (data) {
  586. _.each(data.message_ids, function (message_id) {
  587. var message = _.findWhere(messages, { id: message_id });
  588. if (message) {
  589. chat_manager.invalidate_caches(message.channel_ids);
  590. chat_manager.add_channel_to_message(message, 'channel_inbox');
  591. chat_manager.add_to_cache(message, []);
  592. }
  593. });
  594. var channel_inbox = chat_manager.get_channel('channel_inbox');
  595. channel_inbox.cache = _.pick(channel_inbox.cache, "[]");
  596. _.each(data.channel_ids, function (channel_id) {
  597. var channel = chat_manager.get_channel(channel_id);
  598. if (channel) {
  599. channel.needaction_counter += data.message_ids.length;
  600. }
  601. });
  602. needaction_counter += data.message_ids.length;
  603. chat_manager.bus.trigger('update_needaction', needaction_counter);
  604. }
  605. chat_manager.on_channel_seen_notification = function (data) {
  606. var channel = chat_manager.get_channel(data.id);
  607. if (channel) {
  608. channel.last_seen_message_id = data.last_message_id;
  609. if (channel.unread_counter) {
  610. chat_manager.update_channel_unread_counter(channel, 0);
  611. }
  612. }
  613. }
  614. chat_manager.on_chat_session_notification = function (chat_session) {
  615. var channel;
  616. if ((chat_session.channel_type === "channel") && (chat_session.state === "open")) {
  617. chat_manager.add_channel(chat_session, {autoswitch: false});
  618. if (!chat_session.is_minimized && chat_session.info !== 'creation') {
  619. web_client.do_notify(_t("Invitation"), _t("You have been invited to: ") + chat_session.name);
  620. }
  621. }
  622. // partner specific change (open a detached window for example)
  623. if ((chat_session.state === "open") || (chat_session.state === "folded")) {
  624. channel = chat_session.is_minimized && chat_manager.get_channel(chat_session.id);
  625. if (channel) {
  626. channel.is_detached = true;
  627. channel.is_folded = (chat_session.state === "folded");
  628. chat_manager.bus.trigger("open_chat", channel);
  629. }
  630. } else if (chat_session.state === "closed") {
  631. channel = chat_manager.get_channel(chat_session.id);
  632. if (channel) {
  633. channel.is_detached = false;
  634. chat_manager.bus.trigger("close_chat", channel, {keep_open_if_unread: true});
  635. }
  636. }
  637. }
  638. chat_manager.on_presence_notification = function (data) {
  639. var dm = chat_manager.get_dm_from_partner_id(data.id);
  640. if (dm) {
  641. dm.status = data.im_status;
  642. chat_manager.bus.trigger('update_dm_presence', dm);
  643. }
  644. }
  645. chat_manager.on_transient_message_notification = function(data) {
  646. var last_message = _.last(messages);
  647. data.id = (last_message ? last_message.id : 0) + 0.01;
  648. data.author_id = data.author_id || ODOOBOT_ID;
  649. chat_manager.add_message(data);
  650. }
  651. chat_manager.onActivityUpdateNodification = function (data) {
  652. chat_manager.bus.trigger('activity_updated', data);
  653. }
  654. // Public interface
  655. //----------------------------------------------------------------------------------
  656. // chat_manager.init = function (parent) {
  657. // var self = this;
  658. // Mixins.EventDispatcherMixin.init.call(this);
  659. // this.setParent(parent);
  660. // this.bus = new Bus();
  661. // this.bus.on('client_action_open', null, function (open) {
  662. // client_action_open = open;
  663. // });
  664. // bus.on('notification', null, chat_manager.on_notification);
  665. // this.channel_seen = _.throttle(function (channel) {
  666. // return self._rpc({
  667. // model: 'mail.channel',
  668. // method: 'channel_seen',
  669. // args: [[channel.id]],
  670. // }, {
  671. // shadow: true
  672. // });
  673. // }, 3000);
  674. // }
  675. chat_manager.start = function () {
  676. var self = this;
  677. this.bus.on('client_action_open', null, function (open) {
  678. client_action_open = open;
  679. });
  680. this.is_ready = session.is_bound.then(function(){
  681. var context = _.extend({isMobile: config.device.isMobile}, session.user_context);
  682. return session.rpc('/mail/client_action', {context: context});
  683. }).then(chat_manager._onMailClientAction.bind(this));
  684. this.channel_seen = _.throttle(function (channel) {
  685. return self._rpc({
  686. model: 'mail.channel',
  687. method: 'channel_seen',
  688. args: [[channel.id]],
  689. }, {
  690. shadow: true
  691. });
  692. }, 3000);
  693. chat_manager.add_channel({
  694. id: "channel_inbox",
  695. name: _lt("Inbox"),
  696. type: "static",
  697. }, { display_needactions: true });
  698. chat_manager.add_channel({
  699. id: "channel_starred",
  700. name: _lt("Starred"),
  701. type: "static"
  702. });
  703. },
  704. chat_manager._onMailClientAction = function (result) {
  705. _.each(result.channel_slots, function (channels) {
  706. _.each(channels, chat_manager.add_channel);
  707. });
  708. needaction_counter = result.needaction_inbox_counter;
  709. starred_counter = result.starred_counter;
  710. commands = _.map(result.commands, function (command) {
  711. return _.extend({ id: command.name }, command);
  712. });
  713. mention_partner_suggestions = result.mention_partner_suggestions;
  714. discuss_menu_id = result.menu_id;
  715. // Shortcodes: canned responses and emojis
  716. _.each(result.shortcodes, function (s) {
  717. if (s.shortcode_type === 'text') {
  718. canned_responses.push(_.pick(s, ['id', 'source', 'substitution']));
  719. } else {
  720. emojis.push(_.pick(s, ['id', 'source', 'unicode_source', 'substitution', 'description']));
  721. emoji_substitutions[_.escape(s.source)] = s.substitution;
  722. if (s.unicode_source) {
  723. emoji_substitutions[_.escape(s.unicode_source)] = s.substitution;
  724. emoji_unicodes[_.escape(s.source)] = s.unicode_source;
  725. }
  726. }
  727. });
  728. bus.start_polling();
  729. }
  730. chat_manager.get_domain = function (channel) {
  731. return (channel.id === "channel_inbox") ? [['needaction', '=', true]] :
  732. (channel.id === "channel_starred") ? [['starred', '=', true]] : false;
  733. }
  734. // options: domain, load_more
  735. chat_manager._fetchFromChannel = function (channel, options) {
  736. options = options || {};
  737. var domain = chat_manager.get_domain(channel) || [['channel_ids', 'in', channel.id]];
  738. var cache = chat_manager.get_channel_cache(channel, options.domain);
  739. if (options.domain) {
  740. domain = domain.concat(options.domain || []);
  741. }
  742. if (options.load_more) {
  743. var min_message_id = cache.messages[0].id;
  744. domain = [['id', '<', min_message_id]].concat(domain);
  745. }
  746. return this._rpc({
  747. model: 'mail.message',
  748. method: 'message_fetch',
  749. args: [domain],
  750. kwargs: {limit: LIMIT, context: session.user_context},
  751. })
  752. .then(function (msgs) {
  753. if (!cache.all_history_loaded) {
  754. cache.all_history_loaded = msgs.length < LIMIT;
  755. }
  756. cache.loaded = true;
  757. _.each(msgs, function (msg) {
  758. chat_manager.add_message(msg, {channel_id: channel.id, silent: true, domain: options.domain});
  759. });
  760. var channel_cache = chat_manager.get_channel_cache(channel, options.domain || []);
  761. return channel_cache.messages;
  762. });
  763. }
  764. // options: force_fetch
  765. chat_manager._fetchDocumentMessages = function (ids, options) {
  766. var loaded_msgs = _.filter(messages, function (message) {
  767. return _.contains(ids, message.id);
  768. });
  769. var loaded_msg_ids = _.pluck(loaded_msgs, 'id');
  770. options = options || {};
  771. if (options.force_fetch || _.difference(ids.slice(0, LIMIT), loaded_msg_ids).length) {
  772. var ids_to_load = _.difference(ids, loaded_msg_ids).slice(0, LIMIT);
  773. return this._rpc({
  774. model: 'mail.message',
  775. method: 'message_format',
  776. args: [ids_to_load],
  777. context: session.user_context,
  778. })
  779. .then(function (msgs) {
  780. var processed_msgs = [];
  781. _.each(msgs, function (msg) {
  782. processed_msgs.push(chat_manager.add_message(msg, {silent: true}));
  783. });
  784. return _.sortBy(loaded_msgs.concat(processed_msgs), function (msg) {
  785. return msg.id;
  786. });
  787. });
  788. } else {
  789. return $.when(loaded_msgs);
  790. }
  791. },
  792. chat_manager.post_message = function (data, options) {
  793. var self = this;
  794. options = options || {};
  795. // This message will be received from the mail composer as html content subtype
  796. // but the urls will not be linkified. If the mail composer takes the responsibility
  797. // to linkify the urls we end up with double linkification a bit everywhere.
  798. // Ideally we want to keep the content as text internally and only make html
  799. // enrichment at display time but the current design makes this quite hard to do.
  800. var body = utils.parse_and_transform(_.str.trim(data.content), utils.add_link);
  801. var msg = {
  802. partner_ids: data.partner_ids,
  803. body: body,
  804. attachment_ids: data.attachment_ids,
  805. };
  806. // for module mail_private
  807. if (data.is_private) {
  808. msg.is_private = data.is_private;
  809. msg.channel_ids = data.channel_ids;
  810. }
  811. // Replace emojis by their unicode character
  812. _.each(_.keys(emoji_unicodes), function (key) {
  813. var escaped_key = String(key).replace(/([.*+?=^!:${}()|[\]\/\\])/g, '\\$1');
  814. var regexp = new RegExp("(\\s|^)(" + escaped_key + ")(?=\\s|$)", "g");
  815. msg.body = msg.body.replace(regexp, "$1" + emoji_unicodes[key]);
  816. });
  817. if ('subject' in data) {
  818. msg.subject = data.subject;
  819. }
  820. if ('channel_id' in options) {
  821. // post a message in a channel or execute a command
  822. return this._rpc({
  823. model: 'mail.channel',
  824. method: data.command ? 'execute_command' : 'message_post',
  825. args: [options.channel_id],
  826. kwargs: _.extend(msg, {
  827. message_type: 'comment',
  828. content_subtype: 'html',
  829. subtype: 'mail.mt_comment',
  830. command: data.command,
  831. }),
  832. });
  833. }
  834. if ('model' in options && 'res_id' in options) {
  835. // post a message in a chatter
  836. _.extend(msg, {
  837. content_subtype: data.content_subtype,
  838. context: data.context,
  839. message_type: data.message_type,
  840. subtype: data.subtype,
  841. subtype_id: data.subtype_id,
  842. });
  843. if (options.model && options.res_id) {
  844. return this._rpc({
  845. model: options.model,
  846. method: 'message_post',
  847. args: [options.res_id],
  848. kwargs: msg,
  849. })
  850. .then(function (msg_id) {
  851. return self._rpc({
  852. model: 'mail.message',
  853. method: 'message_format',
  854. args: [msg_id],
  855. })
  856. .then(function (msgs) {
  857. msgs[0].model = options.model;
  858. msgs[0].res_id = options.res_id;
  859. chat_manager.add_message(msgs[0]);
  860. });
  861. });
  862. } else {
  863. // This condition was added to avoid an error in the mail_reply module.
  864. // If the options.channel_id or options.model variables are missing
  865. // the mail.compose.message model has to be used.
  866. // It happens when we send a message not attached to any record or channel
  867. // and hence we cannot call message_post method. */
  868. options.model = 'mail.compose.message';
  869. return this._rpc({
  870. model: options.model,
  871. method: 'create',
  872. args: [msg],
  873. }).then(function (id) {
  874. return self._rpc({
  875. model: options.model,
  876. method: 'send_mail_action',
  877. args: [id]
  878. })
  879. });
  880. }
  881. }
  882. }
  883. chat_manager.get_message = function (id) {
  884. return _.findWhere(messages, {id: id});
  885. }
  886. chat_manager.get_messages = function (options) {
  887. var channel;
  888. if ('channel_id' in options && options.load_more) {
  889. // get channel messages, force load_more
  890. channel = this.get_channel(options.channel_id);
  891. return this._fetchFromChannel(channel, {domain: options.domain || {}, load_more: true});
  892. }
  893. if ('channel_id' in options) {
  894. // channel message, check in cache first
  895. channel = this.get_channel(options.channel_id);
  896. var channel_cache = chat_manager.get_channel_cache(channel, options.domain);
  897. if (channel_cache.loaded) {
  898. return $.when(channel_cache.messages);
  899. } else {
  900. return this._fetchFromChannel(channel, {domain: options.domain});
  901. }
  902. }
  903. if ('ids' in options) {
  904. // get messages from their ids (chatter is the main use case)
  905. return this._fetchDocumentMessages(options.ids, options).then(function(result) {
  906. chat_manager.mark_as_read(options.ids);
  907. return result;
  908. });
  909. }
  910. if ('model' in options && 'res_id' in options) {
  911. // get messages for a chatter, when it doesn't know the ids (use
  912. // case is when using the full composer)
  913. var domain = [['model', '=', options.model], ['res_id', '=', options.res_id]];
  914. this._rpc({
  915. model: 'mail.message',
  916. method: 'message_fetch',
  917. args: [domain],
  918. kwargs: {limit: 30},
  919. })
  920. .then(function (msgs) {
  921. return _.map(msgs, chat_manager.add_message);
  922. });
  923. }
  924. }
  925. chat_manager.toggle_star_status = function (message_id) {
  926. return this._rpc({
  927. model: 'mail.message',
  928. method: 'toggle_message_starred',
  929. args: [[message_id]],
  930. });
  931. }
  932. chat_manager.unstar_all = function () {
  933. return this._rpc({
  934. model: 'mail.message',
  935. method: 'unstar_all',
  936. args: [[]]
  937. });
  938. }
  939. chat_manager.mark_as_read = function (message_ids) {
  940. var ids = _.filter(message_ids, function (id) {
  941. var message = _.findWhere(messages, {id: id});
  942. // If too many messages, not all are fetched, and some might not be found
  943. return !message || message.is_needaction;
  944. });
  945. if (ids.length) {
  946. return this._rpc({
  947. model: 'mail.message',
  948. method: 'set_message_done',
  949. args: [ids],
  950. });
  951. } else {
  952. return $.when();
  953. }
  954. }
  955. chat_manager.mark_all_as_read = function (channel, domain) {
  956. if ((channel.id === "channel_inbox" && needaction_counter) || (channel && channel.needaction_counter)) {
  957. return this._rpc({
  958. model: 'mail.message',
  959. method: 'mark_all_as_read',
  960. kwargs: {channel_ids: channel.id !== "channel_inbox" ? [channel.id] : [], domain: domain},
  961. });
  962. }
  963. return $.when();
  964. }
  965. chat_manager.undo_mark_as_read = function (message_ids, channel) {
  966. return this._rpc({
  967. model: 'mail.message',
  968. method: 'mark_as_unread',
  969. args: [message_ids, [channel.id]],
  970. });
  971. }
  972. chat_manager.mark_channel_as_seen = function (channel) {
  973. if (channel.unread_counter > 0 && channel.type !== 'static') {
  974. chat_manager.update_channel_unread_counter(channel, 0);
  975. this.channel_seen(channel);
  976. }
  977. }
  978. chat_manager.get_channels = function () {
  979. return _.clone(channels);
  980. }
  981. chat_manager.get_channel = function (id) {
  982. return _.findWhere(channels, {id: id});
  983. }
  984. chat_manager.get_dm_from_partner_id = function (partner_id) {
  985. return _.findWhere(channels, {direct_partner_id: partner_id});
  986. }
  987. chat_manager.all_history_loaded = function (channel, domain) {
  988. return chat_manager.get_channel_cache(channel, domain).all_history_loaded;
  989. }
  990. chat_manager.get_mention_partner_suggestions = function (channel) {
  991. if (!channel) {
  992. return mention_partner_suggestions;
  993. }
  994. if (!channel.members_deferred) {
  995. channel.members_deferred = this._rpc({
  996. model: 'mail.channel',
  997. method: 'channel_fetch_listeners',
  998. args: [channel.uuid],
  999. }, {
  1000. shadow: true
  1001. })
  1002. .then(function (members) {
  1003. var suggestions = [];
  1004. _.each(mention_partner_suggestions, function (partners) {
  1005. suggestions.push(_.filter(partners, function (partner) {
  1006. return !_.findWhere(members, { id: partner.id });
  1007. }));
  1008. });
  1009. return [members];
  1010. });
  1011. }
  1012. return channel.members_deferred;
  1013. }
  1014. chat_manager.get_commands = function (channel) {
  1015. return _.filter(commands, function (command) {
  1016. return !command.channel_types || _.contains(command.channel_types, channel.server_type);
  1017. });
  1018. }
  1019. chat_manager.get_canned_responses = function () {
  1020. return canned_responses;
  1021. }
  1022. chat_manager.get_emojis = function() {
  1023. return emojis;
  1024. }
  1025. chat_manager.get_needaction_counter = function () {
  1026. return needaction_counter;
  1027. }
  1028. chat_manager.get_starred_counter = function () {
  1029. return starred_counter;
  1030. }
  1031. chat_manager.get_chat_unread_counter = function () {
  1032. return chat_unread_counter;
  1033. }
  1034. chat_manager.get_unread_conversation_counter = function () {
  1035. return unread_conversation_counter;
  1036. }
  1037. chat_manager.get_last_seen_message = function (channel) {
  1038. if (channel.last_seen_message_id) {
  1039. var messages = channel.cache['[]'].messages;
  1040. var msg = _.findWhere(messages, {id: channel.last_seen_message_id});
  1041. if (msg) {
  1042. var i = _.sortedIndex(messages, msg, 'id') + 1;
  1043. while (i < messages.length && (messages[i].is_author || messages[i].is_system_notification)) {
  1044. msg = messages[i];
  1045. i++;
  1046. }
  1047. return msg;
  1048. }
  1049. }
  1050. }
  1051. chat_manager.get_discuss_menu_id = function () {
  1052. return discuss_menu_id;
  1053. }
  1054. chat_manager.detach_channel = function (channel) {
  1055. return this._rpc({
  1056. model: 'mail.channel',
  1057. method: 'channel_minimize',
  1058. args: [channel.uuid, true],
  1059. }, {
  1060. shadow: true,
  1061. });
  1062. }
  1063. chat_manager.remove_chatter_messages = function (model) {
  1064. messages = _.reject(messages, function (message) {
  1065. return message.channel_ids.length === 0 && message.model === model;
  1066. });
  1067. }
  1068. chat_manager.create_channel = function (name, type) {
  1069. var method = type === "dm" ? "channel_get" : "channel_create";
  1070. var args = type === "dm" ? [[name]] : [name, type];
  1071. var context = _.extend({isMobile: config.device.isMobile}, session.user_context);
  1072. return this._rpc({
  1073. model: 'mail.channel',
  1074. method: method,
  1075. args: args,
  1076. kwargs: {context: context},
  1077. })
  1078. .then(chat_manager.add_channel);
  1079. }
  1080. chat_manager.join_channel = function (channel_id, options) {
  1081. if (channel_id in channel_defs) {
  1082. // prevents concurrent calls to channel_join_and_get_info
  1083. return channel_defs[channel_id];
  1084. }
  1085. var channel = this.get_channel(channel_id);
  1086. if (channel) {
  1087. // channel already joined
  1088. channel_defs[channel_id] = $.when(channel);
  1089. } else {
  1090. channel_defs[channel_id] = this._rpc({
  1091. model: 'mail.channel',
  1092. method: 'channel_join_and_get_info',
  1093. args: [[channel_id]],
  1094. })
  1095. .then(function (result) {
  1096. return chat_manager.add_channel(result, options);
  1097. });
  1098. }
  1099. return channel_defs[channel_id];
  1100. }
  1101. chat_manager.open_and_detach_dm = function (partner_id) {
  1102. return this._rpc({
  1103. model: 'mail.channel',
  1104. method: 'channel_get_and_minimize',
  1105. args: [[partner_id]],
  1106. })
  1107. .then(chat_manager.add_channel);
  1108. }
  1109. chat_manager.open_channel = function (channel) {
  1110. chat_manager.bus.trigger(client_action_open ? 'open_channel' : 'detach_channel', channel);
  1111. }
  1112. chat_manager.unsubscribe = function (channel) {
  1113. if (_.contains(['public', 'private'], channel.type)) {
  1114. return this._rpc({
  1115. model: 'mail.channel',
  1116. method: 'action_unfollow',
  1117. args: [[channel.id]],
  1118. });
  1119. } else {
  1120. return this._rpc({
  1121. model: 'mail.channel',
  1122. method: 'channel_pin',
  1123. args: [channel.uuid, false],
  1124. });
  1125. }
  1126. }
  1127. chat_manager.close_chat_session = function (channel_id) {
  1128. var channel = this.get_channel(channel_id);
  1129. this._rpc({
  1130. model: 'mail.channel',
  1131. method: 'channel_fold',
  1132. kwargs: {uuid : channel.uuid, state : 'closed'},
  1133. }, {shadow: true});
  1134. }
  1135. chat_manager.fold_channel = function (channel_id, folded) {
  1136. var args = {
  1137. uuid: this.get_channel(channel_id).uuid,
  1138. };
  1139. if (_.isBoolean(folded)) {
  1140. args.state = folded ? 'folded' : 'open';
  1141. }
  1142. return this._rpc({
  1143. model: 'mail.channel',
  1144. method: 'channel_fold',
  1145. kwargs: args,
  1146. }, {shadow: true});
  1147. }
  1148. /**
  1149. * Special redirection handling for given model and id
  1150. *
  1151. * If the model is res.partner, and there is a user associated with this
  1152. * partner which isn't the current user, open the DM with this user.
  1153. * Otherwhise, open the record's form view, if this is not the current user's.
  1154. */
  1155. chat_manager.redirect = function (res_model, res_id, dm_redirection_callback) {
  1156. var self = this;
  1157. var redirect_to_document = function (res_model, res_id, view_id) {
  1158. web_client.do_action({
  1159. type:'ir.actions.act_window',
  1160. view_type: 'form',
  1161. view_mode: 'form',
  1162. res_model: res_model,
  1163. views: [[view_id || false, 'form']],
  1164. res_id: res_id,
  1165. });
  1166. };
  1167. if (res_model === "res.partner") {
  1168. var domain = [["partner_id", "=", res_id]];
  1169. this._rpc({
  1170. model: 'res.users',
  1171. method: 'search',
  1172. args: [domain],
  1173. })
  1174. .then(function (user_ids) {
  1175. if (user_ids.length && user_ids[0] !== session.uid && dm_redirection_callback) {
  1176. self.create_channel(res_id, 'dm').then(dm_redirection_callback);
  1177. } else {
  1178. redirect_to_document(res_model, res_id);
  1179. }
  1180. });
  1181. } else {
  1182. this._rpc({
  1183. model: res_model,
  1184. method: 'get_formview_id',
  1185. args: [[res_id], session.user_context],
  1186. })
  1187. .then(function (view_id) {
  1188. redirect_to_document(res_model, res_id, view_id);
  1189. });
  1190. }
  1191. }
  1192. chat_manager.get_channels_preview = function (channels) {
  1193. var channels_preview = _.map(channels, function (channel) {
  1194. var info;
  1195. if (channel.channel_ids && _.contains(channel.channel_ids,"channel_inbox")) {
  1196. // map inbox(mail_message) data with existing channel/chat template
  1197. info = _.pick(channel, 'id', 'body', 'avatar_src', 'res_id', 'model', 'module_icon', 'subject','date', 'record_name', 'status', 'displayed_author', 'email_from', 'unread_counter');
  1198. info.last_message = {
  1199. body: info.body,
  1200. date: info.date,
  1201. displayed_author: info.displayed_author || info.email_from,
  1202. };
  1203. info.name = info.record_name || info.subject || info.displayed_author;
  1204. info.image_src = info.module_icon || info.avatar_src;
  1205. info.message_id = info.id;
  1206. info.id = 'channel_inbox';
  1207. return info;
  1208. }
  1209. info = _.pick(channel, 'id', 'is_chat', 'name', 'status', 'unread_counter');
  1210. info.last_message = channel.last_message || _.last(channel.cache['[]'].messages);
  1211. if (!info.is_chat) {
  1212. info.image_src = '/web/image/mail.channel/'+channel.id+'/image_small';
  1213. } else if (channel.direct_partner_id) {
  1214. info.image_src = '/web/image/res.partner/'+channel.direct_partner_id+'/image_small';
  1215. } else {
  1216. info.image_src = '/mail/static/src/img/smiley/avatar.jpg';
  1217. }
  1218. return info;
  1219. });
  1220. var missing_channels = _.where(channels_preview, {last_message: undefined});
  1221. if (!channels_preview_def) {
  1222. if (missing_channels.length) {
  1223. var missing_channel_ids = _.pluck(missing_channels, 'id');
  1224. channels_preview_def = this._rpc({
  1225. model: 'mail.channel',
  1226. method: 'channel_fetch_preview',
  1227. args: [missing_channel_ids],
  1228. }, {
  1229. shadow: true,
  1230. });
  1231. } else {
  1232. channels_preview_def = $.when();
  1233. }
  1234. }
  1235. return channels_preview_def.then(function (channels) {
  1236. _.each(missing_channels, function (channel_preview) {
  1237. var channel = _.findWhere(channels, {id: channel_preview.id});
  1238. if (channel) {
  1239. channel_preview.last_message = chat_manager.add_message(channel.last_message);
  1240. }
  1241. });
  1242. // sort channels: 1. unread, 2. chat, 3. date of last msg
  1243. channels_preview.sort(function (c1, c2) {
  1244. return Math.min(1, c2.unread_counter) - Math.min(1, c1.unread_counter) ||
  1245. c2.is_chat - c1.is_chat ||
  1246. !!c2.last_message - !!c1.last_message ||
  1247. (c2.last_message && c2.last_message.date.diff(c1.last_message.date));
  1248. });
  1249. // generate last message preview (inline message body and compute date to display)
  1250. _.each(channels_preview, function (channel) {
  1251. if (channel.last_message) {
  1252. channel.last_message_preview = chat_manager.get_message_body_preview(channel.last_message.body);
  1253. channel.last_message_date = channel.last_message.date.fromNow();
  1254. }
  1255. });
  1256. return channels_preview;
  1257. });
  1258. },
  1259. chat_manager.get_message_body_preview = function (message_body) {
  1260. return utils.parse_and_transform(message_body, utils.inline);
  1261. }
  1262. chat_manager.search_partner = function (search_val, limit) {
  1263. var def = $.Deferred();
  1264. var values = [];
  1265. // search among prefetched partners
  1266. var search_regexp = new RegExp(_.str.escapeRegExp(utils.unaccent(search_val)), 'i');
  1267. _.each(mention_partner_suggestions, function (partners) {
  1268. if (values.length < limit) {
  1269. values = values.concat(_.filter(partners, function (partner) {
  1270. return session.partner_id !== partner.id && search_regexp.test(partner.name);
  1271. })).splice(0, limit);
  1272. }
  1273. });
  1274. if (!values.length) {
  1275. // extend the research to all users
  1276. def = this._rpc({
  1277. model: 'res.partner',
  1278. method: 'im_search',
  1279. args: [search_val, limit || 20],
  1280. }, {
  1281. shadow: true,
  1282. });
  1283. } else {
  1284. def = $.when(values);
  1285. }
  1286. return def.then(function (values) {
  1287. var autocomplete_data = _.map(values, function (value) {
  1288. return { id: value.id, value: value.name, label: value.name };
  1289. });
  1290. return _.sortBy(autocomplete_data, 'label');
  1291. });
  1292. }
  1293. chat_manager.start();
  1294. bus.off('notification');
  1295. bus.on('notification', null, function () {
  1296. chat_manager.on_notification.apply(chat_manager, arguments);
  1297. });
  1298. return {
  1299. ODOOBOT_ID: ODOOBOT_ID,
  1300. chat_manager: chat_manager,
  1301. };
  1302. });