All files / lib/sync-engine/helpers write-assets-helpers.ts

100% Statements 42/42
100% Branches 7/7
100% Functions 2/2
100% Lines 42/42

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 421x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 1x 8x 7x 7x 7x 8x 8x 8x
import PQueue from "p-queue";
import {Asset} from "../../photos-library/model/asset.js";
import {PLibraryProcessingQueues} from "../../photos-library/model/photos-entity.js";
import {SyncEngine} from "../sync-engine.js";
import * as SYNC_ENGINE from '../constants.js';
 
/**
 * Writes the asset changes defined in the processing queue to to disk (by downloading the asset or deleting it)
 * @param processingQueue - The asset processing queue
 * @returns A promise that settles, once all asset changes have been written to disk
 */
export async function writeAssets(this: SyncEngine, processingQueue: PLibraryProcessingQueues<Asset>) {
    const toBeDeleted = processingQueue[0];
    const toBeAdded = processingQueue[1];
    // Initializing sync queue
    this.downloadQueue = new PQueue({"concurrency": this.downloadCCY});
 
    this.logger.debug(`Writing data by deleting ${toBeDeleted.length} assets and adding ${toBeAdded.length} assets`);
 
    // Deleting before downloading, in order to ensure no conflicts
    await Promise.all(toBeDeleted.map(asset => this.photosLibrary.deleteAsset(asset)));
    await Promise.all(toBeAdded.map(asset => this.downloadQueue.add(() => this.addAsset(asset))));
}
 
/**
 * Downloads and stores a given asset, unless file is already present on disk
 * @param asset - The asset that needs to be downloaded
 * @returns A promise that resolves, once the file has been successfully written to disk
 */
export async function addAsset(this: SyncEngine, asset: Asset) {
    this.logger.info(`Adding asset ${asset.getDisplayName()}`);
 
    try {
        await this.photosLibrary.verifyAsset(asset);
        this.logger.debug(`Asset ${asset.getDisplayName()} already downloaded`);
    } catch (err) {
        const data = await this.icloud.photos.downloadAsset(asset);
        await this.photosLibrary.writeAsset(asset, data);
    }
 
    this.emit(SYNC_ENGINE.EVENTS.WRITE_ASSET_COMPLETED, asset.getDisplayName());
}