admin.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  1. /* eslint-disable no-use-before-define */
  2. module.exports = function(crowi, app) {
  3. const debug = require('debug')('growi:routes:admin');
  4. const logger = require('@alias/logger')('growi:routes:admin');
  5. const models = crowi.models;
  6. const User = models.User;
  7. const ExternalAccount = models.ExternalAccount;
  8. const UserGroup = models.UserGroup;
  9. const UserGroupRelation = models.UserGroupRelation;
  10. const GlobalNotificationSetting = models.GlobalNotificationSetting;
  11. const GlobalNotificationMailSetting = models.GlobalNotificationMailSetting;
  12. const GlobalNotificationSlackSetting = models.GlobalNotificationSlackSetting; // eslint-disable-line no-unused-vars
  13. const {
  14. configManager,
  15. aclService,
  16. slackNotificationService,
  17. exportService,
  18. } = crowi;
  19. const recommendedWhitelist = require('@commons/service/xss/recommended-whitelist');
  20. const ApiResponse = require('../util/apiResponse');
  21. const importer = require('../util/importer')(crowi);
  22. const searchEvent = crowi.event('search');
  23. const MAX_PAGE_LIST = 50;
  24. const actions = {};
  25. const { check } = require('express-validator/check');
  26. const api = {};
  27. function createPager(total, limit, page, pagesCount, maxPageList) {
  28. const pager = {
  29. page,
  30. pagesCount,
  31. pages: [],
  32. total,
  33. previous: null,
  34. previousDots: false,
  35. next: null,
  36. nextDots: false,
  37. };
  38. if (page > 1) {
  39. pager.previous = page - 1;
  40. }
  41. if (page < pagesCount) {
  42. pager.next = page + 1;
  43. }
  44. let pagerMin = Math.max(1, Math.ceil(page - maxPageList / 2));
  45. let pagerMax = Math.min(pagesCount, Math.floor(page + maxPageList / 2));
  46. if (pagerMin === 1) {
  47. if (MAX_PAGE_LIST < pagesCount) {
  48. pagerMax = MAX_PAGE_LIST;
  49. }
  50. else {
  51. pagerMax = pagesCount;
  52. }
  53. }
  54. if (pagerMax === pagesCount) {
  55. if ((pagerMax - MAX_PAGE_LIST) < 1) {
  56. pagerMin = 1;
  57. }
  58. else {
  59. pagerMin = pagerMax - MAX_PAGE_LIST;
  60. }
  61. }
  62. pager.previousDots = null;
  63. if (pagerMin > 1) {
  64. pager.previousDots = true;
  65. }
  66. pager.nextDots = null;
  67. if (pagerMax < pagesCount) {
  68. pager.nextDots = true;
  69. }
  70. for (let i = pagerMin; i <= pagerMax; i++) {
  71. pager.pages.push(i);
  72. }
  73. return pager;
  74. }
  75. // setup websocket event for rebuild index
  76. searchEvent.on('addPageProgress', (total, current, skip) => {
  77. crowi.getIo().sockets.emit('admin:addPageProgress', { total, current, skip });
  78. });
  79. searchEvent.on('finishAddPage', (total, current, skip) => {
  80. crowi.getIo().sockets.emit('admin:finishAddPage', { total, current, skip });
  81. });
  82. actions.index = function(req, res) {
  83. return res.render('admin/index');
  84. };
  85. // app.get('/admin/app' , admin.app.index);
  86. actions.app = {};
  87. actions.app.index = function(req, res) {
  88. return res.render('admin/app');
  89. };
  90. actions.app.settingUpdate = function(req, res) {
  91. };
  92. // app.get('/admin/security' , admin.security.index);
  93. actions.security = {};
  94. actions.security.index = function(req, res) {
  95. const isWikiModeForced = aclService.isWikiModeForced();
  96. const guestModeValue = aclService.getGuestModeValue();
  97. return res.render('admin/security', {
  98. isWikiModeForced,
  99. guestModeValue,
  100. });
  101. };
  102. // app.get('/admin/markdown' , admin.markdown.index);
  103. actions.markdown = {};
  104. actions.markdown.index = function(req, res) {
  105. const markdownSetting = configManager.getConfigByPrefix('markdown', 'markdown:');
  106. return res.render('admin/markdown', {
  107. markdownSetting,
  108. recommendedWhitelist,
  109. });
  110. };
  111. // app.get('/admin/customize' , admin.customize.index);
  112. actions.customize = {};
  113. actions.customize.index = function(req, res) {
  114. const settingForm = configManager.getConfigByPrefix('crowi', 'customize:');
  115. // TODO delete after apiV3
  116. /* eslint-disable quote-props, no-multi-spaces */
  117. const highlightJsCssSelectorOptions = {
  118. 'github': { name: '[Light] GitHub', border: false },
  119. 'github-gist': { name: '[Light] GitHub Gist', border: true },
  120. 'atom-one-light': { name: '[Light] Atom One Light', border: true },
  121. 'xcode': { name: '[Light] Xcode', border: true },
  122. 'vs': { name: '[Light] Vs', border: true },
  123. 'atom-one-dark': { name: '[Dark] Atom One Dark', border: false },
  124. 'hybrid': { name: '[Dark] Hybrid', border: false },
  125. 'monokai': { name: '[Dark] Monokai', border: false },
  126. 'tomorrow-night': { name: '[Dark] Tomorrow Night', border: false },
  127. 'vs2015': { name: '[Dark] Vs 2015', border: false },
  128. };
  129. /* eslint-enable quote-props, no-multi-spaces */
  130. return res.render('admin/customize', {
  131. settingForm,
  132. highlightJsCssSelectorOptions,
  133. });
  134. };
  135. // app.get('/admin/notification' , admin.notification.index);
  136. actions.notification = {};
  137. actions.notification.index = async(req, res) => {
  138. const UpdatePost = crowi.model('UpdatePost');
  139. let slackSetting = configManager.getConfigByPrefix('notification', 'slack:');
  140. const hasSlackIwhUrl = !!configManager.getConfig('notification', 'slack:incomingWebhookUrl');
  141. const hasSlackToken = !!configManager.getConfig('notification', 'slack:token');
  142. if (!hasSlackIwhUrl) {
  143. slackSetting['slack:incomingWebhookUrl'] = '';
  144. }
  145. if (req.session.slackSetting) {
  146. slackSetting = req.session.slackSetting;
  147. req.session.slackSetting = null;
  148. }
  149. const globalNotifications = await GlobalNotificationSetting.findAll();
  150. const userNotifications = await UpdatePost.findAll();
  151. return res.render('admin/notification', {
  152. userNotifications,
  153. slackSetting,
  154. hasSlackIwhUrl,
  155. hasSlackToken,
  156. globalNotifications,
  157. });
  158. };
  159. // app.post('/admin/notification/slackSetting' , admin.notification.slackauth);
  160. actions.notification.slackSetting = async function(req, res) {
  161. const slackSetting = req.form.slackSetting;
  162. if (req.form.isValid) {
  163. await configManager.updateConfigsInTheSameNamespace('notification', slackSetting);
  164. req.flash('successMessage', ['Successfully Updated!']);
  165. // Re-setup
  166. crowi.setupSlack().then(() => {
  167. });
  168. }
  169. else {
  170. req.flash('errorMessage', req.form.errors);
  171. }
  172. return res.redirect('/admin/notification');
  173. };
  174. // app.get('/admin/notification/slackAuth' , admin.notification.slackauth);
  175. actions.notification.slackAuth = function(req, res) {
  176. const code = req.query.code;
  177. if (!code || !slackNotificationService.hasSlackConfig()) {
  178. return res.redirect('/admin/notification');
  179. }
  180. const slack = crowi.slack;
  181. slack.getOauthAccessToken(code)
  182. .then(async(data) => {
  183. debug('oauth response', data);
  184. try {
  185. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': data.access_token });
  186. req.flash('successMessage', ['Successfully Connected!']);
  187. }
  188. catch (err) {
  189. req.flash('errorMessage', ['Failed to save access_token. Please try again.']);
  190. }
  191. return res.redirect('/admin/notification');
  192. })
  193. .catch((err) => {
  194. debug('oauth response ERROR', err);
  195. req.flash('errorMessage', ['Failed to fetch access_token. Please do connect again.']);
  196. return res.redirect('/admin/notification');
  197. });
  198. };
  199. // app.post('/admin/notification/slackIwhSetting' , admin.notification.slackIwhSetting);
  200. actions.notification.slackIwhSetting = async function(req, res) {
  201. const slackIwhSetting = req.form.slackIwhSetting;
  202. if (req.form.isValid) {
  203. await configManager.updateConfigsInTheSameNamespace('notification', slackIwhSetting);
  204. req.flash('successMessage', ['Successfully Updated!']);
  205. // Re-setup
  206. crowi.setupSlack().then(() => {
  207. return res.redirect('/admin/notification#slack-incoming-webhooks');
  208. });
  209. }
  210. else {
  211. req.flash('errorMessage', req.form.errors);
  212. return res.redirect('/admin/notification#slack-incoming-webhooks');
  213. }
  214. };
  215. // app.post('/admin/notification/slackSetting/disconnect' , admin.notification.disconnectFromSlack);
  216. actions.notification.disconnectFromSlack = async function(req, res) {
  217. await configManager.updateConfigsInTheSameNamespace('notification', { 'slack:token': '' });
  218. req.flash('successMessage', ['Successfully Disconnected!']);
  219. return res.redirect('/admin/notification');
  220. };
  221. actions.globalNotification = {};
  222. actions.globalNotification.detail = async(req, res) => {
  223. const notificationSettingId = req.params.id;
  224. const renderVars = {};
  225. if (notificationSettingId) {
  226. try {
  227. renderVars.setting = await GlobalNotificationSetting.findOne({ _id: notificationSettingId });
  228. }
  229. catch (err) {
  230. logger.error(`Error in finding a global notification setting with {_id: ${notificationSettingId}}`);
  231. }
  232. }
  233. return res.render('admin/global-notification-detail', renderVars);
  234. };
  235. actions.globalNotification.create = (req, res) => {
  236. const form = req.form.notificationGlobal;
  237. let setting;
  238. switch (form.notifyToType) {
  239. case GlobalNotificationSetting.TYPE.MAIL:
  240. setting = new GlobalNotificationMailSetting(crowi);
  241. setting.toEmail = form.toEmail;
  242. break;
  243. case GlobalNotificationSetting.TYPE.SLACK:
  244. setting = new GlobalNotificationSlackSetting(crowi);
  245. setting.slackChannels = form.slackChannels;
  246. break;
  247. default:
  248. logger.error('GlobalNotificationSetting Type Error: undefined type');
  249. req.flash('errorMessage', 'Error occurred in creating a new global notification setting: undefined notification type');
  250. return res.redirect('/admin/notification#global-notification');
  251. }
  252. setting.triggerPath = form.triggerPath;
  253. setting.triggerEvents = getNotificationEvents(form);
  254. setting.save();
  255. return res.redirect('/admin/notification#global-notification');
  256. };
  257. actions.globalNotification.update = async(req, res) => {
  258. const form = req.form.notificationGlobal;
  259. const models = {
  260. [GlobalNotificationSetting.TYPE.MAIL]: GlobalNotificationMailSetting,
  261. [GlobalNotificationSetting.TYPE.SLACK]: GlobalNotificationSlackSetting,
  262. };
  263. let setting = await GlobalNotificationSetting.findOne({ _id: form.id });
  264. setting = setting.toObject();
  265. // when switching from one type to another,
  266. // remove toEmail from slack setting and slackChannels from mail setting
  267. if (setting.__t !== form.notifyToType) {
  268. setting = models[setting.__t].hydrate(setting);
  269. setting.toEmail = undefined;
  270. setting.slackChannels = undefined;
  271. await setting.save();
  272. setting = setting.toObject();
  273. }
  274. switch (form.notifyToType) {
  275. case GlobalNotificationSetting.TYPE.MAIL:
  276. setting = GlobalNotificationMailSetting.hydrate(setting);
  277. setting.toEmail = form.toEmail;
  278. break;
  279. case GlobalNotificationSetting.TYPE.SLACK:
  280. setting = GlobalNotificationSlackSetting.hydrate(setting);
  281. setting.slackChannels = form.slackChannels;
  282. break;
  283. default:
  284. logger.error('GlobalNotificationSetting Type Error: undefined type');
  285. req.flash('errorMessage', 'Error occurred in updating the global notification setting: undefined notification type');
  286. return res.redirect('/admin/notification#global-notification');
  287. }
  288. setting.__t = form.notifyToType;
  289. setting.triggerPath = form.triggerPath;
  290. setting.triggerEvents = getNotificationEvents(form);
  291. await setting.save();
  292. return res.redirect('/admin/notification#global-notification');
  293. };
  294. actions.globalNotification.remove = async(req, res) => {
  295. const id = req.params.id;
  296. try {
  297. await GlobalNotificationSetting.findOneAndRemove({ _id: id });
  298. return res.redirect('/admin/notification#global-notification');
  299. }
  300. catch (err) {
  301. req.flash('errorMessage', 'Error in deleting global notification setting');
  302. return res.redirect('/admin/notification#global-notification');
  303. }
  304. };
  305. const getNotificationEvents = (form) => {
  306. const triggerEvents = [];
  307. const triggerEventKeys = Object.keys(form).filter((key) => { return key.match(/^triggerEvent/) });
  308. triggerEventKeys.forEach((key) => {
  309. if (form[key]) {
  310. triggerEvents.push(form[key]);
  311. }
  312. });
  313. return triggerEvents;
  314. };
  315. actions.search = {};
  316. actions.search.index = function(req, res) {
  317. const search = crowi.getSearcher();
  318. if (!search) {
  319. return res.redirect('/admin');
  320. }
  321. return res.render('admin/search', {});
  322. };
  323. actions.user = {};
  324. actions.user.index = async function(req, res) {
  325. return res.render('admin/users');
  326. };
  327. // これやったときの relation の挙動未確認
  328. actions.user.removeCompletely = function(req, res) {
  329. // ユーザーの物理削除
  330. const id = req.params.id;
  331. User.removeCompletelyById(id, (err, removed) => {
  332. if (err) {
  333. debug('Error while removing user.', err, id);
  334. req.flash('errorMessage', '完全な削除に失敗しました。');
  335. }
  336. else {
  337. req.flash('successMessage', '削除しました');
  338. }
  339. return res.redirect('/admin/users');
  340. });
  341. };
  342. // app.post('/_api/admin/users.resetPassword' , admin.api.usersResetPassword);
  343. actions.user.resetPassword = async function(req, res) {
  344. const id = req.body.user_id;
  345. const User = crowi.model('User');
  346. try {
  347. const newPassword = await User.resetPasswordByRandomString(id);
  348. const user = await User.findById(id);
  349. const result = { user: user.toObject(), newPassword };
  350. return res.json(ApiResponse.success(result));
  351. }
  352. catch (err) {
  353. debug('Error on reseting password', err);
  354. return res.json(ApiResponse.error(err));
  355. }
  356. };
  357. actions.externalAccount = {};
  358. actions.externalAccount.index = function(req, res) {
  359. return res.render('admin/external-accounts');
  360. };
  361. actions.externalAccount.remove = async function(req, res) {
  362. const id = req.params.id;
  363. let account = null;
  364. try {
  365. account = await ExternalAccount.findByIdAndRemove(id);
  366. if (account == null) {
  367. throw new Error('削除に失敗しました。');
  368. }
  369. }
  370. catch (err) {
  371. req.flash('errorMessage', err.message);
  372. return res.redirect('/admin/users/external-accounts');
  373. }
  374. req.flash('successMessage', `外部アカウント '${account.providerType}/${account.accountId}' を削除しました`);
  375. return res.redirect('/admin/users/external-accounts');
  376. };
  377. actions.userGroup = {};
  378. actions.userGroup.index = function(req, res) {
  379. const page = parseInt(req.query.page) || 1;
  380. const isAclEnabled = aclService.isAclEnabled();
  381. const renderVar = {
  382. userGroups: [],
  383. userGroupRelations: new Map(),
  384. pager: null,
  385. isAclEnabled,
  386. };
  387. UserGroup.findUserGroupsWithPagination({ page })
  388. .then((result) => {
  389. const pager = createPager(result.total, result.limit, result.page, result.pages, MAX_PAGE_LIST);
  390. const userGroups = result.docs;
  391. renderVar.userGroups = userGroups;
  392. renderVar.pager = pager;
  393. return userGroups.map((userGroup) => {
  394. return new Promise((resolve, reject) => {
  395. UserGroupRelation.findAllRelationForUserGroup(userGroup)
  396. .then((relations) => {
  397. return resolve({
  398. id: userGroup._id,
  399. relatedUsers: relations.map((relation) => {
  400. return relation.relatedUser;
  401. }),
  402. });
  403. });
  404. });
  405. });
  406. })
  407. .then((allRelationsPromise) => {
  408. return Promise.all(allRelationsPromise);
  409. })
  410. .then((relations) => {
  411. for (const relation of relations) {
  412. renderVar.userGroupRelations[relation.id] = relation.relatedUsers;
  413. }
  414. debug('in findUserGroupsWithPagination findAllRelationForUserGroupResult', renderVar.userGroupRelations);
  415. return res.render('admin/user-groups', renderVar);
  416. })
  417. .catch((err) => {
  418. debug('Error on find all relations', err);
  419. return res.json(ApiResponse.error('Error'));
  420. });
  421. };
  422. // グループ詳細
  423. actions.userGroup.detail = async function(req, res) {
  424. const userGroupId = req.params.id;
  425. const userGroup = await UserGroup.findOne({ _id: userGroupId });
  426. if (userGroup == null) {
  427. logger.error('no userGroup is exists. ', userGroupId);
  428. return res.redirect('/admin/user-groups');
  429. }
  430. return res.render('admin/user-group-detail', { userGroup });
  431. };
  432. // Importer management
  433. actions.importer = {};
  434. actions.importer.api = api;
  435. api.validators = {};
  436. api.validators.importer = {};
  437. actions.importer.index = function(req, res) {
  438. const settingForm = configManager.getConfigByPrefix('crowi', 'importer:');
  439. return res.render('admin/importer', {
  440. settingForm,
  441. });
  442. };
  443. api.validators.importer.esa = function() {
  444. const validator = [
  445. check('importer:esa:team_name').not().isEmpty().withMessage('Error. Empty esa:team_name'),
  446. check('importer:esa:access_token').not().isEmpty().withMessage('Error. Empty esa:access_token'),
  447. ];
  448. return validator;
  449. };
  450. api.validators.importer.qiita = function() {
  451. const validator = [
  452. check('importer:qiita:team_name').not().isEmpty().withMessage('Error. Empty qiita:team_name'),
  453. check('importer:qiita:access_token').not().isEmpty().withMessage('Error. Empty qiita:access_token'),
  454. ];
  455. return validator;
  456. };
  457. // Export management
  458. actions.export = {};
  459. actions.export.index = (req, res) => {
  460. return res.render('admin/export');
  461. };
  462. actions.export.download = (req, res) => {
  463. // TODO: add express validator
  464. const { fileName } = req.params;
  465. try {
  466. const zipFile = exportService.getFile(fileName);
  467. return res.download(zipFile);
  468. }
  469. catch (err) {
  470. // TODO: use ApiV3Error
  471. logger.error(err);
  472. return res.json(ApiResponse.error());
  473. }
  474. };
  475. actions.api = {};
  476. // app.post('/_api/admin/notifications.add' , admin.api.notificationAdd);
  477. actions.api.notificationAdd = function(req, res) {
  478. const UpdatePost = crowi.model('UpdatePost');
  479. const pathPattern = req.body.pathPattern;
  480. const channel = req.body.channel;
  481. debug('notification.add', pathPattern, channel);
  482. UpdatePost.create(pathPattern, channel, req.user)
  483. .then((doc) => {
  484. debug('Successfully save updatePost', doc);
  485. // fixme: うーん
  486. doc.creator = doc.creator._id.toString();
  487. return res.json(ApiResponse.success({ updatePost: doc }));
  488. })
  489. .catch((err) => {
  490. debug('Failed to save updatePost', err);
  491. return res.json(ApiResponse.error());
  492. });
  493. };
  494. // app.post('/_api/admin/notifications.remove' , admin.api.notificationRemove);
  495. actions.api.notificationRemove = function(req, res) {
  496. const UpdatePost = crowi.model('UpdatePost');
  497. const id = req.body.id;
  498. UpdatePost.remove(id)
  499. .then(() => {
  500. debug('Successfully remove updatePost');
  501. return res.json(ApiResponse.success({}));
  502. })
  503. .catch((err) => {
  504. debug('Failed to remove updatePost', err);
  505. return res.json(ApiResponse.error());
  506. });
  507. };
  508. // app.get('/_api/admin/users.search' , admin.api.userSearch);
  509. actions.api.usersSearch = function(req, res) {
  510. const User = crowi.model('User');
  511. const email = req.query.email;
  512. User.findUsersByPartOfEmail(email, {})
  513. .then((users) => {
  514. const result = {
  515. data: users,
  516. };
  517. return res.json(ApiResponse.success(result));
  518. })
  519. .catch((err) => {
  520. return res.json(ApiResponse.error());
  521. });
  522. };
  523. actions.api.toggleIsEnabledForGlobalNotification = async(req, res) => {
  524. const id = req.query.id;
  525. const isEnabled = (req.query.isEnabled === 'true');
  526. try {
  527. if (isEnabled) {
  528. await GlobalNotificationSetting.enable(id);
  529. }
  530. else {
  531. await GlobalNotificationSetting.disable(id);
  532. }
  533. return res.json(ApiResponse.success());
  534. }
  535. catch (err) {
  536. return res.json(ApiResponse.error());
  537. }
  538. };
  539. /**
  540. * save esa settings, update config cache, and response json
  541. *
  542. * @param {*} req
  543. * @param {*} res
  544. */
  545. actions.api.importerSettingEsa = async(req, res) => {
  546. const form = req.body;
  547. const { validationResult } = require('express-validator');
  548. const errors = validationResult(req);
  549. if (!errors.isEmpty()) {
  550. return res.json(ApiResponse.error('esa.io form is blank'));
  551. }
  552. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  553. importer.initializeEsaClient(); // let it run in the back aftert res
  554. return res.json(ApiResponse.success());
  555. };
  556. /**
  557. * save qiita settings, update config cache, and response json
  558. *
  559. * @param {*} req
  560. * @param {*} res
  561. */
  562. actions.api.importerSettingQiita = async(req, res) => {
  563. const form = req.body;
  564. const { validationResult } = require('express-validator');
  565. const errors = validationResult(req);
  566. if (!errors.isEmpty()) {
  567. return res.json(ApiResponse.error('Qiita form is blank'));
  568. }
  569. await configManager.updateConfigsInTheSameNamespace('crowi', form);
  570. importer.initializeQiitaClient(); // let it run in the back aftert res
  571. return res.json(ApiResponse.success());
  572. };
  573. /**
  574. * Import all posts from esa
  575. *
  576. * @param {*} req
  577. * @param {*} res
  578. */
  579. actions.api.importDataFromEsa = async(req, res) => {
  580. const user = req.user;
  581. let errors;
  582. try {
  583. errors = await importer.importDataFromEsa(user);
  584. }
  585. catch (err) {
  586. errors = [err];
  587. }
  588. if (errors.length > 0) {
  589. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  590. }
  591. return res.json(ApiResponse.success());
  592. };
  593. /**
  594. * Import all posts from qiita
  595. *
  596. * @param {*} req
  597. * @param {*} res
  598. */
  599. actions.api.importDataFromQiita = async(req, res) => {
  600. const user = req.user;
  601. let errors;
  602. try {
  603. errors = await importer.importDataFromQiita(user);
  604. }
  605. catch (err) {
  606. errors = [err];
  607. }
  608. if (errors.length > 0) {
  609. return res.json(ApiResponse.error(`<br> - ${errors.join('<br> - ')}`));
  610. }
  611. return res.json(ApiResponse.success());
  612. };
  613. /**
  614. * Test connection to esa and response result with json
  615. *
  616. * @param {*} req
  617. * @param {*} res
  618. */
  619. actions.api.testEsaAPI = async(req, res) => {
  620. try {
  621. await importer.testConnectionToEsa();
  622. return res.json(ApiResponse.success());
  623. }
  624. catch (err) {
  625. return res.json(ApiResponse.error(err));
  626. }
  627. };
  628. /**
  629. * Test connection to qiita and response result with json
  630. *
  631. * @param {*} req
  632. * @param {*} res
  633. */
  634. actions.api.testQiitaAPI = async(req, res) => {
  635. try {
  636. await importer.testConnectionToQiita();
  637. return res.json(ApiResponse.success());
  638. }
  639. catch (err) {
  640. return res.json(ApiResponse.error(err));
  641. }
  642. };
  643. actions.api.searchBuildIndex = async function(req, res) {
  644. const search = crowi.getSearcher();
  645. if (!search) {
  646. return res.json(ApiResponse.error('ElasticSearch Integration is not set up.'));
  647. }
  648. try {
  649. search.buildIndex();
  650. }
  651. catch (err) {
  652. return res.json(ApiResponse.error(err));
  653. }
  654. return res.json(ApiResponse.success());
  655. };
  656. return actions;
  657. };