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.

1423 lines
52 KiB

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