Peertube-dl/public/js/peertube-dl-web.js

82 lines
2.4 KiB
JavaScript

"use strict";
let downloadFormButton;
let videoContainer;
let closeAndResetVideoContainer;
let downloadFormUrl;
let downloadVideo;
let downloadForm;
let video;
function downloadFormButtonHandler(event) {
event.preventDefault();
getRealURL(downloadFormUrl.value).then( (response) => {
video.src = response.url;
videoContainer.style.display = 'block';
generateBlobVideo(response.url).then( blob => {
downloadVideo.href = URL.createObjectURL(blob);
downloadVideo.download = response.filename;
});
});
}
function downloadFormHandler(event) {
downloadFormButtonHandler(event);
}
async function generateBlobVideo(url) {
const blob = await fetch(url, {
mode: 'cors',
})
.then(res => res.blob())
.catch( err => generateBlobVideoByProxy(url) );
return blob;
}
async function generateBlobVideoByProxy(url) {
const blob = await fetch( '/proxy_to_get', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({url: url}),
}
).then(res => res.blob());
return blob;
}
async function getRealURL(url) {
const response = await fetch('/api', {
method: 'POST',
mode: 'cors',
cache: 'no-cache',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({url: url}),
});
return response.json();
}
function closeAndResetVideoContainerHandler(event) {
event.preventDefault();
videoContainer.style.display = 'none';
}
window.addEventListener('load', (event) => {
downloadFormButton = document.querySelector('#download-form-button');
downloadForm = document.querySelector('#download-form');
videoContainer = document.querySelector('#video-container');
video = document.querySelector('#video');
downloadFormUrl = document.querySelector('#download-form-url');
downloadVideo = document.querySelector('#download-video');
closeAndResetVideoContainer = document.querySelector('#close-and-reset-video-container');
downloadFormButton.addEventListener('click', downloadFormButtonHandler);
downloadForm.addEventListener('submit', downloadFormHandler);
closeAndResetVideoContainer.addEventListener('click', closeAndResetVideoContainerHandler);
});