Skip to content

Commit

Permalink
让electron客户端程序打包后正常运行
Browse files Browse the repository at this point in the history
  • Loading branch information
gejiuyuan committed Jun 3, 2023
1 parent f036540 commit a1edc03
Show file tree
Hide file tree
Showing 11 changed files with 1,489 additions and 120 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
.DS_Store
node_modules
/dist
/dist-client


# local env files
Expand Down
2 changes: 1 addition & 1 deletion build/notarize.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ module.exports = async (context) => {
return;
}

const appId = 'com.electron.app';
const appId = 'com.refrain.app';

const { appOutDir } = context;

Expand Down
9 changes: 9 additions & 0 deletions client/main/config/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
/** @format */

export const LOCAL_SERVER_PORT = 8099;

export const LOCAL_SERVER_ADRESS = `http://localhost:${LOCAL_SERVER_PORT}`;

export const NCMAPI_PORT = 1008;

export const NCMAPI_SERVER_ADRESS = `http://localhost:${NCMAPI_PORT}`;
139 changes: 131 additions & 8 deletions client/main/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,103 @@
/** @format */
import { createRequire } from 'module';
const require = createRequire(import.meta.url);

import { app, shell, BrowserWindow, screen } from 'electron';
import {
app,
shell,
BrowserWindow,
screen,
ipcMain,
Menu,
MenuItemConstructorOptions,
protocol,
} from 'electron';
import { join } from 'path';
import { electronApp, optimizer, is } from '@electron-toolkit/utils';
import icon from './public/refrain.png?asset';
import Koa from 'koa';
import Router from 'koa-router';
import Static from 'koa-static';
import KoaServerHttpProxy from 'koa-server-http-proxy';
import * as path from 'path';
import { fstat, writeFile, readFile, write } from 'fs';
import { URL } from 'url';
import os from 'os';

import {
LOCAL_SERVER_ADRESS,
LOCAL_SERVER_PORT,
NCMAPI_PORT,
NCMAPI_SERVER_ADRESS,
} from './config/server';

app.commandLine.appendSwitch('block-insecure-private-network-requests', 'Disabled');

function createProtocol(scheme: string, customProtocol?: typeof protocol) {
(customProtocol || protocol).registerBufferProtocol(scheme, (request, respond) => {
let pathName = new URL(request.url).pathname;
pathName = decodeURI(pathName); // Needed in case URL contains spaces

readFile(path.join(__dirname, pathName), (error, data) => {
if (error) {
console.error(`Failed to read ${pathName} on ${scheme} protocol`, error);
}
const extension = path.extname(pathName).toLowerCase();
let mimeType = '';

if (extension === '.js') {
mimeType = 'text/javascript';
} else if (extension === '.html') {
mimeType = 'text/html';
} else if (extension === '.css') {
mimeType = 'text/css';
} else if (extension === '.svg' || extension === '.svgz') {
mimeType = 'image/svg+xml';
} else if (extension === '.json') {
mimeType = 'application/json';
} else if (extension === '.wasm') {
mimeType = 'application/wasm';
}

respond({ mimeType, data });
});
});
}

function startUpLocalServer() {
return new Promise((resolve, reject) => {
let koaApp: Koa | null = new Koa();
const lcoalServer = koaApp
.use(Static(join(__dirname, '../renderer')))
.use(
KoaServerHttpProxy('/api', {
target: NCMAPI_SERVER_ADRESS,
changeOrigin: true,
pathRewrite: (path) => path.replace(/^\/api/, ''),
}),
)
.listen(LOCAL_SERVER_PORT, () => {
resolve(true);
})
.on('error', (err) => {
reject(err);
});

app.on('quit', () => {
lcoalServer.close();
koaApp = null;
});
});
}

function startLocalAndNCMAPIServer() {
return Promise.allSettled([
require('NeteaseCloudMusicApi').serveNcmApi({
port: NCMAPI_PORT,
}),
startUpLocalServer(),
]);
}

function createWindow() {
const primaryDisplay = screen.getPrimaryDisplay();
Expand All @@ -17,11 +111,15 @@ function createWindow() {
show: true,
fullscreenable: true,
skipTaskbar: false,
autoHideMenuBar: true,
// autoHideMenuBar: true,
...(process.platform === 'linux' ? { icon } : { icon }),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false,
webSecurity: false,
contextIsolation: false,
nodeIntegration: true,
allowRunningInsecureContent: true,
},
});

Expand All @@ -35,12 +133,29 @@ function createWindow() {
});

// HMR for renderer base on electron-vite cli.
// Load the remote URL for development or the local html file for production.
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL']);
if (is.dev) {
mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'] || 'http://localhost');
} else {
mainWindow.loadFile(join(__dirname, '../renderer/index.html'));
createProtocol('app');
mainWindow.loadURL(LOCAL_SERVER_ADRESS);
}

const template: MenuItemConstructorOptions[] = [
{
label: '开发者扩展工具',
click(menuItem) {
mainWindow.webContents.openDevTools();
},
},
];
const menu = Menu.buildFromTemplate(template);
Menu.setApplicationMenu(menu);

ipcMain.on('show-context-menu', (event) => {
menu.popup({
window: BrowserWindow.fromWebContents(event.sender)!,
});
});
}

app.whenReady().then(() => {
Expand All @@ -53,13 +168,21 @@ app.whenReady().then(() => {
optimizer.watchWindowShortcuts(window);
});

createWindow();

app.on('activate', function () {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

app.on('quit', () => {});

if (is.dev) {
createWindow();
} else {
startLocalAndNCMAPIServer().then((res) => {
createWindow();
});
}
});

// Quit when all windows are closed, except on macOS. There, it's common
Expand Down
14 changes: 8 additions & 6 deletions electron-builder.yml
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
# @format

appId: com.electron.app
appId: com.refrain.app
productName: refrain-music
directories:
buildResources: build
output: dist-client
files:
- '**/*'
- '!**/.md'
- '!**/.vscode/*'
- '!src/*'
- '!**/electron.vite.config.{js,ts,mjs,cjs}'
- '!{.eslintignore,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
- '!{.eslintignore,.editorconfig,.eslintrc.cjs,.prettierignore,.prettierrc.yaml,dev-app-update.yml,CHANGELOG.md,README.md}'
- '!{.env,.env.*,.npmrc,pnpm-lock.yaml,yarn.lock}'
- '!{tsconfig.json,tsconfig.node.json,tsconfig.web.json}'
asarUnpack:
- client/main/public/**
afterSign: build/notarize.js
extends: null
win:
icon: build/icon.png
executableName: refrain-music
Expand All @@ -22,6 +23,7 @@ nsis:
shortcutName: ${productName}
uninstallDisplayName: ${productName}
createDesktopShortcut: always
createStartMenuShortcut: true
mac:
icon: build/icon.png
entitlementsInherit: build/entitlements.mac.plist
Expand All @@ -45,4 +47,4 @@ appImage:
npmRebuild: false
publish:
provider: generic
url: https://example.com/auto-updates
url: https://refrain-music.vercel.app
3 changes: 3 additions & 0 deletions global.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/** @format */

import { ElectronAPI } from '@electron-toolkit/preload';

interface document {
documentMode: number;
}
Expand Down Expand Up @@ -33,6 +35,7 @@ interface Navigator {
interface window {
webkitAudioContext: AudioContext;
requestIdleCallback: (cb: CommonFunction, options?: { timeout: number }) => void;
electron: ElectronAPI;
}

declare type CommonFunction = (...args: any[]) => any;
Expand Down
6 changes: 6 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
window.addEventListener('contextmenu', (e) => {
e.preventDefault();
if(electron) {
electron.ipcRenderer.send('show-context-menu');
}
});
</script>
</head>
<body>
Expand Down
13 changes: 11 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
"main": "./dist/main/index.js",
"license": "MIT",
"private": true,
"description": "a tiny music player!!!",
"author": "guoxiaoyou",
"scripts": {
"rebuild:githooks": "npx simple-git-hooks",
"dev": "vite -c scripts/vite/vite.config.ts",
Expand Down Expand Up @@ -34,6 +36,7 @@
"dependencies": {
"@electron-toolkit/preload": "^1.0.3",
"@electron-toolkit/utils": "^1.0.2",
"@types/koa": "^2.13.6",
"@vueuse/core": "^6.5.3",
"crypto-js": "^4.1.1",
"dexie": "^3.0.3",
Expand All @@ -45,7 +48,8 @@
"ryoko": "^0.1.6",
"swiper": "^8.4.4",
"vue": "^3.2.41",
"vue-router": "~4.0.10"
"vue-router": "~4.0.10",
"NeteaseCloudMusicApi": "^4.6.7"
},
"devDependencies": {
"@electron-toolkit/tsconfig": "^1.0.1",
Expand All @@ -54,6 +58,8 @@
"@types/crypto-js": "^4.0.2",
"@types/howler": "^2.2.3",
"@types/js-cookie": "^2.2.7",
"@types/koa-router": "^7.4.4",
"@types/koa-static": "^4.0.2",
"@types/node": "^16.4.8",
"@typescript-eslint/eslint-plugin": "^4.29.1",
"@typescript-eslint/parser": "^4.29.1",
Expand All @@ -62,14 +68,17 @@
"@vue/compiler-sfc": "^3.2.19",
"@vuedx/typecheck": "^0.7.4",
"@vuedx/typescript-plugin-vue": "^0.7.4",
"NeteaseCloudMusicApi": "^4.6.7",
"autoprefixer": "^10.3.1",
"cross-env": "^7.0.3",
"electron": "^24.2.0",
"electron-builder": "^23.6.0",
"electron-vite": "^1.0.22",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^7.16.0",
"koa": "^2.14.2",
"koa-router": "^12.0.0",
"koa-server-http-proxy": "^0.1.0",
"koa-static": "^5.0.0",
"lint-staged": "^11.1.2",
"npm-run-all": "^4.1.5",
"postcss": "^8.3.6",
Expand Down
45 changes: 32 additions & 13 deletions tsconfig.client.json
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
{
"extends": "@electron-toolkit/tsconfig/tsconfig.node.json",
"include": ["scripts/vite/electron.vite.config.*", "client/main/*", "client/preload/*"],
"compilerOptions": {
"composite": true,
"types": ["electron-vite/node"],
"baseUrl": ".",
"paths": {
"@/*": ["client/*"],
"@main/*": ["client/main/*"],
"@preload/*": ["client/preload/*"]
}
}
}
"extends": "@electron-toolkit/tsconfig/tsconfig.node.json",
"include": [
"scripts/vite/electron.vite.config.*",
"client/main/**/*",
"client/preload/**/*"
],
"compilerOptions": {
"composite": true,
"types": [
"electron-vite/node"
],
"baseUrl": ".",
"allowJs": true,
"strict": true,
"isolatedModules": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"paths": {
"@/*": [
"client/*"
],
"@main/*": [
"client/main/*"
],
"@preload/*": [
"client/preload/*"
]
}
}
}
Loading

0 comments on commit a1edc03

Please sign in to comment.