Просмотр исходного кода

refactor global notification slack

mizozobu 6 лет назад
Родитель
Сommit
9b82b29b1c

+ 99 - 3
src/server/service/global-notification/global-notification-slack.js

@@ -1,4 +1,5 @@
 const logger = require('@alias/logger')('growi:service:GlobalNotificationSlackService'); // eslint-disable-line no-unused-vars
+const urljoin = require('url-join');
 
 /**
  * sub service class of GlobalNotificationSetting
@@ -9,25 +10,120 @@ class GlobalNotificationSlackService {
     this.crowi = crowi;
     this.type = 'slack';
     this.slack = crowi.getSlack();
+    this.event = crowi.model('GlobalNotificationSetting').schema.EVENT;
   }
 
   /**
    * send slack global notification
    *
    * @memberof GlobalNotificationSlackService
+   *
    * @param {string} event
    * @param {string} path
-   * @param {obejct} option
+   * @param {User} triggeredBy user who triggered the event
+   * @param {{ comment: Comment, oldPath: string }} _ event specific vars
    */
-  async fire(event, path, option) {
+  async fire(event, path, triggeredBy, vars) {
     const GlobalNotification = this.crowi.model('GlobalNotificationSetting');
     const notifications = await GlobalNotification.findSettingByPathAndEvent(event, path, this.type);
 
+    const messageBody = this.generateMessageBody(event, path, triggeredBy, vars);
+    const attachmentBody = this.generateAttachmentBody(event, path, triggeredBy, vars);
+
     await Promise.all(notifications.map((notification) => {
-      return this.slack.sendGlobalNotification({ ...option, slackChannels: notification.slackChannels });
+      return this.slack.sendGlobalNotification(messageBody, attachmentBody, notification.slackChannels);
     }));
   }
 
+  /**
+   * generate slack message body
+   *
+   * @memberof GlobalNotificationSlackService
+   *
+   * @param {string} event event name triggered
+   * @param {string} path path triggered the event
+   * @param {User} triggeredBy user triggered the event
+   * @param {{ comment: Comment, oldPath: string }} _ event specific vars
+   *
+   * @return  {string} slack message body
+   */
+  generateMessageBody(event, path, triggeredBy, { comment, oldPath }) {
+    const pageUrl = `<${urljoin(this.crowi.appService.getSiteUrl(), path)}|${path}>`;
+    const username = `<${urljoin(this.crowi.appService.getSiteUrl(), 'user', triggeredBy.username)}|${triggeredBy.username}>`;
+    let messageBody;
+
+    switch (event) {
+      case this.event.PAGE_CREATE:
+        messageBody = `:bell: ${username} created ${pageUrl}`;
+        break;
+      case this.event.PAGE_EDIT:
+        messageBody = `:bell: ${username} edited ${pageUrl}`;
+        break;
+      case this.event.PAGE_DELETE:
+        messageBody = `:bell: ${username} deleted ${pageUrl}`;
+        break;
+      case this.event.PAGE_MOVE:
+        // validate for page move
+        if (oldPath == null) {
+          throw new Error(`invalid vars supplied to GlobalNotificationSlackService.generateOption for event ${event}`);
+        }
+        messageBody = `:bell: ${username} moved ${oldPath} to ${pageUrl}`;
+        break;
+      case this.event.PAGE_LIKE:
+        messageBody = `:bell: ${username} liked ${pageUrl}`;
+        break;
+      case this.event.COMMENT:
+        // validate for comment
+        if (comment == null) {
+          throw new Error(`invalid vars supplied to GlobalNotificationSlackService.generateOption for event ${event}`);
+        }
+        messageBody = `:bell: ${username} commented on ${pageUrl}`;
+        break;
+      default:
+        throw new Error(`unknown global notificaiton event: ${event}`);
+    }
+
+    return messageBody;
+  }
+
+  /**
+   * generate slack attachment body
+   *
+   * @memberof GlobalNotificationSlackService
+   *
+   * @param {string} event event name triggered
+   * @param {string} path path triggered the event
+   * @param {User} triggeredBy user triggered the event
+   * @param {{ comment: Comment, oldPath: string }} _ event specific vars
+   *
+   * @return  {string} slack attachment body
+   */
+  generateAttachmentBody(event, path, triggeredBy, { comment, oldPath }) {
+    const attachmentBody = '';
+
+    // TODO: create attachment
+    // attachment body is intended for comment or page diff
+
+    // switch (event) {
+    //   case this.event.PAGE_CREATE:
+    //     break;
+    //   case this.event.PAGE_EDIT:
+    //     break;
+    //   case this.event.PAGE_DELETE:
+    //     break;
+    //   case this.event.PAGE_MOVE:
+    //     break;
+    //   case this.event.PAGE_LIKE:
+    //     break;
+    //   case this.event.COMMENT:
+    //     break;
+    //   default:
+    //     throw new Error(`unknown global notificaiton event: ${event}`);
+    // }
+
+    return attachmentBody;
+  }
+
 }
 
 module.exports = GlobalNotificationSlackService;

+ 8 - 87
src/server/service/global-notification/index.js

@@ -1,5 +1,4 @@
 const logger = require('@alias/logger')('growi:service:GlobalNotificationService');
-const nodePath = require('path');
 const GloabalNotificationSlack = require('./global-notification-slack');
 const GloabalNotificationMail = require('./global-notification-mail');
 
@@ -11,7 +10,6 @@ class GlobalNotificationService {
   constructor(crowi) {
     this.crowi = crowi;
     this.defaultLang = 'en-US'; // TODO: get defaultLang from app global config
-    this.event = crowi.model('GlobalNotificationSetting').schema.EVENT;
 
     this.gloabalNotificationMail = new GloabalNotificationMail(crowi);
     this.gloabalNotificationSlack = new GloabalNotificationSlack(crowi);
@@ -21,101 +19,24 @@ class GlobalNotificationService {
    * fire global notification
    *
    * @memberof GlobalNotificationService
+   *
    * @param {string} event event name triggered
    * @param {string} path path triggered the event
-   * @param {User} triggeredBy user triggered the event
+   * @param {User} triggeredBy user who triggered the event
    * @param {object} vars event specific vars
    */
   async fire(event, path, triggeredBy, vars = {}) {
-    const option = await this.generateOption(event, path, triggeredBy, vars);
-
     logger.debug(`global notficatoin event ${event} was triggered`);
 
-    await Promise.all([
-      this.gloabalNotificationMail.fire(event, path, option),
-      this.gloabalNotificationSlack.fire(event, path, option),
-    ]);
-  }
-
-  /**
-   * fire global notification
-   *
-   * @memberof GlobalNotificationService
-   *
-   * @param {string} event event name triggered
-   * @param {string} path path triggered the event
-   * @param {User} triggeredBy user triggered the event
-   * @param {{ comment: Comment, oldPath: string }} _ event specific vars
-   *
-   * @return  {{ subject: string, template: string, vars: object }}
-   */
-  async generateOption(event, path, triggeredBy, { comment, oldPath }) {
-    // validate for all events
+    // validation
     if (event == null || path == null || triggeredBy == null) {
-      throw new Error(`invalid vars supplied to generateOption for event ${event}`);
-    }
-
-    const template = nodePath.join(this.crowi.localeDir, `${this.defaultLang}/notifications/${event}.txt`);
-    let subject;
-    let vars = {
-      appTitle: this.crowi.appService.getAppTitle(),
-      path,
-      username: triggeredBy.username,
-    };
-
-    switch (event) {
-      case this.event.PAGE_CREATE:
-        subject = `#${event} - ${triggeredBy.username} created ${path}`;
-        break;
-
-      case this.event.PAGE_EDIT:
-        subject = `#${event} - ${triggeredBy.username} edited ${path}`;
-        break;
-
-      case this.event.PAGE_DELETE:
-        subject = `#${event} - ${triggeredBy.username} deleted ${path}`;
-        break;
-
-      case this.event.PAGE_MOVE:
-        // validate for page move
-        if (oldPath == null) {
-          throw new Error(`invalid vars supplied to generateOption for event ${event}`);
-        }
-
-        subject = `#${event} - ${triggeredBy.username} moved ${oldPath} to ${path}`;
-        vars = {
-          ...vars,
-          oldPath,
-          newPath: path,
-        };
-        break;
-
-      case this.event.PAGE_LIKE:
-        subject = `#${event} - ${triggeredBy.username} liked ${path}`;
-        break;
-
-      case this.event.COMMENT:
-        // validate for comment
-        if (comment == null) {
-          throw new Error(`invalid vars supplied to generateOption for event ${event}`);
-        }
-
-        subject = `#${event} - ${triggeredBy.username} commented on ${path}`;
-        vars = {
-          ...vars,
-          comment: comment.comment,
-        };
-        break;
-
-      default:
-        throw new Error(`unknown global notificaiton event: ${event}`);
+      throw new Error(`invalid vars supplied to GlobalNotificationSlackService.generateOption for event ${event}`);
     }
 
-    return {
-      subject,
-      template,
-      vars,
-    };
+    await Promise.all([
+      this.gloabalNotificationMail.fire(event, path, triggeredBy, vars),
+      this.gloabalNotificationSlack.fire(event, path, triggeredBy, vars),
+    ]);
   }
 
 }

+ 12 - 15
src/server/util/slack.js

@@ -1,7 +1,5 @@
 const debug = require('debug')('growi:util:slack');
-const { promisify } = require('util');
 const urljoin = require('url-join');
-const swig = require('swig-templates');
 
 /**
  * slack
@@ -172,25 +170,24 @@ module.exports = function(crowi) {
 
   /**
    * For GlobalNotification
-   * @param {{ template: string, vars: object, slackChannels: string }} option
+   *
+   * @param {string} messageBody
+   * @param {string} attachmentBody
+   * @param {string} slackChannel
   */
-  const prepareSlackMessageForGlobalNotification = async(option) => {
-    const templateVars = option.vars || {};
-    const output = await promisify(swig.renderFile)(
-      option.template,
-      templateVars,
-    );
+  const prepareSlackMessageForGlobalNotification = async(messageBody, attachmentBody, slackChannel) => {
+    const appTitle = crowi.appService.getAppTitle();
 
     const attachment = {
       color: '#263a3c',
-      text: output,
+      text: attachmentBody,
       mrkdwn_in: ['text'],
     };
 
     const message = {
-      channel: `#${option.slackChannels}`,
-      username: option.appTitle,
-      text: option.subject,
+      channel: `#${slackChannel}`,
+      username: appTitle,
+      text: messageBody,
       attachments: [attachment],
     };
 
@@ -233,8 +230,8 @@ module.exports = function(crowi) {
     return slackPost(messageObj);
   };
 
-  slack.sendGlobalNotification = async(option) => {
-    const messageObj = await prepareSlackMessageForGlobalNotification(option);
+  slack.sendGlobalNotification = async(messageBody, attachmentBody, slackChannel) => {
+    const messageObj = await prepareSlackMessageForGlobalNotification(messageBody, attachmentBody, slackChannel);
 
     return slackPost(messageObj);
   };