index.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812
  1. /* eslint-disable @typescript-eslint/no-this-alias */
  2. import http from 'http';
  3. import path from 'path';
  4. import { createTerminus } from '@godaddy/terminus';
  5. import attachmentRoutes from '@growi/remark-attachment-refs/dist/server';
  6. import lsxRoutes from '@growi/remark-lsx/dist/server/index.cjs';
  7. import mongoose from 'mongoose';
  8. import next from 'next';
  9. import pkg from '^/package.json';
  10. import { KeycloakUserGroupSyncService } from '~/features/external-user-group/server/service/keycloak-user-group-sync';
  11. import { LdapUserGroupSyncService } from '~/features/external-user-group/server/service/ldap-user-group-sync';
  12. import QuestionnaireService from '~/features/questionnaire/server/service/questionnaire';
  13. import QuestionnaireCronService from '~/features/questionnaire/server/service/questionnaire-cron';
  14. import Xss from '~/services/xss';
  15. import loggerFactory from '~/utils/logger';
  16. import { projectRoot } from '~/utils/project-dir-utils';
  17. import UserEvent from '../events/user';
  18. import { modelsDependsOnCrowi } from '../models';
  19. import { aclService as aclServiceSingletonInstance } from '../service/acl';
  20. import AppService from '../service/app';
  21. import AttachmentService from '../service/attachment';
  22. import { configManager as configManagerSingletonInstance } from '../service/config-manager';
  23. import { instanciate as instanciateExternalAccountService } from '../service/external-account';
  24. import { FileUploader, getUploader } from '../service/file-uploader'; // eslint-disable-line no-unused-vars
  25. import { G2GTransferPusherService, G2GTransferReceiverService } from '../service/g2g-transfer';
  26. import { InstallerService } from '../service/installer';
  27. import { normalizeData } from '../service/normalize-data';
  28. import PageService from '../service/page';
  29. import PageGrantService from '../service/page-grant';
  30. import PageOperationService from '../service/page-operation';
  31. import PassportService from '../service/passport';
  32. import SearchService from '../service/search';
  33. import { SlackIntegrationService } from '../service/slack-integration';
  34. import UserGroupService from '../service/user-group';
  35. import { UserNotificationService } from '../service/user-notification';
  36. import { instantiateYjsConnectionManager } from '../service/yjs-connection-manager';
  37. import { getMongoUri, mongoOptions } from '../util/mongoose-utils';
  38. import { OpenTelemetry } from './opentelemetry';
  39. const logger = loggerFactory('growi:crowi');
  40. const httpErrorHandler = require('../middlewares/http-error-handler');
  41. const sep = path.sep;
  42. class Crowi {
  43. /** @type {AppService} */
  44. appService;
  45. /** @type {import('../service/page').IPageService} */
  46. pageService;
  47. /** @type UserNotificationService */
  48. userNotificationService;
  49. /** @type {FileUploader} */
  50. fileUploadService;
  51. constructor() {
  52. this.version = pkg.version;
  53. this.runtimeVersions = undefined; // initialized by scanRuntimeVersions()
  54. this.publicDir = path.join(projectRoot, 'public') + sep;
  55. this.resourceDir = path.join(projectRoot, 'resource') + sep;
  56. this.localeDir = path.join(this.resourceDir, 'locales') + sep;
  57. this.viewsDir = path.resolve(__dirname, '../views') + sep;
  58. this.tmpDir = path.join(projectRoot, 'tmp') + sep;
  59. this.cacheDir = path.join(this.tmpDir, 'cache');
  60. this.express = null;
  61. this.config = {};
  62. this.configManager = null;
  63. this.s2sMessagingService = null;
  64. this.g2gTransferPusherService = null;
  65. this.g2gTransferReceiverService = null;
  66. this.mailService = null;
  67. this.passportService = null;
  68. this.globalNotificationService = null;
  69. this.xssService = null;
  70. this.aclService = null;
  71. this.appService = null;
  72. this.fileUploadService = null;
  73. this.restQiitaAPIService = null;
  74. this.growiBridgeService = null;
  75. this.exportService = null;
  76. this.importService = null;
  77. this.pluginService = null;
  78. this.searchService = null;
  79. this.socketIoService = null;
  80. this.syncPageStatusService = null;
  81. this.slackIntegrationService = null;
  82. this.inAppNotificationService = null;
  83. this.activityService = null;
  84. this.commentService = null;
  85. this.xss = new Xss();
  86. this.questionnaireService = null;
  87. this.questionnaireCronService = null;
  88. this.tokens = null;
  89. this.models = {};
  90. this.env = process.env;
  91. this.node_env = this.env.NODE_ENV || 'development';
  92. this.port = this.env.PORT || 3000;
  93. this.events = {
  94. user: new UserEvent(this),
  95. page: new (require('../events/page'))(this),
  96. activity: new (require('../events/activity'))(this),
  97. bookmark: new (require('../events/bookmark'))(this),
  98. tag: new (require('../events/tag'))(this),
  99. admin: new (require('../events/admin'))(this),
  100. };
  101. }
  102. }
  103. Crowi.prototype.init = async function() {
  104. await this.setupDatabase();
  105. await this.setupModels();
  106. await this.setupConfigManager();
  107. await this.setupSessionConfig();
  108. this.setupCron();
  109. // setup messaging services
  110. await this.setupS2sMessagingService();
  111. await this.setupSocketIoService();
  112. // customizeService depends on AppService and XssService
  113. // passportService depends on appService
  114. // export and import depends on setUpGrowiBridge
  115. await Promise.all([
  116. this.setUpApp(),
  117. this.setUpXss(),
  118. this.setUpGrowiBridge(),
  119. ]);
  120. await Promise.all([
  121. this.scanRuntimeVersions(),
  122. this.setupPassport(),
  123. this.setupSearcher(),
  124. this.setupMailer(),
  125. this.setupSlackIntegrationService(),
  126. this.setupG2GTransferService(),
  127. this.setUpFileUpload(),
  128. this.setUpFileUploaderSwitchService(),
  129. this.setupAttachmentService(),
  130. this.setUpAcl(),
  131. this.setUpRestQiitaAPI(),
  132. this.setupUserGroupService(),
  133. this.setupExport(),
  134. this.setupImport(),
  135. this.setupGrowiPluginService(),
  136. this.setupPageService(),
  137. this.setupInAppNotificationService(),
  138. this.setupActivityService(),
  139. this.setupCommentService(),
  140. this.setupSyncPageStatusService(),
  141. this.setupQuestionnaireService(),
  142. this.setUpCustomize(), // depends on pluginService
  143. ]);
  144. await Promise.all([
  145. // globalNotification depends on slack and mailer
  146. this.setUpGlobalNotification(),
  147. this.setUpUserNotification(),
  148. // depends on passport service
  149. this.setupExternalAccountService(),
  150. this.setupExternalUserGroupSyncService(),
  151. ]);
  152. await normalizeData();
  153. };
  154. /**
  155. * Execute functions that should be run after the express server is ready.
  156. */
  157. Crowi.prototype.asyncAfterExpressServerReady = async function() {
  158. if (this.pageOperationService != null) {
  159. await this.pageOperationService.afterExpressServerReady();
  160. }
  161. };
  162. Crowi.prototype.isPageId = function(pageId) {
  163. if (!pageId) {
  164. return false;
  165. }
  166. if (typeof pageId === 'string' && pageId.match(/^[\da-f]{24}$/)) {
  167. return true;
  168. }
  169. return false;
  170. };
  171. Crowi.prototype.setConfig = function(config) {
  172. this.config = config;
  173. };
  174. Crowi.prototype.getConfig = function() {
  175. return this.config;
  176. };
  177. Crowi.prototype.getEnv = function() {
  178. return this.env;
  179. };
  180. // getter/setter of model instance
  181. //
  182. Crowi.prototype.model = function(name, model) {
  183. if (model != null) {
  184. this.models[name] = model;
  185. }
  186. return this.models[name];
  187. };
  188. // getter/setter of event instance
  189. Crowi.prototype.event = function(name, event) {
  190. if (event) {
  191. this.events[name] = event;
  192. }
  193. return this.events[name];
  194. };
  195. Crowi.prototype.setupDatabase = function() {
  196. mongoose.Promise = global.Promise;
  197. // mongoUri = mongodb://user:password@host/dbname
  198. const mongoUri = getMongoUri();
  199. return mongoose.connect(mongoUri, mongoOptions);
  200. };
  201. Crowi.prototype.setupSessionConfig = async function() {
  202. const session = require('express-session');
  203. const sessionMaxAge = this.configManager.getConfig('crowi', 'security:sessionMaxAge') || 2592000000; // default: 30days
  204. const redisUrl = this.env.REDISTOGO_URL || this.env.REDIS_URI || this.env.REDIS_URL || null;
  205. const uid = require('uid-safe').sync;
  206. // generate pre-defined uid for healthcheck
  207. const healthcheckUid = uid(24);
  208. const sessionConfig = {
  209. rolling: true,
  210. secret: this.env.SECRET_TOKEN || 'this is default session secret',
  211. resave: false,
  212. saveUninitialized: true,
  213. cookie: {
  214. maxAge: sessionMaxAge,
  215. },
  216. genid(req) {
  217. // return pre-defined uid when healthcheck
  218. if (req.path === '/_api/v3/healthcheck') {
  219. return healthcheckUid;
  220. }
  221. return uid(24);
  222. },
  223. };
  224. if (this.env.SESSION_NAME) {
  225. sessionConfig.name = this.env.SESSION_NAME;
  226. }
  227. // use Redis for session store
  228. if (redisUrl) {
  229. const redis = require('redis');
  230. const redisClient = redis.createClient({ url: redisUrl });
  231. const RedisStore = require('connect-redis')(session);
  232. sessionConfig.store = new RedisStore({ client: redisClient });
  233. }
  234. // use MongoDB for session store
  235. else {
  236. const MongoStore = require('connect-mongo');
  237. sessionConfig.store = MongoStore.create({ client: mongoose.connection.getClient() });
  238. }
  239. this.sessionConfig = sessionConfig;
  240. };
  241. Crowi.prototype.setupConfigManager = async function() {
  242. this.configManager = configManagerSingletonInstance;
  243. return this.configManager.loadConfigs();
  244. };
  245. Crowi.prototype.setupS2sMessagingService = async function() {
  246. const s2sMessagingService = require('../service/s2s-messaging')(this);
  247. if (s2sMessagingService != null) {
  248. s2sMessagingService.subscribe();
  249. this.configManager.setS2sMessagingService(s2sMessagingService);
  250. // add as a message handler
  251. s2sMessagingService.addMessageHandler(this.configManager);
  252. this.s2sMessagingService = s2sMessagingService;
  253. }
  254. };
  255. Crowi.prototype.setupSocketIoService = async function() {
  256. const SocketIoService = require('../service/socket-io');
  257. if (this.socketIoService == null) {
  258. this.socketIoService = new SocketIoService(this);
  259. }
  260. };
  261. Crowi.prototype.setupModels = async function() {
  262. Object.keys(modelsDependsOnCrowi).forEach((key) => {
  263. const factory = modelsDependsOnCrowi[key];
  264. if (!(factory instanceof Function)) {
  265. logger.warn(`modelsDependsOnCrowi['${key}'] is not a function. skipped.`);
  266. return;
  267. }
  268. return this.model(key, modelsDependsOnCrowi[key](this));
  269. });
  270. };
  271. Crowi.prototype.setupCron = function() {
  272. this.questionnaireCronService = new QuestionnaireCronService(this);
  273. this.questionnaireCronService.startCron();
  274. };
  275. Crowi.prototype.setupQuestionnaireService = function() {
  276. this.questionnaireService = new QuestionnaireService(this);
  277. };
  278. Crowi.prototype.scanRuntimeVersions = async function() {
  279. const self = this;
  280. const check = require('check-node-version');
  281. return new Promise((resolve, reject) => {
  282. check((err, result) => {
  283. if (err) {
  284. reject(err);
  285. }
  286. self.runtimeVersions = result;
  287. resolve();
  288. });
  289. });
  290. };
  291. Crowi.prototype.getSlack = function() {
  292. return this.slack;
  293. };
  294. Crowi.prototype.getSlackLegacy = function() {
  295. return this.slackLegacy;
  296. };
  297. Crowi.prototype.getGlobalNotificationService = function() {
  298. return this.globalNotificationService;
  299. };
  300. Crowi.prototype.getUserNotificationService = function() {
  301. return this.userNotificationService;
  302. };
  303. Crowi.prototype.getRestQiitaAPIService = function() {
  304. return this.restQiitaAPIService;
  305. };
  306. Crowi.prototype.setupPassport = async function() {
  307. logger.debug('Passport is enabled');
  308. // initialize service
  309. if (this.passportService == null) {
  310. this.passportService = new PassportService(this);
  311. }
  312. this.passportService.setupSerializer();
  313. // setup strategies
  314. try {
  315. this.passportService.setupStrategyById('local');
  316. this.passportService.setupStrategyById('ldap');
  317. this.passportService.setupStrategyById('saml');
  318. this.passportService.setupStrategyById('oidc');
  319. this.passportService.setupStrategyById('google');
  320. this.passportService.setupStrategyById('github');
  321. }
  322. catch (err) {
  323. logger.error(err);
  324. }
  325. // add as a message handler
  326. if (this.s2sMessagingService != null) {
  327. this.s2sMessagingService.addMessageHandler(this.passportService);
  328. }
  329. return Promise.resolve();
  330. };
  331. Crowi.prototype.setupSearcher = async function() {
  332. this.searchService = new SearchService(this);
  333. };
  334. Crowi.prototype.setupMailer = async function() {
  335. const MailService = require('~/server/service/mail');
  336. this.mailService = new MailService(this);
  337. // add as a message handler
  338. if (this.s2sMessagingService != null) {
  339. this.s2sMessagingService.addMessageHandler(this.mailService);
  340. }
  341. };
  342. Crowi.prototype.autoInstall = async function() {
  343. const isInstalled = this.configManager.getConfig('crowi', 'app:installed');
  344. const username = this.configManager.getConfig('crowi', 'autoInstall:adminUsername');
  345. if (isInstalled || username == null) {
  346. return;
  347. }
  348. logger.info('Start automatic installation');
  349. const firstAdminUserToSave = {
  350. username,
  351. name: this.configManager.getConfig('crowi', 'autoInstall:adminName'),
  352. email: this.configManager.getConfig('crowi', 'autoInstall:adminEmail'),
  353. password: this.configManager.getConfig('crowi', 'autoInstall:adminPassword'),
  354. admin: true,
  355. };
  356. const globalLang = this.configManager.getConfig('crowi', 'autoInstall:globalLang');
  357. const allowGuestMode = this.configManager.getConfig('crowi', 'autoInstall:allowGuestMode');
  358. const serverDate = this.configManager.getConfig('crowi', 'autoInstall:serverDate');
  359. const installerService = new InstallerService(this);
  360. try {
  361. await installerService.install(firstAdminUserToSave, globalLang ?? 'en_US', {
  362. allowGuestMode,
  363. serverDate,
  364. });
  365. }
  366. catch (err) {
  367. logger.warn('Automatic installation failed.', err);
  368. }
  369. };
  370. Crowi.prototype.getTokens = function() {
  371. return this.tokens;
  372. };
  373. Crowi.prototype.start = async function() {
  374. const dev = process.env.NODE_ENV !== 'production';
  375. await this.init();
  376. await this.buildServer();
  377. // 具体的な設定値については、https://redmine.weseek.co.jp/issues/144351 で決定予定
  378. const otel = new OpenTelemetry('next-app', this.version);
  379. otel.startInstrumentation();
  380. // setup Next.js
  381. this.nextApp = next({ dev });
  382. await this.nextApp.prepare();
  383. // setup CrowiDev
  384. if (dev) {
  385. const CrowiDev = require('./dev');
  386. this.crowiDev = new CrowiDev(this);
  387. this.crowiDev.init();
  388. }
  389. const { express } = this;
  390. const app = (this.node_env === 'development') ? this.crowiDev.setupServer(express) : express;
  391. const httpServer = http.createServer(app);
  392. // setup terminus
  393. this.setupTerminus(httpServer);
  394. // attach to socket.io
  395. this.socketIoService.attachServer(httpServer);
  396. // Initialization YjsConnectionManager
  397. instantiateYjsConnectionManager(this.socketIoService.io);
  398. this.socketIoService.setupYjsConnection();
  399. await this.autoInstall();
  400. // listen
  401. const serverListening = httpServer.listen(this.port, () => {
  402. logger.info(`[${this.node_env}] Express server is listening on port ${this.port}`);
  403. if (this.node_env === 'development') {
  404. this.crowiDev.setupExpressAfterListening(express);
  405. }
  406. });
  407. // setup Express Routes
  408. this.setupRoutesForPlugins();
  409. this.setupRoutesAtLast();
  410. // setup Global Error Handlers
  411. this.setupGlobalErrorHandlers();
  412. // Execute this asynchronously after the express server is ready so it does not block the ongoing process
  413. this.asyncAfterExpressServerReady();
  414. return serverListening;
  415. };
  416. Crowi.prototype.buildServer = async function() {
  417. const env = this.node_env;
  418. const express = require('express')();
  419. require('./express-init')(this, express);
  420. // use bunyan
  421. if (env === 'production') {
  422. const expressBunyanLogger = require('express-bunyan-logger');
  423. const logger = loggerFactory('express');
  424. express.use(expressBunyanLogger({
  425. logger,
  426. excludes: ['*'],
  427. }));
  428. }
  429. // use morgan
  430. else {
  431. const morgan = require('morgan');
  432. express.use(morgan('dev'));
  433. }
  434. this.express = express;
  435. };
  436. Crowi.prototype.setupTerminus = function(server) {
  437. createTerminus(server, {
  438. signals: ['SIGINT', 'SIGTERM'],
  439. onSignal: async() => {
  440. logger.info('Server is starting cleanup');
  441. await mongoose.disconnect();
  442. return;
  443. },
  444. onShutdown: async() => {
  445. logger.info('Cleanup finished, server is shutting down');
  446. },
  447. });
  448. };
  449. Crowi.prototype.setupRoutesForPlugins = function() {
  450. lsxRoutes(this, this.express);
  451. attachmentRoutes(this, this.express);
  452. };
  453. /**
  454. * setup Express Routes
  455. * !! this must be at last because it includes '/*' route !!
  456. */
  457. Crowi.prototype.setupRoutesAtLast = function() {
  458. require('../routes')(this, this.express);
  459. };
  460. /**
  461. * setup global error handlers
  462. * !! this must be after the Routes setup !!
  463. */
  464. Crowi.prototype.setupGlobalErrorHandlers = function() {
  465. this.express.use(httpErrorHandler);
  466. };
  467. /**
  468. * require API for plugins
  469. *
  470. * @param {string} modulePath relative path from /lib/crowi/index.js
  471. * @return {module}
  472. *
  473. * @memberof Crowi
  474. */
  475. Crowi.prototype.require = function(modulePath) {
  476. return require(modulePath);
  477. };
  478. /**
  479. * setup GlobalNotificationService
  480. */
  481. Crowi.prototype.setUpGlobalNotification = async function() {
  482. const GlobalNotificationService = require('../service/global-notification');
  483. if (this.globalNotificationService == null) {
  484. this.globalNotificationService = new GlobalNotificationService(this);
  485. }
  486. };
  487. /**
  488. * setup UserNotificationService
  489. */
  490. Crowi.prototype.setUpUserNotification = async function() {
  491. if (this.userNotificationService == null) {
  492. this.userNotificationService = new UserNotificationService(this);
  493. }
  494. };
  495. /**
  496. * setup XssService
  497. */
  498. Crowi.prototype.setUpXss = async function() {
  499. const XssService = require('../service/xss');
  500. if (this.xssService == null) {
  501. this.xssService = new XssService(this.configManager);
  502. }
  503. };
  504. /**
  505. * setup AclService
  506. */
  507. Crowi.prototype.setUpAcl = async function() {
  508. this.aclService = aclServiceSingletonInstance;
  509. };
  510. /**
  511. * setup CustomizeService
  512. */
  513. Crowi.prototype.setUpCustomize = async function() {
  514. const CustomizeService = require('../service/customize');
  515. if (this.customizeService == null) {
  516. this.customizeService = new CustomizeService(this);
  517. this.customizeService.initCustomCss();
  518. this.customizeService.initCustomTitle();
  519. this.customizeService.initGrowiTheme();
  520. // add as a message handler
  521. if (this.s2sMessagingService != null) {
  522. this.s2sMessagingService.addMessageHandler(this.customizeService);
  523. }
  524. }
  525. };
  526. /**
  527. * setup AppService
  528. */
  529. Crowi.prototype.setUpApp = async function() {
  530. if (this.appService == null) {
  531. this.appService = new AppService(this);
  532. // add as a message handler
  533. const isInstalled = this.configManager.getConfig('crowi', 'app:installed');
  534. if (this.s2sMessagingService != null && !isInstalled) {
  535. this.s2sMessagingService.addMessageHandler(this.appService);
  536. }
  537. }
  538. };
  539. /**
  540. * setup FileUploadService
  541. */
  542. Crowi.prototype.setUpFileUpload = async function(isForceUpdate = false) {
  543. if (this.fileUploadService == null || isForceUpdate) {
  544. this.fileUploadService = getUploader(this);
  545. }
  546. };
  547. /**
  548. * setup FileUploaderSwitchService
  549. */
  550. Crowi.prototype.setUpFileUploaderSwitchService = async function() {
  551. const FileUploaderSwitchService = require('../service/file-uploader-switch');
  552. this.fileUploaderSwitchService = new FileUploaderSwitchService(this);
  553. // add as a message handler
  554. if (this.s2sMessagingService != null) {
  555. this.s2sMessagingService.addMessageHandler(this.fileUploaderSwitchService);
  556. }
  557. };
  558. /**
  559. * setup AttachmentService
  560. */
  561. Crowi.prototype.setupAttachmentService = async function() {
  562. if (this.attachmentService == null) {
  563. this.attachmentService = new AttachmentService(this);
  564. }
  565. };
  566. /**
  567. * setup RestQiitaAPIService
  568. */
  569. Crowi.prototype.setUpRestQiitaAPI = async function() {
  570. const RestQiitaAPIService = require('../service/rest-qiita-API');
  571. if (this.restQiitaAPIService == null) {
  572. this.restQiitaAPIService = new RestQiitaAPIService(this);
  573. }
  574. };
  575. Crowi.prototype.setupUserGroupService = async function() {
  576. if (this.userGroupService == null) {
  577. this.userGroupService = new UserGroupService(this);
  578. return this.userGroupService.init();
  579. }
  580. };
  581. Crowi.prototype.setUpGrowiBridge = async function() {
  582. const GrowiBridgeService = require('../service/growi-bridge');
  583. if (this.growiBridgeService == null) {
  584. this.growiBridgeService = new GrowiBridgeService(this);
  585. }
  586. };
  587. Crowi.prototype.setupExport = async function() {
  588. const ExportService = require('../service/export');
  589. if (this.exportService == null) {
  590. this.exportService = new ExportService(this);
  591. }
  592. };
  593. Crowi.prototype.setupImport = async function() {
  594. const ImportService = require('../service/import');
  595. if (this.importService == null) {
  596. this.importService = new ImportService(this);
  597. }
  598. };
  599. Crowi.prototype.setupGrowiPluginService = async function() {
  600. const growiPluginService = await import('~/features/growi-plugin/server/services').then(mod => mod.growiPluginService);
  601. // download plugin repositories, if document exists but there is no repository
  602. // TODO: Cannot download unless connected to the Internet at setup.
  603. await growiPluginService.downloadNotExistPluginRepositories();
  604. };
  605. Crowi.prototype.setupPageService = async function() {
  606. if (this.pageGrantService == null) {
  607. this.pageGrantService = new PageGrantService(this);
  608. }
  609. // initialize after pageGrantService since pageService uses pageGrantService in constructor
  610. if (this.pageService == null) {
  611. this.pageService = new PageService(this);
  612. await this.pageService.createTtlIndex();
  613. }
  614. if (this.pageOperationService == null) {
  615. this.pageOperationService = new PageOperationService(this);
  616. await this.pageOperationService.init();
  617. }
  618. };
  619. Crowi.prototype.setupInAppNotificationService = async function() {
  620. const InAppNotificationService = require('../service/in-app-notification');
  621. if (this.inAppNotificationService == null) {
  622. this.inAppNotificationService = new InAppNotificationService(this);
  623. }
  624. };
  625. Crowi.prototype.setupActivityService = async function() {
  626. const ActivityService = require('../service/activity');
  627. if (this.activityService == null) {
  628. this.activityService = new ActivityService(this);
  629. await this.activityService.createTtlIndex();
  630. }
  631. };
  632. Crowi.prototype.setupCommentService = async function() {
  633. const CommentService = require('../service/comment');
  634. if (this.commentService == null) {
  635. this.commentService = new CommentService(this);
  636. }
  637. };
  638. Crowi.prototype.setupSyncPageStatusService = async function() {
  639. const SyncPageStatusService = require('../service/system-events/sync-page-status');
  640. if (this.syncPageStatusService == null) {
  641. this.syncPageStatusService = new SyncPageStatusService(this, this.s2sMessagingService, this.socketIoService);
  642. // add as a message handler
  643. if (this.s2sMessagingService != null) {
  644. this.s2sMessagingService.addMessageHandler(this.syncPageStatusService);
  645. }
  646. }
  647. };
  648. Crowi.prototype.setupSlackIntegrationService = async function() {
  649. if (this.slackIntegrationService == null) {
  650. this.slackIntegrationService = new SlackIntegrationService(this);
  651. }
  652. // add as a message handler
  653. if (this.s2sMessagingService != null) {
  654. this.s2sMessagingService.addMessageHandler(this.slackIntegrationService);
  655. }
  656. };
  657. Crowi.prototype.setupG2GTransferService = async function() {
  658. if (this.g2gTransferPusherService == null) {
  659. this.g2gTransferPusherService = new G2GTransferPusherService(this);
  660. }
  661. if (this.g2gTransferReceiverService == null) {
  662. this.g2gTransferReceiverService = new G2GTransferReceiverService(this);
  663. }
  664. };
  665. // execute after setupPassport
  666. Crowi.prototype.setupExternalAccountService = function() {
  667. instanciateExternalAccountService(this.passportService);
  668. };
  669. // execute after setupPassport, s2sMessagingService, socketIoService
  670. Crowi.prototype.setupExternalUserGroupSyncService = function() {
  671. this.ldapUserGroupSyncService = new LdapUserGroupSyncService(this.passportService, this.s2sMessagingService, this.socketIoService);
  672. this.keycloakUserGroupSyncService = new KeycloakUserGroupSyncService(this.s2sMessagingService, this.socketIoService);
  673. };
  674. export default Crowi;