All files / lib/resources resource-manager.ts

100% Statements 361/361
100% Branches 50/50
100% Functions 39/39
100% Lines 361/361

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 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 3611x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 583x 139x 139x 139x 139x 139x 138x 138x 138x 138x 138x 138x 138x 139x 583x 583x 583x 583x 583x 139x 139x 139x 139x 139x 139x 139x 139x 139x 139x 137x 137x 137x 139x 583x 583x 583x 583x 583x 1638x 1638x 583x 583x 583x 583x 583x 557x 557x 557x 557x 557x 583x 583x 583x 583x 583x 1x 1x 1x 1x 1x 583x 583x 583x 583x 583x 8x 8x 8x 8x 8x 583x 583x 583x 583x 583x 2x 2x 2x 2x 2x 583x 583x 583x 583x 583x 2x 2x 2x 2x 2x 583x 583x 583x 583x 583x 583x 202x 202x 583x 583x 583x 583x 583x 583x 16x 16x 16x 16x 16x 583x 583x 583x 583x 583x 583x 584x 584x 584x 583x 583x 583x 583x 583x 55x 55x 583x 583x 583x 583x 583x 12x 12x 583x 583x 583x 583x 583x 316x 316x 583x 583x 583x 583x 583x 12x 12x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 2x 2x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 3x 3x 583x 583x 583x 583x 583x 5x 5x 583x 583x 583x 583x 583x 25x 25x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 16x 16x 583x 583x 583x 583x 583x 583x 12x 1x 1x 11x 11x 11x 583x 583x 583x 583x 583x 583x 71x 71x 583x 583x 583x 583x 583x 583x 16x 1x 1x 15x 15x 15x 583x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 583x 16x 1x 1x 15x 15x 15x 583x 583x 583x 583x 583x 583x 1x 1x 583x 583x 583x 583x 583x 2x 2x 583x 583x 583x 583x 583x 33x 33x 583x
import {iCPSError} from "../../app/error/error.js";
import {RESOURCES_ERR} from "../../app/error/error-codes.js";
import {iCPSAppOptions} from "../../app/factory.js";
import * as PHOTOS_LIBRARY from '../photos-library/constants.js';
import * as path from 'path';
import {readFileSync, writeFileSync} from "fs";
import {FILE_ENCODING, HAR_FILE_NAME, LIBRARY_LOCK_FILE_NAME, LOG_FILE_NAME, METRICS_FILE_NAME, PhotosAccountZone, RESOURCE_FILE_NAME, ResourceFile, iCPSResources} from "./resource-types.js";
import {LogLevel} from "../../app/event/log.js";
import {Resources} from "./main.js";
import {iCPSEventRuntimeWarning} from "./events-types.js";
import {jsonc} from "jsonc";
 
/**
 * This class handles access to the .icloud-photos-sync resource file and handles currently applied configurations from the CLI and environment variables
 */
export class ResourceManager {
    /**
     * The shared resources held by this instances of the icps application
     */
    _resources: iCPSResources = {} as iCPSResources;
 
    /**
     * Creates the resource manager, based on the previously parsed iCPSAppOptions.
     * Should not be called directly, but through the static setup function.
     * @param appOptions - The parsed app options
     */
    constructor(appOptions: iCPSAppOptions) {
        // Cannot use logger here
        Object.assign(this._resources, appOptions);
 
        const resourceFile = this._readResourceFile(); // Getting data from the resource file
        this._resources.libraryVersion = resourceFile.libraryVersion; // 'soft' setting the library version (not writing back to file)
 
        // writing back whatever trust token should be used
        this.trustToken = this._resources.refreshToken
            ? undefined // If we force refresh the token set to undefined
            : this._resources.trustToken ?? resourceFile.trustToken; // Use app option over whatever was already in the file
    }
 
    /**
     * Reads the resource file from disk and parses it
     */
    _readResourceFile(): ResourceFile {
        try {
            Resources.logger(this).debug(`Reading resource file from ${this.resourceFilePath}`);
            const resourceFileData = jsonc.parse(readFileSync(this.resourceFilePath, {encoding: FILE_ENCODING}));
            return Resources.validator().validateResourceFile(resourceFileData);
        } catch (err) {
            Resources.emit(iCPSEventRuntimeWarning.RESOURCE_FILE_ERROR,
                new iCPSError(RESOURCES_ERR.UNABLE_TO_READ_FILE).addCause(err));
            return {
                libraryVersion: PHOTOS_LIBRARY.LIBRARY_VERSION,
                trustToken: undefined,
            };
        }
    }
 
    /**
     * Writes the resources to the resource file
     */
    _writeResourceFile() {
        try {
            const formattedResourceFile: ResourceFile = {
                libraryVersion: this._resources.libraryVersion,
                trustToken: this._resources.trustToken,
            };
            const resourceFileData = jsonc.stringify(formattedResourceFile, null, 4);
            Resources.logger(this).debug(`Writing resource file to ${this.resourceFilePath}`);
 
            writeFileSync(this.resourceFilePath, resourceFileData, {encoding: FILE_ENCODING});
        } catch (err) {
            Resources.emit(iCPSEventRuntimeWarning.RESOURCE_FILE_ERROR,
                new iCPSError(RESOURCES_ERR.UNABLE_TO_WRITE_FILE).addCause(err));
        }
    }
 
    /**
     * @returns The data dir read from the CLI Options
     */
    get dataDir(): string {
        return this._resources.dataDir;
    }
 
    /**
     * @returns The path to the resource file
     */
    get resourceFilePath(): string {
        return path.format({
            dir: this.dataDir,
            base: RESOURCE_FILE_NAME,
        });
    }
 
    /**
     * @returns The path to the log file
     */
    get logFilePath(): string {
        return path.format({
            dir: this.dataDir,
            base: LOG_FILE_NAME,
        });
    }
 
    /**
     * @returns The path to the library lock file
     */
    get lockFilePath(): string {
        return path.format({
            dir: this.dataDir,
            base: LIBRARY_LOCK_FILE_NAME,
        });
    }
 
    /**
     * @returns The path to the metrics file
     */
    get metricsFilePath(): string {
        return path.format({
            dir: this.dataDir,
            base: METRICS_FILE_NAME,
        });
    }
 
    /**
     * @returns The path to the har file
     */
    get harFilePath(): string {
        return path.format({
            dir: this.dataDir,
            base: HAR_FILE_NAME,
        });
    }
 
    /**
     * Even though present in the resource file, this will only be loaded once and not re-read
     * @returns The currently loaded libraries version
     */
    get libraryVersion(): number {
        return this._resources.libraryVersion;
    }
 
    /**
     * This will always read the resource file for the most recently trust token and update the internal data structure
     * @returns The currently used trust token, or undefined if none is set.
     */
    get trustToken(): string | undefined {
        const resourceFile = this._readResourceFile();
        this._resources.trustToken = resourceFile.trustToken;
 
        return this._resources.trustToken;
    }
 
    /**
     * Sets the trust token and syncs the resource file.
     * @param trustToken - The trust token to use
     */
    set trustToken(trustToken: string | undefined) {
        this._resources.trustToken = trustToken;
        this._writeResourceFile();
    }
 
    /**
     * @returns The iCloud username
     */
    get username(): string {
        return this._resources.username;
    }
 
    /**
     * @returns The iCloud user password
     */
    get password(): string {
        return this._resources.password;
    }
 
    /**
     * @returns The port to use for the MFA server
     */
    get mfaServerPort(): number {
        return this._resources.port;
    }
 
    /**
     * @returns The number of retries to use for downloading
     */
    get maxRetries(): number {
        return this._resources.maxRetries;
    }
 
    /**
     * @returns The number of threads to use for downloading
     */
    get downloadThreads(): number {
        return this._resources.downloadThreads;
    }
 
    /**
     * @returns The schedule of the application
     */
    get schedule(): string {
        return this._resources.schedule;
    }
 
    /**
     * @returns If the application should enable crash reporting
     */
    get enableCrashReporting(): boolean {
        return this._resources.enableCrashReporting;
    }
 
    /**
     * @returns If the application should fail on MFA requirement
     */
    get failOnMfa(): boolean {
        return this._resources.failOnMfa;
    }
 
    /**
     * @returns If an existing library lock should be forcefully removed
     */
    get force(): boolean {
        return this._resources.force;
    }
 
    /**
     * @returns If the application should delete remote files
     */
    get remoteDelete(): boolean {
        return this._resources.remoteDelete;
    }
 
    /**
     * @returns The log level of the application
     */
    get logLevel(): LogLevel {
        return this._resources.logLevel;
    }
 
    /**
     * @returns If the application should run in silent mode
     */
    get silent(): boolean {
        return this._resources.silent;
    }
 
    /**
     * @returns If the application should log to the CLI
     */
    get logToCli(): boolean {
        return this._resources.logToCli;
    }
 
    /**
     * @returns If the application should suppress warnings
     */
    get suppressWarnings(): boolean {
        return this._resources.suppressWarnings;
    }
 
    /**
     * @returns If the application should export metrics
     */
    get exportMetrics(): boolean {
        return this._resources.exportMetrics;
    }
 
    /**
     * @returns The rate at which the metadata should be downloaded
     */
    get metadataRate(): [number, number] {
        return this._resources.metadataRate;
    }
 
    /**
     * @returns If the application should capture network traffic
     */
    get enableNetworkCapture(): boolean {
        return this._resources.enableNetworkCapture;
    }
 
    /**
     * @returns The region to be used for this app
     */
    get region(): Resources.Types.Region {
        return this._resources.region;
    }
 
    /**
     * @returns The session secret of the account
     * @throws If no session secret is set
     */
    get sessionSecret(): string {
        if (this._resources.sessionSecret === undefined) {
            throw new iCPSError(RESOURCES_ERR.NO_SESSION_SECRET);
        }
 
        return this._resources.sessionSecret;
    }
 
    /**
     * Sets the session secret of the account
     * @param sessionSecret - The session secret to set
     */
    set sessionSecret(sessionSecret: string) {
        this._resources.sessionSecret = sessionSecret;
    }
 
    /**
     * @returns The primary zone of the account
     * @throws If no primary zone is set
     */
    get primaryZone(): PhotosAccountZone {
        if (!this._resources.primaryZone) {
            throw new iCPSError(RESOURCES_ERR.NO_PRIMARY_ZONE);
        }
 
        return this._resources.primaryZone;
    }
 
    /**
     * Sets the primary zone of the account
     * @param primaryZone - The primary zone to set
     */
    set primaryZone(primaryZone: PhotosAccountZone) {
        this._resources.primaryZone = primaryZone;
    }
 
    /**
     * @returns The shared zone of the account
     * @throws If no shared zone is set
     */
    get sharedZone(): PhotosAccountZone {
        if (!this._resources.sharedZone) {
            throw new iCPSError(RESOURCES_ERR.NO_SHARED_ZONE);
        }
 
        return this._resources.sharedZone;
    }
 
    /**
     * Sets the shared zone of the account
     * @param primaryZone - The shared zone to set
     */
    set sharedZone(sharedZone: PhotosAccountZone) {
        this._resources.sharedZone = sharedZone;
    }
 
    /**
     * @returns If the shared zone is available
     */
    get sharedZoneAvailable(): boolean {
        return Boolean(this._resources.sharedZone);
    }
 
    /**
     * @returns True if legacy login should be used, false otherwise
     */
    get legacyLogin(): boolean {
        return this._resources.legacyLogin;
    }
}