index.js 23 KB

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