95 lines
2.0 KiB
JavaScript
95 lines
2.0 KiB
JavaScript
export const sdcard = navigator.getDeviceStorage('sdcard')
|
|
export let root
|
|
|
|
export function promisify(request) {
|
|
return new Promise((resolve, reject) => {
|
|
request.onsuccess = (event) => {
|
|
resolve(request.result)
|
|
}
|
|
request.onerror = (event) => {
|
|
reject(request.error)
|
|
console.error(request.error)
|
|
}
|
|
})
|
|
}
|
|
|
|
export function joinPath(left, right) {
|
|
return (left + right).replaceAll(/\/{2,}/g, '/')
|
|
}
|
|
|
|
function handle(sPath, sName) {
|
|
return {
|
|
name: sName,
|
|
path: sPath,
|
|
kind: 'directory'
|
|
}
|
|
}
|
|
|
|
function resolveHandle(handle) {
|
|
let cs = handle.path.split('/')
|
|
let f = root
|
|
|
|
for(let c of cs) {
|
|
f = f.entries[c]
|
|
if(f == undefined) {
|
|
throw new Error('Invalid path:', handle.path)
|
|
}
|
|
}
|
|
|
|
return f
|
|
}
|
|
|
|
export function Start() {
|
|
|
|
}
|
|
|
|
export const createIndex = () => {
|
|
return new Promise(filesystemIndexHandler)
|
|
}
|
|
|
|
const filesystemIndexHandler = (resolve, reject) => {
|
|
let cursor = sdcard.enumerate();
|
|
root = {}
|
|
|
|
cursor.onerror = function() {
|
|
reject(cursor.error)
|
|
}
|
|
cursor.onsuccess = function() {
|
|
if(!this.result) {
|
|
return resolve(root)
|
|
}
|
|
let cs = this.result.name.split('/').slice(1)
|
|
let f = root
|
|
let c
|
|
for(let i = 0; i < cs.length; i++) {
|
|
c = cs[i]
|
|
if(!f.entries) {
|
|
f.kind = 'directory'
|
|
f.entries = {}
|
|
}
|
|
f = f.entries[c] ??= handle('/' + cs.slice(0, i + 1).join('/'), c)
|
|
}
|
|
f.kind = 'file'
|
|
// f.file = this.result
|
|
|
|
this.continue()
|
|
}
|
|
}
|
|
|
|
export async function Entries(handle) {
|
|
if(!root)
|
|
await createIndex()
|
|
let pool = new Map()
|
|
let t = handle == null ? root : handle
|
|
for(let n in t.entries ?? {}) {
|
|
let h = t.entries[n]
|
|
pool.set(h.name, h)
|
|
}
|
|
|
|
return pool
|
|
}
|
|
|
|
export function Open(hFile) {
|
|
// return hFile.file
|
|
return promisify(sdcard.get(hFile.path))
|
|
} |