]> git.immae.eu Git - github/Chocobozzz/PeerTube.git/blame - client/src/root-helpers/peertube-web-storage.ts
Try to fix live segments check
[github/Chocobozzz/PeerTube.git] / client / src / root-helpers / peertube-web-storage.ts
CommitLineData
0bd78bf3
C
1// Thanks: https://github.com/capaj/localstorage-polyfill
2
3const valuesMap = new Map()
4
fd8f73cf
C
5function proxify (instance: MemoryStorage) {
6 return new Proxy(instance, {
7 set: function (obj, prop: string | number, value) {
8 if (MemoryStorage.prototype.hasOwnProperty(prop)) {
9 instance[prop] = value
10 } else {
11 instance.setItem(prop, value)
12 }
13 return true
14 },
15 get: function (target, name: string | number) {
16 if (MemoryStorage.prototype.hasOwnProperty(name)) {
17 return instance[name]
18 }
19 if (valuesMap.has(name)) {
20 return instance.getItem(name)
21 }
22 }
23 })
24}
25
0bd78bf3
C
26class MemoryStorage {
27 [key: string]: any
28 [index: number]: string
29
244b4ae3 30 getItem (key: any) {
0bd78bf3
C
31 const stringKey = String(key)
32 if (valuesMap.has(key)) {
33 return String(valuesMap.get(stringKey))
34 }
35
36 return null
37 }
38
244b4ae3 39 setItem (key: any, val: any) {
0bd78bf3
C
40 valuesMap.set(String(key), String(val))
41 }
42
244b4ae3 43 removeItem (key: any) {
0bd78bf3
C
44 valuesMap.delete(key)
45 }
46
47 clear () {
48 valuesMap.clear()
49 }
50
51 key (i: any) {
52 if (arguments.length === 0) {
53 throw new TypeError('Failed to execute "key" on "Storage": 1 argument required, but only 0 present.')
54 }
55
56 const arr = Array.from(valuesMap.keys())
57 return arr[i]
58 }
59
60 get length () {
61 return valuesMap.size
62 }
63}
64
65let peertubeLocalStorage: Storage
88a7f93f 66let peertubeSessionStorage: Storage
61379e43
RK
67
68function reinitStorage () {
6189b699
C
69 const instanceLocalStorage = new MemoryStorage()
70 const instanceSessionStorage = new MemoryStorage()
0bd78bf3 71
6189b699
C
72 peertubeLocalStorage = proxify(instanceLocalStorage)
73 peertubeSessionStorage = proxify(instanceSessionStorage)
0bd78bf3
C
74}
75
61379e43
RK
76try {
77 peertubeLocalStorage = localStorage
78 peertubeSessionStorage = sessionStorage
79} catch (err) {
80 // support Firefox and other browsers using an exception rather than null
81 reinitStorage()
82}
83
84// support Brave and other browsers using null rather than an exception
85if (peertubeLocalStorage === null || peertubeSessionStorage === null) {
86 reinitStorage()
87}
88
88a7f93f
RK
89export {
90 peertubeLocalStorage,
91 peertubeSessionStorage
92}