@mieweb/wikigdrive
Version:
Google Drive to MarkDown synchronization
244 lines (243 loc) • 12.7 kB
JavaScript
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
var useValue = arguments.length > 2;
for (var i = 0; i < initializers.length; i++) {
value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
}
return useValue ? value : void 0;
};
var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
var _, done = false;
for (var i = decorators.length - 1; i >= 0; i--) {
var context = {};
for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
for (var p in contextIn.access) context.access[p] = contextIn.access[p];
context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
if (kind === "accessor") {
if (result === void 0) continue;
if (result === null || typeof result !== "object") throw new TypeError("Object expected");
if (_ = accept(result.get)) descriptor.get = _;
if (_ = accept(result.set)) descriptor.set = _;
if (_ = accept(result.init)) initializers.unshift(_);
}
else if (_ = accept(result)) {
if (kind === "field") initializers.unshift(_);
else descriptor[key] = _;
}
}
if (target) Object.defineProperty(target, contextIn.name, descriptor);
done = true;
};
var __setFunctionName = (this && this.__setFunctionName) || function (f, name, prefix) {
if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : "";
return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name });
};
import { Container } from '../../ContainerEngine.js';
import { GoogleDriveService } from '../../google/GoogleDriveService.js';
import { GoogleTreeProcessor } from '../google_folder/GoogleTreeProcessor.js';
import { initJob } from '../job/JobManagerContainer.js';
import { UserConfigService } from '../google_folder/UserConfigService.js';
import { TelemetryClass, TelemetryMethod, TelemetryMethodDisable } from '../../telemetry.js';
const __filename = globalThis[Symbol.for("import-meta-ponyfill-esmodule")](import.meta).filename;
let WatchChangesContainer = (() => {
let _classDecorators = [TelemetryClass()];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
let _classSuper = Container;
let _instanceExtraInitializers = [];
let _init_decorators;
let _startWatching_decorators;
let _watchDriveChanges_decorators;
let _run_decorators;
var WatchChangesContainer = _classThis = class extends _classSuper {
constructor() {
super(...arguments);
Object.defineProperty(this, "logger", {
enumerable: true,
configurable: true,
writable: true,
value: __runInitializers(this, _instanceExtraInitializers)
});
Object.defineProperty(this, "auth", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "googleDriveService", {
enumerable: true,
configurable: true,
writable: true,
value: void 0
});
Object.defineProperty(this, "lastToken", {
enumerable: true,
configurable: true,
writable: true,
value: {}
});
Object.defineProperty(this, "intervals", {
enumerable: true,
configurable: true,
writable: true,
value: {}
});
Object.defineProperty(this, "working", {
enumerable: true,
configurable: true,
writable: true,
value: {}
});
}
async init(engine) {
await super.init(engine);
this.logger = engine.logger.child({ filename: __filename });
const googleApiContainer = engine.getContainer('google_api');
this.auth = googleApiContainer.getAuth();
this.googleDriveService = new GoogleDriveService(this.logger, googleApiContainer.getQuotaLimiter());
this.engine.subscribe('gdrive:changed', async (driveId) => {
const folderFilesService = await this.filesService.getSubFileService(driveId, '/');
const treeProcessor = new GoogleTreeProcessor(folderFilesService);
await treeProcessor.load();
const changes = await this.getChanges(driveId);
const filteredChanges = [];
for (const change of changes) {
const [leaf] = await treeProcessor.findById(change.id);
if (!leaf) {
if (!change.trashed) {
filteredChanges.push(change);
}
continue;
}
if (leaf.modifiedTime < change.modifiedTime) {
filteredChanges.push(change);
}
}
await this.setChanges(driveId, filteredChanges);
});
this.engine.subscribe('drive:register', (driveId, drive) => {
if (drive.driveId) {
this.startWatching(drive.driveId);
}
});
this.engine.subscribe('drive:unregister', (driveId) => {
this.stopWatching(driveId);
this.engine.emit(driveId, 'toasts:added', {
type: 'drive:unregister',
links: {},
title: 'WikiGDrive access to Google Drive removed',
description: `Access for ${this.params.share_email} has been removed`
});
});
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
async destroy() {
}
async getChanges(driveId) {
const driveFileSystem = await this.filesService.getSubFileService(driveId, '');
return await driveFileSystem.readJson('.changes.json') || [];
}
async setChanges(driveId, changes) {
const driveFileSystem = await this.filesService.getSubFileService(driveId, '');
await driveFileSystem.writeJson('.changes.json', changes);
this.engine.emit(driveId, 'changes:changed', changes);
const userConfigService = new UserConfigService(driveFileSystem);
await userConfigService.load();
if (changes.length > 0 && userConfigService.config.auto_sync) {
const fileIdsString = changes.map(change => change.id).join(',');
const jobManagerContainer = this.engine.getContainer('job_manager');
await jobManagerContainer.schedule(driveId, {
...initJob(),
type: 'sync',
payload: fileIdsString,
title: 'Syncing file: ' + fileIdsString
});
}
}
async startWatching(driveId) {
if (this.intervals[driveId]) {
return;
}
// TODO: remove me
if (Object.keys(this.intervals).length > 0) {
// return;
}
this.logger.info('Starting watching: ' + driveId);
this.intervals[driveId] = setInterval(async () => {
if (!this.auth) {
return;
}
if (this.working[driveId]) {
return;
}
this.working[driveId] = true;
try {
if (!this.lastToken[driveId]) {
this.lastToken[driveId] = await this.googleDriveService.getStartTrackToken(this.auth, driveId);
return;
}
await this.watchDriveChanges(driveId);
}
catch (err) {
this.logger.warn(err.message);
if (err.status === 403 && err.message.indexOf('The attempted action requires shared drive membership') > -1) {
const folderRegistryContainer = this.engine.getContainer('folder_registry');
await folderRegistryContainer.refreshDrives();
}
}
finally {
delete this.working[driveId];
}
}, 3000);
}
async watchDriveChanges(driveId) {
const changes = await this.googleDriveService.watchChanges(this.auth, this.lastToken[driveId], driveId);
if (changes.files.length > 0) {
let dbChanges = await this.getChanges(driveId);
for (const file of changes.files) {
dbChanges = dbChanges.filter(f => f.id !== file.id);
dbChanges.push(file);
}
await this.setChanges(driveId, dbChanges);
}
this.lastToken[driveId] = changes.token;
}
stopWatching(driveId) {
if (!this.intervals[driveId]) {
return;
}
clearInterval(this.intervals[driveId]);
this.intervals[driveId] = null;
}
async run() {
const folderRegistryContainer = this.engine.getContainer('folder_registry');
const folders = await folderRegistryContainer.getFolders();
for (const folderId in folders) {
await this.startWatching(folders[folderId].id);
}
}
};
__setFunctionName(_classThis, "WatchChangesContainer");
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
_init_decorators = [TelemetryMethodDisable()];
_startWatching_decorators = [TelemetryMethodDisable()];
_watchDriveChanges_decorators = [TelemetryMethod({ paramsCount: 1 })];
_run_decorators = [TelemetryMethodDisable()];
__esDecorate(_classThis, null, _init_decorators, { kind: "method", name: "init", static: false, private: false, access: { has: obj => "init" in obj, get: obj => obj.init }, metadata: _metadata }, null, _instanceExtraInitializers);
__esDecorate(_classThis, null, _startWatching_decorators, { kind: "method", name: "startWatching", static: false, private: false, access: { has: obj => "startWatching" in obj, get: obj => obj.startWatching }, metadata: _metadata }, null, _instanceExtraInitializers);
__esDecorate(_classThis, null, _watchDriveChanges_decorators, { kind: "method", name: "watchDriveChanges", static: false, private: false, access: { has: obj => "watchDriveChanges" in obj, get: obj => obj.watchDriveChanges }, metadata: _metadata }, null, _instanceExtraInitializers);
__esDecorate(_classThis, null, _run_decorators, { kind: "method", name: "run", static: false, private: false, access: { has: obj => "run" in obj, get: obj => obj.run }, metadata: _metadata }, null, _instanceExtraInitializers);
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
WatchChangesContainer = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
__runInitializers(_classThis, _classExtraInitializers);
})();
return WatchChangesContainer = _classThis;
})();
export { WatchChangesContainer };