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

Move from botkit to @slack/client

Sotaro KARASAWA 8 лет назад
Родитель
Сommit
4ede6e5964
3 измененных файлов с 90 добавлено и 324 удалено
  1. 45 198
      lib/routes/admin.js
  2. 1 1
      lib/routes/page.js
  3. 44 125
      lib/util/slack.js

+ 45 - 198
lib/routes/admin.js

@@ -6,8 +6,6 @@ module.exports = function(crowi, app) {
     , Page = models.Page
     , User = models.User
     , Config = models.Config
-    , PluginUtils = require('../plugins/plugin-utils')
-    , pluginUtils = new PluginUtils()
     , ApiResponse = require('../util/apiResponse')
 
     , MAX_PAGE_LIST = 5
@@ -68,12 +66,9 @@ module.exports = function(crowi, app) {
   }
 
   actions.index = function(req, res) {
-    return res.render('admin/index', {
-      plugins: pluginUtils.listPlugins(crowi.rootDir),
-    });
+    return res.render('admin/index');
   };
 
-  // app.get('/admin/app'                  , admin.app.index);
   actions.app = {};
   actions.app.index = function(req, res) {
     var settingForm;
@@ -87,75 +82,23 @@ module.exports = function(crowi, app) {
   actions.app.settingUpdate = function(req, res) {
   };
 
-  // app.get('/admin/security'                  , admin.security.index);
-  actions.security = {};
-  actions.security.index = function(req, res) {
-    var settingForm;
-    settingForm = Config.setupCofigFormData('crowi', req.config);
-    return res.render('admin/security', { settingForm });
-  };
-
-  // app.get('/admin/markdown'                  , admin.markdown.index);
-  actions.markdown = {};
-  actions.markdown.index = function(req, res) {
-    var config = crowi.getConfig();
-    var markdownSetting = Config.setupCofigFormData('markdown', config);
-    return res.render('admin/markdown', {
-      markdownSetting: markdownSetting,
-    });
-  };
-
-  // app.post('/admin/markdown/lineBreaksSetting' , admin.markdown.lineBreaksSetting);
-  actions.markdown.lineBreaksSetting = function(req, res) {
-    var markdownSetting = req.form.markdownSetting;
-
-    req.session.markdownSetting = markdownSetting;
-    if (req.form.isValid) {
-      Config.updateNamespaceByArray('markdown', markdownSetting, function(err, config) {
-        Config.updateConfigCache('markdown', config);
-        req.session.markdownSetting = null;
-        req.flash('successMessage', ['Successfully updated!']);
-        return res.redirect('/admin/markdown');
-      });
-    } else {
-      req.flash('errorMessage', req.form.errors);
-      return res.redirect('/admin/markdown');
-    }
-  };
-
-  // app.get('/admin/customize' , admin.customize.index);
-  actions.customize = {};
-  actions.customize.index = function(req, res) {
-    var settingForm;
-    settingForm = Config.setupCofigFormData('crowi', req.config);
-
-    return res.render('admin/customize', {
-      settingForm: settingForm,
-    });
-  };
-
   // app.get('/admin/notification'               , admin.notification.index);
   actions.notification = {};
   actions.notification.index = function(req, res) {
     var config = crowi.getConfig();
     var UpdatePost = crowi.model('UpdatePost');
     var slackSetting = Config.setupCofigFormData('notification', config);
-    var hasSlackAppConfig = Config.hasSlackAppConfig(config);
-    var hasSlackIwhUrl = Config.hasSlackIwhUrl(config);
+    var hasSlackConfig = Config.hasSlackConfig(config);
     var hasSlackToken = Config.hasSlackToken(config);
     var slack = crowi.slack;
     var slackAuthUrl = '';
 
-    if (!Config.hasSlackAppConfig(req.config)) {
+    if (!Config.hasSlackConfig(req.config)) {
       slackSetting['slack:clientId'] = '';
       slackSetting['slack:clientSecret'] = '';
-    }
-    else {
+    } else {
       slackAuthUrl = slack.getAuthorizeURL();
     }
-    if (!Config.hasSlackIwhUrl(req.config)) {
-      slackSetting['slack:incomingWebhookUrl'] = '';
-    }
 
     if (req.session.slackSetting) {
       slackSetting = req.session.slackSetting;
@@ -167,15 +110,14 @@ module.exports = function(crowi, app) {
       return res.render('admin/notification', {
         settings,
         slackSetting,
-        hasSlackAppConfig,
-        hasSlackIwhUrl,
+        hasSlackConfig,
         hasSlackToken,
         slackAuthUrl
       });
     });
   };
 
-  // app.post('/admin/notification/slackSetting' , admin.notification.slackSetting);
+  // app.post('/admin/notification/slackSetting' , admin.notification.slackauth);
   actions.notification.slackSetting = function(req, res) {
     var slackSetting = req.form.slackSetting;
 
@@ -183,10 +125,8 @@ module.exports = function(crowi, app) {
     if (req.form.isValid) {
       Config.updateNamespaceByArray('notification', slackSetting, function(err, config) {
         Config.updateConfigCache('notification', config);
-        req.flash('successMessage', ['Successfully Updated!']);
         req.session.slackSetting = null;
 
-        // Re-setup
         crowi.setupSlack().then(function() {
           return res.redirect('/admin/notification');
         });
@@ -202,23 +142,14 @@ module.exports = function(crowi, app) {
     const code = req.query.code;
     const config = crowi.getConfig();
 
-    if (!code || !Config.hasSlackAppConfig(req.config)) {
+    if (!code || !Config.hasSlackConfig(req.config)) {
       return res.redirect('/admin/notification');
     }
 
-    var slack = crowi.slack;
-    var bot = slack.initAppBot(true);
-    var args = {
-      code,
-      client_id: config.notification['slack:clientId'],
-      client_secret: config.notification['slack:clientSecret'],
-    }
-    bot.api.oauth.access(args, function(err, data) {
-      debug('oauth response', err, data);
-      if (!data.ok || !data.access_token) {
-        req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
-        return res.redirect('/admin/notification');
-      } else {
+    const slack = crowi.slack;
+    slack.getOauthAccessToken(code)
+    .then(data => {
+      debug('oauth response', data);
         Config.updateNamespaceByArray('notification', {'slack:token': data.access_token}, function(err, config) {
           if (err) {
             req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
@@ -227,23 +158,11 @@ module.exports = function(crowi, app) {
             req.flash('successMessage', ['Successfully Connected!']);
           }
 
-          slack.initAppBot();
           return res.redirect('/admin/notification');
         });
-      }
-    });
-  };
-
-  // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
-  actions.notification.disconnectFromSlack = function(req, res) {
-    const config = crowi.getConfig();
-    const slack = crowi.slack;
-
-    Config.updateNamespaceByArray('notification', {'slack:token': ''}, function(err, config) {
-      Config.updateConfigCache('notification', config);
-      req.flash('successMessage', ['Successfully Disconnected!']);
-
-      slack.initAppBot();
+    }).catch(err => {
+      debug('oauth response ERROR', err);
+      req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
       return res.redirect('/admin/notification');
     });
   };
@@ -259,64 +178,43 @@ module.exports = function(crowi, app) {
     });
   };
 
-  // app.post('/admin/notification/slackIwhSetting' , admin.notification.slackIwhSetting);
-  actions.notification.slackIwhSetting = function(req, res) {
-    var slackIwhSetting = req.form.slackIwhSetting;
-
-    if (req.form.isValid) {
-      Config.updateNamespaceByArray('notification', slackIwhSetting, function(err, config) {
-        Config.updateConfigCache('notification', config);
-        req.flash('successMessage', ['Successfully Updated!']);
-
-        // Re-setup
-        crowi.setupSlack().then(function() {
-          return res.redirect('/admin/notification#slack-incoming-webhooks');
-        });
-      });
-    } else {
-      req.flash('errorMessage', req.form.errors);
-      return res.redirect('/admin/notification#slack-incoming-webhooks');
-    }
-  };
-
   actions.search.buildIndex = function(req, res) {
     var search = crowi.getSearcher();
     if (!search) {
       return res.redirect('/admin');
     }
 
-    return new Promise(function(resolve, reject) {
-      search.deleteIndex()
+    Promise.resolve().then(function() {
+      return new Promise(function(resolve, reject) {
+        search.deleteIndex()
+          .then(function(data) {
+            debug('Index deleted.');
+            resolve();
+          }).catch(function(err) {
+            debug('Delete index Error, but if it is initialize, its ok.', err);
+            resolve();
+          });
+      });
+    }).then(function() {
+      search.buildIndex()
         .then(function(data) {
-          debug('Index deleted.');
-          resolve();
-        }).catch(function(err) {
-          debug('Delete index Error, but if it is initialize, its ok.', err);
-          resolve();
+          if (!data.errors) {
+            debug('Index created.');
+          }
+          return search.addAllPages();
+        })
+        .then(function(data) {
+          if (!data.errors) {
+            debug('Data is successfully indexed.');
+          } else {
+            debug('Data index error.', data.errors);
+          }
+        })
+        .catch(function(err) {
+          debug('Error', err);
         });
-    })
-    .then(function() {
-      return search.buildIndex()
-    })
-    .then(function(data) {
-      if (!data.errors) {
-        debug('Index created.');
-      }
-      return search.addAllPages();
-    })
-    .then(function(data) {
-      if (!data.errors) {
-        debug('Data is successfully indexed.');
-        req.flash('successMessage', 'Data is successfully indexed.');
-      } else {
-        debug('Data index error.', data.errors);
-        req.flash('errorMessage', `Data index error: ${data.errors}`);
-      }
-      return res.redirect('/admin/search');
-    })
-    .catch(function(err) {
-      debug('Error', err);
-      req.flash('errorMessage', `Error: ${err}`);
+
+      req.flash('successMessage', 'Now re-building index ... this takes a while.');
       return res.redirect('/admin/search');
     });
   };
@@ -415,37 +313,8 @@ module.exports = function(crowi, app) {
   };
 
   actions.user.remove = function(req, res) {
-    var id = req.params.id;
-    let username = '';
-
-    return new Promise((resolve, reject) => {
-      User.findById(id, (err, userData) => {
-        username = userData.username;
-        return resolve(userData);
-      });
-    })
-    .then((userData) => {
-      return new Promise((resolve, reject) => {
-        userData.statusDelete((err, userData) => {
-          if (err) {
-            reject(err);
-          }
-          resolve(userData);
-        });
-      });
-    })
-    .then((userData) => {
-      return Page.removePageByPath(`/user/${username}`)
-        .then(() => userData);
-    })
-    .then((userData) => {
-      req.flash('successMessage', `${username} さんのアカウントを削除しました`);
-      return res.redirect('/admin/users');
-    })
-    .catch((err) => {
-      req.flash('errorMessage', '削除に失敗しました。');
-      return res.redirect('/admin/users');
-    });
+    // 未実装
+    return res.redirect('/admin/users');
   };
 
   // これやったときの relation の挙動未確認
@@ -505,28 +374,6 @@ module.exports = function(crowi, app) {
     }
   };
 
-  actions.api.securitySetting = function(req, res) {
-    var form = req.form.settingForm;
-
-    if (req.form.isValid) {
-      debug('form content', form);
-      return saveSetting(req, res, form);
-    } else {
-      return res.json({status: false, message: req.form.errors.join('\n')});
-    }
-  };
-
-  actions.api.customizeSetting = function(req, res) {
-    var form = req.form.settingForm;
-
-    if (req.form.isValid) {
-      debug('form content', form);
-      return saveSetting(req, res, form);
-    } else {
-      return res.json({status: false, message: req.form.errors.join('\n')});
-    }
-  }
-
   // app.post('/_api/admin/notifications.add'    , admin.api.notificationAdd);
   actions.api.notificationAdd = function(req, res) {
     var UpdatePost = crowi.model('UpdatePost');

+ 1 - 1
lib/routes/page.js

@@ -605,7 +605,7 @@ module.exports = function(crowi, app) {
           if (crowi.slack) {
             notify.slack.channel.split(',').map(function(chan) {
               var message = crowi.slack.prepareSlackMessage(pageData, req.user, chan, updateOrCreate, previousRevision);
-              crowi.slack.post(message).then(function(){}).catch(function(){});
+              crowi.slack.post(message.channel, message.text, message).then(function(){}).catch(function(){});
             });
           }
         }

+ 44 - 125
lib/util/slack.js

@@ -5,113 +5,33 @@
 module.exports = function(crowi) {
   'use strict';
 
-  var debug = require('debug')('crowi:util:slack'),
+  const SLACK_URL = 'https://slack.com';
+
+  const debug = require('debug')('crowi:util:slack'),
     Config = crowi.model('Config'),
-    Botkit = require('botkit'),
-    isDebugSlackbot = false,
-    appBot = null,                  // for Slack App
-    iwhBot = null,                  // for Slack Incoming Webhooks
+    SlackWebClient = require('@slack/client').WebClient,
+    sprintf = require('sprintf'),
     slack = {};
-  slack.appController = undefined;  // for Slack App
-  slack.iwhController = undefined;  // for Slack Incoming Webhooks
-
-  // isDebugSlackbot = true;           // for debug
 
-  slack.getBot = function() {
-    var config = crowi.getConfig();
+  slack.client = undefined;
 
-    // when incoming Webhooks is prioritized
-    if (Config.isIncomingWebhookPrioritized(config)) {
-      if (Config.hasSlackIwhUrl(config)) {
-        return iwhBot || slack.initIwhBot();
-      }
-      else if (Config.hasSlackToken(config)) {
-        return appBot || slack.initAppBot();
-      }
+  slack.getClient = function() {
+    // alreay created
+    if (slack.client) {
+      return slack.client;
     }
-    // else
-    else {
-      if (Config.hasSlackToken(config)) {
-        return appBot || slack.initAppBot();
-      }
-      else if (Config.hasSlackIwhUrl(config)) {
-        return iwhBot || slack.initIwhBot();
-      }
-    }
-
-    return false;
-  };
 
-  slack.initAppBot = function(isClearToken) {
-    var config = crowi.getConfig();
-
-    if (!slack.appController) {
-      slack.configureSlackApp();
-    }
+    const config = crowi.getConfig();
 
-    if (!slack.appController) {
-      return false;
+    let client;
+    if (Config.hasSlackToken(config)) {
+      client = new SlackWebClient(config.notification['slack:token']);
+      slack.client = client;
     }
 
-    if (!isClearToken && Config.hasSlackToken(config)) {
-      appBot = slack.appController.spawn({token: config.notification['slack:token']});
-    } else {
-      appBot = slack.appController.spawn();
-    }
-    return appBot;
+    return slack.client;
   };
 
-  slack.initIwhBot = function() {
-    var config = crowi.getConfig();
-
-    if (!slack.iwhController) {
-      slack.configureSlackIwh();
-    }
-
-    if (!slack.iwhController) {
-      return false;
-    }
-
-    iwhBot = slack.iwhController.spawn({
-      incoming_webhook: {
-        url: config.notification['slack:incomingWebhookUrl']
-      }
-    });
-
-    return iwhBot;
-  }
-
-  slack.configureSlackApp = function ()
-  {
-    var config = crowi.getConfig();
-
-    if (Config.hasSlackAppConfig(config)) {
-      slack.appController = Botkit.slackbot({debug: isDebugSlackbot});
-      slack.appController.configureSlackApp({
-        clientId: config.notification['slack:clientId'],
-        clientSecret: config.notification['slack:clientSecret'],
-        redirectUri: slack.getSlackAuthCallbackUrl(),
-        scopes: ['chat:write:bot']
-      });
-
-      return true;
-    }
-
-    return false;
-  }
-
-  slack.configureSlackIwh = function ()
-  {
-    var config = crowi.getConfig();
-
-    if (Config.hasSlackIwhUrl(config)) {
-      slack.iwhController = Botkit.slackbot({debug: isDebugSlackbot});
-      return true;
-    }
-
-    return false;
-  }
-
   // hmmm
   slack.getSlackAuthCallbackUrl = function()
   {
@@ -122,39 +42,35 @@ module.exports = function(crowi) {
   }
 
   slack.getAuthorizeURL = function () {
-    if (!slack.appController) {
-      slack.configureSlackApp();
-    }
+    const config = crowi.getConfig();
+    if (Config.hasSlackConfig(config)) {
+      const slackClientId = config.notification['slack:clientId'];
+      const redirectUri = slack.getSlackAuthCallbackUrl();
+
+      return `${SLACK_URL}/oauth/authorize?client_id=${slackClientId}&redirect_uri=${redirectUri}&scope=chat:write:bot`;
+    } else {
 
-    if (!slack.appController) {
       return '';
     }
-
-    return slack.appController.getAuthorizeURL();
   }
 
-  slack.post = function (message) {
-    var bot = slack.getBot();
-    let sendMethod = undefined;
+  slack.getOauthAccessToken = function(code) {
 
-    // use Slack App
-    if (bot === appBot) {
-      debug(`sendMethod: bot.api.chat.postMessage`);
-      sendMethod = bot.api.chat.postMessage;
-    }
-    // use Slack Incoming Webhooks
-    else if (bot === iwhBot) {
-      debug(`sendMethod: bot.sendWebhook`);
-      sendMethod = bot.sendWebhook;
-    }
+    const client = new SlackWebClient();
 
-    if (sendMethod === undefined) {
-      debug(`sendMethod is undefined`);
-      return Promise.resolve();
-    }
+    const config = crowi.getConfig();
+    const clientId = config.notification['slack:clientId'];
+    const clientSecret = config.notification['slack:clientSecret'];
+    const redirectUri = slack.getSlackAuthCallbackUrl();
+
+    return client.oauth.access(clientId, clientSecret, code, {redirect_uri: redirectUri});
+  }
+
+  slack.post = function (channel, message, opts) {
+    const client = slack.getClient();
 
     return new Promise(function(resolve, reject) {
-      sendMethod(message, function(err, res) {
+      client.chat.postMessage(channel, message, opts, function(err, res) {
         if (err) {
           debug('Post error', err, res);
           debug('Sent data to slack is:', message);
@@ -200,12 +116,12 @@ module.exports = function(crowi) {
       debug('diff line', line)
       var value = line.value.replace(/\r\n|\r/g, '\n');
       if (line.added) {
-        diffText += `:pencil2: ...\n${line.value}`;
+        diffText += sprintf(':pencil2: ...\n%s', line.value);
       } else if (line.removed) {
         // diffText += '-' + line.value.replace(/(.+)?\n/g, '- $1\n');
         // 1以下は無視
         if (line.count > 1) {
-          diffText += `:wastebasket: ... ${line.count} lines\n`;
+          diffText += sprintf(':wastebasket: ... %s lines\n', line.count);
         }
       } else {
         //diffText += '...\n';
@@ -253,12 +169,15 @@ module.exports = function(crowi) {
   };
 
   slack.getSlackMessageText = function(path, user, updateType) {
-    var text;
+    let text;
+    const config = crowi.getConfig();
+    const url = config.crowi['app:url'] || '';
 
+    const pageUrl = `<${url}${path}|${path}>`;
     if (updateType == 'create') {
-      text = `:white_check_mark: ${user.username} created a new page! ${path}`;
+      text = sprintf(':white_check_mark: %s created a new page! %s', user.username, pageUrl);
     } else {
-      text = `:up: ${user.username} updated ${path}`;
+      text = sprintf(':up: %s updated %s', user.username, pageUrl);
     }
 
     return text;