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