g2g-transfer.ts 23 KB

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