Handle subtitles in player
[oweals/peertube.git] / client / src / assets / player / utils.ts
1 import { VideoFile } from '../../../../shared/models/videos'
2
3 function toTitleCase (str: string) {
4   return str.charAt(0).toUpperCase() + str.slice(1)
5 }
6
7 // https://github.com/danrevah/ngx-pipes/blob/master/src/pipes/math/bytes.ts
8 // Don't import all Angular stuff, just copy the code with shame
9 const dictionaryBytes: Array<{max: number, type: string}> = [
10   { max: 1024, type: 'B' },
11   { max: 1048576, type: 'KB' },
12   { max: 1073741824, type: 'MB' },
13   { max: 1.0995116e12, type: 'GB' }
14 ]
15 function bytes (value) {
16   const format = dictionaryBytes.find(d => value < d.max) || dictionaryBytes[dictionaryBytes.length - 1]
17   const calc = Math.floor(value / (format.max / 1024)).toString()
18
19   return [ calc, format.type ]
20 }
21
22 function isMobile () {
23   return /iPhone|iPad|iPod|Android/i.test(navigator.userAgent)
24 }
25
26 function buildVideoLink (time?: number) {
27   let href = window.location.href.replace('/embed/', '/watch/')
28   if (time) {
29     const timeInt = Math.floor(time)
30
31     if (window.location.search) href += '&start=' + timeInt
32     else href += '?start=' + timeInt
33   }
34
35   return href
36 }
37
38 function buildVideoEmbed (embedUrl: string) {
39   return '<iframe width="560" height="315" ' +
40     'sandbox="allow-same-origin allow-scripts" ' +
41     'src="' + embedUrl + '" ' +
42     'frameborder="0" allowfullscreen>' +
43     '</iframe>'
44 }
45
46 function copyToClipboard (text: string) {
47   const el = document.createElement('textarea')
48   el.value = text
49   el.setAttribute('readonly', '')
50   el.style.position = 'absolute'
51   el.style.left = '-9999px'
52   document.body.appendChild(el)
53   el.select()
54   document.execCommand('copy')
55   document.body.removeChild(el)
56 }
57
58 function videoFileMaxByResolution (files: VideoFile[]) {
59   let max = files[0]
60
61   for (let i = 1; i < files.length; i++) {
62     const file = files[i]
63     if (max.resolution.id < file.resolution.id) max = file
64   }
65
66   return max
67 }
68
69 function videoFileMinByResolution (files: VideoFile[]) {
70   let min = files[0]
71
72   for (let i = 1; i < files.length; i++) {
73     const file = files[i]
74     if (min.resolution.id > file.resolution.id) min = file
75   }
76
77   return min
78 }
79
80 // ---------------------------------------------------------------------------
81
82 export {
83   toTitleCase,
84   buildVideoLink,
85   buildVideoEmbed,
86   videoFileMaxByResolution,
87   videoFileMinByResolution,
88   copyToClipboard,
89   isMobile,
90   bytes
91 }