-
Notifications
You must be signed in to change notification settings - Fork 7
/
dia-backend-asset-repository.service.ts
427 lines (388 loc) · 11.9 KB
/
dia-backend-asset-repository.service.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import {
HttpClient,
HttpErrorResponse,
HttpParams,
} from '@angular/common/http';
import { Injectable } from '@angular/core';
import {
BehaviorSubject,
ReplaySubject,
Subject,
defer,
forkJoin,
iif,
merge,
of,
throwError,
} from 'rxjs';
import {
concatMap,
distinctUntilChanged,
first,
map,
pluck,
repeatWhen,
switchMap,
tap,
} from 'rxjs/operators';
import { base64ToBlob } from '../../../utils/encoding/encoding';
import { MimeType, toExtension } from '../../../utils/mime-type';
import { VOID$, isNonNullable } from '../../../utils/rx-operators/rx-operators';
import { CaptureAppWebCryptoApiSignatureProvider } from '../../collector/signature/capture-app-web-crypto-api-signature-provider/capture-app-web-crypto-api-signature-provider.service';
import { Tuple } from '../../database/table/table';
import {
OldSignature,
SortedProofInformation,
getOldProof,
getOldSignatures,
getSortedProofInformation,
} from '../../repositories/proof/old-proof-adapter';
import {
Proof,
getSerializedSortedProofMetadata,
} from '../../repositories/proof/proof';
import { DiaBackendAuthService } from '../auth/dia-backend-auth.service';
import { PaginatedResponse } from '../pagination';
import { BASE_URL } from '../secret';
@Injectable({
providedIn: 'root',
})
export class DiaBackendAssetRepository {
private readonly postCapturesCache$ = new ReplaySubject<
PaginatedResponse<DiaBackendAsset>
>(1);
private readonly postCapturesImageCache$ = new BehaviorSubject(
new Map<string, Blob>()
);
readonly fetchOriginallyOwnedCount$ = this.list$({
limit: 1,
isOriginalOwner: true,
}).pipe(pluck('count'));
private readonly postCapturesCount$ = this.list$({
limit: 1,
orderBy: 'source_transaction',
}).pipe(
pluck('count'),
repeatWhen(() => this.postCapturesUpdated$)
);
private readonly postCapturesUpdated$ = new Subject<{ reason?: string }>();
readonly postCaptures$ = merge(
this.postCapturesCache$,
this.postCapturesCount$.pipe(
first(),
concatMap(count =>
this.list$({
orderBy: 'source_transaction',
limit: count,
})
),
tap(response => this.postCapturesCache$.next(response)),
repeatWhen(() => this.postCapturesUpdated$)
)
).pipe(distinctUntilChanged());
constructor(
private readonly httpClient: HttpClient,
private readonly authService: DiaBackendAuthService
) {}
fetchById$(id: string) {
return this.read$({ id });
}
fetchByProof$(proof: Proof) {
return this.list$({ proofHash: getOldProof(proof).hash }).pipe(
concatMap(response =>
iif(
() => response.count > 0,
of(response.results[0]),
throwError(new HttpErrorResponse({ status: 404 }))
)
)
);
}
fetchOriginallyOwned$({
limit,
offset = 0,
}: {
limit: number;
offset?: number;
}) {
return this.list$({ offset, limit, isOriginalOwner: true });
}
getPostCaptureById$(id: string) {
return merge(
this.postCapturesCache$.pipe(
map(postCaptures => postCaptures.results.find(p => p.id === id)),
isNonNullable()
),
this.fetchById$(id)
);
}
getAndCachePostCaptureMedia$(postCapture: DiaBackendAsset) {
return this.postCapturesImageCache$.pipe(
map(cache => cache.get(postCapture.id)),
switchMap(image =>
iif(
() => !!image,
of(image).pipe(isNonNullable()),
this.downloadFile$({ id: postCapture.id, field: 'asset_file' }).pipe(
first(),
tap(blob => {
// eslint-disable-next-line rxjs/no-subject-value
const currentCache = this.postCapturesImageCache$.value;
currentCache.set(postCapture.id, blob);
this.postCapturesImageCache$.next(currentCache);
})
)
)
)
);
}
private list$({
offset,
limit,
orderBy,
isOriginalOwner,
proofHash,
}: {
offset?: number;
limit?: number;
orderBy?: 'source_transaction';
isOriginalOwner?: boolean;
proofHash?: string;
}) {
return defer(() => this.authService.getAuthHeaders()).pipe(
concatMap(headers => {
let params = new HttpParams();
if (offset !== undefined) {
params = params.set('offset', `${offset}`);
}
if (limit !== undefined) {
params = params.set('limit', `${limit}`);
}
if (isOriginalOwner !== undefined) {
params = params.set('is_original_owner', `${isOriginalOwner}`);
}
if (orderBy !== undefined) {
params = params.set('order_by', `${orderBy}`);
}
if (proofHash !== undefined) {
params = params.set('proof_hash', `${proofHash}`);
}
return this.httpClient.get<PaginatedResponse<DiaBackendAsset>>(
`${BASE_URL}/api/v3/assets/`,
{ headers, params }
);
})
);
}
private read$({ id }: { id: string }) {
return defer(() => this.authService.getAuthHeaders()).pipe(
concatMap(headers =>
this.httpClient.get<DiaBackendAsset>(
`${BASE_URL}/api/v3/assets/${id}/`,
{ headers }
)
)
);
}
downloadC2pa$(id: string) {
return defer(() => this.authService.getAuthHeaders()).pipe(
concatMap(headers =>
this.httpClient.post<DownloadC2paResponse>(
`${BASE_URL}/api/v3/assets/${id}/c2pa/`,
{},
{ headers }
)
)
);
}
downloadFile$({ id, field }: { id: string; field: AssetDownloadField }) {
const formData = new FormData();
formData.append('field', field);
return defer(() => this.authService.getAuthHeaders()).pipe(
concatMap(headers =>
this.httpClient.post(
`${BASE_URL}/api/v3/assets/${id}/download/`,
formData,
{ headers, responseType: 'blob' }
)
)
);
}
addCapture$(proof: Proof) {
return forkJoin([
defer(() => this.authService.getAuthHeadersWithApiKey()),
defer(() => buildFormDataToCreateAsset(proof)),
]).pipe(
concatMap(([headers, formData]) =>
this.httpClient.post<CreateAssetResponse>(
`${BASE_URL}/api/v3/assets/`,
formData,
{ headers }
)
)
);
}
updateCaptureSignature$(proof: Proof) {
const update$ = forkJoin([
defer(() => this.authService.getAuthHeaders()),
defer(() => buildFormDataToUpdateSignature(proof)),
]).pipe(
concatMap(([headers, formData]) =>
this.httpClient.patch<UpdateAssetResponse>(
`${BASE_URL}/api/v3/assets/${proof.diaBackendAssetId}/`,
formData,
{ headers }
)
)
);
return defer(() =>
iif(() => proof.diaBackendAssetId === undefined, VOID$, update$)
);
}
updateCapture$(id: string, formData: any) {
return defer(() => this.authService.getAuthHeaders()).pipe(
concatMap(headers =>
this.httpClient.patch<UpdateAssetResponse>(
`${BASE_URL}/api/v3/assets/${id}/`,
formData,
{ headers }
)
)
);
}
removeCaptureById$(id: string) {
return defer(() => this.authService.getAuthHeaders()).pipe(
concatMap(headers =>
this.httpClient.delete<DeleteAssetResponse>(
`${BASE_URL}/api/v3/assets/${id}/`,
{ headers }
)
),
tap(() => this.refreshPostCaptures({ reason: 'removeCaptureById' }))
);
}
/**
* The reason argument is only for debugging purpose for code tracing.
*/
refreshPostCaptures(options?: { reason?: string }) {
this.postCapturesUpdated$.next({ reason: options?.reason });
}
mintNft$(id: string) {
const formData = new FormData();
formData.append('no_blocking', 'true');
formData.append('nft_blockchain_name', 'thundercore');
return defer(() => this.authService.getAuthHeadersWithApiKey()).pipe(
concatMap(headers => {
return this.httpClient.post(
`${BASE_URL}/api/v3/assets/${id}/mint/`,
formData,
{ headers }
);
})
);
}
}
export interface DiaBackendAssetTransaction extends Tuple {
readonly id: string;
readonly sender: string;
readonly receiver_email: string;
readonly created_at: string;
readonly fulfilled_at: string | null;
readonly expired: boolean;
}
export interface DiaBackendAssetParsedMeta extends Tuple {
readonly proof_hash: string;
readonly capture_time?: number;
readonly capture_device?: string;
readonly capture_latitude?: string;
readonly capture_longitude?: string;
}
export interface DiaBackendAsset extends Tuple {
readonly id: string;
readonly uuid: string;
readonly cid: string;
readonly proof_hash: string;
readonly is_original_owner: boolean;
readonly owner: string;
readonly owner_name: string;
readonly owner_profile_display_name: string;
readonly owner_addresses: OwnerAddresses;
readonly asset_file: string;
readonly asset_file_thumbnail: string;
readonly asset_file_mime_type: MimeType;
readonly information: Partial<SortedProofInformation>;
readonly signature: OldSignature[];
readonly signed_metadata: string;
readonly sharable_copy: string;
readonly source_transaction: DiaBackendAssetTransaction | null;
readonly parsed_meta: DiaBackendAssetParsedMeta;
readonly creator_name: string;
readonly creator_profile_display_name: string | null;
readonly supporting_file: string | null;
readonly source_type: 'original' | 'post_capture' | 'store';
readonly cai_file: string;
readonly nft_token_id: string | null;
readonly nft_token_uri: string;
readonly nft_blockchain_name: string;
readonly nft_contract_address: string;
readonly caption: string;
readonly post_creation_workflow_id: string;
readonly mint_workflow_id: string;
readonly uploaded_at: string;
readonly public_access: boolean;
readonly parent_asset_cid: string;
}
export interface OwnerAddresses extends Tuple {
asset_wallet_address: string;
managed_wallet_address: string;
}
export type AssetDownloadField =
| 'asset_file'
| 'asset_file_thumbnail'
| 'sharable_copy';
type CreateAssetResponse = DiaBackendAsset;
type UpdateAssetResponse = DiaBackendAsset;
// eslint-disable-next-line @typescript-eslint/no-empty-interface
interface DeleteAssetResponse {}
interface DownloadC2paResponse {
url: string;
cid: string;
}
async function buildFormDataToCreateAsset(proof: Proof) {
const formData = new FormData();
const info = await getSortedProofInformation(proof);
const recorder = CaptureAppWebCryptoApiSignatureProvider.recorderFor(
proof.cameraSource
);
const proofMetadata = await proof.generateProofMetadata(recorder);
const serializedSortedProofMetadata =
getSerializedSortedProofMetadata(proofMetadata);
formData.set('meta', JSON.stringify(info));
formData.set('signed_metadata', serializedSortedProofMetadata);
formData.set('signature', JSON.stringify(getOldSignatures(proof)));
// The default value for 'claim_is_creator' is set to false.
// However, for captures uploaded using the capture cam,
// this value should be specifically set to true.
formData.set('claim_is_creator', 'true');
const fileBase64 = Object.keys(await proof.getAssets())[0];
const mimeType = Object.values(proof.indexedAssets)[0].mimeType;
formData.set(
'asset_file',
await base64ToBlob(fileBase64, mimeType),
`proof.${toExtension(mimeType)}`
);
formData.set('asset_file_mime_type', mimeType);
return formData;
}
async function buildFormDataToUpdateSignature(proof: Proof) {
const formData = new FormData();
const recorder = CaptureAppWebCryptoApiSignatureProvider.recorderFor(
proof.cameraSource
);
const ProofMetadata = await proof.generateProofMetadata(recorder);
const serializedSortedProofMetadata =
getSerializedSortedProofMetadata(ProofMetadata);
formData.set('signed_metadata', serializedSortedProofMetadata);
formData.set('signature', JSON.stringify(getOldSignatures(proof)));
return formData;
}