slack.js 6.5 KB

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