index.js 24 KB

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