g2g-transfer.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. import type { ReadStream } from 'fs';
  2. import { createReadStream } from 'fs';
  3. import { basename } from 'path';
  4. import type { Readable } from 'stream';
  5. // eslint-disable-next-line no-restricted-imports
  6. import type { IUser } from '@growi/core';
  7. import rawAxios, { type AxiosRequestConfig } from 'axios';
  8. import FormData from 'form-data';
  9. import mongoose, { Types as MongooseTypes } from 'mongoose';
  10. import { G2G_PROGRESS_STATUS } from '~/interfaces/g2g-transfer';
  11. import GrowiArchiveImportOption from '~/models/admin/growi-archive-import-option';
  12. import TransferKeyModel from '~/server/models/transfer-key';
  13. import { generateOverwriteParams } from '~/server/routes/apiv3/import';
  14. import { type ImportSettings } from '~/server/service/import';
  15. import { createBatchStream } from '~/server/util/batch-stream';
  16. import axios from '~/utils/axios';
  17. import loggerFactory from '~/utils/logger';
  18. import { TransferKey } from '~/utils/vo/transfer-key';
  19. import type Crowi from '../crowi';
  20. import { Attachment } from '../models/attachment';
  21. import { G2GTransferError, G2GTransferErrorCode } from '../models/vo/g2g-transfer-error';
  22. import { configManager } from './config-manager';
  23. const logger = loggerFactory('growi:service:g2g-transfer');
  24. /**
  25. * Header name for transfer key
  26. */
  27. export const X_GROWI_TRANSFER_KEY_HEADER_NAME = 'x-growi-transfer-key';
  28. /**
  29. * Keys for file upload related config
  30. */
  31. const UPLOAD_CONFIG_KEYS = [
  32. 'app:fileUploadType',
  33. 'app:useOnlyEnvVarForFileUploadType',
  34. 'aws:referenceFileWithRelayMode',
  35. 'aws:lifetimeSecForTemporaryUrl',
  36. 'gcs:apiKeyJsonPath',
  37. 'gcs:bucket',
  38. 'gcs:uploadNamespace',
  39. 'gcs:referenceFileWithRelayMode',
  40. 'gcs:useOnlyEnvVarsForSomeOptions',
  41. 'azure:storageAccountName',
  42. 'azure:storageContainerName',
  43. 'azure:referenceFileWithRelayMode',
  44. 'azure:useOnlyEnvVarsForSomeOptions',
  45. ] as const;
  46. /**
  47. * File upload related configs
  48. */
  49. type FileUploadConfigs = { [key in typeof UPLOAD_CONFIG_KEYS[number] ]: any; }
  50. /**
  51. * Data used for comparing to/from GROWI information
  52. */
  53. export type IDataGROWIInfo = {
  54. /** GROWI version */
  55. version: string
  56. /** Max user count */
  57. userUpperLimit: number | null // Handle null as Infinity
  58. /** Whether file upload is disabled */
  59. fileUploadDisabled: boolean;
  60. /** Total file size allowed */
  61. fileUploadTotalLimit: number | null // Handle null as Infinity
  62. /** Attachment infromation */
  63. attachmentInfo: {
  64. /** File storage type */
  65. type: string;
  66. /** Whether the storage is writable */
  67. writable: boolean;
  68. /** Bucket name (S3 and GCS only) */
  69. bucket?: string;
  70. /** S3 custom endpoint */
  71. customEndpoint?: string;
  72. /** GCS namespace */
  73. uploadNamespace?: string;
  74. };
  75. }
  76. /**
  77. * File metadata in storage
  78. * TODO: mv this to "./file-uploader/uploader"
  79. */
  80. interface FileMeta {
  81. /** File name */
  82. name: string;
  83. /** File size in bytes */
  84. size: number;
  85. }
  86. /**
  87. * Return type for {@link Pusher.getTransferability}
  88. */
  89. type Transferability = { canTransfer: true; } | { canTransfer: false; reason: string; };
  90. /**
  91. * G2g transfer pusher
  92. */
  93. interface Pusher {
  94. /**
  95. * Merge axios config with transfer key
  96. * @param {TransferKey} tk Transfer key
  97. * @param {AxiosRequestConfig} config Axios config
  98. */
  99. generateAxiosConfig(tk: TransferKey, config: AxiosRequestConfig): AxiosRequestConfig
  100. /**
  101. * Send to-growi a request to get GROWI info
  102. * @param {TransferKey} tk Transfer key
  103. */
  104. askGROWIInfo(tk: TransferKey): Promise<IDataGROWIInfo>
  105. /**
  106. * Check if transfering is proceedable
  107. * @param {IDataGROWIInfo} destGROWIInfo GROWI info from dest GROWI
  108. */
  109. getTransferability(destGROWIInfo: IDataGROWIInfo): Promise<Transferability>
  110. /**
  111. * List files in the storage
  112. * @param {TransferKey} tk Transfer key
  113. */
  114. listFilesInStorage(tk: TransferKey): Promise<FileMeta[]>
  115. /**
  116. * Transfer all Attachment data to dest GROWI
  117. * @param {TransferKey} tk Transfer key
  118. */
  119. transferAttachments(tk: TransferKey): Promise<void>
  120. /**
  121. * Start transfer data between GROWIs
  122. * @param {TransferKey} tk TransferKey object
  123. * @param {any} user User operating g2g transfer
  124. * @param {IDataGROWIInfo} destGROWIInfo GROWI info of dest GROWI
  125. * @param {string[]} collections Collection name string array
  126. * @param {any} optionsMap Options map
  127. */
  128. startTransfer(
  129. tk: TransferKey,
  130. user: any,
  131. collections: string[],
  132. optionsMap: any,
  133. destGROWIInfo: IDataGROWIInfo,
  134. ): Promise<void>
  135. }
  136. /**
  137. * G2g transfer receiver
  138. */
  139. interface Receiver {
  140. /**
  141. * Check if key is not expired
  142. * @throws {import('../models/vo/g2g-transfer-error').G2GTransferError}
  143. * @param {string} key Transfer key
  144. */
  145. validateTransferKey(key: string): Promise<void>
  146. /**
  147. * Generate GROWIInfo
  148. * @throws {import('../models/vo/g2g-transfer-error').G2GTransferError}
  149. */
  150. answerGROWIInfo(): Promise<IDataGROWIInfo>
  151. /**
  152. * DO NOT USE TransferKeyModel.create() directly, instead, use this method to create a TransferKey document.
  153. * This method receives appSiteUrlOrigin to create a TransferKey document and returns generated transfer key string.
  154. * UUID is the same value as the created document's _id.
  155. * @param {string} appSiteUrlOrigin GROWI app site URL origin
  156. * @returns {string} Transfer key string (e.g. http://localhost:3000__grw_internal_tranferkey__<uuid>)
  157. */
  158. createTransferKey(appSiteUrlOrigin: string): Promise<string>
  159. /**
  160. * Returns a map of collection name and ImportSettings
  161. * @param {any[]} innerFileStats
  162. * @param {{ [key: string]: GrowiArchiveImportOption; }} optionsMap Map of collection name and GrowiArchiveImportOption
  163. * @param {string} operatorUserId User ID
  164. * @returns {{ [key: string]: ImportSettings; }} Map of collection name and ImportSettings
  165. */
  166. getImportSettingMap(
  167. innerFileStats: any[],
  168. optionsMap: { [key: string]: GrowiArchiveImportOption; },
  169. operatorUserId: string,
  170. ): { [key: string]: ImportSettings; }
  171. /**
  172. * Import collections
  173. * @param {string} collections Array of collection name
  174. * @param {{ [key: string]: ImportSettings; }} importSettingsMap Map of collection name and ImportSettings
  175. * @param {FileUploadConfigs} sourceGROWIUploadConfigs File upload configs from src GROWI
  176. */
  177. importCollections(
  178. collections: string[],
  179. importSettingsMap: { [key: string]: ImportSettings; },
  180. sourceGROWIUploadConfigs: FileUploadConfigs,
  181. ): Promise<void>
  182. /**
  183. * Returns file upload configs
  184. */
  185. getFileUploadConfigs(): Promise<FileUploadConfigs>
  186. /**
  187. * Update file upload configs
  188. * @param fileUploadConfigs File upload configs
  189. */
  190. updateFileUploadConfigs(fileUploadConfigs: FileUploadConfigs): Promise<void>
  191. /**
  192. * Upload attachment file
  193. * @param {ReadStream} content Pushed attachment data from source GROWI
  194. * @param {any} attachmentMap Map-ped Attachment instance
  195. */
  196. receiveAttachment(content: ReadStream, attachmentMap: any): Promise<void>
  197. }
  198. /**
  199. * G2g transfer pusher
  200. */
  201. export class G2GTransferPusherService implements Pusher {
  202. crowi: Crowi;
  203. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  204. constructor(crowi: any) {
  205. this.crowi = crowi;
  206. }
  207. public generateAxiosConfig(tk: TransferKey, baseConfig: AxiosRequestConfig = {}): AxiosRequestConfig {
  208. const { appSiteUrlOrigin, key } = tk;
  209. return {
  210. ...baseConfig,
  211. baseURL: appSiteUrlOrigin,
  212. headers: {
  213. ...baseConfig.headers,
  214. [X_GROWI_TRANSFER_KEY_HEADER_NAME]: key,
  215. },
  216. maxBodyLength: Infinity,
  217. };
  218. }
  219. public async askGROWIInfo(tk: TransferKey): Promise<IDataGROWIInfo> {
  220. try {
  221. const { data: { growiInfo } } = await axios.get('/_api/v3/g2g-transfer/growi-info', this.generateAxiosConfig(tk));
  222. return growiInfo;
  223. }
  224. catch (err) {
  225. logger.error(err);
  226. throw new G2GTransferError('Failed to retrieve GROWI info.', G2GTransferErrorCode.FAILED_TO_RETRIEVE_GROWI_INFO);
  227. }
  228. }
  229. public async getTransferability(destGROWIInfo: IDataGROWIInfo): Promise<Transferability> {
  230. const { fileUploadService } = this.crowi;
  231. const version = this.crowi.version;
  232. if (version !== destGROWIInfo.version) {
  233. return {
  234. canTransfer: false,
  235. // TODO: i18n for reason
  236. reason: `GROWI versions mismatch. src GROWI: ${version} / dest GROWI: ${destGROWIInfo.version}.`,
  237. };
  238. }
  239. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  240. const User = mongoose.model<IUser, any>('User');
  241. const activeUserCount = await User.countActiveUsers();
  242. if ((destGROWIInfo.userUpperLimit ?? Infinity) < activeUserCount) {
  243. return {
  244. canTransfer: false,
  245. // TODO: i18n for reason
  246. // eslint-disable-next-line max-len
  247. reason: `The number of active users (${activeUserCount} users) exceeds the limit of the destination GROWI (up to ${destGROWIInfo.userUpperLimit} users).`,
  248. };
  249. }
  250. if (destGROWIInfo.fileUploadDisabled) {
  251. return {
  252. canTransfer: false,
  253. // TODO: i18n for reason
  254. reason: 'The file upload setting is disabled in the destination GROWI.',
  255. };
  256. }
  257. if (configManager.getConfig('crowi', 'app:fileUploadType') === 'none') {
  258. return {
  259. canTransfer: false,
  260. // TODO: i18n for reason
  261. reason: 'File upload is not configured for src GROWI.',
  262. };
  263. }
  264. if (destGROWIInfo.attachmentInfo.type === 'none') {
  265. return {
  266. canTransfer: false,
  267. // TODO: i18n for reason
  268. reason: 'File upload is not configured for dest GROWI.',
  269. };
  270. }
  271. if (!destGROWIInfo.attachmentInfo.writable) {
  272. return {
  273. canTransfer: false,
  274. // TODO: i18n for reason
  275. reason: 'The storage of the destination GROWI is not writable.',
  276. };
  277. }
  278. const totalFileSize = await fileUploadService.getTotalFileSize();
  279. if ((destGROWIInfo.fileUploadTotalLimit ?? Infinity) < totalFileSize) {
  280. return {
  281. canTransfer: false,
  282. // TODO: i18n for reason
  283. // eslint-disable-next-line max-len
  284. reason: `The total file size of attachments exceeds the file upload limit of the destination GROWI. Requires ${totalFileSize.toLocaleString()} bytes, but got ${(destGROWIInfo.fileUploadTotalLimit as number).toLocaleString()} bytes.`,
  285. };
  286. }
  287. return { canTransfer: true };
  288. }
  289. public async listFilesInStorage(tk: TransferKey): Promise<FileMeta[]> {
  290. try {
  291. const { data: { files } } = await axios.get<{ files: FileMeta[] }>('/_api/v3/g2g-transfer/files', this.generateAxiosConfig(tk));
  292. return files;
  293. }
  294. catch (err) {
  295. logger.error(err);
  296. throw new G2GTransferError('Failed to retrieve file metadata', G2GTransferErrorCode.FAILED_TO_RETRIEVE_FILE_METADATA);
  297. }
  298. }
  299. public async transferAttachments(tk: TransferKey): Promise<void> {
  300. const BATCH_SIZE = 100;
  301. const { fileUploadService, socketIoService } = this.crowi;
  302. const socket = socketIoService?.getAdminSocket();
  303. const filesFromSrcGROWI = await this.listFilesInStorage(tk);
  304. /**
  305. * Given these documents,
  306. *
  307. * | fileName | fileSize |
  308. * | -- | -- |
  309. * | a.png | 1024 |
  310. * | b.png | 2048 |
  311. * | c.png | 1024 |
  312. * | d.png | 2048 |
  313. *
  314. * this filter
  315. *
  316. * ```jsonc
  317. * {
  318. * $and: [
  319. * // a file transferred
  320. * {
  321. * $or: [
  322. * { fileName: { $ne: "a.png" } },
  323. * { fileSize: { $ne: 1024 } }
  324. * ]
  325. * },
  326. * // a file failed to transfer
  327. * {
  328. * $or: [
  329. * { fileName: { $ne: "b.png" } },
  330. * { fileSize: { $ne: 0 } }
  331. * ]
  332. * }
  333. * ]
  334. * }
  335. * ```
  336. *
  337. * results in
  338. *
  339. * | fileName | fileSize |
  340. * | -- | -- |
  341. * | b.png | 2048 |
  342. * | c.png | 1024 |
  343. * | d.png | 2048 |
  344. */
  345. const filter = filesFromSrcGROWI.length > 0 ? {
  346. $and: filesFromSrcGROWI.map(({ name, size }) => ({
  347. $or: [
  348. { fileName: { $ne: basename(name) } },
  349. { fileSize: { $ne: size } },
  350. ],
  351. })),
  352. } : {};
  353. const attachmentsCursor = await Attachment.find(filter).cursor();
  354. const batchStream = createBatchStream(BATCH_SIZE);
  355. for await (const attachmentBatch of attachmentsCursor.pipe(batchStream)) {
  356. for await (const attachment of attachmentBatch) {
  357. logger.debug(`processing attachment: ${attachment}`);
  358. let fileStream;
  359. try {
  360. // get read stream of each attachment
  361. fileStream = await fileUploadService.findDeliveryFile(attachment);
  362. }
  363. catch (err) {
  364. logger.warn(`Error occured when getting Attachment(ID=${attachment.id}), skipping: `, err);
  365. socket?.emit('admin:g2gError', {
  366. message: `Error occured when uploading Attachment(ID=${attachment.id})`,
  367. key: `Error occured when uploading Attachment(ID=${attachment.id})`,
  368. // TODO: emit error with params
  369. // key: 'admin:g2g:error_upload_attachment',
  370. });
  371. continue;
  372. }
  373. // post each attachment file data to receiver
  374. try {
  375. await this.doTransferAttachment(tk, attachment, fileStream);
  376. }
  377. catch (err) {
  378. logger.error(`Error occured when uploading attachment(ID=${attachment.id})`, err);
  379. socket?.emit('admin:g2gError', {
  380. message: `Error occured when uploading Attachment(ID=${attachment.id})`,
  381. key: `Error occured when uploading Attachment(ID=${attachment.id})`,
  382. // TODO: emit error with params
  383. // key: 'admin:g2g:error_upload_attachment',
  384. });
  385. }
  386. }
  387. }
  388. }
  389. // eslint-disable-next-line max-len
  390. public async startTransfer(tk: TransferKey, user: any, collections: string[], optionsMap: any, destGROWIInfo: IDataGROWIInfo): Promise<void> {
  391. const socket = this.crowi.socketIoService?.getAdminSocket();
  392. socket?.emit('admin:g2gProgress', {
  393. mongo: G2G_PROGRESS_STATUS.IN_PROGRESS,
  394. attachments: G2G_PROGRESS_STATUS.PENDING,
  395. });
  396. const targetConfigKeys = UPLOAD_CONFIG_KEYS;
  397. const uploadConfigs = Object.fromEntries(targetConfigKeys.map((key) => {
  398. return [key, configManager.getConfig('crowi', key)];
  399. }));
  400. let zipFileStream: ReadStream;
  401. try {
  402. const zipFileStat = await this.crowi.exportService.export(collections);
  403. const zipFilePath = zipFileStat.zipFilePath;
  404. zipFileStream = createReadStream(zipFilePath);
  405. }
  406. catch (err) {
  407. logger.error(err);
  408. socket?.emit('admin:g2gProgress', {
  409. mongo: G2G_PROGRESS_STATUS.ERROR,
  410. attachments: G2G_PROGRESS_STATUS.PENDING,
  411. });
  412. socket?.emit('admin:g2gError', { message: 'Failed to generate GROWI archive file', key: 'admin:g2g:error_generate_growi_archive' });
  413. throw err;
  414. }
  415. // Send a zip file to other GROWI via axios
  416. try {
  417. // Use FormData to immitate browser's form data object
  418. const form = new FormData();
  419. const appTitle = this.crowi.appService.getAppTitle();
  420. form.append('transferDataZipFile', zipFileStream, `${appTitle}-${Date.now}.growi.zip`);
  421. form.append('collections', JSON.stringify(collections));
  422. form.append('optionsMap', JSON.stringify(optionsMap));
  423. form.append('operatorUserId', user._id.toString());
  424. form.append('uploadConfigs', JSON.stringify(uploadConfigs));
  425. await rawAxios.post('/_api/v3/g2g-transfer/', form, this.generateAxiosConfig(tk, { headers: form.getHeaders() }));
  426. }
  427. catch (err) {
  428. logger.error(err);
  429. socket?.emit('admin:g2gProgress', {
  430. mongo: G2G_PROGRESS_STATUS.ERROR,
  431. attachments: G2G_PROGRESS_STATUS.PENDING,
  432. });
  433. socket?.emit('admin:g2gError', { message: 'Failed to send GROWI archive file to the destination GROWI', key: 'admin:g2g:error_send_growi_archive' });
  434. throw err;
  435. }
  436. socket?.emit('admin:g2gProgress', {
  437. mongo: G2G_PROGRESS_STATUS.COMPLETED,
  438. attachments: G2G_PROGRESS_STATUS.IN_PROGRESS,
  439. });
  440. try {
  441. await this.transferAttachments(tk);
  442. }
  443. catch (err) {
  444. logger.error(err);
  445. socket?.emit('admin:g2gProgress', {
  446. mongo: G2G_PROGRESS_STATUS.COMPLETED,
  447. attachments: G2G_PROGRESS_STATUS.ERROR,
  448. });
  449. socket?.emit('admin:g2gError', { message: 'Failed to transfer attachments', key: 'admin:g2g:error_upload_attachment' });
  450. throw err;
  451. }
  452. socket?.emit('admin:g2gProgress', {
  453. mongo: G2G_PROGRESS_STATUS.COMPLETED,
  454. attachments: G2G_PROGRESS_STATUS.COMPLETED,
  455. });
  456. }
  457. /**
  458. * Transfer attachment to dest GROWI
  459. * @param {TransferKey} tk Transfer key
  460. * @param {any} attachment Attachment model instance
  461. * @param {Readable} fileStream Attachment data(loaded from storage)
  462. */
  463. private async doTransferAttachment(tk: TransferKey, attachment: any, fileStream: Readable): Promise<void> {
  464. // Use FormData to immitate browser's form data object
  465. const form = new FormData();
  466. form.append('content', fileStream, attachment.fileName);
  467. form.append('attachmentMetadata', JSON.stringify(attachment));
  468. await rawAxios.post('/_api/v3/g2g-transfer/attachment', form, this.generateAxiosConfig(tk, { headers: form.getHeaders() }));
  469. }
  470. }
  471. /**
  472. * G2g transfer receiver
  473. */
  474. export class G2GTransferReceiverService implements Receiver {
  475. crowi: Crowi;
  476. constructor(crowi: Crowi) {
  477. this.crowi = crowi;
  478. }
  479. public async validateTransferKey(key: string): Promise<void> {
  480. const transferKey = await (TransferKeyModel as any).findOne({ key });
  481. if (transferKey == null) {
  482. throw new Error(`Transfer key "${key}" was expired or not found`);
  483. }
  484. try {
  485. TransferKey.parse(transferKey.keyString);
  486. }
  487. catch (err) {
  488. logger.error(err);
  489. throw new Error(`Transfer key "${key}" is invalid`);
  490. }
  491. }
  492. public async answerGROWIInfo(): Promise<IDataGROWIInfo> {
  493. const { version, fileUploadService } = this.crowi;
  494. const userUpperLimit = configManager.getConfig('crowi', 'security:userUpperLimit');
  495. const fileUploadDisabled = configManager.getConfig('crowi', 'app:fileUploadDisabled');
  496. const fileUploadTotalLimit = fileUploadService.getFileUploadTotalLimit();
  497. const isWritable = await fileUploadService.isWritable();
  498. const attachmentInfo = {
  499. type: configManager.getConfig('crowi', 'app:fileUploadType'),
  500. writable: isWritable,
  501. bucket: undefined,
  502. customEndpoint: undefined, // for S3
  503. uploadNamespace: undefined, // for GCS
  504. accountName: undefined, // for Azure Blob
  505. containerName: undefined,
  506. };
  507. // put storage location info to check storage identification
  508. switch (attachmentInfo.type) {
  509. case 'aws':
  510. attachmentInfo.bucket = configManager.getConfig('crowi', 'aws:s3Bucket');
  511. attachmentInfo.customEndpoint = configManager.getConfig('crowi', 'aws:s3CustomEndpoint');
  512. break;
  513. case 'gcs':
  514. attachmentInfo.bucket = configManager.getConfig('crowi', 'gcs:bucket');
  515. attachmentInfo.uploadNamespace = configManager.getConfig('crowi', 'gcs:uploadNamespace');
  516. break;
  517. case 'azure':
  518. attachmentInfo.accountName = configManager.getConfig('crowi', 'azure:storageAccountName');
  519. attachmentInfo.containerName = configManager.getConfig('crowi', 'azure:storageContainerName');
  520. break;
  521. default:
  522. }
  523. return {
  524. userUpperLimit,
  525. fileUploadDisabled,
  526. fileUploadTotalLimit,
  527. version,
  528. attachmentInfo,
  529. };
  530. }
  531. public async createTransferKey(appSiteUrlOrigin: string): Promise<string> {
  532. const uuid = new MongooseTypes.ObjectId().toString();
  533. const transferKeyString = TransferKey.generateKeyString(uuid, appSiteUrlOrigin);
  534. // Save TransferKey document
  535. let tkd;
  536. try {
  537. tkd = await TransferKeyModel.create({ _id: uuid, keyString: transferKeyString, key: uuid });
  538. }
  539. catch (err) {
  540. logger.error(err);
  541. throw err;
  542. }
  543. return tkd.keyString;
  544. }
  545. public getImportSettingMap(
  546. innerFileStats: any[],
  547. optionsMap: { [key: string]: GrowiArchiveImportOption; },
  548. operatorUserId: string,
  549. ): { [key: string]: ImportSettings; } {
  550. const { importService } = this.crowi;
  551. const importSettingsMap = {};
  552. innerFileStats.forEach(({ fileName, collectionName }) => {
  553. const options = new GrowiArchiveImportOption(null, optionsMap[collectionName]);
  554. if (collectionName === 'configs' && options.mode !== 'flushAndInsert') {
  555. throw new Error('`flushAndInsert` is only available as an import setting for configs collection');
  556. }
  557. if (collectionName === 'pages' && options.mode === 'insert') {
  558. throw new Error('`insert` is not available as an import setting for pages collection');
  559. }
  560. if (collectionName === 'attachmentFiles.chunks') {
  561. throw new Error('`attachmentFiles.chunks` must not be transferred. Please omit it from request body `collections`.');
  562. }
  563. if (collectionName === 'attachmentFiles.files') {
  564. throw new Error('`attachmentFiles.files` must not be transferred. Please omit it from request body `collections`.');
  565. }
  566. const importSettings = importService.generateImportSettings(options.mode);
  567. importSettings.jsonFileName = fileName;
  568. importSettings.overwriteParams = generateOverwriteParams(collectionName, operatorUserId, options);
  569. importSettingsMap[collectionName] = importSettings;
  570. });
  571. return importSettingsMap;
  572. }
  573. public async importCollections(
  574. collections: string[],
  575. importSettingsMap: { [key: string]: ImportSettings; },
  576. sourceGROWIUploadConfigs: FileUploadConfigs,
  577. ): Promise<void> {
  578. const { importService, appService } = this.crowi;
  579. /** whether to keep current file upload configs */
  580. const shouldKeepUploadConfigs = configManager.getConfig('crowi', 'app:fileUploadType') !== 'none';
  581. if (shouldKeepUploadConfigs) {
  582. /** cache file upload configs */
  583. const fileUploadConfigs = await this.getFileUploadConfigs();
  584. // import mongo collections(overwrites file uplaod configs)
  585. await importService.import(collections, importSettingsMap);
  586. // restore file upload config from cache
  587. await configManager.removeConfigsInTheSameNamespace('crowi', UPLOAD_CONFIG_KEYS);
  588. await configManager.updateConfigsInTheSameNamespace('crowi', fileUploadConfigs);
  589. }
  590. else {
  591. // import mongo collections(overwrites file uplaod configs)
  592. await importService.import(collections, importSettingsMap);
  593. // update file upload config
  594. await configManager.updateConfigsInTheSameNamespace('crowi', sourceGROWIUploadConfigs);
  595. }
  596. await this.crowi.setUpFileUpload(true);
  597. await appService.setupAfterInstall();
  598. }
  599. public async getFileUploadConfigs(): Promise<FileUploadConfigs> {
  600. const fileUploadConfigs = Object.fromEntries(UPLOAD_CONFIG_KEYS.map((key) => {
  601. return [key, configManager.getConfigFromDB('crowi', key)];
  602. })) as FileUploadConfigs;
  603. return fileUploadConfigs;
  604. }
  605. public async updateFileUploadConfigs(fileUploadConfigs: FileUploadConfigs): Promise<void> {
  606. const { appService } = this.crowi;
  607. await configManager.removeConfigsInTheSameNamespace('crowi', Object.keys(fileUploadConfigs));
  608. await configManager.updateConfigsInTheSameNamespace('crowi', fileUploadConfigs);
  609. await this.crowi.setUpFileUpload(true);
  610. await appService.setupAfterInstall();
  611. }
  612. public async receiveAttachment(content: ReadStream, attachmentMap): Promise<void> {
  613. const { fileUploadService } = this.crowi;
  614. return fileUploadService.uploadAttachment(content, attachmentMap);
  615. }
  616. }