index.ts 26 KB

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