Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / docs-core / lib / UseCase / CreateEmptyDocumentForConversion.ts
blob05ff35d38475f5573f1b2ffd1d5bebf9c4feb7da
1 import type { DecryptedNode, DriveCompat, NodeMeta } from '@proton/drive-store'
2 import type { FileToDocConversionResult } from '../Types/FileToDocConversionResult'
3 import type { GetDocumentMeta } from './GetDocumentMeta'
4 import { SupportedMimeTypes } from '@proton/shared/lib/drive/constants'
5 import { getErrorString } from '../Util/GetErrorString'
6 import type { UseCaseInterface } from '../Domain/UseCase/UseCaseInterface'
7 import { Result } from '@proton/docs-shared'
8 import { getNodeNameWithoutExtension } from '@proton/docs-shared'
10 /**
11  * Creates a new empty document shell file. This file will then be opened, and the contents will be converted by the editor.
12  */
13 export class CreateEmptyDocumentForConversion implements UseCaseInterface<FileToDocConversionResult> {
14   constructor(
15     private driveCompat: DriveCompat,
16     private getDocumentMeta: GetDocumentMeta,
17   ) {}
19   async execute({
20     node,
21     contents,
22   }: {
23     node: DecryptedNode
24     contents: Uint8Array
25   }): Promise<Result<FileToDocConversionResult>> {
26     try {
27       const parentMeta: NodeMeta = node.parentNodeId
28         ? {
29             volumeId: node.volumeId,
30             linkId: node.parentNodeId,
31           }
32         : await this.driveCompat.getMyFilesNodeMeta()
34       const nodeNameWithoutExtension = getNodeNameWithoutExtension(node)
35       const newDocName = await this.driveCompat.findAvailableNodeName(parentMeta, nodeNameWithoutExtension)
36       const shellResult = await this.driveCompat.createDocumentNode(parentMeta, newDocName)
38       const documentMetaResult = await this.getDocumentMeta.execute({
39         volumeId: shellResult.volumeId,
40         linkId: shellResult.linkId,
41       })
43       if (documentMetaResult.isFailed()) {
44         return Result.fail(documentMetaResult.getError())
45       }
47       const newDocMeta = documentMetaResult.getValue()
49       return Result.ok({
50         newDocMeta,
51         newShell: shellResult,
52         dataToConvert: { data: contents, type: node.mimeType === SupportedMimeTypes.docx ? 'docx' : 'md' },
53       })
54     } catch (error) {
55       return Result.fail(getErrorString(error) ?? 'Failed to create empty document for conversion')
56     }
57   }