Skip to content

TagSpaces is an offline, open source, document manager with tagging support

feat: new media player based on vidstack library (#2207)

Stanimirb72ac5849163
diff --git a/package.json b/package.json
index 83ea1a833..2f15724f9 100644
--- a/package.json
+++ b/package.json
@@ -170,7 +170,7 @@
"@tagspaces/tagspaces-common-aws3": "4.5.40",
"@tagspaces/tagspaces-common-cordova": "4.5.40",
"@tagspaces/tagspaces-indexer": "4.5.40",
- "@tagspaces/tagspaces-md": "4.5.19",
+ "@tagspaces/tagspaces-md": "4.5.38",
"aws-amplify": "^4.3.8",
"classnames": "^2.3.1",
"clone": "^2.1.2",
diff --git a/release/app/package.json b/release/app/package.json
index 79a499872..7c6ad7a3a 100644
--- a/release/app/package.json
+++ b/release/app/package.json
@@ -18,7 +18,7 @@
},
"dependencies": {
"@elife/pm2": "3.6.1",
- "@tagspaces/extensions": "1.0.135",
+ "@tagspaces/extensions": "1.0.145",
"@tagspaces/tagspaces-common-node": "4.5.40",
"@tagspaces/tagspaces-ws": "4.5.40",
"sharp": "0.32.6",
diff --git a/src/main/main.ts b/src/main/main.ts
index 126f3fb8a..3f995e264 100644
--- a/src/main/main.ts
+++ b/src/main/main.ts
@@ -33,6 +33,7 @@ import buildDockMenu from './electron-dock-menu';
import buildDesktopMenu from './electron-menus';
import loadMainEvents from './mainEvents';
import { Extensions } from './types';
+import protocol from './protocol';
// class AppUpdater {
// constructor() {
@@ -705,6 +706,8 @@ startWS();
let appI18N;
+protocol.register();
+
app
.whenReady()
.then(() => {
@@ -728,6 +731,8 @@ app
}
createWindow(i18n);
+ protocol.initialize();
+
i18n.on('languageChanged', (lng) => {
try {
console.log('languageChanged:' + lng);
diff --git a/src/main/protocol.ts b/src/main/protocol.ts
new file mode 100644
index 000000000..59981f86c
--- /dev/null
+++ b/src/main/protocol.ts
@@ -0,0 +1,224 @@
+// Custom app protocol handler for Electron
+// https://www.electronjs.org/docs/latest/api/protocol
+// https://www.electronjs.org/docs/latest/tutorial/launch-app-from-url-in-another-app
+
+import { protocol, net } from 'electron';
+import * as fs from 'fs-extra';
+import { createReadStream } from 'fs';
+import path from 'path';
+import { mediaProtocol } from '@tagspaces/tagspaces-common/AppConfig';
+
+const register = () => {
+ //Logger.status(`Registering file protocol: ${mediaProtocol}`);
+ protocol.registerSchemesAsPrivileged([
+ {
+ scheme: mediaProtocol,
+ privileges: {
+ supportFetchAPI: true,
+
+ // Don't trigger mixed content warnings (see https://stackoverflow.com/a/75988466)
+ //secure: true,
+
+ // Allows loading localStorage/sessionStorage and similar APIs
+ //standard: true,
+
+ // Allows loading <video>/<audio> streaming elements
+ stream: true,
+
+ // corsEnabled: true,
+ // codeCache: true, Code cache can only be enabled when the custom scheme is registered as standard scheme.
+ // allowServiceWorkers: true,
+ // bypassCSP: true,
+ },
+ },
+ ]);
+};
+
+const initialize = () => {
+ if (!protocol?.handle) {
+ // Old versions of Electron don't have protocol.handle
+ return null;
+ }
+
+ // By default, we serve files from the assets folder
+ protocol.handle(mediaProtocol, (request: any) => {
+ // list all files in the directory
+ const filepath = decodeURIComponent(
+ request.url.slice(`${mediaProtocol}://`.length).replace(/\/$/, ''),
+ ); // remove trailing slash
+ const asFileUrl = `file://${filepath}`; //pathToFileURL(filepath).toString();
+ console.log(
+ 'protocol handler: Fetch file ' + filepath + ' as:' + asFileUrl,
+ );
+
+ const rangeHeader = request.headers.get('Range');
+ if (!rangeHeader) {
+ return net.fetch(asFileUrl);
+ } else {
+ return handleRangeRequest(request, filepath);
+ }
+ });
+};
+
+// In some cases, the NodeJS built-in adapter (Readable.toWeb) closes its controller twice,
+// leading to an error dialog. See:
+// - https://github.com/nodejs/node/blob/e578c0b1e8d3dd817e692a0c5df1b97580bc7c7f/lib/internal/webstreams/adapters.js#L454
+// - https://github.com/nodejs/node/issues/54205
+// We work around this by creating a more-error-tolerant custom adapter.
+const nodeStreamToWeb = (resultStream: fs.ReadStream) => {
+ resultStream.pause();
+
+ let closed = false;
+
+ return new ReadableStream(
+ {
+ start: (controller) => {
+ resultStream.on('data', (chunk) => {
+ if (closed) {
+ return;
+ }
+
+ if (Buffer.isBuffer(chunk)) {
+ controller.enqueue(new Uint8Array(chunk));
+ } else {
+ controller.enqueue(chunk);
+ }
+
+ if (controller.desiredSize <= 0) {
+ resultStream.pause();
+ }
+ });
+
+ resultStream.on('error', (error) => {
+ controller.error(error);
+ });
+
+ resultStream.on('end', () => {
+ if (!closed) {
+ closed = true;
+ controller.close();
+ }
+ });
+ },
+ pull: (_controller) => {
+ if (closed) {
+ return;
+ }
+
+ resultStream.resume();
+ },
+ cancel: () => {
+ if (!closed) {
+ closed = true;
+ resultStream.close();
+ }
+ },
+ },
+ { highWaterMark: resultStream.readableHighWaterMark },
+ );
+};
+
+// Allows seeking videos.
+// See https://github.com/electron/electron/issues/38749 for why this is necessary.
+const handleRangeRequest = async (request: Request, targetPath: string) => {
+ const makeUnsupportedRangeResponse = () => {
+ return new Response('unsupported range', {
+ status: 416, // Range Not Satisfiable
+ });
+ };
+
+ const rangeHeader = request.headers.get('Range');
+ if (!rangeHeader.startsWith('bytes=')) {
+ return makeUnsupportedRangeResponse();
+ }
+
+ const stat = await fs.stat(targetPath);
+ // Ranges are requested using one of the following formats
+ // bytes=1234-5679
+ // bytes=-5678
+ // bytes=1234-
+ // See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range
+ const startByte = Number(rangeHeader.match(/(\d+)-/)?.[1] || '0');
+ const endByte = Number(
+ rangeHeader.match(/-(\d+)/)?.[1] || `${stat.size - 1}`,
+ );
+
+ if (endByte > stat.size || startByte < 0) {
+ return makeUnsupportedRangeResponse();
+ }
+
+ // Note: end is inclusive.
+ const resultStream = createReadStream(targetPath, {
+ start: startByte,
+ end: endByte,
+ });
+
+ // See the HTTP range requests guide: https://developer.mozilla.org/en-US/docs/Web/HTTP/Range_requests
+ const headers = new Headers([
+ ['Accept-Ranges', 'bytes'],
+ ['Content-Type', getMimeType(path.extname(targetPath))], //fromFilename(targetPath)],
+ ['Content-Length', `${endByte + 1 - startByte}`],
+ ['Content-Range', `bytes ${startByte}-${endByte}/${stat.size}`],
+ ]);
+
+ return new Response(nodeStreamToWeb(resultStream), { headers, status: 206 });
+};
+
+/**
+ * Returns the MIME type for a given file extension.
+ * @param ext - The file extension (e.g., ".html", ".mp4").
+ * @returns The MIME type string or a default fallback if not found.
+ */
+function getMimeType(ext: string): string {
+ const mimeTypes: { [key: string]: string } = {
+ // Text and document types
+ '.html': 'text/html',
+ '.css': 'text/css',
+ '.js': 'application/javascript',
+ '.json': 'application/json',
+ '.txt': 'text/plain',
+ '.xml': 'application/xml',
+ '.pdf': 'application/pdf',
+
+ // Image types
+ '.png': 'image/png',
+ '.jpg': 'image/jpeg',
+ '.jpeg': 'image/jpeg',
+ '.gif': 'image/gif',
+ '.svg': 'image/svg+xml',
+ '.ico': 'image/x-icon',
+ '.bmp': 'image/bmp',
+ '.webp': 'image/webp',
+
+ // Video types
+ '.mp4': 'video/mp4',
+ '.avi': 'video/x-msvideo',
+ '.mov': 'video/quicktime',
+ '.mkv': 'video/x-matroska',
+ '.webm': 'video/webm',
+ '.flv': 'video/x-flv',
+ '.wmv': 'video/x-ms-wmv',
+ '.3gp': 'video/3gpp',
+
+ // Audio types
+ '.mp3': 'audio/mpeg',
+ '.wav': 'audio/wav',
+ '.ogg': 'audio/ogg',
+ '.m4a': 'audio/mp4',
+ '.aac': 'audio/aac',
+
+ // Compressed file types
+ '.zip': 'application/zip',
+ '.tar': 'application/x-tar',
+ '.gz': 'application/gzip',
+ '.rar': 'application/vnd.rar',
+ '.7z': 'application/x-7z-compressed',
+
+ // Default fallback
+ '.bin': 'application/octet-stream',
+ };
+
+ return mimeTypes[ext.toLowerCase()] || 'application/octet-stream';
+}
+
+export default { initialize, register };
diff --git a/src/renderer/hooks/DirectoryContentContextProvider.tsx b/src/renderer/hooks/DirectoryContentContextProvider.tsx
index 378c41326..4766de668 100644
--- a/src/renderer/hooks/DirectoryContentContextProvider.tsx
+++ b/src/renderer/hooks/DirectoryContentContextProvider.tsx
@@ -355,8 +355,9 @@ export const DirectoryContentContextProvider = ({
};
}
if (
+ action.entry &&
cleanTrailingDirSeparator(currentDirectoryPath.current) ===
- cleanTrailingDirSeparator(action.entry.path)
+ cleanTrailingDirSeparator(action.entry.path)
) {
directoryMeta.current = {
...directoryMeta.current,