Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support IndexDB url storage #676

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 13 additions & 12 deletions lib/browser/index.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import BaseUpload from '../upload.js'
import NoopUrlStorage from '../noopUrlStorage.js'
import { enableDebugLog } from '../logger.js'
import DetailedError from '../error.js'

import { canStoreURLs, WebStorageUrlStorage } from './urlStorage.js'
import DefaultHttpStack from './httpStack.js'
import { enableDebugLog } from '../logger.js'
import NoopUrlStorage from '../noopUrlStorage.js'
import BaseUpload from '../upload.js'
import FileReader from './fileReader.js'
import fingerprint from './fileSignature.js'
import DefaultHttpStack from './httpStack.js'
import { canStoreURLsInIndexDB, WebIndexDBStorageUrlStorage } from './urlStorageIndexDB.js'
import { canStoreURLsInLocalStorage, WebLocalStorageUrlStorage } from './urlStorageLocalStorage.js'

const defaultOptions = {
...BaseUpload.defaultOptions,
httpStack: new DefaultHttpStack(),
fileReader: new FileReader(),
urlStorage: canStoreURLs ? new WebStorageUrlStorage() : new NoopUrlStorage(),
urlStorage:canStoreURLsInIndexDB ? new WebIndexDBStorageUrlStorage() : canStoreURLsInLocalStorage ? new WebLocalStorageUrlStorage() : new NoopUrlStorage(),
fingerprint,
}

Expand All @@ -35,11 +35,12 @@ const isSupported =
typeof Blob.prototype.slice === 'function'

export {
Upload,
canStoreURLs,
defaultOptions,
isSupported,
enableDebugLog,
canStoreURLsInIndexDB,
canStoreURLsInLocalStorage,
DefaultHttpStack,
defaultOptions,
DetailedError,
enableDebugLog,
isSupported,
Upload
}
118 changes: 118 additions & 0 deletions lib/browser/urlStorageIndexDB.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
const isSupportIndexDB = () => {
return 'indexedDB' in window && !/iPad|iPhone|iPod/.test(navigator.platform);
};
let hasStorage = false;
try {
hasStorage = isSupportIndexDB();
} catch (e) {
if (e.code === e.SECURITY_ERR || e.code === e.QUOTA_EXCEEDED_ERR) {
hasStorage = false;
} else {
throw e;
}
}

export const canStoreURLsInIndexDB = hasStorage;

export class WebIndexDBStorageUrlStorage {
constructor() {
this.dbName = 'tusUrlStorage';
this.storeName = 'upload';
this.dbPromise = this.openDatabase();
}

openDatabase() {
return new Promise((resolve, reject) => {
const openRequest = indexedDB.open(this.dbName);
openRequest.onupgradeneeded = function () {
const db = openRequest.result;
if (!db.objectStoreNames.contains(this.storeName)) {
db.createObjectStore(this.storeName, {keyPath: 'urlStorageKey'});
}
}.bind(this);
openRequest.onsuccess = function () {
resolve(openRequest.result);
};
openRequest.onerror = reject;
});
}

async _getAllUploadWithKeys() {
try {
const db = await this.dbPromise;
const transaction = db.transaction(this.storeName, 'readonly');
const store = transaction.objectStore(this.storeName);
const request = store.getAll();
const results = await new Promise((resolve, reject) => {
request.onsuccess = () => resolve(request.result);
request.onerror = reject;
});
return results.map((result) => ({
...result,
urlStorageKey: result.urlStorageKey,
}));
} catch (error) {
console.error('Error getting all uploads with keys:', error);
throw error;
}
}

async findAllUploads() {
try {
const results = await this._getAllUploadWithKeys();
return results;
} catch (error) {
console.error('Error finding all uploads:', error);
throw error;
}
}

async findUploadsByFingerprint(fingerprint) {
try {
const allData = await this._getAllUploadWithKeys();
const results = allData.find(
(data) => data.urlStorageKey.indexOf(`tus::${fingerprint}::`) === 0
);

return results ? [results] : [];
} catch (error) {
console.error('Error finding uploads by fingerprint:', error);
throw error;
}
}

async removeUpload(urlStorageKey) {
try {
const db = await this.dbPromise;
const transaction = db.transaction(this.storeName, 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.delete(urlStorageKey);
await new Promise((resolve, reject) => {
request.onsuccess = resolve;
request.onerror = reject;
});
} catch (error) {
console.error('Error removing upload:', error);
throw error;
}
}

async addUpload(fingerprint, upload) {
try {
const id = Math.round(Math.random() * 1e12);
const key = `tus::${fingerprint}::${id}`;
const db = await this.dbPromise;
const transaction = db.transaction(this.storeName, 'readwrite');
const store = transaction.objectStore(this.storeName);
const request = store.put({urlStorageKey: key, ...upload});
await new Promise((resolve, reject) => {
request.onsuccess = () => resolve(key);
request.onerror = reject;
});
return key;
} catch (error) {
console.error('Error adding upload:', error);
throw error;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,9 @@ try {
}
}

export const canStoreURLs = hasStorage
export const canStoreURLsInLocalStorage = hasStorage

export class WebStorageUrlStorage {
export class WebLocalStorageUrlStorage {
findAllUploads() {
const results = this._findEntries('tus::')
return Promise.resolve(results)
Expand Down