2
0

index.js 24 KB

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