Skip to content

Commit 6da935c

Browse files
authored
Merge pull request #84 from YiFanAn/feature/windows
Feature/windows
2 parents bc0c968 + 12d44fb commit 6da935c

19 files changed

Lines changed: 682 additions & 128 deletions

File tree

‎app/package-lock.json‎

Lines changed: 8 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,10 +19,10 @@
1919
"pack": "npm run dist --dir -c.compression=store -c.mac.identity=null",
2020
"lint": "eslint ./src/**/*.ts ./src/**/*.tsx --fix",
2121
"upgrade:whistle": "git subtree pull --prefix=vendor/whistle https://github.com/avwo/whistle master --squash && npm run install-deps && npm run update:node_modules",
22-
"update:node_modules": "npx rimraf vendor/files/node/modules && cd vendor/files/node && echo {} > package.json && yarn add --ignore-engines ../../whistle-start ../../whistle whistle.vase ../../whistle.scriptfile ../../whistle.chii-internal -S && mv node_modules modules && cd ../../.. && npm run update:zip",
22+
"update:node_modules": "npx rimraf vendor/files/node/modules && cd vendor/files/node && echo {} > package.json && yarn add --ignore-engines ../../whistle-start ../../whistle whistle.vase ../../whistle.scriptfile ../../whistle.chii-internal -S && node -e \"require('fs').renameSync('node_modules', 'modules')\" && cd ../../.. && npm run update:zip",
2323
"update:zip": "cd vendor && npx rimraf files.zip && bestzip files.zip files/",
2424
"update:zip-fullnode": "cd vendor && npx rimraf files.zip && bestzip files.zip files/",
25-
"cleanbuild": "rm -rf node_modules && yarn && npm run dist",
25+
"cleanbuild": "npx rimraf node_modules && yarn && npm run dist",
2626
"build-doc": "cd docs && yarn && npm run build",
2727
"install-deps": "yarn --ignore-engines && npm run update:node_modules",
2828
"ci": "npm run install-deps && npm run dist",

‎src/main/api.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import checkInstallStatus from './install';
99
import treeKill from 'tree-kill';
1010
import ip from 'ip';
1111
import path from 'path';
12+
import fs from 'fs-extra';
1213
import { IPROXY_FILES_DIR, SYSTEM_IS_MACOS, SYSTEM_IS_LINUX } from './const';
1314
import { app, nativeTheme, BrowserWindow } from 'electron';
1415
import http from 'http';
@@ -31,7 +32,10 @@ async function spawnModule(props: any) {
3132

3233
logger.info('boardcast port', boardcastPort);
3334

34-
const nodeModulePath = path.join(IPROXY_FILES_DIR, `/node/node_modules/`);
35+
let nodeModulePath = path.join(IPROXY_FILES_DIR, `/node/node_modules/`);
36+
if (!fs.existsSync(nodeModulePath)) {
37+
nodeModulePath = path.join(IPROXY_FILES_DIR, `/node/modules/`);
38+
}
3539
const modulePath = encodeURIComponent(path.join(nodeModulePath, `${moduleId}/index.js`));
3640

3741
let nodeEXE = '';

‎src/main/const.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,6 @@ export const WINDOW_DEFAULT_HEIGHT = 700;
6060
export const WINDOW_MIN_WIDTH = 640;
6161
export const WINDOW_MIN_HEIGHT = 375;
6262

63-
6463
export const BYPASS_DOMAINS = [
6564
'*.lan',
6665
'*.ali.com',

‎src/main/main.ts‎

Lines changed: 194 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,9 @@ import { hideOrQuit } from './platform';
2121
import { installCertAndHelper } from './install';
2222

2323
// @ts-ignore
24-
import extract from 'extract-zip';
24+
import yauzl from 'yauzl';
25+
import { promisify } from 'util';
26+
import { pipeline } from 'stream';
2527

2628
import {
2729
WINDOW_DEFAULT_WIDTH,
@@ -36,6 +38,7 @@ import {
3638
APP_VERSION,
3739
IS_BUILD_FOR_PR,
3840
} from './const';
41+
import { setSystemProxy } from './platform';
3942
import ua from 'universal-analytics';
4043
import { CoreAPI } from '../renderer/core-api';
4144
import { uuidv4 } from '../renderer/utils';
@@ -131,6 +134,12 @@ const IPROXY_FILES_ZIP_IN_ASAR_PATH = electronIsDev
131134

132135
let splashWindow: BrowserWindow | null;
133136

137+
function updateSplashProgress(percent: number, message: string) {
138+
if (splashWindow && !splashWindow.isDestroyed()) {
139+
splashWindow.webContents.send('splash-progress', { percent, message });
140+
}
141+
}
142+
134143
async function initSplashScreen() {
135144
// start a splash window
136145
return new Promise((resolve) => {
@@ -157,6 +166,10 @@ async function initSplashScreen() {
157166
autoHideMenuBar: true,
158167
resizable: false,
159168
movable: true,
169+
webPreferences: {
170+
nodeIntegration: true,
171+
contextIsolation: false,
172+
},
160173
});
161174

162175
splashWindow.loadURL(splashContent);
@@ -169,6 +182,148 @@ async function initSplashScreen() {
169182
});
170183
}
171184

185+
function getExtractedMode(mode: number, isDir: boolean) {
186+
if (mode === 0) {
187+
if (isDir) {
188+
return 0o755;
189+
} else {
190+
return 0o644;
191+
}
192+
}
193+
return mode;
194+
}
195+
196+
async function extractZipWithProgress(zipPath: string, destDir: string) {
197+
const zipfile = await new Promise<any>((resolve, reject) => {
198+
yauzl.open(zipPath, { lazyEntries: true }, (err: Error | null, zf: any) => {
199+
if (err) {
200+
reject(err);
201+
} else {
202+
resolve(zf);
203+
}
204+
});
205+
});
206+
const totalEntries = zipfile.entryCount;
207+
let extractedCount = 0;
208+
const pipelineAsync = promisify(pipeline);
209+
const updateInterval = Math.max(1, Math.floor(totalEntries / 100));
210+
211+
return new Promise<void>((resolve, reject) => {
212+
let canceled = false;
213+
214+
zipfile.on('error', (err: Error) => {
215+
canceled = true;
216+
reject(err);
217+
});
218+
219+
zipfile.on('close', () => {
220+
if (!canceled) {
221+
resolve();
222+
}
223+
});
224+
225+
const processEntry = (entry: any) => {
226+
if (canceled) {
227+
return;
228+
}
229+
230+
if (entry.fileName.startsWith('__MACOSX/')) {
231+
zipfile.readEntry();
232+
return;
233+
}
234+
235+
const entryDest = path.join(destDir, entry.fileName);
236+
const entryDestDir = path.dirname(entryDest);
237+
238+
fs.mkdirp(entryDestDir)
239+
.then(() => {
240+
const mode = (entry.externalFileAttributes >> 16) & 0xffff;
241+
const IFMT = 61440;
242+
const IFDIR = 16384;
243+
const IFLNK = 40960;
244+
const symlink = (mode & IFMT) === IFLNK;
245+
let isDir = (mode & IFMT) === IFDIR;
246+
247+
if (!isDir && entry.fileName.endsWith('/')) {
248+
isDir = true;
249+
}
250+
251+
const madeBy = entry.versionMadeBy >> 8;
252+
if (!isDir) isDir = madeBy === 0 && entry.externalFileAttributes === 16;
253+
254+
const procMode = getExtractedMode(mode, isDir) & 0o777;
255+
256+
if (isDir) {
257+
return fs.mkdirp(entryDest).then(() => {
258+
return fs.chmod(entryDest, procMode).then(() => {
259+
extractedCount++;
260+
if (extractedCount % updateInterval === 0 || extractedCount === totalEntries) {
261+
const percent = 10 + (extractedCount / totalEntries) * 70;
262+
updateSplashProgress(percent, `Extracting ${entry.fileName}...`);
263+
}
264+
zipfile.readEntry();
265+
});
266+
});
267+
}
268+
269+
return new Promise<void>((res, rej) => {
270+
zipfile.openReadStream(entry, (err: Error | null, readStream: any) => {
271+
if (err) {
272+
rej(err);
273+
return;
274+
}
275+
276+
if (symlink) {
277+
const chunks: Buffer[] = [];
278+
readStream.on('data', (chunk: Buffer) => chunks.push(chunk));
279+
readStream.on('end', () => {
280+
const link = Buffer.concat(chunks).toString();
281+
fs.symlink(link, entryDest)
282+
.then(() => fs.chmod(entryDest, procMode))
283+
.then(() => {
284+
extractedCount++;
285+
if (
286+
extractedCount % updateInterval === 0 ||
287+
extractedCount === totalEntries
288+
) {
289+
const percent = 10 + (extractedCount / totalEntries) * 70;
290+
updateSplashProgress(percent, `Extracting ${entry.fileName}...`);
291+
}
292+
zipfile.readEntry();
293+
res();
294+
})
295+
.catch(rej);
296+
});
297+
readStream.on('error', rej);
298+
} else {
299+
const writeStream = fs.createWriteStream(entryDest, { mode: procMode });
300+
pipelineAsync(readStream, writeStream)
301+
.then(() => {
302+
extractedCount++;
303+
if (extractedCount % updateInterval === 0 || extractedCount === totalEntries) {
304+
const percent = 10 + (extractedCount / totalEntries) * 70;
305+
updateSplashProgress(percent, `Extracting ${entry.fileName}...`);
306+
}
307+
zipfile.readEntry();
308+
res();
309+
})
310+
.catch(rej);
311+
}
312+
});
313+
});
314+
})
315+
.catch((err: Error) => {
316+
canceled = true;
317+
zipfile.close();
318+
reject(err);
319+
});
320+
};
321+
322+
zipfile.on('entry', processEntry);
323+
zipfile.readEntry();
324+
});
325+
}
326+
172327
async function initCopyFiles() {
173328
try {
174329
if (!fs.existsSync(IPROXY_FILES_DIR)) {
@@ -177,25 +332,29 @@ async function initCopyFiles() {
177332

178333
const versionFile = path.join(IPROXY_FILES_DIR, 'version');
179334
if (fs.existsSync(versionFile) && fs.readFileSync(versionFile, 'utf-8') === version && !electronIsDev) {
180-
// pass
335+
updateSplashProgress(100, 'Files already up to date');
181336
} else {
182337
console.log('copy files');
338+
updateSplashProgress(5, 'Removing old files...');
183339
fs.removeSync(IPROXY_FILES_DIR);
184340

185-
await extract(IPROXY_FILES_ZIP_IN_ASAR_PATH, {
186-
dir: IPROXY_HOME_PATH,
187-
});
341+
updateSplashProgress(10, 'Extracting files (this may take a while on Windows)...');
342+
await extractZipWithProgress(IPROXY_FILES_ZIP_IN_ASAR_PATH, IPROXY_HOME_PATH);
188343

189-
// copyFolderRecursiveSync(IPROXY_FILES_IN_ASAR_PATH, IPROXY_HOME_PATH);
190-
// fs.chmodSync(IPROXY_NODEJS_PATH, '775');
344+
updateSplashProgress(80, 'Moving node_modules...');
191345
fs.moveSync(
192346
path.join(IPROXY_FILES_DIR, '/node/modules'),
193347
path.join(IPROXY_FILES_DIR, '/node/node_modules'),
194348
);
349+
350+
updateSplashProgress(95, 'Writing version file...');
195351
fs.writeFileSync(versionFile, version, 'utf-8');
352+
353+
updateSplashProgress(100, 'Files extracted successfully');
196354
}
197355
} catch (e) {
198356
console.error(e);
357+
updateSplashProgress(0, 'Error extracting files');
199358
}
200359
}
201360

@@ -392,9 +551,29 @@ app.on('before-quit', function () {
392551
forceQuit = true;
393552
});
394553

395-
app.on('will-quit', () => {
396-
// 注销所有快捷键
554+
app.on('will-quit', async () => {
397555
globalShortcut.unregisterAll();
556+
await setSystemProxy(0);
557+
});
558+
559+
process.on('SIGINT', () => {
560+
setSystemProxy(0)
561+
.then(() => {
562+
process.exit(0);
563+
})
564+
.catch(() => {
565+
process.exit(1);
566+
});
567+
});
568+
569+
process.on('SIGTERM', () => {
570+
setSystemProxy(0)
571+
.then(() => {
572+
process.exit(0);
573+
})
574+
.catch(() => {
575+
process.exit(1);
576+
});
398577
});
399578

400579
// quit application when all windows are closed
@@ -420,9 +599,15 @@ app.on('activate', () => {
420599
// create main BrowserWindow when electron is ready
421600
app.on('ready', async () => {
422601
appReady = true;
602+
updateSplashProgress(0, 'Initializing splash screen...');
423603
await initSplashScreen();
604+
updateSplashProgress(0, 'Checking files...');
424605
await initCopyFiles();
606+
updateSplashProgress(0, 'Creating main window...');
425607
mainWindow = createMainWindow();
608+
updateSplashProgress(0, 'Setting up menu...');
426609
setApplicationMenu();
610+
updateSplashProgress(0, 'Initializing IPC...');
427611
initIPC(mainWindow);
612+
updateSplashProgress(100, 'Ready!');
428613
});

0 commit comments

Comments
 (0)