Skip to content
This repository has been archived by the owner on May 20, 2022. It is now read-only.

Commit

Permalink
Better on the fly video conversation
Browse files Browse the repository at this point in the history
Better on the fly video conversation
  • Loading branch information
izu-co authored Jun 20, 2021
2 parents 9404681 + 76ba805 commit 2e655da
Show file tree
Hide file tree
Showing 36 changed files with 194 additions and 270 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ $ node index.js --vd [Video directory]
This project is under license from MIT. For more details, see the [LICENSE](LICENSE.md) file.


Made with :heart: by <a href="https://github.com/AnAppleforlife" target="_blank">Me</a>
Made with :heart: by <a href="https://github.com/izu-co" target="_blank">Me</a>

&#xa0;

Expand Down
2 changes: 1 addition & 1 deletion backend/userManagment/addNewUser.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { uuidv4 } from '../util';
import { db } from '../../index';
import { BackendRequest } from "../../interfaces";
import { BackendRequest } from '../../interfaces';

const PermissionLevel = ['User', 'Admin'];

Expand Down
8 changes: 3 additions & 5 deletions backend/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import * as fs from 'fs';
import { SettingsDataInterface } from '../interfaces';
import * as loginBackend from './UserMangement';
import { db } from '../index';
import { RunResult } from 'better-sqlite3';
import { UserData, BackendRequest} from '../interfaces';

function isEmptyObject(obj:object) : boolean {
Expand Down Expand Up @@ -53,12 +52,11 @@ function saveUserData (token:string, ip:string, data:SettingsDataInterface) : Ba
return {isOk: false, statusCode: 400, message: 'Malformatted data' };

const exists = db.prepare('SELECT * FROM settings WHERE UUID=?').get(user.value.uuid);
let answer:RunResult;
if (exists)
answer = db.prepare('UPDATE settings SET volume = ? WHERE UUID = ?').run(data['volume'], user.value.uuid);
db.prepare('UPDATE settings SET volume = ? WHERE UUID = ?').run(data.volume, user.value.uuid);
else
answer = db.prepare('INSERT INTO settings VALUES(?,?)').run(user.value.uuid, data['volume']);
return { isOk: true, value: undefined }
db.prepare('INSERT INTO settings VALUES(?,?)').run(user.value.uuid, data.volume);
return { isOk: true, value: undefined };
}

function readdir(path:string) : string[] {
Expand Down
10 changes: 5 additions & 5 deletions backend/videoServing/getFiles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,8 @@ function getFilesFromWatchList(token:string, ip:string) : BackendRequest<Array<F
'stars': stars.isOk ? stars.value : 0
};
if (push['type'] === 'video') {
const time = loadTime(file['path'], token, ip, user)
push['timeStemp'] = time.isOk ? time.value : 0
const time = loadTime(file['path'], token, ip, user);
push['timeStemp'] = time.isOk ? time.value : 0;
}
retarr.push(push);
});
Expand Down Expand Up @@ -113,8 +113,8 @@ function getFileFromFolder(path:string, token:string, ip:string): BackendRequest
'stars': stars.isOk ? stars.value : 0
};
if (push['type'] === 'video') {
const time = loadTime(file['path'], token, ip, user)
push['timeStemp'] = time.isOk ? time.value : 0
const time = loadTime(file['path'], token, ip, user);
push['timeStemp'] = time.isOk ? time.value : 0;
}
retarr.push(push);

Expand All @@ -140,7 +140,7 @@ function getFileFromCreated(path:string, token:string, ip:string) : BackendReque
if (!file['isDir'])
name = name.substring(0, name.lastIndexOf('.'));
const stars = getStars(token, ip, file['path']);
const time = loadTime(path + Path.sep + file, token, ip, user)
const time = loadTime(path + Path.sep + file, token, ip, user);
const watchlist = IsOnWatchList(user.value, file['path'].replace(index.argv['Video Directory'], ''));
const push = {
'name' : name,
Expand Down
4 changes: 2 additions & 2 deletions backend/videoServing/loadTime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@ function loadTime(path:string, token:string, ip:string, user:BackendRequest<User
return {
isOk: true,
value: 0
}
};
else
return {
isOk: true,
value: data['data']
}
};
}

export {loadTime};
2 changes: 1 addition & 1 deletion backend/videoServing/saveTime.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { checkPath } from '../util';
import * as loginBackend from '../UserMangement';
import { db } from '../..';
import { BackendRequest } from "../../interfaces";
import { BackendRequest } from '../../interfaces';

function saveTime (path:string, token:string, percent:number, ip:string) : BackendRequest<undefined> {
const pathCeck = checkPath(path);
Expand Down
4 changes: 2 additions & 2 deletions html/js/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,8 @@ fetchBackend(url.toString(), {
method: 'POST'
}, (val) => {
if (val !== undefined) {
alert(val)
checkavtive.checked = !checkavtive.checked
alert(val);
checkavtive.checked = !checkavtive.checked;
}
}, false, true);
});
Expand Down
34 changes: 17 additions & 17 deletions html/js/generalFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,23 +19,23 @@ function setCookie(name: string, cookie: string, expires: Date, path = '/') : vo

function fetchBackend(url: string, options: RequestInit, callback?: ((data: any) => void)|undefined, sendBack = false, canFail = false) : void {
fetch(url, options).then(async data => {
if (!data.ok) {
console.log('[Request Error] ' + data.bodyUsed ? await data.text() : '')
if (sendBack)
document.location.href = '/';
else if (!canFail)
document.getElementById('offline').classList.remove('false');
} else {
document.getElementById('offline').classList.add('false');
const text = await data.text()
if (callback)
try {
callback(JSON.parse(text))
} catch {
callback(text)
}
}
})
if (!data.ok) {
console.log('[Request Error] ' + data.bodyUsed ? await data.text() : '');
if (sendBack)
document.location.href = '/';
else if (!canFail)
document.getElementById('offline').classList.remove('false');
} else {
document.getElementById('offline').classList.add('false');
const text = await data.text();
if (callback)
try {
callback(JSON.parse(text));
} catch {
callback(text);
}
}
})
.catch(error => {
document.getElementById('offline').classList.remove('false');
console.log(error);
Expand Down
8 changes: 4 additions & 4 deletions html/js/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,10 +66,10 @@ async function login() {
setTimeout(() => { wrongPassText.className = 'unvis'; }, 600);
}
})
.catch(error => {
document.getElementById('offline').classList.remove('false');
console.log(error);
});
.catch(error => {
document.getElementById('offline').classList.remove('false');
console.log(error);
});
return;
} else {
wrongPassText.className = 'vis';
Expand Down
81 changes: 36 additions & 45 deletions html/js/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,23 @@ const skipButton = document.getElementById('SkipButton');
const next = <HTMLButtonElement> document.getElementById('next');
const controls = document.getElementById('controls');
const info = document.getElementById('info');
const blueJuice = document.getElementById('blue-juice');

let mouseDown = false;
let skiped = false;
let timer: NodeJS.Timeout;
const WaitToHideTime = 1000;
let infoProgress: HTMLParagraphElement;
const socket = io({
auth: {
token: loadCookie('token')
}
});

socket.on("error", (err:string, critical:boolean) => {
console.log(`[SocketIO] Recived error: ${err}`)
socket.on('error', (err:string, critical:boolean) => {
console.log(`[SocketIO] Recived error: ${err}`);
if (critical)
socket.disconnect()
})
socket.disconnect();
});

document.body.onmousedown = function() {
mouseDown = true;
Expand All @@ -55,40 +55,22 @@ fetchBackend('/api/checkToken/', {

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
type LiveTranscodingData = {
duration: number,
} | undefined
let liveTranscodingData: LiveTranscodingData = undefined;

if (!video.canPlayType(getVideoType(urlParams.get('path').split('.').pop()))) {
socket.on(urlParams.get('path') + '.mp4', (data) => {
switch (data.type) {
case 'error':
console.error(data.data);
showError();
break;
case 'progress':
if (!infoProgress) {
infoProgress = document.createElement('p');
info.appendChild(infoProgress);
}
infoProgress.innerHTML = Math.ceil(data.data * 100) / 100 + '%';
break;
case 'finish':
if (!video.src)
video.src = '/video/' + urlParams.get('path') + '.mp4';
}
});

socket.emit('transcodeStatus', encodeURIComponent(urlParams.get('path')) + '.mp4', (res) => {
console.log(res.type);
switch (res.type) {
case 'error':
showError();
break;
case 'ready':
video.src = '/video/' + urlParams.get('path') + '.mp4';
break;
case 'notFound':
socket.emit('startTranscoding', urlParams.get('path') + '.mp4');
break;
if (!video.canPlayType(getVideoType(urlParams.get('path').split('.').pop()))) {
socket.emit('videoMetaData', urlParams.get('path'), (res) => {
if (res.type === 'error') {
console.log(`[Error] ${typeof res.msg === 'object' ? JSON.stringify(res.msg) : res.msg}`);
return showError(typeof res.msg === 'object' ? JSON.stringify(res.msg) : res.msg);
}
liveTranscodingData = {
duration: res.format.duration
};
video.src = '/video/' + urlParams.get('path') + '.mp4';
});
} else {
video.src = '/video/' + urlParams.get('path');
Expand Down Expand Up @@ -130,11 +112,11 @@ function loadData(res: SkipData) {
if (res.next) {
next.style.opacity = '1';
next.addEventListener('click', function() {
const nextURL = new URL(document.location.href)
const nextURL = new URL(document.location.href);
nextURL.search = new URLSearchParams({
path: res.next
}).toString()
document.location.href = nextURL.toString()
}).toString();
document.location.href = nextURL.toString();
});
} else
next.disabled = true;
Expand Down Expand Up @@ -196,7 +178,7 @@ barContainer.addEventListener('click', getClickPosition, false);

TimeTooltipBar.addEventListener('mousemove', function(e) {
const width = (e.clientX - (this.offsetLeft + (<HTMLElement>this.offsetParent).offsetLeft)) / this.offsetWidth;
const time = width * video.duration;
const time = width * (liveTranscodingData ? liveTranscodingData.duration : video.duration);
const mincur = Math.floor(time / 60);
let seccur: number|string = Math.floor(time % 60);
if (seccur < 10)
Expand All @@ -210,6 +192,9 @@ TimeTooltipBar.addEventListener('mousemove', function(e) {
tooltip.style.left = (TimeTooltipBar.offsetWidth - 70) + 'px';

if (mouseDown) {
if (time > video.duration && liveTranscodingData) {
return alert('You may only seek backward or on the blue line');
}
video.currentTime = time;
if (seccur < 10)
seccur = '0' + seccur;
Expand All @@ -221,7 +206,7 @@ TimeTooltipBar.addEventListener('mousemove', function(e) {
function getClickPosition(e) {
if (e.target === barContainer || e.target === bar || e.target === document.getElementById('TimeBar')) {
const width = (e.clientX - (this.offsetLeft + this.offsetParent.offsetLeft)) / this.offsetWidth;
const time = width * video.duration;
const time = width * (liveTranscodingData ? liveTranscodingData.duration : video.duration);
video.currentTime = time;
const mincur = Math.floor(time / 60);
let seccur:number|string = Math.floor(time % 60);
Expand Down Expand Up @@ -252,11 +237,17 @@ buttonPlay.onclick = function() {
let last = 0;

video.addEventListener('timeupdate', function() {
const barPos = video.currentTime / video.duration;
const barPos = video.currentTime / ( liveTranscodingData ? liveTranscodingData.duration : video.duration);
bar.style.width = barPos * 100 + '%';

if (liveTranscodingData) {
const bluePos = video.duration / liveTranscodingData.duration;
blueJuice.style.width = bluePos * 100 + '%';
blueJuice.style.display = 'inherit';
}

const currTime = Math.round(video.currentTime);
const dur = Math.round(video.duration);
const dur = Math.round((liveTranscodingData ? liveTranscodingData.duration : video.duration));

const min = Math.floor(dur / 60);
let sec:number|string = Math.floor(dur % 60);
Expand All @@ -272,7 +263,7 @@ video.addEventListener('timeupdate', function() {
time.innerHTML = mincur + ':' + seccur + ' / ' + min + ':' + sec;
if (video.ended)
buttonPlay.className = 'play';
const timePer = Math.floor(video.currentTime / video.duration * 100) / 100;
const timePer = Math.floor(video.currentTime / (liveTranscodingData ? liveTranscodingData.duration : video.duration) * 100) / 100;
if (timePer !== last) {
last = timePer;
fetchBackend('/api/setTime/', {
Expand Down Expand Up @@ -331,7 +322,7 @@ document.addEventListener('fullscreenchange', function() {

video.addEventListener('loadeddata', function () {
info.style.display = 'none';
if (!skiped) {
if (!skiped && !liveTranscodingData) {
const url = new URL(window.location.origin + '/api/getTime/');
url.search = new URLSearchParams({
'token': loadCookie('token'),
Expand Down
8 changes: 4 additions & 4 deletions html/js/videoSelector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,15 +92,15 @@ class FileData {
'content-type': 'application/json; charset=UTF-8'
},
method: 'GET'
})
});

if (!response.ok) {
document.getElementById('offline').classList.remove('false');
console.log(`[Request Failed] ${response.body ? await response.text() : ''}`)
console.log(`[Request Failed] ${response.body ? await response.text() : ''}`);
return;
}

const parsedData : GetFilesResponse = await response.json()
const parsedData : GetFilesResponse = await response.json();

this.data = parsedData.files;
this.pathSep = parsedData.pathSep;
Expand Down Expand Up @@ -153,7 +153,7 @@ class FileData {
}),
method: (add.classList.contains('already') ? 'DELETE' : 'PUT')
}, (data) => {
console.log(data)
console.log(data);
if (data === 'added') {
add.classList.remove('add');
add.classList.add('already');
Expand Down
5 changes: 4 additions & 1 deletion html/player/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@
<div id="controls">
<div class="orange-bar" id ="orange-bar">
<div class="TimeBar" id="TimeBar">
<div class="orange-juice" id="orange-juice"></div>
<div>
<div class="orange-juice" id="orange-juice"></div>
<div class="orange-juice" id="blue-juice"></div>
</div>
<span class="tooltiptext" id="tooltiptext">Tooltip text</span>
</div>
<div class="buttons">
Expand Down
Loading

0 comments on commit 2e655da

Please sign in to comment.