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,
23 keys.documentContentKey,
24 keys.userAddressPrivateKey,
26 : await this.encryption.encryptAnonymousData(
27 stringToUtf8Array(comment),
28 GetAssociatedEncryptionDataForComment({
29 authorAddress: undefined,
32 keys.documentContentKey,
35 if (encrypted.isFailed()) {
36 metrics.docs_comments_error_total.increment({
37 reason: 'encryption_error',
40 return Result.fail(encrypted.getError())
43 return Result.ok(uint8ArrayToBase64String(encrypted.getValue()))