-
Notifications
You must be signed in to change notification settings - Fork 0
/
getFileEntryAndroid.js
110 lines (104 loc) · 3.42 KB
/
getFileEntryAndroid.js
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
const memoize = require("lodash/memoize")
const cordovaReady = require("./utils/cordovaReady")
const getFsRoot = memoize(fsName => {
if (fsName === "external") {
return new Promise((resolve, reject) =>
// demande la permission d'accéder au stockage externe, nécessaire pour le getExternalSdCardDetails (Android 6+)
cordova.plugins.diagnostic.requestExternalStorageAuthorization(
function() {
cordova.plugins.diagnostic.getExternalSdCardDetails(
// onSuccess
function(details) {
if (details.length > 0) {
details.forEach(function(detail) {
if (detail.canWrite && detail.type === "application") {
resolve(detail.filePath)
}
})
}
// error if cannot find one
reject()
},
reject // onError
)
},
reject
)
)
} else
return Promise.resolve(
{
privateAppData: cordova.file.dataDirectory,
temp: cordova.file.externalCacheDirectory,
home: cordova.file.externalDataDirectory, // anciennement externalRootDirectory, mais plus dispo depuis Android API 29
publicAppData: cordova.file.externalDataDirectory,
}[fsName]
)
})
const getDirectory = (rootDirEntry, dirName, opts) =>
new Promise((resolve, reject) => {
rootDirEntry.getDirectory(dirName, opts, resolve, reject)
})
function createDirHierarchy(rootDirEntry, directories) {
// Throw out './' or '/' and move on to prevent something like '/foo/.//bar'.
if (directories[0] == "." || directories[0] == "") {
directories = directories.slice(1)
}
if (directories.length === 0) {
return Promise.resolve()
}
return getDirectory(rootDirEntry, directories[0], {
create: true,
}).then(function(dirEntry) {
// Recursively add subdirectories
return createDirHierarchy(dirEntry, directories.slice(1))
})
}
module.exports = (fsRootName, path, opts = {}) => {
const { create = false, dir = false } = opts
return cordovaReady.then(() =>
getFsRoot(fsRootName).then(
fsRoot =>
new Promise((resolve, reject) => {
window.resolveLocalFileSystemURL(
fsRoot,
function(fs) {
const getFileEntry = () => {
fs[dir ? "getDirectory" : "getFile"](
path,
opts,
fileEntry => {
console.debug(
"getFile: ok",
path,
fileEntry,
fileEntry.toURL()
)
resolve(fileEntry)
},
err => {
if (err.name === "NotFoundError" || err.code === 1) {
console.debug("getFile: not found", path)
resolve(null)
} else {
console.error(err)
reject(err)
}
}
)
}
if (create) {
// create directory hierarchy then get file
return createDirHierarchy(fs, path.split("/").slice(0, -1))
.then(getFileEntry)
.catch(reject)
} else {
getFileEntry()
}
},
reject
)
})
)
)
}