Merge branch 'feat/inda-383-daily-stat' into 'main'
[ProtonMail-WebClient.git] / packages / docs-core / lib / UseCase / EncryptComment.ts
blob6311d754eae5e8ea28280cb55cb1fb5f331bf9ad
1 import type { UseCaseInterface } from '../Domain/UseCase/UseCaseInterface'
2 import { Result } from '@proton/docs-shared'
3 import type { EncryptionService } from '../Services/Encryption/EncryptionService'
4 import type { DocumentKeys } from '@proton/drive-store'
5 import { GetAssociatedEncryptionDataForComment } from './GetAdditionalEncryptionData'
6 import type { EncryptionContext } from '../Services/Encryption/EncryptionContext'
7 import { stringToUtf8Array } from '@proton/crypto/lib/utils'
8 import { uint8ArrayToBase64String } from '@proton/shared/lib/helpers/encoding'
9 import metrics from '@proton/metrics'
10 import { isPrivateDocumentKeys, type PublicDocumentKeys } from '../Types/DocumentEntitlements'
12 export class EncryptComment implements UseCaseInterface<string> {
13   constructor(private encryption: EncryptionService<EncryptionContext.PersistentComment>) {}
15   async execute(comment: string, markId: string, keys: DocumentKeys | PublicDocumentKeys): Promise<Result<string>> {
16     const encrypted = isPrivateDocumentKeys(keys)
17       ? await this.encryption.signAndEncryptData(
18           stringToUtf8Array(comment),
19           GetAssociatedEncryptionDataForComment({
20             authorAddress: keys.userOwnAddress,
21             markId: markId,
22           }),
23           keys.documentContentKey,
24           keys.userAddressPrivateKey,
25         )
26       : await this.encryption.encryptAnonymousData(
27           stringToUtf8Array(comment),
28           GetAssociatedEncryptionDataForComment({
29             authorAddress: undefined,
30             markId: markId,
31           }),
32           keys.documentContentKey,
33         )
35     if (encrypted.isFailed()) {
36       metrics.docs_comments_error_total.increment({
37         reason: 'encryption_error',
38       })
40       return Result.fail(encrypted.getError())
41     }
43     return Result.ok(uint8ArrayToBase64String(encrypted.getValue()))
44   }