@rsweeten/dropbox-sync
Version:
Reusable Dropbox synchronization module with framework adapters
208 lines (207 loc) • 9.28 kB
JavaScript
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 __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 __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 { Injectable } from '@angular/core';
import { Observable, from, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { createDropboxSyncClient } from '../core/client';
let DropboxSyncService = (() => {
let _classDecorators = [Injectable({
providedIn: 'root',
})];
let _classDescriptor;
let _classExtraInitializers = [];
let _classThis;
var DropboxSyncService = _classThis = class {
constructor(http) {
this.http = http;
this.client = null;
}
/**
* Initialize the Dropbox sync client with credentials
*/
initialize(credentials) {
this.client = createDropboxSyncClient(credentials);
return this.client;
}
/**
* Get the current Dropbox sync client instance, or initialize with credentials if not exists
*/
getClient(credentials) {
if (!this.client && credentials) {
return this.initialize(credentials);
}
if (!this.client) {
throw new Error('DropboxSyncService not initialized. Call initialize() first.');
}
return this.client;
}
/**
* Check the connection status with Dropbox
*/
checkConnection() {
return this.http
.get('/api/dropbox/status')
.pipe(map((response) => response.connected), catchError(() => of(false)));
}
/**
* Start the OAuth flow to connect to Dropbox
*/
connectDropbox() {
window.location.href = '/api/dropbox/auth/start';
}
/**
* Disconnect from Dropbox
*/
disconnectDropbox() {
return this.http
.post('/api/dropbox/logout', {})
.pipe(map((response) => response.success), catchError(() => of(false)));
}
/**
* Start the sync process
*/
startSync(options) {
if (!this.client) {
throw new Error('DropboxSyncService not initialized. Call initialize() first.');
}
// Connect to socket before starting sync
this.client.socket.connect();
// Setup socket listeners for sync events
this.setupSocketListeners();
return from(this.client.sync.syncFiles(options));
}
/**
* Cancel an ongoing sync process
*/
cancelSync() {
if (!this.client) {
return;
}
this.client.sync.cancelSync();
}
/**
* Set up socket listeners for sync events
* Returns an RxJS Observable that emits sync progress events
*/
setupSocketListeners() {
if (!this.client) {
throw new Error('DropboxSyncService not initialized. Call initialize() first.');
}
// Create observable for sync progress events
return new Observable((observer) => {
// Listen for progress updates
this.client.socket.on('sync:progress', (data) => {
observer.next({ type: 'progress', data });
});
// Listen for queue information
this.client.socket.on('sync:queue', (data) => {
observer.next({ type: 'queue', data });
});
// Listen for sync completion
this.client.socket.on('sync:complete', (data) => {
observer.next({ type: 'complete', data });
observer.complete();
});
// Listen for sync errors
this.client.socket.on('sync:error', (data) => {
if (!data.continue) {
observer.error(data.message);
}
else {
observer.next({ type: 'error', data });
}
});
// Cleanup function - remove event listeners when subscription is disposed
return () => {
this.client.socket.off('sync:progress');
this.client.socket.off('sync:queue');
this.client.socket.off('sync:complete');
this.client.socket.off('sync:error');
};
});
}
/**
* Handle OAuth callback on the client side
*/
handleOAuthCallback(code) {
if (!this.client) {
throw new Error('DropboxSyncService not initialized. Call initialize() first.');
}
const redirectUri = window.location.origin + '/api/dropbox/auth/callback';
return from(this.client.auth.exchangeCodeForToken(code, redirectUri)).pipe(tap((tokens) => {
// Store tokens in local storage for client-side access
localStorage.setItem('dropbox_access_token', tokens.accessToken);
if (tokens.refreshToken) {
localStorage.setItem('dropbox_refresh_token', tokens.refreshToken);
}
localStorage.setItem('dropbox_connected', 'true');
}));
}
/**
* Create a sync queue to determine which files need to be uploaded/downloaded
*/
createSyncQueue(options) {
if (!this.client) {
throw new Error('DropboxSyncService not initialized. Call initialize() first.');
}
return from(this.client.sync.createSyncQueue(options));
}
};
__setFunctionName(_classThis, "DropboxSyncService");
(() => {
const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0;
__esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
DropboxSyncService = _classThis = _classDescriptor.value;
if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
__runInitializers(_classThis, _classExtraInitializers);
})();
return DropboxSyncService = _classThis;
})();
export { DropboxSyncService };
/**
* Function to extract credentials from Angular environment
*/
export function getCredentialsFromEnvironment(environment) {
return {
clientId: environment.dropboxAppKey || '',
clientSecret: environment.dropboxAppSecret,
accessToken: localStorage.getItem('dropbox_access_token') || undefined,
refreshToken: localStorage.getItem('dropbox_refresh_token') || undefined,
};
}