-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfile.ts
More file actions
496 lines (447 loc) · 16.7 KB
/
file.ts
File metadata and controls
496 lines (447 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
import AdmZip from 'adm-zip';
import { execFileSync, execSync, spawn } from 'child_process';
import {
createReadStream,
chmodSync,
existsSync,
mkdirSync,
readdirSync,
readFileSync,
rmSync,
statSync,
unlinkSync,
writeFileSync,
} from 'fs';
import { createHash } from 'crypto';
import { unpack } from '7zip-min';
import stream from 'stream/promises';
import { GlobOptionsWithFileTypesFalse, globSync } from 'glob';
import { moveSync } from 'fs-extra/esm';
import os from 'os';
import * as tar from 'tar';
import path, { dirname } from 'path';
import yaml from 'js-yaml';
import { ZodIssueCode, ZodParsedType } from 'zod';
import { PackageInterface } from '../types/Package.js';
import { PluginFile } from '../types/Plugin.js';
import { PresetFile } from '../types/Preset.js';
import { ProjectFile } from '../types/Project.js';
import { ZodIssue } from 'zod';
import { SystemType } from '../types/SystemType.js';
import { fileURLToPath } from 'url';
import sudoPrompt from '@vscode/sudo-prompt';
import { getSystem } from './utilsLocal.js';
import { log } from './utils.js';
export async function archiveExtract(filePath: string, dirPath: string) {
log('⎋', dirPath);
const ext = path.extname(filePath).trim().toLowerCase();
if (ext === '.zip') {
const zip: AdmZip = new AdmZip(filePath);
try {
return zip.extractAllTo(dirPath);
} catch (error: any) {
// Handle Windows special character issues by extracting files manually
if (getSystem() === SystemType.Win && error.message?.includes('ENOENT')) {
log('⚠️', 'Extracting files manually due to special characters in filenames');
const entries = zip.getEntries();
entries.forEach(entry => {
const sanitizedName: string = entry.entryName.replace(/[<>:"|?*]/g, '_').replace(/[\r\n]/g, '');
if (!entry.isDirectory) {
const outputPath = path.join(dirPath, sanitizedName);
dirCreate(path.dirname(outputPath));
writeFileSync(outputPath, entry.getData());
} else {
dirCreate(path.join(dirPath, sanitizedName));
}
});
return;
}
}
} else if (ext === '.tar' || ext === '.gz' || ext === '.tgz') {
return await tar.extract({
file: filePath,
cwd: dirPath,
});
} else if (ext === '.7z') {
return new Promise<void>((resolve, reject) => {
unpack(filePath, dirPath, (err2: any) => {
if (err2)
return reject(new Error(`7z extraction failed: ${err2 && err2.message ? err2.message : String(err2)}`));
return resolve();
});
});
}
}
export function dirApp(dirName = 'open-audio-stack') {
if (getSystem() === SystemType.Win) return process.env.APPDATA || path.join(os.homedir(), dirName);
else if (getSystem() === SystemType.Mac) return path.join(os.homedir(), 'Library', 'Preferences', dirName);
return path.join(os.homedir(), '.local', 'share', dirName);
}
export function dirContains(parentDir: string, childDir: string): boolean {
return path.normalize(childDir).startsWith(path.normalize(parentDir));
}
export function dirCreate(dir: string) {
if (!dirExists(dir)) {
log('+', dir);
mkdirSync(dir, { recursive: true });
return dir;
}
return false;
}
export function dirDelete(dir: string) {
if (dirExists(dir)) {
log('-', dir);
return rmSync(dir, { recursive: true });
}
return false;
}
export function dirEmpty(dir: string) {
const files: string[] = readdirSync(dir);
return files.length === 0 || (files.length === 1 && files[0] === '.DS_Store');
}
export function dirExists(dir: string) {
return existsSync(dir);
}
export function dirIs(dir: string) {
return statSync(dir).isDirectory();
}
export function dirMove(dir: string, dirNew: string): void | boolean {
if (dirExists(dir)) {
log('-', dir);
log('+', dirNew);
return moveSync(dir, dirNew, { overwrite: true });
}
return false;
}
export function dirOpen(dir: string) {
let command: string = '';
if (process.env.CI) return Buffer.from('');
if (getSystem() === SystemType.Win) command = 'start ""';
else if (getSystem() === SystemType.Mac) command = 'open';
else command = 'xdg-open';
log('⎋', `${command} "${dir}"`);
return execSync(`${command} "${dir}"`);
}
export function dirPackage(pkg: PackageInterface) {
const parts: string[] = pkg.slug.split('/');
parts.push(pkg.version);
return path.join(...parts);
}
export function dirPlugins() {
if (getSystem() === SystemType.Win) return path.join('Program Files', 'Common Files');
else if (getSystem() === SystemType.Mac) return path.join(os.homedir(), 'Library', 'Audio', 'Plug-ins');
return path.join('usr', 'local', 'lib');
}
export function dirPresets() {
if (getSystem() === SystemType.Win) return path.join(os.homedir(), 'Documents', 'VST3 Presets');
else if (getSystem() === SystemType.Mac) return path.join(os.homedir(), 'Library', 'Audio', 'Presets');
return path.join(os.homedir(), '.vst3', 'presets');
}
export function dirProjects() {
// Windows throws permissions errors if you scan hidden folders
// Therefore set to a more specific path than Documents
if (getSystem() === SystemType.Win) return path.join(os.homedir(), 'Documents', 'Audio');
else if (getSystem() === SystemType.Mac) return path.join(os.homedir(), 'Documents', 'Audio');
return path.join(os.homedir(), 'Documents', 'Audio');
}
export function dirApps() {
if (getSystem() === SystemType.Win) return path.join(os.homedir(), 'AppData', 'Local', 'Programs');
else if (getSystem() === SystemType.Mac) return path.join('/Applications');
return path.join('/usr', 'local', 'bin');
}
export function dirRead(dir: string, options?: GlobOptionsWithFileTypesFalse): string[] {
log('⌕', dir);
// Glob now expects forward slashes on Windows
// Convert backslashes from path.join() to forwardslashes
if (getSystem() === SystemType.Win) {
dir = dir.replace(/\\/g, '/');
}
// Ignore Mac files in Contents folders
// Filter out any paths not starting with the base directory
// This is to prevent issues with symlinks.
const baseDir: string = dir.includes('*') ? dir.split('*')[0] : dir;
const allPaths = globSync(dir, {
ignore: [`${baseDir}/**/*.{app,component,lv2,vst,vst3}/**/*`],
realpath: true,
...options,
});
// Glob input paths use forward slashes.
// Glob output paths are system-specific.
const baseDirCrossPlatform: string = baseDir.split('/').join(path.sep);
return allPaths.filter(p => p.startsWith(baseDirCrossPlatform));
}
export function dirRename(dir: string, dirNew: string): void | boolean {
if (dirExists(dir)) {
return moveSync(dir, dirNew, { overwrite: true });
}
return false;
}
export function fileCreate(filePath: string, data: string | Buffer): void {
log('+', filePath);
return writeFileSync(filePath, data);
}
export function fileCreateJson(filePath: string, data: object): void {
return fileCreate(filePath, JSON.stringify(data, null, 2));
}
export function fileCreateYaml(filePath: string, data: object): void {
return fileCreate(filePath, yaml.dump(data));
}
export function fileDate(filePath: string): Date {
return statSync(filePath).mtime;
}
export function fileDelete(filePath: string): boolean | void {
if (fileExists(filePath)) {
log('-', filePath);
return unlinkSync(filePath);
}
return false;
}
export function fileExec(filePath: string): void {
return chmodSync(filePath, '755');
}
export function fileExists(filePath: string): boolean {
return existsSync(filePath);
}
export async function fileHash(filePath: string, algorithm = 'sha256'): Promise<string> {
log('⎋', filePath);
const input = createReadStream(filePath);
const hash = createHash(algorithm);
await stream.pipeline(input, hash);
return hash.digest('hex');
}
export function fileInstall(filePath: string) {
if (process.env.CI) return Buffer.from('');
const ext = path.extname(filePath).toLowerCase();
let command: string | null = null;
switch (ext) {
case '.dmg':
command = `hdiutil attach -nobrowse "${filePath}" && sudo installer -pkg "$(find /Volumes -name '*.pkg' -maxdepth 2 | head -n 1)" -target / && hdiutil detach "$(dirname "$(find /Volumes -name '*.pkg' -maxdepth 2 | head -n 1)")"`;
break;
case '.pkg':
command = `sudo installer -pkg "${filePath}" -target /`;
break;
case '.deb':
command = `sudo dpkg -i "${filePath}" || sudo apt-get install -f -y`;
break;
case '.rpm':
command = `sudo rpm -i --nodigest --nofiledigest --nosignature --force "${filePath}" || sudo dnf install -y "${filePath}" || sudo yum install -y "${filePath}"`;
break;
case '.exe':
command = `start /wait "" "${filePath}" /quiet /norestart`;
break;
case '.msi':
command = `msiexec /i "${filePath}" /quiet /norestart`;
break;
default:
throw new Error(`Unsupported file format: ${ext}`);
}
log('⎋', command);
return execSync(command, { stdio: 'inherit' });
}
export function fileMove(filePath: string, newPath: string): void | boolean {
if (fileExists(filePath)) {
log('-', filePath);
log('+', newPath);
return moveSync(filePath, newPath, { overwrite: true });
}
return false;
}
export function filesMove(dirSource: string, dirTarget: string, dirSub: string, formatDir: Record<string, string>) {
const filesAndFolders: string[] = dirRead(`${dirSource}/**/*`);
log('filesAndFolders', filesAndFolders);
const files = filesAndFolders.filter(f => {
// Include files.
if (!dirIs(f)) return true;
// Include macOS application bundles (directory of files presented as a single file).
if (fileExists(path.join(f, 'Contents', 'Info.plist'))) return true;
// Include LV2 plugin folders.
if (fileExists(path.join(f, 'manifest.ttl'))) return true;
// Otherwise ignore.
return false;
});
const filesMoved: string[] = [];
log('files', files);
// For each file, move to correct folder based on type
files.forEach((fileSource: string) => {
const fileExt: string = path.extname(fileSource).slice(1).toLowerCase();
const fileExtTarget = formatDir[fileExt];
// If this is not a supported file format, then ignore.
if (fileExtTarget === undefined)
return log(`${fileSource} - ${fileExt || 'no extension'} not mapped to a installation folder, skipping.`);
const fileTarget: string = path.join(dirTarget, fileExtTarget, dirSub, path.basename(fileSource));
if (fileExists(fileTarget)) return log(`${fileSource} - ${fileTarget} already exists, skipping.`);
dirCreate(path.dirname(fileTarget));
fileMove(fileSource, fileTarget);
// Set executable permissions for executable file types
if (fileExt === 'app') {
// For .app bundles, find and set permissions on the actual executable
const executablePath = path.join(fileTarget, 'Contents', 'MacOS', path.basename(fileTarget, '.app'));
if (fileExists(executablePath)) {
fileExec(executablePath);
}
} else if (['elf', 'exe', ''].includes(fileExt)) {
fileExec(fileTarget);
}
filesMoved.push(fileTarget);
});
return filesMoved;
}
export function fileOpen(filePath: string, options: string[] = []) {
if (process.env.CI) return Buffer.from('');
if (getSystem() === SystemType.Mac) {
const isExecutable = !path.extname(filePath);
if (isExecutable) {
// Use spawn for executables with stdio inherit to show output
log('⎋', `spawn "${filePath}" ${options.join(' ')}`);
const child = spawn(filePath, options, { stdio: 'inherit' });
return child;
} else {
log('⎋', `open "${filePath}"`);
return execSync(`open "${filePath}"`);
}
}
let command: string = '';
if (getSystem() === SystemType.Win) command = 'start ""';
else command = 'xdg-open';
log('⎋', `${command} "${filePath}"`);
return execSync(`${command} "${filePath}"`);
}
export function fileRead(filePath: string) {
log('⎋', filePath);
return readFileSync(filePath, 'utf8');
}
export function fileReadJson(filePath: string) {
if (fileExists(filePath)) {
log('⎋', filePath);
return JSON.parse(readFileSync(filePath, 'utf8').toString());
}
return false;
}
export function fileReadString(filePath: string) {
log('⎋', filePath);
return readFileSync(filePath, 'utf8').toString();
}
export function fileReadYaml(filePath: string) {
const file: string = fileReadString(filePath);
return yaml.load(file);
}
export function fileSize(filePath: string) {
return statSync(filePath).size;
}
export function isAdmin(): boolean {
if (process.platform === 'win32') {
try {
execFileSync('net', ['session'], { stdio: 'ignore' });
return true;
} catch {
return false;
}
} else {
return process && process.getuid ? process.getuid() === 0 : false;
}
}
export async function fileValidateMetadata(filePath: string, fileMetadata: PluginFile | PresetFile | ProjectFile) {
const errors: ZodIssue[] = [];
const hash = await fileHash(filePath);
if (fileMetadata.sha256 !== hash) {
errors.push({
code: ZodIssueCode.invalid_type,
expected: fileMetadata.sha256 as ZodParsedType,
message: 'Required',
path: ['sha256'],
received: hash as ZodParsedType,
});
}
if (fileMetadata.size !== fileSize(filePath)) {
errors.push({
code: ZodIssueCode.invalid_type,
expected: String(fileMetadata.size) as ZodParsedType,
message: 'Required',
path: ['size'],
received: String(fileSize(filePath)) as ZodParsedType,
});
}
return errors;
}
export function getPlatform() {
if (getSystem() === SystemType.Win) return SystemType.Win;
else if (getSystem() === SystemType.Mac) return SystemType.Mac;
return SystemType.Linux;
}
export function runCliAsAdmin(args: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
const filename: string = fileURLToPath(import.meta.url).replace('src/', 'build/');
const dirPathClean: string = dirname(filename).replace('app.asar', 'app.asar.unpacked');
const script: string = path.join(dirPathClean, 'admin.js');
log(`Running as admin: node "${script}" ${args}`);
const cmd = `node "${script}" ${args}`;
sudoPrompt.exec(
cmd,
{ name: 'Open Audio Stack' },
(error?: Error | undefined, stdout?: string | Buffer | undefined, stderr?: string | Buffer | undefined) => {
// Prefer explicit error from sudo-prompt callback
if (error) {
const stderrStr = stderr ? (typeof stderr === 'string' ? stderr : stderr.toString()) : '';
const msg = `runCliAsAdmin: admin command failed: ${error && error.message ? error.message : String(error)}${
stderrStr ? `\nstderr: ${stderrStr}` : ''
}`;
const err: any = new Error(msg);
err.code = (error as any) && (error as any).code ? (error as any).code : undefined;
return reject(err);
}
// Convert stdout/stderr buffers to strings for inspection
const stdoutStr = stdout ? (typeof stdout === 'string' ? stdout : stdout.toString()) : '';
const stderrStr = stderr ? (typeof stderr === 'string' ? stderr : stderr.toString()) : '';
const out = stdoutStr + stderrStr;
log(out);
// Try to parse structured JSON output from the admin script first.
// Admin script outputs JSON on its own line after a newline, so look for the last JSON object.
const lines = out.split('\n');
let jsonPayload = null;
for (let i = lines.length - 1; i >= 0; i--) {
const line = lines[i].trim();
if (!line) continue; // Skip empty lines
try {
jsonPayload = JSON.parse(line);
break; // Found valid JSON, stop searching backwards
} catch {
// This line is not JSON, continue searching
}
}
if (jsonPayload) {
if (jsonPayload && (jsonPayload.status === 'ok' || jsonPayload.code === 0)) {
return resolve();
}
const errMsg = jsonPayload && jsonPayload.message ? jsonPayload.message : JSON.stringify(jsonPayload);
return reject(new Error(`runCliAsAdmin: admin command reported error: ${errMsg}`));
}
return reject(
new Error(
`runCliAsAdmin: admin command did not report completion. stdout: ${stdoutStr} stderr: ${stderrStr}`,
),
);
},
);
});
}
export function zipCreate(filesPath: string, zipPath: string): void {
if (fileExists(zipPath)) {
unlinkSync(zipPath);
}
const zip: AdmZip = new AdmZip();
const pathList: string[] = dirRead(filesPath);
pathList.forEach(pathItem => {
log('⎋', pathItem);
try {
if (dirIs(pathItem)) {
zip.addLocalFolder(pathItem, path.basename(pathItem));
} else {
zip.addLocalFile(pathItem);
}
} catch (error) {
log(error);
}
});
log('+', zipPath);
return zip.writeZip(zipPath);
}