index.js 24 KB

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