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