index.js 24 KB

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