1 |
|
2 |
|
3 |
|
4 | function findUppyInstances () {
|
5 | const instances = []
|
6 | for (let i = 0; i < localStorage.length; i++) {
|
7 | const key = localStorage.key(i)
|
8 | if (/^uppyState:/.test(key)) {
|
9 | instances.push(key.slice('uppyState:'.length))
|
10 | }
|
11 | }
|
12 | return instances
|
13 | }
|
14 |
|
15 |
|
16 |
|
17 |
|
18 | function maybeParse (str) {
|
19 | try {
|
20 | return JSON.parse(str)
|
21 | } catch (err) {
|
22 | return null
|
23 | }
|
24 | }
|
25 |
|
26 | let cleanedUp = false
|
27 | module.exports = class MetaDataStore {
|
28 | constructor (opts) {
|
29 | this.opts = Object.assign({
|
30 | expires: 24 * 60 * 60 * 1000
|
31 | }, opts)
|
32 | this.name = `uppyState:${opts.storeName}`
|
33 |
|
34 | if (!cleanedUp) {
|
35 | cleanedUp = true
|
36 | MetaDataStore.cleanup()
|
37 | }
|
38 | }
|
39 |
|
40 | |
41 |
|
42 |
|
43 | load () {
|
44 | const savedState = localStorage.getItem(this.name)
|
45 | if (!savedState) return null
|
46 | const data = maybeParse(savedState)
|
47 | if (!data) return null
|
48 |
|
49 |
|
50 |
|
51 | if (!data.metadata) {
|
52 | this.save(data)
|
53 | return data
|
54 | }
|
55 |
|
56 | return data.metadata
|
57 | }
|
58 |
|
59 | save (metadata) {
|
60 | const expires = Date.now() + this.opts.expires
|
61 | const state = JSON.stringify({
|
62 | metadata,
|
63 | expires
|
64 | })
|
65 | localStorage.setItem(this.name, state)
|
66 | }
|
67 |
|
68 | |
69 |
|
70 |
|
71 | static cleanup () {
|
72 | const instanceIDs = findUppyInstances()
|
73 | const now = Date.now()
|
74 | instanceIDs.forEach((id) => {
|
75 | const data = localStorage.getItem(`uppyState:${id}`)
|
76 | if (!data) return null
|
77 | const obj = maybeParse(data)
|
78 | if (!obj) return null
|
79 |
|
80 | if (obj.expires && obj.expires < now) {
|
81 | localStorage.removeItem(`uppyState:${id}`)
|
82 | }
|
83 | })
|
84 | }
|
85 | }
|