index.ts 26 KB

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