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 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 1x 5x 5x 5x 5x 1x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 153x 153x 18x 18x 7x 7x 11x 11x 11x 11x 11x 11x 18x 3x 3x 18x 8x 8x 11x 11x 11x 1x 1x 1x 1x 1x 1x 8x 5x 5x 5x 3x 3x 8x 8x 1x 1x 1x 1x 1x 1x 6x 6x 6x 1x 1x 1x 5x 5x 5x 5x 4x 4x 6x 2x 2x 6x 1x 1x 1x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 1x 1x 1x 12x 1x 1x 1x 1x 1x 11x 11x 11x 11x 11x 11x 11x 1x 1x 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 1x 1x 5x 5x 5x 1x 1x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 88x 88x 88x 88x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 3x 3x 4x 4x 7x 1x 1x 7x 7x 7x 4x 4x 7x 7x 1x 1x 1x 1x 1x 6x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 34x 34x 34x 34x 1x 1x 1x 1x 1x 1x 1x 34x 34x 34x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 1x 1x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 3x 3x 1x | import {Cron} from "croner";
import {ArchiveEngine} from "../lib/archive-engine/archive-engine.js";
import {iCloud} from "../lib/icloud/icloud.js";
import {Album} from "../lib/photos-library/model/album.js";
import {Asset} from "../lib/photos-library/model/asset.js";
import {PhotosLibrary} from "../lib/photos-library/photos-library.js";
import {iCPSEventApp, iCPSEventCloud, iCPSEventPhotos, iCPSEventRuntimeError, iCPSEventRuntimeWarning, iCPSEventWebServer} from "../lib/resources/events-types.js";
import {Resources} from "../lib/resources/main.js";
import {SyncEngine} from "../lib/sync-engine/sync-engine.js";
import {APP_ERR, AUTH_ERR } from "./error/error-codes.js";
import {iCPSError} from "./error/error.js";
import {StateType} from "../lib/resources/state-manager.js";
/**
* Abstract class returned by the factory function
*/
export abstract class iCPSApp {
/**
* Executes this app
*/
abstract run(): Promise<unknown>;
}
/**
* This app will allow running in scheduled daemon mode - where a sync is executed based on a cron schedule
*/
export class DaemonApp extends iCPSApp {
/**
* Holds the cron job - available once the app is running
*/
job?: Cron;
/**
* Schedules triggering syncs closer than this interval (in ms) are most likely misconfigured
*/
static readonly MIN_SCHEDULE_INTERVAL = 60 * 60 * 1000;
/**
* Number of upcoming runs that are inspected to determine the schedule's frequency
*/
static readonly INSPECTED_RUNS = 10;
/**
* Schedule the synchronization based on the provided cron string
* @returns Once the job has been scheduled
* @emits iCPSEventRuntimeWarning.SCHEDULE_FREQUENCY - If the schedule triggers syncs more often than once per hour - provides the iCPSError as argument
*/
async run() {
this.job = new Cron(
Resources.manager().schedule,
async () => {
await this.performScheduledSync();
},
{
protect: () => {
Resources.emit(iCPSEventApp.SCHEDULED_OVERRUN, this.job?.nextRun());
},
},
);
Resources.events(this).on(iCPSEventWebServer.SYNC_REQUESTED, async () => {
this.job?.trigger();
});
this.checkScheduleFrequency(this.job);
Resources.emit(iCPSEventApp.SCHEDULED, this.job?.nextRun());
}
/**
* Warns, if the schedule triggers syncs more often than once per hour. This is most likely a misconfiguration, e.g. `* 2 * * *` (every minute between 02:00 and 02:59) instead of `0 2 * * *` (daily at 02:00).
* @param job - The scheduled job
* @emits iCPSEventRuntimeWarning.SCHEDULE_FREQUENCY - If the schedule triggers syncs more often than once per hour - provides the iCPSError as argument
*/
checkScheduleFrequency(job: Cron) {
const nextRuns = job.nextRuns(DaemonApp.INSPECTED_RUNS);
let shortestInterval = Infinity;
for (let i = 1; i < nextRuns.length; i++) {
shortestInterval = Math.min(shortestInterval, nextRuns[i].getTime() - nextRuns[i - 1].getTime());
}
if (shortestInterval >= DaemonApp.MIN_SCHEDULE_INTERVAL) {
return;
}
const schedule = Resources.manager().schedule;
const warning = new iCPSError(APP_ERR.SCHEDULE_FREQUENCY);
// The common mistake of a wildcard minute with a fixed hour - e.g. `* 2 * * *` instead of `0 2 * * *`
const [minute, hour, ...rest] = schedule.trim().split(/\s+/);
if (rest.length === 3 && minute === `*` && /^\d{1,2}$/.test(hour)) {
const paddedHour = hour.padStart(2, `0`);
warning.addMessage(`'${schedule}' runs every minute between ${paddedHour}:00 and ${paddedHour}:59 - did you mean '0 ${hour} ${rest.join(` `)}'?`);
} else {
warning.addMessage(`'${schedule}' runs as often as every ${DaemonApp.formatInterval(shortestInterval)}`);
}
Resources.emit(iCPSEventRuntimeWarning.SCHEDULE_FREQUENCY, warning);
}
/**
* @param interval - The interval in ms
* @returns A human readable representation of the interval, in seconds or minutes
*/
static formatInterval(interval: number): string {
if (interval < 60 * 1000) {
const seconds = Math.max(1, Math.round(interval / 1000));
return seconds === 1 ? `second` : `${seconds} seconds`;
}
const minutes = Math.round(interval / (60 * 1000));
return minutes === 1 ? `minute` : `${minutes} minutes`;
}
/**
* Perform a scheduled sync
* @param syncApp - Parametrized for testability - will be freshly initiated if omitted
*/
async performScheduledSync(syncApp: SyncApp = new SyncApp()) {
// Another operation (e.g. a re-authentication triggered through the Web UI) is still in progress - skipping this run
// This needs to be checked before emitting SCHEDULED_START, since that event moves the state to RUNNING
if (Resources.state().state !== StateType.READY) {
Resources.emit(iCPSEventApp.SCHEDULED_OVERRUN, this.job?.nextRun());
return;
}
try {
Resources.emit(iCPSEventApp.SCHEDULED_START);
const remoteState = await syncApp.run() as [Asset[], Album[]] | undefined;
// No remote state means that the MFA code was not provided - the state was already updated (an empty library is a successful sync)
if (remoteState !== undefined) {
Resources.emit(iCPSEventApp.SCHEDULED_DONE, this.job?.nextRun());
}
} catch (err) {
Resources.emit(iCPSEventRuntimeError.SCHEDULED_ERROR, new iCPSError(APP_ERR.DAEMON).addCause(err));
Resources.emit(iCPSEventApp.SCHEDULED_RETRY, this.job?.nextRun());
}
}
}
/**
* This is the base application class which will setup and manage the iCloud connection and local Photos Library
*/
abstract class iCloudApp extends iCPSApp {
/**
* This sessions' iCloud object
*/
icloud: iCloud = new iCloud()
/**
* This function establishes the iCloud connection.
* @returns A promise that resolves to true once the iCloud service is fully available. If it resolves to false, the MFA code was not provided in time and the object is not ready.
* @throws An iCPSError in case an error occurs
*/
async run(): Promise<unknown> {
try {
return await this.icloud.authenticate();
} catch (err) {
throw new iCPSError(AUTH_ERR.FAILED)
.addCause(err);
}
}
/**
* Removes all established event listeners, resets the network connection
*/
async clean() {
await Resources.network().resetSession();
Resources.events(this.icloud.photos).removeListeners();
Resources.events(this.icloud).removeListeners();
try {
await this.icloud.logout();
} catch (err) {
Resources.logger(this).warn(`Failed to logout from iCloud: ${err}`);
}
}
}
/**
* This application will print the locally stored token, acquire a new one (if necessary) and print it to the CLI
*/
export class TokenApp extends iCloudApp {
/**
* This function will validate the currently stored account token and print it afterwards
* @returns A promise that resolves once the operation has been completed
* @throws An iCPSError in case an error occurs
* @emits iCPSEventPhotos.READY - Once the token has been validated in order for the Promise to resolve
* @emits iCPSEventApp.TOKEN - Once the token has been validated in order for the CLI to print it
*/
async run(): Promise<unknown> {
try {
// Making sure execution stops after TRUSTED event, by removing existing listeners
Resources.events(this.icloud).removeListeners(iCPSEventCloud.TRUSTED);
Resources.events(this).once(iCPSEventCloud.TRUSTED, token => {
Resources.emit(iCPSEventPhotos.READY);
Resources.emit(iCPSEventApp.TOKEN, token);
});
return await super.run();
} catch (err) {
throw new iCPSError(APP_ERR.TOKEN)
.addCause(err);
} finally {
// Only if this is the initiated class, release the lock
if (this.constructor.name === TokenApp.name) {
await this.clean();
}
}
}
/**
* Removes all established event listeners and releases the library lock
*/
async clean() {
await super.clean();
Resources.events(this).removeListeners();
}
}
/**
* This application will perform a synchronization of the provided Photos Library using the authenticated iCloud connection
*/
export class SyncApp extends iCloudApp {
/**
* This sessions' Photos Library object
*/
photosLibrary: PhotosLibrary = new PhotosLibrary();
/**
* This sessions' Sync Engine object
*/
syncEngine: SyncEngine = new SyncEngine(this.icloud, this.photosLibrary);
/**
* Runs the synchronization of the local Photo Library
* @returns A Promise that resolves to a tuple containing the list of assets and albums as fetched from the remote state, or undefined, if the iCloud connection was not established successfully (because the MFA code was not provided in time).
* @throws An iCPSError in case an error occurs
*/
async run(): Promise<unknown> {
try {
const ready = await super.run() as boolean;
if (!ready) {
return undefined;
}
return await this.syncEngine.sync();
} catch (err) {
throw new iCPSError(APP_ERR.SYNC)
.addCause(err);
} finally {
// If this is the initiated class, release the lock
if (this.constructor.name === SyncApp.name) {
await this.clean();
}
}
}
/**
* Removes all established event listeners and releases the library lock
*/
async clean() {
await super.clean();
}
}
/**
* This application will first perform a synchronization and then archive a given local path
*/
export class ArchiveApp extends SyncApp {
/**
* This sessions' Archive Engine object
*/
archiveEngine: ArchiveEngine = new ArchiveEngine(this.icloud, this.photosLibrary);
/**
* The local path to be archived
*/
archivePath: string;
/**
* Creates and sets up the necessary infrastructure for this app
* @param archivePath - The path to the folder that should get archived
*/
constructor(archivePath: string) {
super();
this.archivePath = archivePath;
}
/**
* This function will first perform a synchronization run and then attempt to archive the provided path
* @returns A promise that resolves once the operation has finished
* @throws An ArchiveError in case an error occurs
*/
async run(): Promise<unknown> {
try {
const remoteState = await super.run() as [Asset[], Album[]] | undefined;
// If the MFA code was not provided, no remote assets are available (and therefore none are deleted remotely)
return await this.archiveEngine.archivePath(this.archivePath, remoteState?.[0] ?? []);
} catch (err) {
throw new iCPSError(APP_ERR.ARCHIVE)
.addCause(err).addContext(`archivePath`, this.archivePath);
} finally {
// If this is the initiated class, release the lock
if (this.constructor.name === ArchiveApp.name) {
await this.clean();
}
}
}
/**
* Removes all established event listeners and releases the library lock
*/
async clean() {
await super.clean();
}
} |