commons.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. import type { ColorScheme, IUserHasId } from '@growi/core';
  2. import { AllLang, Lang } from '@growi/core';
  3. import { DevidedPagePath } from '@growi/core/dist/models';
  4. import { isServer } from '@growi/core/dist/utils';
  5. import type { GetServerSideProps, GetServerSidePropsContext } from 'next';
  6. import type { SSRConfig, UserConfig } from 'next-i18next';
  7. import * as nextI18NextConfig from '^/config/next-i18next.config';
  8. import { detectLocaleFromBrowserAcceptLanguage } from '~/client/util/locale-utils';
  9. import { type SupportedActionType } from '~/interfaces/activity';
  10. import type { CrowiRequest } from '~/interfaces/crowi-request';
  11. import type { ISidebarConfig } from '~/interfaces/sidebar-config';
  12. import type { IUserUISettings } from '~/interfaces/user-ui-settings';
  13. import type { PageDocument } from '~/server/models/page';
  14. import type { UserUISettingsDocument } from '~/server/models/user-ui-settings';
  15. import {
  16. useCurrentProductNavWidth, useCurrentSidebarContents, usePreferCollapsedMode,
  17. } from '~/stores/ui';
  18. export type CommonProps = {
  19. namespacesRequired: string[], // i18next
  20. currentPathname: string,
  21. appTitle: string,
  22. siteUrl: string,
  23. confidential: string,
  24. customTitleTemplate: string,
  25. csrfToken: string,
  26. isContainerFluid: boolean,
  27. growiVersion: string,
  28. isMaintenanceMode: boolean,
  29. redirectDestination: string | null,
  30. isDefaultLogo: boolean,
  31. growiCloudUri: string,
  32. isAccessDeniedForNonAdminUser?: boolean,
  33. currentUser?: IUserHasId,
  34. forcedColorScheme?: ColorScheme,
  35. sidebarConfig: ISidebarConfig,
  36. userUISettings?: IUserUISettings
  37. } & Partial<SSRConfig>;
  38. // eslint-disable-next-line max-len
  39. export const getServerSideCommonProps: GetServerSideProps<CommonProps> = async(context: GetServerSidePropsContext) => {
  40. const getModelSafely = await import('~/server/util/mongoose-utils').then(mod => mod.getModelSafely);
  41. const req = context.req as CrowiRequest;
  42. const { crowi, user } = req;
  43. const {
  44. appService, configManager, customizeService, attachmentService,
  45. } = crowi;
  46. const url = new URL(context.resolvedUrl, 'http://example.com');
  47. const currentPathname = decodeURIComponent(url.pathname);
  48. const isMaintenanceMode = appService.isMaintenanceMode();
  49. let currentUser;
  50. if (user != null) {
  51. currentUser = user.toObject();
  52. }
  53. // Redirect destination for page transition by next/link
  54. let redirectDestination: string | null = null;
  55. if (!crowi.aclService.isGuestAllowedToRead() && currentUser == null) {
  56. redirectDestination = '/login';
  57. }
  58. else if (!isMaintenanceMode && currentPathname === '/maintenance') {
  59. redirectDestination = '/';
  60. }
  61. else if (isMaintenanceMode && !currentPathname.match('/admin/*') && !(currentPathname === '/maintenance')) {
  62. redirectDestination = '/maintenance';
  63. }
  64. else {
  65. redirectDestination = null;
  66. }
  67. const isCustomizedLogoUploaded = await attachmentService.isBrandLogoExist();
  68. const isDefaultLogo = crowi.configManager.getConfig('crowi', 'customize:isDefaultLogo') || !isCustomizedLogoUploaded;
  69. const forcedColorScheme = crowi.customizeService.forcedColorScheme;
  70. // retrieve UserUISett ings
  71. const UserUISettings = getModelSafely<UserUISettingsDocument>('UserUISettings');
  72. const userUISettings = user != null && UserUISettings != null
  73. ? await UserUISettings.findOne({ user: user._id }).exec()
  74. : req.session.uiSettings; // for guests
  75. const props: CommonProps = {
  76. namespacesRequired: ['translation'],
  77. currentPathname,
  78. appTitle: appService.getAppTitle(),
  79. siteUrl: configManager.getConfig('crowi', 'app:siteUrl'), // DON'T USE appService.getSiteUrl()
  80. confidential: appService.getAppConfidential() || '',
  81. customTitleTemplate: customizeService.customTitleTemplate,
  82. csrfToken: req.csrfToken(),
  83. isContainerFluid: configManager.getConfig('crowi', 'customize:isContainerFluid') ?? false,
  84. growiVersion: crowi.version,
  85. isMaintenanceMode,
  86. redirectDestination,
  87. currentUser,
  88. isDefaultLogo,
  89. forcedColorScheme,
  90. growiCloudUri: configManager.getConfig('crowi', 'app:growiCloudUri'),
  91. sidebarConfig: {
  92. isSidebarCollapsedMode: configManager.getConfig('crowi', 'customize:isSidebarCollapsedMode'),
  93. },
  94. userUISettings: userUISettings?.toObject?.() ?? userUISettings,
  95. };
  96. return { props };
  97. };
  98. export const getNextI18NextConfig = async(
  99. // 'serverSideTranslations' method should be given from Next.js Page
  100. // because importing it in this file causes https://github.com/isaachinman/next-i18next/issues/1545
  101. serverSideTranslations: (
  102. initialLocale: string, namespacesRequired?: string[] | undefined, configOverride?: UserConfig | null, extraLocales?: string[] | false
  103. ) => Promise<SSRConfig>,
  104. context: GetServerSidePropsContext, namespacesRequired?: string[] | undefined, preloadAllLang = false,
  105. ): Promise<SSRConfig> => {
  106. const req: CrowiRequest = context.req as CrowiRequest;
  107. const { crowi, user, headers } = req;
  108. const { configManager } = crowi;
  109. // determine language
  110. const locale = user == null ? detectLocaleFromBrowserAcceptLanguage(headers)
  111. : (user.lang ?? configManager.getConfig('crowi', 'app:globalLang') as Lang ?? Lang.en_US);
  112. const namespaces = ['commons'];
  113. if (namespacesRequired != null) {
  114. namespaces.push(...namespacesRequired);
  115. }
  116. // TODO: deprecate 'translation.json' in the future
  117. else {
  118. namespaces.push('translation');
  119. }
  120. return serverSideTranslations(locale, namespaces, nextI18NextConfig, preloadAllLang ? AllLang : false);
  121. };
  122. /**
  123. * Generate whole title string for the specified title
  124. * @param props
  125. * @param title
  126. */
  127. export const generateCustomTitle = (props: CommonProps, title: string): string => {
  128. return props.customTitleTemplate
  129. .replace('{{sitename}}', props.appTitle)
  130. .replace('{{pagepath}}', title)
  131. .replace('{{pagename}}', title);
  132. };
  133. /**
  134. * Generate whole title string for the specified page path
  135. * @param props
  136. * @param pagePath
  137. */
  138. export const generateCustomTitleForPage = (props: CommonProps, pagePath: string): string => {
  139. const dPagePath = new DevidedPagePath(pagePath, true, true);
  140. return props.customTitleTemplate
  141. .replace('{{sitename}}', props.appTitle)
  142. .replace('{{pagepath}}', pagePath)
  143. .replace('{{pagename}}', dPagePath.latter);
  144. };
  145. export const useInitSidebarConfig = (sidebarConfig: ISidebarConfig, userUISettings?: IUserUISettings): void => {
  146. // UserUISettings
  147. usePreferCollapsedMode(userUISettings?.preferCollapsedModeByUser ?? sidebarConfig.isSidebarCollapsedMode);
  148. useCurrentSidebarContents(userUISettings?.currentSidebarContents);
  149. useCurrentProductNavWidth(userUISettings?.currentProductNavWidth);
  150. };
  151. export const skipSSR = async(page: PageDocument, ssrMaxRevisionBodyLength: number): Promise<boolean> => {
  152. if (!isServer()) {
  153. throw new Error('This method is not available on the client-side');
  154. }
  155. const latestRevisionBodyLength = await page.getLatestRevisionBodyLength();
  156. if (latestRevisionBodyLength == null) {
  157. return true;
  158. }
  159. return ssrMaxRevisionBodyLength < latestRevisionBodyLength;
  160. };
  161. export const addActivity = async(context: GetServerSidePropsContext, action: SupportedActionType): Promise<void> => {
  162. const req = context.req as CrowiRequest;
  163. const parameters = {
  164. ip: req.ip,
  165. endpoint: req.originalUrl,
  166. action,
  167. user: req.user?._id,
  168. snapshot: {
  169. username: req.user?.username,
  170. },
  171. };
  172. await req.crowi.activityService.createActivity(parameters);
  173. };