All files / lib/resources resource-manager.ts

100% Statements 423/423
100% Branches 60/60
100% Functions 45/45
100% Lines 423/423

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 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 4231x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 774x 151x 151x 151x 151x 151x 150x 150x 150x 150x 150x 150x 150x 151x 774x 774x 774x 774x 774x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 151x 149x 149x 149x 151x 774x 774x 774x 774x 774x 1721x 1721x 774x 774x 774x 774x 774x 605x 605x 605x 605x 605x 774x 774x 774x 774x 774x 4x 4x 4x 4x 4x 774x 774x 774x 774x 774x 11x 11x 11x 11x 11x 774x 774x 774x 774x 774x 2x 2x 2x 2x 2x 774x 774x 774x 774x 774x 3x 3x 3x 3x 3x 774x 774x 774x 774x 774x 774x 204x 204x 774x 774x 774x 774x 774x 774x 16x 16x 16x 16x 16x 774x 774x 774x 774x 774x 774x 776x 776x 776x 774x 774x 774x 774x 774x 774x 270x 270x 134x 134x 134x 134x 270x 270x 774x 774x 774x 774x 774x 774x 57x 57x 57x 57x 774x 774x 774x 774x 774x 774x 1x 1x 1x 1x 774x 774x 774x 774x 774x 774x 2x 1x 1x 1x 1x 1x 2x 774x 774x 774x 774x 774x 188x 188x 774x 774x 774x 774x 774x 12x 12x 774x 774x 774x 774x 774x 136x 136x 774x 774x 774x 774x 774x 341x 341x 774x 774x 774x 774x 774x 12x 12x 774x 774x 774x 774x 774x 1x 1x 774x 774x 774x 774x 774x 5x 5x 774x 774x 774x 774x 774x 1x 1x 774x 774x 774x 774x 774x 4x 4x 774x 774x 774x 774x 774x 5x 5x 774x 774x 774x 774x 774x 25x 25x 774x 774x 774x 774x 774x 1x 1x 774x 774x 774x 774x 774x 1x 1x 774x 774x 774x 774x 774x 1x 1x 774x 774x 774x 774x 774x 1x 1x 774x 774x 774x 774x 774x 1x 1x 774x 774x 774x 774x 774x 1x 1x 774x 774x 774x 774x 774x 7x 7x 774x 774x 774x 774x 774x 29x 29x 774x 774x 774x 774x 774x 774x 12x 1x 1x 11x 11x 11x 774x 774x 774x 774x 774x 774x 81x 81x 774x 774x 774x 774x 774x 774x 16x 1x 1x 15x 15x 15x 774x 774x 774x 774x 774x 774x 8x 8x 774x 774x 774x 774x 774x 774x 30x 1x 1x 29x 29x 29x 774x 774x 774x 774x 774x 774x 3x 3x 774x 774x 774x 774x 774x 2x 2x 774x 774x 774x 774x 774x 33x 33x 774x 774x 16x 16x 774x
import {readFileSync, writeFileSync} from "fs";
import {jsonc} from "jsonc";
import * as path from 'path';
import {RESOURCES_ERR} from "../../app/error/error-codes.js";
import {iCPSError} from "../../app/error/error.js";
import {LogLevel} from "../../app/event/log.js";
import {iCPSAppOptions} from "../../app/factory.js";
import * as PHOTOS_LIBRARY from '../photos-library/constants.js';
import {iCPSEventRuntimeWarning} from "./events-types.js";
import {Resources} from "./main.js";
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 { PushSubscription } from "./web-server-types.js";
import webpush from 'web-push'
 
/**
 * 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,
                notificationVapidCredentials: this._resources.notificationVapidCredentials,
                notificationSubscriptions: this._resources.notificationSubscriptions
            };
            const resourceFileData = jsonc.stringify(formattedResourceFile, null, 4);
            Resources.logger(this).debug(`Writing resource file to ${this.resourceFilePath}`);
 
            writeFileSync(this.resourceFilePath, resourceFileData, {encoding: FILE_ENCODING, flush: true});
        } 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();
    }
 
    /**
     * Retrieves the notification vapid credentials, generating them if they do not exist.
     * @returns The notification vapid credentials, containing the public and private key
     */
    get notificationVapidCredentials(): { publicKey: string, privateKey: string } {
        let credentials = this._resources.notificationVapidCredentials;
        if (!credentials) {
            credentials = webpush.generateVAPIDKeys();
            this._resources.notificationVapidCredentials = credentials;
            this._writeResourceFile();
        }
        return credentials;
    }
 
    /**
     * Gets the notification subscriptions from the resource file.
     * @returns The notification subscriptions, or an empty map if none are set
     */
    get notificationSubscriptions(): webpush.PushSubscription[] {
        return this._resources.notificationSubscriptions 
            ? Object.values(this._resources.notificationSubscriptions) 
            : [];
    }
 
    /**
     * Adds a subscription to the notification subscriptions in the resource file.
     * @param subscription - The notification subscription to add
     */
    addNotificationSubscription(subscription: PushSubscription) {
        this._resources.notificationSubscriptions = this._resources.notificationSubscriptions || {};
        this._resources.notificationSubscriptions[subscription.endpoint] = subscription;
        this._writeResourceFile();
    }
 
    /**
     * Removes a subscription from the notification subscriptions in the resource file.
     * @param subscription - The notification subscription to remove
     */
    removeNotificationSubscription(subscription: webpush.PushSubscription) {
        if (this._resources.notificationSubscriptions && subscription.endpoint in this._resources.notificationSubscriptions) {
            delete this._resources.notificationSubscriptions[subscription.endpoint]
            this._writeResourceFile();
        } else {
            Resources.logger(this).warn(`No notification subscriptions found to remove endpoint: ${subscription.endpoint}`);
        }
    }
 
    /**
     * @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 webServerPort(): number {
        return this._resources.port;
    }
 
    /**
     * @returns The web base path for subpath deployment
     */
    get webBasePath(): string {
        return this._resources.webBasePath;
    }
 
    /**
     * @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 sharedZone - 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;
    }
 
    get healthCheckUrl(): string {
        return this._resources.healthCheckUrl;
    }
}