forked from owncloud/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmediaSource.js
71 lines (67 loc) · 2.02 KB
/
mediaSource.js
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
import store from '../store'
const { default: PQueue } = require('p-queue')
export default {
install(Vue) {
function _mediaSource(source, returnAs = 'url', headers = null) {
return new Promise((resolve, reject) => {
if (headers === null) {
headers = new Headers()
headers.append('Authorization', 'Bearer ' + store.getters.getToken)
}
headers.append('X-Requested-With', 'XMLHttpRequest')
fetch(source, { headers })
.then(response => {
if (!response.ok) {
reject(response)
return
}
response.blob().then(blob => {
if (returnAs === 'base64') {
const reader = new FileReader()
reader.readAsDataURL(blob)
reader.onloadend = function() {
resolve(reader)
}
} else if (returnAs === 'url') {
const source = window.URL.createObjectURL(blob)
resolve(source)
}
})
})
.catch(e => {
console.warn('media-source', e)
reject(e)
})
})
}
// For use with <img> tags
Vue.directive('image-source', {
bind(el, binding) {
// Set an empty image while resolving
el.setAttribute(
'src',
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='
)
_mediaSource(binding.value)
.then(dataImage => {
el.setAttribute('src', dataImage)
})
.catch(e => {
console.warn('image-source', e)
})
}
})
Vue.mixin({
data: function() {
return {
mediaSourceQueue: new PQueue({ concurrency: 2 })
}
},
methods: {
mediaSource(source, returnAs = 'url', headers = null) {
return this.mediaSourceQueue.add(() => _mediaSource(source, returnAs, headers))
}
}
})
}
}