Make it works with new autoplay policy
[oweals/peertube.git] / client / src / assets / player / utils.ts
1 function toTitleCase (str: string) {
2   return str.charAt(0).toUpperCase() + str.slice(1)
3 }
4
5 // https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
6 // Don't import all Angular stuff, just copy the code with shame
7 const dictionaryBytes: Array<{max: number, type: string}> = [
8   { max: 1024, type: 'B' },
9   { max: 1048576, type: 'KB' },
10   { max: 1073741824, type: 'MB' },
11   { max: 1.0995116e12, type: 'GB' }
12 ]
13 function bytes (value) {
14   const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
15   const calc = Math.floor(value / (format.max / 1024)).toString()
16
17   return [ calc, format.type ]
18 }
19
20 function getStoredVolume () {
21   const value = getLocalStorage('volume')
22   if (value !== null && value !== undefined) {
23     const valueNumber = parseFloat(value)
24     if (isNaN(valueNumber)) return undefined
25
26     return valueNumber
27   }
28
29   return undefined
30 }
31
32 function getStoredMute () {
33   const value = getLocalStorage('mute')
34   if (value !== null && value !== undefined) return value === 'true'
35
36   return undefined
37 }
38
39 function getAverageBandwidth () {
40   const value = getLocalStorage('average-bandwidth')
41   if (value !== null && value !== undefined) {
42     const valueNumber = parseInt(value, 10)
43     if (isNaN(valueNumber)) return undefined
44
45     return valueNumber
46   }
47
48   return undefined
49 }
50
51 function saveVolumeInStore (value: number) {
52   return setLocalStorage('volume', value.toString())
53 }
54
55 function saveMuteInStore (value: boolean) {
56   return setLocalStorage('mute', value.toString())
57 }
58
59 function saveAverageBandwidth (value: number) {
60   return setLocalStorage('average-bandwidth', value.toString())
61 }
62
63 function isMobile () {
64   return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent)
65 }
66
67 export {
68   toTitleCase,
69   getStoredVolume,
70   saveVolumeInStore,
71   saveAverageBandwidth,
72   getAverageBandwidth,
73   saveMuteInStore,
74   getStoredMute,
75   isMobile,
76   bytes
77 }
78
79 // ---------------------------------------------------------------------------
80
81 const KEY_PREFIX = 'peertube-videojs-'
82
83 function getLocalStorage (key: string) {
84   try {
85     return localStorage.getItem(KEY_PREFIX + key)
86   } catch {
87     return undefined
88   }
89 }
90
91 function setLocalStorage (key: string, value: string) {
92   try {
93     localStorage.setItem(KEY_PREFIX + key, value)
94   } catch { /* empty */ }
95 }