[Remote] Full PWA support, misc bugfixes (#280)

- Fix setting remote port properly
- Add web worker support (so it can be installed as an "app")
- build fixes/removing stray console.log
This commit is contained in:
Kendall Garner 2023-10-18 17:49:09 +00:00 committed by GitHub
parent fe298d3232
commit 9964f95d5d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 314 additions and 194 deletions

View File

@ -9,14 +9,14 @@ import checkNodeEnv from '../scripts/check-node-env';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
const { version } = require('../../package.json');
// When an ESLint server is running, we can't set the NODE_ENV so we'll check if it's
// at the dev webpack config is not accidentally run in a production environment
if (process.env.NODE_ENV === 'production') {
checkNodeEnv('development');
}
const port = process.env.PORT || 4343;
const configuration: webpack.Configuration = {
devtool: 'inline-source-map',
@ -24,12 +24,15 @@ const configuration: webpack.Configuration = {
target: ['web'],
entry: [path.join(webpackPaths.srcRemotePath, 'index.tsx')],
entry: {
remote: path.join(webpackPaths.srcRemotePath, 'index.tsx'),
worker: path.join(webpackPaths.srcRemotePath, 'service-worker.ts'),
},
output: {
path: webpackPaths.dllPath,
publicPath: '/',
filename: 'remote.js',
filename: '[name].js',
library: {
type: 'umd',
},
@ -106,6 +109,10 @@ const configuration: webpack.Configuration = {
env: process.env.NODE_ENV,
isDevelopment: process.env.NODE_ENV !== 'production',
nodeModules: webpackPaths.appNodeModulesPath,
templateParameters: {
version,
prod: false,
},
}),
],

View File

@ -17,6 +17,8 @@ import deleteSourceMaps from '../scripts/delete-source-maps';
import baseConfig from './webpack.config.base';
import webpackPaths from './webpack.paths';
const { version } = require('../../package.json');
checkNodeEnv('production');
deleteSourceMaps();
@ -34,12 +36,15 @@ const configuration: webpack.Configuration = {
target: ['web'],
entry: [path.join(webpackPaths.srcRemotePath, 'index.tsx')],
entry: {
remote: path.join(webpackPaths.srcRemotePath, 'index.tsx'),
worker: path.join(webpackPaths.srcRemotePath, 'service-worker.ts'),
},
output: {
path: webpackPaths.distRemotePath,
publicPath: './',
filename: 'remote.js',
filename: '[name].js',
library: {
type: 'umd',
},
@ -116,15 +121,20 @@ const configuration: webpack.Configuration = {
new HtmlWebpackPlugin({
filename: 'index.html',
template: path.join(webpackPaths.srcRendererPath, 'index.ejs'),
template: path.join(webpackPaths.srcRemotePath, 'index.ejs'),
favicon: path.join(webpackPaths.assetsPath, 'icons', 'favicon.ico'),
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true,
},
isBrowser: false,
isBrowser: true,
env: process.env.NODE_ENV,
isDevelopment: process.env.NODE_ENV !== 'production',
templateParameters: {
version,
prod: true,
},
}),
],
};

View File

@ -6,6 +6,7 @@ import { deflate, gzip } from 'zlib';
import axios from 'axios';
import { app, ipcMain } from 'electron';
import { Server as WsServer, WebSocketServer, WebSocket } from 'ws';
import manifest from './manifest.json';
import { ClientEvent, ServerEvent } from '../../../../remote/types';
import { PlayerRepeat, SongUpdate } from '../../../../renderer/types';
import { getMainWindow } from '../../../main';
@ -297,6 +298,12 @@ const enableServer = (config: RemoteConfig): Promise<void> => {
await serveFile(req, 'remote', 'js', res);
break;
}
case '/manifest.json': {
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(manifest));
break;
}
case '/credentials': {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
@ -304,9 +311,13 @@ const enableServer = (config: RemoteConfig): Promise<void> => {
break;
}
default: {
if (req.url?.startsWith('/worker.js')) {
await serveFile(req, 'worker', 'js', res);
} else {
res.statusCode = 404;
res.setHeader('Content-Type', 'text/plain');
res.end('Not FOund');
res.end('Not Found');
}
}
}
} catch (error) {

View File

@ -0,0 +1,17 @@
{
"name": "Feishin Remote",
"short_name": "Feishin Remote",
"start_url": "/",
"background_color": "#000100",
"theme_color": "#E7E7E7",
"icons": [
{
"src": "favicon.ico",
"sizes": "32x32",
"type": "image/png",
"purpose": "maskable any"
}
],
"display": "standalone",
"orientation": "portrait"
}

View File

@ -6,6 +6,14 @@
<meta http-equiv="Content-Security-Policy" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Feishin Remote</title>
<link rel="manifest" href="manifest.json">
<script>
if ('serviceWorker' in navigator) {
const version = encodeURIComponent("<%= version %>");
const prod = encodeURIComponent("<%= prod %>");
navigator.serviceWorker.register(`/worker.js?version=${version}&prod=${prod}`);
}
</script>
</head>
<body>

17
src/remote/manifest.json Normal file
View File

@ -0,0 +1,17 @@
{
"name": "Feishin Remote",
"short_name": "Feishin Remote",
"start_url": "/",
"background_color": "#FFDCB5",
"theme_color": "#1E003D",
"icons": [
{
"src": "favicon.ico",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable any"
}
],
"display": "standalone",
"orientation": "portrait"
}

View File

@ -0,0 +1,48 @@
/// <reference lib="WebWorker" />
export type {};
// eslint-disable-next-line no-undef
declare const self: ServiceWorkerGlobalScope;
// eslint-disable-next-line no-restricted-globals
const url = new URL(location.toString());
const version = url.searchParams.get('version');
const prod = url.searchParams.get('prod') === 'true';
const cacheName = `Feishin-remote-${version}`;
const resourcesToCache = ['./', './remote.js', './favicon.ico'];
if (prod) {
resourcesToCache.push('./remote.css');
}
self.addEventListener('install', (e) => {
e.waitUntil(
caches.open(cacheName).then((cache) => {
return cache.addAll(resourcesToCache);
}),
);
});
self.addEventListener('fetch', (e) => {
e.respondWith(
caches.match(e.request).then((response) => {
return response || fetch(e.request);
}),
);
});
self.addEventListener('activate', (e) => {
e.waitUntil(
caches.keys().then((keyList) => {
return Promise.all(
keyList.map((key) => {
if (key !== cacheName) {
return caches.delete(key);
}
return Promise.resolve();
}),
);
}),
);
});

View File

@ -194,7 +194,6 @@ export const useRemoteStore = create<SettingsSlice>()(
});
},
send: (data: ClientEvent) => {
console.log(data, get().socket);
get().socket?.send(JSON.stringify(data));
},
toggleIsDark: () => {

0
src/remote/worker.js Normal file
View File

View File

@ -28,24 +28,27 @@ export const RemoteSettings = () => {
title: enabled ? 'Error enabling remote' : 'Error disabling remote',
});
}
}, 100);
}, 50);
const debouncedChangeRemotePort = debounce(async (port: number) => {
const errorMsg = await remote!.setRemotePort(port);
if (errorMsg === null) {
if (!errorMsg) {
setSettings({
remote: {
...settings,
port,
},
});
toast.warn({
message: 'To have your port change take effect, stop and restart the server',
});
} else {
toast.error({
message: errorMsg,
title: 'Error setting port',
});
}
});
}, 100);
const isHidden = !isElectron();

View File

@ -2,7 +2,7 @@
"compilerOptions": {
"target": "es2021",
"module": "commonjs",
"lib": ["dom", "es2021"],
"lib": ["dom", "es2021", "WebWorker"],
"baseUrl": "./src",
"paths": {
"/@/*": ["*"]