index.ts 28 KB

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