aboutsummaryrefslogtreecommitdiffhomepage
path: root/client/src/root-helpers/peertube-web-storage.ts
blob: 68a2462de04837d5fa14ec080daa8397d4e5b87f (plain) (blame)
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
// Thanks: https://github.com/capaj/localstorage-polyfill

const valuesMap = new Map()

function proxify (instance: MemoryStorage) {
  return new Proxy(instance, {
    set: function (obj, prop: string | symbol, value) {
      if (Object.prototype.hasOwnProperty.call(MemoryStorage, prop)) {
        // FIXME: symbol typing issue https://github.com/microsoft/TypeScript/issues/1863
        instance[prop as any] = value
      } else {
        instance.setItem(prop, value)
      }
      return true
    },
    get: function (target, name: string | symbol | number) {
      if (Object.prototype.hasOwnProperty.call(MemoryStorage, name)) {
        // FIXME: symbol typing issue https://github.com/microsoft/TypeScript/issues/1863
        return instance[name as any]
      }
      if (valuesMap.has(name)) {
        return instance.getItem(name)
      }
    }
  })
}

class MemoryStorage implements Storage {
  [key: string]: any

  getItem (key: any) {
    const stringKey = String(key)
    if (valuesMap.has(key)) {
      return String(valuesMap.get(stringKey))
    }

    return null
  }

  setItem (key: any, val: any) {
    valuesMap.set(String(key), String(val))
  }

  removeItem (key: any) {
    valuesMap.delete(key)
  }

  clear () {
    valuesMap.clear()
  }

  key (i: any) {
    if (arguments.length === 0) {
      throw new TypeError('Failed to execute "key" on "Storage": 1 argument required, but only 0 present.')
    }

    const arr = Array.from(valuesMap.keys())
    return arr[i]
  }

  get length () {
    return valuesMap.size
  }
}

let peertubeLocalStorage: Storage
let peertubeSessionStorage: Storage

function reinitStorage () {
  const instanceLocalStorage = new MemoryStorage()
  const instanceSessionStorage = new MemoryStorage()

  peertubeLocalStorage = proxify(instanceLocalStorage)
  peertubeSessionStorage = proxify(instanceSessionStorage)
}

try {
  peertubeLocalStorage = localStorage
  peertubeSessionStorage = sessionStorage
} catch (err) {
  // support Firefox and other browsers using an exception rather than null
  reinitStorage()
}

// support Brave and other browsers using null rather than an exception
if (peertubeLocalStorage === null || peertubeSessionStorage === null) {
  reinitStorage()
}

export {
  peertubeLocalStorage,
  peertubeSessionStorage
}