Add status indicator to videos that are not yet downscaled

This commit is contained in:
regent 2023-11-18 17:55:14 -05:00
parent 832189a346
commit 63c4c5837f
5 changed files with 217 additions and 3767 deletions

View file

@ -5,6 +5,8 @@ import ffmpegInstaller from "@ffmpeg-installer/ffmpeg";
import ffprobeInstaller from "@ffprobe-installer/ffprobe"; import ffprobeInstaller from "@ffprobe-installer/ffprobe";
import which from "which"; import which from "which";
import fs from "fs";
/** /**
* Enum to represent different types of video encoding methods. * Enum to represent different types of video encoding methods.
* *
@ -52,7 +54,7 @@ export const setEncodingType = (type: EncodingType) => {
const getExecutablePath = ( const getExecutablePath = (
envVar: string, envVar: string,
executable: string, executable: string,
installer: { path: string }, installer: { path: string }
) => { ) => {
if (process.env[envVar]) { if (process.env[envVar]) {
return process.env[envVar]; return process.env[envVar];
@ -68,12 +70,12 @@ const getExecutablePath = (
const ffmpegPath = getExecutablePath( const ffmpegPath = getExecutablePath(
"EB_FFMPEG_PATH", "EB_FFMPEG_PATH",
"ffmpeg", "ffmpeg",
ffmpegInstaller, ffmpegInstaller
); );
const ffprobePath = getExecutablePath( const ffprobePath = getExecutablePath(
"EB_FFPROBE_PATH", "EB_FFPROBE_PATH",
"ffprobe", "ffprobe",
ffprobeInstaller, ffprobeInstaller
); );
console.log(`Using ffmpeg from path: ${ffmpegPath}`); console.log(`Using ffmpeg from path: ${ffmpegPath}`);
@ -87,14 +89,14 @@ const checkEnvForEncoder = () => {
if (envEncoder && Object.keys(EncodingType).includes(envEncoder)) { if (envEncoder && Object.keys(EncodingType).includes(envEncoder)) {
setEncodingType( setEncodingType(
EncodingType[envEncoder as keyof typeof EncodingType] as EncodingType, EncodingType[envEncoder as keyof typeof EncodingType] as EncodingType
); );
console.log( console.log(
`Setting encoding type to ${envEncoder} based on environment variable.`, `Setting encoding type to ${envEncoder} based on environment variable.`
); );
} else if (envEncoder) { } else if (envEncoder) {
console.warn( console.warn(
`Invalid encoder value "${envEncoder}" in environment variable, defaulting to CPU.`, `Invalid encoder value "${envEncoder}" in environment variable, defaulting to CPU.`
); );
} }
}; };
@ -119,7 +121,7 @@ checkEnvForEncoder();
export const ffmpegDownscale = ( export const ffmpegDownscale = (
path: string, path: string,
filename: string, filename: string,
extension: string, extension: string
) => { ) => {
const startTime = Date.now(); const startTime = Date.now();
const outputOptions = [ const outputOptions = [
@ -138,15 +140,32 @@ export const ffmpegDownscale = (
.input(path) .input(path)
.outputOptions(outputOptions) .outputOptions(outputOptions)
.output(`uploads/720p-${filename}${extension}`) .output(`uploads/720p-${filename}${extension}`)
.on("start", () => {
// Create the .processing file
fs.closeSync(
fs.openSync(`uploads/720p-${filename}${extension}.processing`, "w")
);
})
.on("end", () => { .on("end", () => {
console.log( console.log(
`720p copy complete using ${currentEncoding}, took ${ `720p copy complete using ${currentEncoding}, took ${
Date.now() - startTime Date.now() - startTime
}ms to complete`, }ms to complete`
); );
// Delete the .processing file
fs.unlinkSync(`uploads/720p-${filename}${extension}.processing`);
resolve(); resolve();
}) })
.on("error", (e) => reject(new Error(e))) .on("error", (e) => {
// Ensure to delete the .processing file even on error
if (fs.existsSync(`uploads/720p-${filename}${extension}.processing`)) {
fs.unlinkSync(`uploads/720p-${filename}${extension}.processing`);
}
reject(new Error(e));
})
.run(); .run();
}); });
}; };
@ -169,7 +188,7 @@ export const ffmpegDownscale = (
export const ffmpegConvert = ( export const ffmpegConvert = (
path: string, path: string,
filename: string, filename: string,
extension: string, extension: string
) => { ) => {
const startTime = Date.now(); const startTime = Date.now();
const outputOptions = [ const outputOptions = [
@ -206,7 +225,7 @@ export const ffmpegConvert = (
.output(`uploads/${filename}${outputFormat}`) .output(`uploads/${filename}${outputFormat}`)
.on("end", function () { .on("end", function () {
console.log( console.log(
`Conversion complete, took ${Date.now() - startTime} to complete`, `Conversion complete, took ${Date.now() - startTime} to complete`
); );
console.log(`uploads/${filename}${outputFormat}`); console.log(`uploads/${filename}${outputFormat}`);
resolve(); resolve();
@ -219,7 +238,7 @@ export const ffmpegConvert = (
export const ffProbe = async ( export const ffProbe = async (
path: string, path: string,
filename: string, filename: string,
extension: string, extension: string
) => { ) => {
return new Promise<FfprobeData>((resolve, reject) => { return new Promise<FfprobeData>((resolve, reject) => {
ffprobe(path, (err, data) => { ffprobe(path, (err, data) => {

View file

@ -4,6 +4,7 @@ import type {
Response, Response,
NextFunction, NextFunction,
} from "express"; } from "express";
import multer from "multer"; import multer from "multer";
import express from "express"; import express from "express";
import imageProbe from "probe-image-size"; import imageProbe from "probe-image-size";
@ -65,6 +66,10 @@ router.get(
}, },
); );
/*router.get("/media-list", fetchMedia, (req: Request, res: Response) => {
res.render("partials/_fileList"); // Render only the file list partial
});*/
router.get( router.get(
"/gifv/:file", "/gifv/:file",
async (req: Request, res: Response, next: NextFunction) => { async (req: Request, res: Response, next: NextFunction) => {
@ -166,4 +171,3 @@ router.post(
); );
export default router; export default router;

View file

@ -11,14 +11,7 @@
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png"> <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"> <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest"> <link rel="manifest" href="/site.webmanifest">
<% <script src="https://unpkg.com/htmx.org@1.9.8"></script>
function extension(string) {
return string.slice((string.lastIndexOf(".") - 2 >>> 0) + 2);
}
const videoExtensions = ['.mp4', '.mov', '.avi', '.flv', '.mkv', '.wmv', '.webm'];
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.tiff', '.webp'];
%>
</head> </head>
<body> <body>
<section class="embedderapp"> <section class="embedderapp">
@ -65,68 +58,13 @@
<p class="dragregion">Click the file to copy the url</p> <p class="dragregion">Click the file to copy the url</p>
</div> </div>
</form> </form>
<% if (Count > 0) { %>
<section class="main"> <section class="main">
<ul class="embedder-list"> <ul class="embedder-list">
<% files.forEach(function(file) { %> <% if (files && files.length > 0) { %>
<li id="<%= file.path %>" class="show"> <%- include('partials/_fileList.ejs',) %>
<form action="<%= file.url %>" method="post">
<div class="view">
<% if (videoExtensions.includes(extension(file.path))) { %>
<div class="video">
<video class="image" autoplay loop muted playsinline loading="lazy">
<source src="/uploads/720p-<%= file.path %>" loading="lazy">
</video>
<div class="overlay">
<% if(user.username == "admin" && file.username != "admin") { %>
<small class="username"><%= file.username %></small>
<br>
<% } %> <% } %>
<a href="/gifv/<%=file.path %>" onclick="copyA(event)">Copy as GIFv</a>
</div>
</div>
<% } else if (extension(file.path) == ".gif") { %>
<div class="video">
<img class="image" src="/uploads/720p-<%=file.path %>" width="100%" onclick="copyURI(event);" loading="lazy">
<div class="overlay">
<% if(user.username == "admin" && file.username != "admin") { %>
<small class="username"><%= file.username %></small>
<br>
<% } %>
<a href="/gifv/<%=file.path %>" onclick="copyA(event)">Copy as GIFv</a>
</div>
</div>
<% } else if (imageExtensions.includes(extension(file.path))) { %>
<div class="video">
<img class="image" src="/uploads/<%=file.path %>" width="100%" onclick="copyURI(event)" loading="lazy">
<% if(user.username == "admin" && file.username != "admin") { %>
<div class="overlay">
<small class="username"><%= file.username %></small>
</div>
<% } %>
</div>
<% } else {%> <!-- non-media file -->
<div class="nonmedia" onclick="copyPath('/uploads/<%=file.path%>')">
<p><%=extension(file.path)%> file</p>
<% if(user.username == "admin" && file.username != "admin") { %>
<div class="overlay">
<small class="username"><%= file.username %></small>
</div>
<% } %>
</div>
<% } %>
<label><%= file.path %></label>
<button class="destroy" form="delete-<%= file.path %>"></button>
<button type="button" class="fullsize" onclick="openFullSize('/uploads/<%=file.path%>')"></button>
</div>
</form>
<form name="delete-<%= file.path %>" id="delete-<%= file.path %>" action="<%= file.url %>/delete" method="post">
</form>
</li>
<% }); %>
</ul> </ul>
</section> </section>
<% } %>
</section> </section>
<footer class="info"> <footer class="info">
<p><a href="https://l.nekomimi.pet/project">Created by Wavering Ana</a></p> <p><a href="https://l.nekomimi.pet/project">Created by Wavering Ana</a></p>

View file

@ -0,0 +1,176 @@
<%
function extension(string) {
return string.slice((string.lastIndexOf(".") - 2 >>> 0) + 2);
}
const videoExtensions = ['.mp4', '.mov', '.avi', '.flv', '.mkv', '.wmv', '.webm'];
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.tiff', '.webp'];
%>
<script>
let files = JSON.parse('<%- JSON.stringify(files) %>');
const videoExtensions = ['.mp4', '.mov', '.avi', '.flv', '.mkv', '.wmv', '.webm'];
const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.tiff', '.webp'];
function extension(string) {
console.log(string)
const file = string.split("/").pop();
return [
file.substr(0, file.lastIndexOf(".")),
file.substr(file.lastIndexOf("."), file.length).toLowerCase(),
];
}
console.log(files)
files.forEach(file => {
if (videoExtensions.includes(extension(file.path)[1])) {
console.log(`Fetching /uploads/720p-${file.path}.processing`)
fetch(`/uploads/720p-${file.path}.processing`)
.then(response => {
if (response.ok) {
// Video is still processing
console.log(`File /uploads/720p-${file.path}.processing exists, starting check...`)
checkFileAvailability(file.path);
} else {
// Video done processing, display it immediately
console.log(`File /uploads/720p-${file.path}.processing no longer exists, displaying...`)
createVideoElement(file.path);
}
})
.catch(error => console.error('Error:', error));
}
});
function checkFileAvailability(filePath) {
const interval = setInterval(() => {
fetch(`/uploads/720p-${filePath}.processing`)
.then(response => {
if (!response.ok) {
clearInterval(interval);
createVideoElement(filePath);
}
})
.catch(error => console.error('Error:', error));
}, 5000); // Check every 5 seconds
}
function createVideoElement(filePath) {
const videoContainer = document.getElementById(`video-${filePath}`);
videoContainer.innerHTML = `
<video class="image" autoplay loop muted playsinline loading="lazy">
<source src="/uploads/720p-${filePath}" loading="lazy">
</video>
`;
videoContainer.style.display = 'block';
document.getElementById(`spinner-${filePath}`).style.display = 'none';
}
</script>
<style>
.spinner {
/* Positioning and Sizing */
width: 100px;
height: 100px;
position: relative;
margin: 50px auto; /* Centering the spinner */
/* Text Styling */
color: #555;
text-align: center;
font-family: Arial, sans-serif;
font-size: 14px;
padding-top: 80px; /* Adjust as needed for text position */
/* Adding a background to the spinner for better visibility */
background-color: rgba(255, 255, 255, 0.8);
border-radius: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
/* Keyframes for the spinner animation */
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
/* Spinner Animation */
.spinner::before {
content: '';
box-sizing: border-box;
position: absolute;
top: 50%;
left: 50%;
width: 40px; /* Spinner Size */
height: 40px;
margin-top: -20px; /* Half of height */
margin-left: -20px; /* Half of width */
border-radius: 50%;
border: 2px solid transparent;
border-top-color: #007bff; /* Spinner Color */
animation: spin 1s linear infinite;
}
</style>
<!-- _fileList.ejs -->
<% files.forEach(function(file) { %>
<li id="<%= file.path %>" class="show">
<form action="<%= file.url %>" method="post">
<div class="view">
<% if (videoExtensions.includes(extension(file.path))) { %>
<!-- Show spinner initially -->
<div id="spinner-<%= file.path %>" class="spinner">Optimizing Video for Sharing...</div>
<!-- Hidden video container to be displayed later -->
<div class="video">
<video id="video-<%= file.path %>" class="image" autoplay loop muted playsinline loading="lazy" style="display: none;">
<source src="/uploads/720p-<%= file.path %>" loading="lazy">
</video>
<div class="overlay">
<% if(user.username == "admin" && file.username != "admin") { %>
<small class="username"><%= file.username %></small>
<br>
<% } %>
<a href="/gifv/<%=file.path %>" onclick="copyA(event)">Copy as GIFv</a>
</div>
</div>
<% } else if (extension(file.path) == ".gif") { %>
<div class="video">
<img class="image" src="/uploads/720p-<%=file.path %>" width="100%" onclick="copyURI(event);" loading="lazy">
<div class="overlay">
<% if(user.username == "admin" && file.username != "admin") { %>
<small class="username"><%= file.username %></small>
<br>
<% } %>
<a href="/gifv/<%=file.path %>" onclick="copyA(event)">Copy as GIFv</a>
</div>
</div>
<% } else if (imageExtensions.includes(extension(file.path))) { %>
<div class="video">
<img class="image" src="/uploads/<%=file.path %>" width="100%" onclick="copyURI(event)" loading="lazy">
<% if(user.username == "admin" && file.username != "admin") { %>
<div class="overlay">
<small class="username"><%= file.username %></small>
</div>
<% } %>
</div>
<% } else {%>
<!-- non-media file -->
<div class="nonmedia" onclick="copyPath('/uploads/<%=file.path%>')">
<p><%=extension(file.path)%> file</p>
<% if(user.username == "admin" && file.username != "admin") { %>
<div class="overlay">
<small class="username"><%= file.username %></small>
</div>
<% } %>
</div>
<% } %>
<label><%= file.path %></label>
<button class="destroy" form="delete-<%= file.path %>"></button>
<button type="button" class="fullsize" onclick="openFullSize('/uploads/<%=file.path%>')"></button>
</div>
</form>
<form name="delete-<%= file.path %>" id="delete-<%= file.path %>" action="<%= file.url %>/delete" method="post">
</form>
</li>
<% }); %>

3689
package-lock.json generated

File diff suppressed because it is too large Load diff