slack.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221
  1. /**
  2. * slack
  3. */
  4. module.exports = function(crowi) {
  5. 'use strict';
  6. const debug = require('debug')('growi:util:slack'),
  7. config = crowi.getConfig(),
  8. Config = crowi.model('Config'),
  9. Slack = require('slack-node'),
  10. slack = {};
  11. const postWithIwh = function(messageObj, callback) {
  12. const client = new Slack();
  13. client.setWebhook(config.notification['slack:incomingWebhookUrl']);
  14. client.webhook(messageObj, callback);
  15. };
  16. const postWithWebApi = function(messageObj, callback) {
  17. const client = new Slack(config.notification['slack:token']);
  18. // stringify attachments
  19. if (messageObj.attachments != null) {
  20. messageObj.attachments = JSON.stringify(messageObj.attachments);
  21. }
  22. client.api('chat.postMessage', messageObj, callback);
  23. };
  24. const convertMarkdownToMrkdwn = function(body) {
  25. var url = '';
  26. if (config.crowi && config.crowi['app:url']) {
  27. url = config.crowi['app:url'];
  28. }
  29. body = body
  30. .replace(/\n\*\s(.+)/g, '\n• $1')
  31. .replace(/#{1,}\s?(.+)/g, '\n*$1*')
  32. .replace(/(\[(.+)\]\((https?:\/\/.+)\))/g, '<$3|$2>')
  33. .replace(/(\[(.+)\]\((\/.+)\))/g, '<' + url + '$3|$2>')
  34. ;
  35. return body;
  36. };
  37. const prepareAttachmentTextForCreate = function(page, user) {
  38. var body = page.revision.body;
  39. if (body.length > 2000) {
  40. body = body.substr(0, 2000) + '...';
  41. }
  42. return convertMarkdownToMrkdwn(body);
  43. };
  44. const prepareAttachmentTextForUpdate = function(page, user, previousRevision) {
  45. var diff = require('diff');
  46. var diffText = '';
  47. diff.diffLines(previousRevision.body, page.revision.body).forEach(function(line) {
  48. debug('diff line', line);
  49. /* eslint-disable no-unused-vars */
  50. var value = line.value.replace(/\r\n|\r/g, '\n');
  51. /* eslint-enable */
  52. if (line.added) {
  53. diffText += `:pencil2: ...\n${line.value}`;
  54. }
  55. else if (line.removed) {
  56. // diffText += '-' + line.value.replace(/(.+)?\n/g, '- $1\n');
  57. // 1以下は無視
  58. if (line.count > 1) {
  59. diffText += `:wastebasket: ... ${line.count} lines\n`;
  60. }
  61. }
  62. else {
  63. //diffText += '...\n';
  64. }
  65. });
  66. debug('diff is', diffText);
  67. return diffText;
  68. };
  69. const prepareAttachmentTextForComment = function(page, user, channel, updateType, previousRevision) {
  70. return {
  71. channel: '#general',
  72. username: 'Growi',
  73. text: '`comment uploaded`'
  74. };
  75. };
  76. const prepareSlackMessageForPage = function(page, user, channel, updateType, previousRevision) {
  77. const url = config.crowi['app:url'] || '';
  78. let body = page.revision.body;
  79. if (updateType == 'create') {
  80. body = prepareAttachmentTextForCreate(page, user);
  81. }
  82. else {
  83. body = prepareAttachmentTextForUpdate(page, user, previousRevision);
  84. }
  85. const attachment = {
  86. color: '#263a3c',
  87. author_name: '@' + user.username,
  88. author_link: url + '/user/' + user.username,
  89. author_icon: user.image,
  90. title: page.path,
  91. title_link: url + '/' + page._id,
  92. text: body,
  93. mrkdwn_in: ['text'],
  94. };
  95. if (user.image) {
  96. attachment.author_icon = user.image;
  97. }
  98. const message = {
  99. channel: '#' + channel,
  100. username: Config.appTitle(config),
  101. text: getSlackMessageText(page.path, user, updateType),
  102. attachments: [attachment],
  103. };
  104. return message;
  105. };
  106. const prepareSlackMessageForComment = function(comment, user, channel, updateType) {
  107. const url = config.crowi['app:url'] || '';
  108. const body = prepareAttachmentTextForComment(comment, user);
  109. const attachment = {
  110. color: '#263a3c',
  111. author_name: '@' + user.username,
  112. author_link: url + '/user/' + user.username,
  113. author_icon: user.image,
  114. title: comment.comment,
  115. title_link: url + '/' + comment._id,
  116. text: body,
  117. mrkdwn_in: ['text'],
  118. };
  119. if (user.image) {
  120. attachment.author_icon = user.image;
  121. }
  122. const message = {
  123. channel: '#' + channel,
  124. username: Config.appTitle(config),
  125. text: getSlackMessageText(comment.path, user, updateType),
  126. attachments: [attachment],
  127. };
  128. return message;
  129. };
  130. const getSlackMessageText = function(path, user, updateType) {
  131. let text;
  132. const url = config.crowi['app:url'] || '';
  133. const pageUrl = `<${url}${path}|${path}>`;
  134. if (updateType == 'create') {
  135. text = `:white_check_mark: ${user.username} created a new page! ${pageUrl}`;
  136. }
  137. else if (updateType == 'comment') {
  138. text = `:speech_balloon: ${user.username} commented on ${pageUrl}`;
  139. }
  140. else {
  141. text = `:up: ${user.username} updated ${pageUrl}`;
  142. }
  143. return text;
  144. };
  145. // slack.post = function (channel, message, opts) {
  146. slack.post = (pageOrComment, user, channel, updateType, previousRevision) => {
  147. let messageObj;
  148. if (updateType === 'comment') {
  149. messageObj = prepareSlackMessageForComment(pageOrComment, user, channel, updateType);
  150. }
  151. else {
  152. messageObj = prepareSlackMessageForPage(pageOrComment, user, channel, updateType, previousRevision);
  153. }
  154. return new Promise((resolve, reject) => {
  155. // define callback function for Promise
  156. const callback = function(err, res) {
  157. if (err) {
  158. debug('Post error', err, res);
  159. debug('Sent data to slack is:', messageObj);
  160. return reject(err);
  161. }
  162. resolve(res);
  163. };
  164. // when incoming Webhooks is prioritized
  165. if (Config.isIncomingWebhookPrioritized(config)) {
  166. if (Config.hasSlackIwhUrl(config)) {
  167. debug('posting message with IncomingWebhook');
  168. postWithIwh(messageObj, callback);
  169. }
  170. else if (Config.hasSlackToken(config)) {
  171. debug('posting message with Web API');
  172. postWithWebApi(messageObj, callback);
  173. }
  174. }
  175. // else
  176. else {
  177. if (Config.hasSlackToken(config)) {
  178. debug('posting message with Web API');
  179. postWithWebApi(messageObj, callback);
  180. }
  181. else if (Config.hasSlackIwhUrl(config)) {
  182. debug('posting message with IncomingWebhook');
  183. postWithIwh(messageObj, callback);
  184. }
  185. }
  186. resolve();
  187. });
  188. };
  189. return slack;
  190. };