-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathserver.js
More file actions
2471 lines (2126 loc) · 81.9 KB
/
Copy pathserver.js
File metadata and controls
2471 lines (2126 loc) · 81.9 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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import express from 'express';
import cors from 'cors';
import fs from 'fs';
import path from 'path';
import AdmZip from 'adm-zip';
import { fileURLToPath } from 'url';
import os from 'os';
import { exec } from 'child_process';
import { DOMParser, XMLSerializer } from '@xmldom/xmldom';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const PORT = 3001;
app.use(cors());
app.use(express.json({ limit: '50mb' })); // support large XML payloads
// Writable AppData Directory for config files (persists in packaged Electron app)
const USER_DATA_DIR = (() => {
const homeDir = os.homedir();
let appDataPath;
if (process.platform === 'win32') {
appDataPath = process.env.APPDATA || path.join(homeDir, 'AppData', 'Roaming');
} else if (process.platform === 'darwin') {
appDataPath = path.join(homeDir, 'Library', 'Application Support');
} else {
appDataPath = process.env.XDG_CONFIG_HOME || path.join(homeDir, '.config');
}
const targetDir = path.join(appDataPath, 'studio-one-project-hub');
try {
if (!fs.existsSync(targetDir)) {
fs.mkdirSync(targetDir, { recursive: true });
}
return targetDir;
} catch (e) {
console.error('Failed to create settings directory, falling back to home dir:', e);
return homeDir;
}
})();
const CONFIG_FILE = path.join(USER_DATA_DIR, 'workspace-config.json');
const CACHE_FILE = path.join(USER_DATA_DIR, 'workspace-cache.json');
// Migrate existing configuration from local folder to USER_DATA_DIR if present
const OLD_CONFIG_FILE = path.join(__dirname, 'workspace-config.json');
const OLD_CACHE_FILE = path.join(__dirname, 'workspace-cache.json');
if (fs.existsSync(OLD_CONFIG_FILE) && !fs.existsSync(CONFIG_FILE)) {
try {
fs.copyFileSync(OLD_CONFIG_FILE, CONFIG_FILE);
console.log('Migrated configuration file to:', CONFIG_FILE);
} catch (e) {
console.error('Failed to migrate config file:', e);
}
}
if (fs.existsSync(OLD_CACHE_FILE) && !fs.existsSync(CACHE_FILE)) {
try {
fs.copyFileSync(OLD_CACHE_FILE, CACHE_FILE);
console.log('Migrated cache file to:', CACHE_FILE);
} catch (e) {
console.error('Failed to migrate cache file:', e);
}
}
function getDefaultWorkspace() {
const username = os.userInfo().username;
const homeDir = os.homedir();
const candidates = [
// 1. C:\Users\<username>\Documents\Studio One\Songs
path.join(homeDir, 'Documents', 'Studio One', 'Songs'),
// 2. D:\Users\<username>\Documents\Studio One\Songs
path.join('D:', 'Users', username, 'Documents', 'Studio One', 'Songs'),
// 3. D:\Documents\Studio One\Songs
path.join('D:', 'Documents', 'Studio One', 'Songs'),
// 4. C:\Documents\Studio One\Songs
path.join('C:', 'Documents', 'Studio One', 'Songs'),
];
for (const dir of candidates) {
try {
if (fs.existsSync(dir) && fs.statSync(dir).isDirectory()) {
console.log('Found default Studio One songs directory:', dir);
return dir;
}
} catch (e) {
// ignore
}
}
// Fallback to parent of project root
return path.resolve(__dirname, '..');
}
let WORKSPACE_DIR = getDefaultWorkspace();
let PROJECT_CACHE = {};
if (fs.existsSync(CONFIG_FILE)) {
try {
const config = JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
if (config.workspaceDir && fs.existsSync(config.workspaceDir) && fs.statSync(config.workspaceDir).isDirectory()) {
WORKSPACE_DIR = config.workspaceDir;
console.log('Loaded persisted workspace directory:', WORKSPACE_DIR);
}
} catch (e) {
console.error('Error reading workspace-config.json:', e);
}
}
if (fs.existsSync(CACHE_FILE)) {
try {
PROJECT_CACHE = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8'));
console.log('Loaded project metadata cache with', Object.keys(PROJECT_CACHE).length, 'entries');
} catch (e) {
console.error('Error reading workspace-cache.json:', e);
}
}
function saveCache() {
try {
fs.writeFileSync(CACHE_FILE, JSON.stringify(PROJECT_CACHE, null, 2), 'utf8');
} catch (e) {
console.error('Error saving workspace-cache.json:', e);
}
}
// Helper: Scan for projects
function scanProjects(baseDir) {
const projects = [];
let cacheUpdated = false;
try {
function walk(dir, depth = 0) {
if (depth > 3) return;
try {
const items = fs.readdirSync(dir);
const songFiles = items.filter(f => f.endsWith('.song'));
if (songFiles.length > 0) {
songFiles.forEach(songFile => {
const songPath = path.join(dir, songFile);
try {
const stat = fs.statSync(songPath);
const mtime = stat.mtime.getTime();
const size = stat.size;
let trackCount = 0;
let pluginCount = 0;
const cached = PROJECT_CACHE[songPath];
if (cached && cached.mtime === mtime && cached.size === size) {
trackCount = cached.trackCount;
pluginCount = cached.pluginCount;
} else {
try {
const zip = new AdmZip(songPath);
const metainfoEntry = zip.getEntry('metainfo.xml');
if (metainfoEntry) {
const text = metainfoEntry.getData().toString('utf8');
const tcMatch = text.match(/id="Media:TrackCount"\s+value="(\d+)"/);
if (tcMatch) trackCount = parseInt(tcMatch[1], 10);
}
const mixerEntry = zip.getEntry('Devices/audiomixer.xml');
if (mixerEntry) {
const mixerText = mixerEntry.getData().toString('utf8');
const matches = mixerText.match(/classID=/g);
pluginCount = matches ? matches.length : 0;
}
} catch (e) {
// ignore zip reading errors
}
PROJECT_CACHE[songPath] = { mtime, size, trackCount, pluginCount };
cacheUpdated = true;
}
projects.push({
name: songFile.replace(/\.song$/i, ''),
dirPath: dir,
songPath: songPath,
songName: songFile,
mtime,
size,
trackCount,
pluginCount
});
} catch (e) {
// fallback if stat fails
projects.push({
name: songFile.replace(/\.song$/i, ''),
dirPath: dir,
songPath: songPath,
songName: songFile,
mtime: 0,
size: 0,
trackCount: 0,
pluginCount: 0
});
}
});
} else {
for (const item of items) {
if (item.startsWith('.') || item === 'node_modules' || item === 'System Volume Information' || item === 'History' || item === 'Backup_Unused_Media') continue;
const itemPath = path.join(dir, item);
try {
if (fs.statSync(itemPath).isDirectory()) {
walk(itemPath, depth + 1);
}
} catch (e) { /* skip inaccessible directories */ }
}
}
} catch (err) { /* skip inaccessible folders */ }
}
walk(baseDir);
} catch (err) {
console.error('Error scanning projects:', err);
}
// Sort by mtime descending (most recently modified/created first)
projects.sort((a, b) => b.mtime - a.mtime);
if (cacheUpdated) {
saveCache();
}
return projects;
}
// 0. Get / Set workspace root
app.get('/api/workspace', (req, res) => {
res.json({ workspaceDir: WORKSPACE_DIR });
});
app.post('/api/workspace', (req, res) => {
const { dir } = req.body;
if (!dir || !fs.existsSync(dir) || !fs.statSync(dir).isDirectory()) {
return res.status(400).json({ error: 'Invalid directory path.' });
}
WORKSPACE_DIR = path.resolve(dir);
console.log('Workspace changed to:', WORKSPACE_DIR);
// Persist workspace setting to config file
try {
fs.writeFileSync(CONFIG_FILE, JSON.stringify({ workspaceDir: WORKSPACE_DIR }, null, 2), 'utf8');
} catch (e) {
console.error('Error saving workspace-config.json:', e);
}
res.json({ workspaceDir: WORKSPACE_DIR, projects: scanProjects(WORKSPACE_DIR) });
});
// 0b. Open native OS folder selector dialog and return the selected path
app.post('/api/browse-workspace', (req, res) => {
if (process.platform !== 'win32') {
return res.status(400).json({ error: 'Folder selection browser is only supported on Windows in web mode.' });
}
// PowerShell command to open Windows native FolderBrowserDialog
const psCommand = `powershell -NoProfile -ExecutionPolicy Bypass -Command "Add-Type -AssemblyName System.Windows.Forms; $d = New-Object System.Windows.Forms.FolderBrowserDialog; $d.Description = 'Select Studio One Songs Folder'; $d.ShowNewFolderButton = $true; $r = $d.ShowDialog(); if ($r -eq 'OK') { Write-Output $d.SelectedPath }"`;
exec(psCommand, (err, stdout, stderr) => {
if (err) {
console.error('Error opening folder dialog:', err);
return res.status(500).json({ error: 'Failed to open directory browser.' });
}
const selectedPath = stdout.trim();
if (selectedPath) {
res.json({ selectedPath });
} else {
res.json({ cancelled: true });
}
});
});
// 1. Get all projects in the workspace
app.get('/api/projects', (req, res) => {
const projects = scanProjects(WORKSPACE_DIR);
res.json({ projects });
});
// 1b. Resolve a .song file by filename only (for file picker)
app.get('/api/resolve-song', (req, res) => {
const { songName } = req.query;
if (!songName) return res.status(400).json({ error: 'songName required.' });
// Search all projects in workspace
const projects = scanProjects(WORKSPACE_DIR);
const match = projects.find(p => p.songName === songName);
if (match) {
return res.json({ project: match });
}
// Deep search: walk workspace subfolders looking for the file
function findSong(dir, depth = 0) {
if (depth > 4) return null;
try {
const items = fs.readdirSync(dir);
for (const item of items) {
const itemPath = path.join(dir, item);
try {
const stat = fs.statSync(itemPath);
if (stat.isFile() && item === songName) {
const dirPath = path.dirname(itemPath);
return { name: path.basename(dirPath), dirPath, songPath: itemPath, songName: item };
}
if (stat.isDirectory()) {
const found = findSong(itemPath, depth + 1);
if (found) return found;
}
} catch (e) { /* skip */ }
}
} catch (e) { /* skip */ }
return null;
}
const found = findSong(WORKSPACE_DIR);
if (found) return res.json({ project: found });
res.json({ project: null });
});
// 2. Load raw XML strings from the .song ZIP file
app.get('/api/load-xmls', (req, res) => {
const { songPath } = req.query;
if (!songPath || !fs.existsSync(songPath)) {
return res.status(404).json({ error: 'Song file not found.' });
}
try {
const zip = new AdmZip(songPath);
const result = {
metainfo: '',
song: '',
mediapool: '',
audiomixer: '',
notepad: '',
notes: ''
};
const filesToRead = {
'metainfo.xml': 'metainfo',
'Song/song.xml': 'song',
'Song/mediapool.xml': 'mediapool',
'Devices/audiomixer.xml': 'audiomixer',
'notepad.xml': 'notepad',
'notes.txt': 'notes'
};
for (const [zipEntryPath, key] of Object.entries(filesToRead)) {
const entry = zip.getEntry(zipEntryPath);
if (entry) {
let content = entry.getData();
// Decode correctly
let text = '';
try {
// Remove UTF-8 BOM if present
text = content.toString('utf8').replace(/^\uFEFF/, '');
} catch (e) {
text = content.toString('utf16le');
}
result[key] = text;
}
}
res.json(result);
} catch (err) {
console.error('Error reading .song zip:', err);
res.status(500).json({ error: `Failed to parse .song archive: ${err.message}` });
}
});
// 2b. Upload a .song file as binary — no path needed, works for any file
app.post('/api/upload-song', express.raw({ type: 'application/octet-stream', limit: '200mb' }), (req, res) => {
try {
const buf = req.body; // Buffer
if (!buf || !buf.length) {
return res.status(400).json({ error: 'No file data received.' });
}
const zip = new AdmZip(buf);
const result = { metainfo: '', song: '', mediapool: '', audiomixer: '', notepad: '', notes: '' };
const filesToRead = {
'metainfo.xml': 'metainfo',
'Song/song.xml': 'song',
'Song/mediapool.xml': 'mediapool',
'Devices/audiomixer.xml': 'audiomixer',
'notepad.xml': 'notepad',
'notes.txt': 'notes'
};
for (const [zipEntryPath, key] of Object.entries(filesToRead)) {
const entry = zip.getEntry(zipEntryPath);
if (entry) {
let text = '';
try {
text = entry.getData().toString('utf8').replace(/^\uFEFF/, '');
} catch (e) {
text = entry.getData().toString('utf16le');
}
result[key] = text;
}
}
res.json(result);
} catch (err) {
console.error('Error parsing uploaded .song:', err);
res.status(500).json({ error: `Failed to parse uploaded .song: ${err.message}` });
}
});
// 3. Scan physical Media/ directory and compare with mediapool active files
app.get('/api/media-status', (req, res) => {
const { projectDir } = req.query;
if (!projectDir || !fs.existsSync(projectDir)) {
return res.status(404).json({ error: 'Project folder not found.' });
}
const mediaDir = path.join(projectDir, 'Media');
const filesOnDisk = [];
if (fs.existsSync(mediaDir)) {
try {
const items = fs.readdirSync(mediaDir);
for (const item of items) {
const itemPath = path.join(mediaDir, item);
if (fs.statSync(itemPath).isFile()) {
const stats = fs.statSync(itemPath);
filesOnDisk.push({
name: item,
path: itemPath,
size: stats.size,
mtime: stats.mtime
});
}
}
} catch (e) {
console.error('Error scanning media dir:', e);
}
}
const backupDir = path.join(projectDir, 'Backup_Unused_Media');
const filesInBackup = [];
if (fs.existsSync(backupDir)) {
try {
const items = fs.readdirSync(backupDir);
for (const item of items) {
const itemPath = path.join(backupDir, item);
if (fs.statSync(itemPath).isFile()) {
const stats = fs.statSync(itemPath);
filesInBackup.push({
name: item,
path: itemPath,
size: stats.size,
mtime: stats.mtime
});
}
}
} catch (e) {
console.error('Error scanning backup dir:', e);
}
}
// Gather all used media filenames across all versions
const usedMediaAcrossVersions = new Set();
try {
const songFiles = [];
const mainFiles = fs.readdirSync(projectDir);
mainFiles.forEach(f => {
if (f.endsWith('.song')) {
songFiles.push(path.join(projectDir, f));
}
});
const historyDir = path.join(projectDir, 'History');
if (fs.existsSync(historyDir)) {
const historyFiles = fs.readdirSync(historyDir);
historyFiles.forEach(f => {
if (f.endsWith('.song')) {
songFiles.push(path.join(historyDir, f));
}
});
}
songFiles.forEach(songPath => {
try {
const zip = new AdmZip(songPath);
const poolEntry = zip.getEntry('Song/mediapool.xml');
if (poolEntry) {
const xmlText = poolEntry.getData().toString('utf8');
const clipRegex = /<AudioClip[^>]*useCount="([^"]+)"[^>]*>([\s\S]*?)<\/AudioClip>/g;
let match;
while ((match = clipRegex.exec(xmlText)) !== null) {
const useCount = parseInt(match[1], 10);
if (useCount > 0) {
const inner = match[2];
const urlMatch = inner.match(/url="([^"]+)"/i);
if (urlMatch) {
const fileUrl = urlMatch[1];
const filename = fileUrl.split(/[/\\]/).pop().toLowerCase();
usedMediaAcrossVersions.add(filename);
}
}
}
}
} catch (e) {
// ignore zip reading errors for snapshots
}
});
} catch (err) {
console.error("Error gathering media references across versions:", err);
}
res.json({
filesOnDisk,
filesInBackup,
usedMediaAcrossVersions: Array.from(usedMediaAcrossVersions)
});
});
// 4. Move unused files to a backup directory inside the project
app.post('/api/clean-media', (req, res) => {
const { projectDir, filesToClean } = req.body; // filesToClean is array of filenames
if (!projectDir || !fs.existsSync(projectDir)) {
return res.status(404).json({ error: 'Project folder not found.' });
}
const mediaDir = path.join(projectDir, 'Media');
const backupDir = path.join(projectDir, 'Backup_Unused_Media');
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true });
}
const moved = [];
const errors = [];
for (const filename of filesToClean) {
const srcPath = path.join(mediaDir, filename);
const destPath = path.join(backupDir, filename);
if (fs.existsSync(srcPath)) {
try {
fs.renameSync(srcPath, destPath);
moved.push(filename);
} catch (err) {
errors.push({ filename, error: err.message });
}
} else {
errors.push({ filename, error: 'File does not exist on disk' });
}
}
res.json({ success: true, moved, errors, backupDir });
});
// 4.5. Move files from Backup_Unused_Media back to Media folder (Undo Clean)
app.post('/api/restore-media', (req, res) => {
const { projectDir, filesToRestore } = req.body;
if (!projectDir || !fs.existsSync(projectDir)) {
return res.status(404).json({ error: 'Project folder not found.' });
}
const mediaDir = path.join(projectDir, 'Media');
const backupDir = path.join(projectDir, 'Backup_Unused_Media');
if (!fs.existsSync(mediaDir)) {
fs.mkdirSync(mediaDir, { recursive: true });
}
const restored = [];
const errors = [];
for (const filename of filesToRestore) {
const srcPath = path.join(backupDir, filename);
const destPath = path.join(mediaDir, filename);
if (fs.existsSync(srcPath)) {
try {
fs.renameSync(srcPath, destPath);
restored.push(filename);
} catch (err) {
errors.push({ filename, error: err.message });
}
} else {
errors.push({ filename, error: 'File does not exist in backup' });
}
}
res.json({ success: true, restored, errors });
});
// 4.6. Workspace Plugin Audit: scans all projects in parent workspace
app.get('/api/workspace-audit', (req, res) => {
const projects = scanProjects(WORKSPACE_DIR);
const totalProjects = projects.length;
const pluginCounts = {};
const pluginRegistry = {}; // classID -> name
const stockPlugins = new Set([
"Pro EQ", "Pro EQ³", "Compressor", "Limiter", "Binaural Pan", "Beat Delay",
"Analog Delay", "Room Reverb", "MixVerb", "RedLightDist", "Ampire", "Pedalboard",
"Autofilter", "Chorus", "Flanger", "Phaser", "Tremolo", "X-Trem", "Rotary",
"Gate", "Expander", "Limiter2", "Fat Channel", "Pipeline", "Scope",
"Spectrum Meter", "Tuner", "Level Meter", "Dual Pan", "Splitter", "Console Shaper",
"CTC-1", "PortaCassette", "Vocoder", "Open AIR", "Empire", "Tone Generator",
"Input Delay", "Phase Meter", "IR Maker", "VU Meter"
]);
const projectComplexity = [];
for (const proj of projects) {
let trackCount = 0;
let pluginCount = 0;
let localPlugins = [];
try {
if (fs.existsSync(proj.songPath)) {
const zip = new AdmZip(proj.songPath);
// Count tracks from metainfo if available
const metainfoEntry = zip.getEntry('metainfo.xml');
if (metainfoEntry) {
const text = metainfoEntry.getData().toString('utf8');
const trackCountMatch = text.match(/id="Media:TrackCount"\s+value="(\d+)"/);
if (trackCountMatch) {
trackCount = parseInt(trackCountMatch[1]);
}
}
// Parse audiomixer to extract plugins
const mixerEntry = zip.getEntry('Devices/audiomixer.xml');
if (mixerEntry) {
const mixerText = mixerEntry.getData().toString('utf8');
const matches = mixerText.matchAll(/<Attributes\s+([^>]+)>/g);
for (const match of matches) {
const attribsStr = match[1];
if (attribsStr.includes('classID=')) {
const classIDMatch = attribsStr.match(/classID="([^"]+)"/);
const nameMatch = attribsStr.match(/name="([^"]+)"/);
if (classIDMatch && nameMatch) {
const name = nameMatch[1];
const classID = classIDMatch[1];
pluginCounts[name] = (pluginCounts[name] || 0) + 1;
pluginRegistry[classID] = name;
pluginCount++;
localPlugins.push(name);
}
}
}
}
}
} catch (e) {
console.error(`Error auditing project ${proj.name}:`, e);
}
projectComplexity.push({
name: proj.name,
songPath: proj.songPath,
trackCount,
pluginCount,
plugins: localPlugins
});
}
// Sort plugins by popularity
const sortedPlugins = Object.entries(pluginCounts)
.map(([name, count]) => ({
name,
count,
isStock: stockPlugins.has(name)
}))
.sort((a, b) => b.count - a.count);
const workspacePlugins = Object.entries(pluginRegistry).map(([classID, name]) => {
let format = 'VST3';
if (stockPlugins.has(name)) {
format = 'Stock';
} else if (classID.startsWith('{565354')) {
format = 'VST2';
} else if (classID.toLowerCase().startsWith('{4155') || classID.toLowerCase().startsWith('{4175')) {
format = 'Audio Unit (AU)';
}
return { name, classID, format };
});
res.json({
totalProjects,
plugins: sortedPlugins,
projectComplexity,
workspacePlugins
});
});
// 4.7. Package project for collaboration: copies song and active files to collab ZIP
app.post('/api/package-project', (req, res) => {
const { projectDir, activeFiles, songName } = req.body;
if (!projectDir || !fs.existsSync(projectDir)) {
return res.status(404).json({ error: 'Project folder not found.' });
}
try {
const songPath = path.join(projectDir, songName);
const mediaDir = path.join(projectDir, 'Media');
const collabZipName = `${path.basename(projectDir)} - Collab.zip`;
const collabZipPath = path.join(projectDir, collabZipName);
const zip = new AdmZip();
// 1. Add the .song file
if (fs.existsSync(songPath)) {
zip.addLocalFile(songPath);
} else {
throw new Error(`Song file ${songName} not found in project folder.`);
}
// 2. Add only the active media files
if (fs.existsSync(mediaDir)) {
for (const filename of activeFiles) {
const filePath = path.join(mediaDir, filename);
if (fs.existsSync(filePath)) {
// Add into a 'Media' directory within the zip
zip.addLocalFile(filePath, 'Media');
}
}
}
// Write zip to project folder
zip.writeZip(collabZipPath);
const stats = fs.statSync(collabZipPath);
res.json({
success: true,
collabZipPath,
filename: collabZipName,
size: stats.size
});
} catch (err) {
console.error('Error packaging project:', err);
res.status(500).json({ error: `Failed to package collaboration project: ${err.message}` });
}
});
// Helper: Update XML colors based on keyword rules
function updateXmlColors(xmlContent, rules) {
const tagRegex = /<(MediaTrack|AudioTrackChannel|AudioSynthChannel|AudioGroupChannel|AudioOutputChannel|FolderTrack|ChordTrack|ArrangerTrack|LyricsTrack|VideoTrack|SynthTrack)\s+([^>]+)>/g;
return xmlContent.replace(tagRegex, (match, tagName, attrsStr) => {
const nameMatch = attrsStr.match(/name="([^"]+)"/);
if (!nameMatch) return match;
const name = nameMatch[1];
const matchingRule = rules.find(r => {
const pat = r.pattern.toLowerCase().trim();
return pat && name.toLowerCase().includes(pat);
});
if (matchingRule) {
let targetColor = matchingRule.color.toLowerCase().replace('#', '');
if (targetColor.length === 6) {
targetColor = 'ff' + targetColor;
}
let updatedAttrs = attrsStr;
if (attrsStr.includes('color=')) {
updatedAttrs = attrsStr.replace(/color="[^"]*"/, `color="${targetColor}"`);
} else {
updatedAttrs = attrsStr + ` color="${targetColor}"`;
}
return `<${tagName} ${updatedAttrs}>`;
}
return match;
});
}
// API: Recolor tracks in a project
app.post('/api/recolor-tracks', (req, res) => {
const { songPath, rules } = req.body;
if (!songPath || !fs.existsSync(songPath)) {
return res.status(404).json({ error: 'Song file not found.' });
}
if (!rules || !Array.isArray(rules)) {
return res.status(400).json({ error: 'Rules array is required.' });
}
try {
const zip = new AdmZip(songPath);
// 1. Process Song/song.xml
const songEntry = zip.getEntry('Song/song.xml');
if (songEntry) {
let xml = songEntry.getData().toString('utf8');
xml = updateXmlColors(xml, rules);
zip.updateFile('Song/song.xml', Buffer.from(xml, 'utf8'));
}
// 2. Process Devices/audiomixer.xml
const mixerEntry = zip.getEntry('Devices/audiomixer.xml');
if (mixerEntry) {
let xml = mixerEntry.getData().toString('utf8');
xml = updateXmlColors(xml, rules);
zip.updateFile('Devices/audiomixer.xml', Buffer.from(xml, 'utf8'));
}
// Write changes back to the .song ZIP
zip.writeZip(songPath);
res.json({ success: true });
} catch (err) {
console.error('Error recoloring tracks:', err);
res.status(500).json({ error: `Failed to recolor tracks: ${err.message}` });
}
});
// API: Remap VST classIDs and names in Devices/audiomixer.xml
app.post('/api/remap-plugins', (req, res) => {
const { songPath, rules } = req.body;
if (!songPath || !fs.existsSync(songPath)) {
return res.status(404).json({ error: 'Song file not found.' });
}
if (!rules || !Array.isArray(rules) || rules.length === 0) {
return res.status(400).json({ error: 'Rules array is required.' });
}
try {
const projectDir = path.dirname(songPath);
// 1. Create a backup snapshot in History/
const historyDir = path.join(projectDir, 'History');
if (!fs.existsSync(historyDir)) {
fs.mkdirSync(historyDir, { recursive: true });
}
const date = new Date();
const pad = (n) => String(n).padStart(2, '0');
const timestamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
const baseName = path.basename(songPath, '.song');
const backupName = `${baseName} ${timestamp} (Before Plugin Remap).song`;
const backupPath = path.join(historyDir, backupName);
fs.copyFileSync(songPath, backupPath);
console.log(`Created plugin remap backup at: ${backupPath}`);
// 2. Open ZIP and modify Devices/audiomixer.xml
const zip = new AdmZip(songPath);
const mixerEntry = zip.getEntry('Devices/audiomixer.xml');
if (mixerEntry) {
let xml = mixerEntry.getData().toString('utf8');
rules.forEach(rule => {
// Remap classIDs
const srcClassID = rule.sourceClassID;
const targetClassID = rule.targetClassID;
const escapedClassID = srcClassID.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const classIDRegex = new RegExp(`classID="${escapedClassID}"`, 'g');
xml = xml.replace(classIDRegex, `classID="${targetClassID}"`);
// Remap names
const srcName = rule.sourceName;
const targetName = rule.targetName;
const escapedName = srcName.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
const nameRegex = new RegExp(`name="${escapedName}"`, 'g');
xml = xml.replace(nameRegex, `name="${targetName}"`);
});
zip.updateFile('Devices/audiomixer.xml', Buffer.from(xml, 'utf8'));
}
// Write changes back to the ZIP
zip.writeZip(songPath);
res.json({ success: true, backupName });
} catch (err) {
console.error('Error remapping plugins:', err);
res.status(500).json({ error: `Failed to remap plugins: ${err.message}` });
}
});
// XML escaping helper
function escapeXml(unsafe) {
return unsafe.replace(/[<>&'"]/g, function (c) {
switch (c) {
case '<': return '<';
case '>': return '>';
case '&': return '&';
case '\'': return ''';
case '"': return '"';
}
});
}
// XML unescaping helper
function unescapeXml(safe) {
return safe.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, "'");
}
// Convert file URL to OS path
function fileUrlToPath(url) {
let unescaped = unescapeXml(url);
let pathPart = unescaped.replace(/^file:\/\/\//i, '').replace(/^file:\/\//i, '');
try {
pathPart = decodeURIComponent(pathPart);
} catch (e) {
// ignore
}
return path.normalize(pathPart);
}
// Helper: walk directory recursively and index standard media files
function buildWorkspaceIndex(baseDir) {
const index = new Map(); // filename.toLowerCase() -> array of absolute paths
let count = 0;
function walk(dir, depth = 0) {
if (depth > 6) return;
if (count > 50000) return;
try {
const items = fs.readdirSync(dir);
for (const item of items) {
if (item.startsWith('.') || item === 'node_modules' || item === 'System Volume Information' || item === 'History' || item === 'Backup_Unused_Media') {
continue;
}
const fullPath = path.join(dir, item);
try {
const stat = fs.statSync(fullPath);
if (stat.isFile()) {
const ext = path.extname(item).toLowerCase();
const mediaExtensions = ['.wav', '.mp3', '.ogg', '.flac', '.aif', '.aiff', '.mid', '.midi', '.mp4', '.m4a', '.mov', '.avi'];
if (mediaExtensions.includes(ext)) {
const lowerName = item.toLowerCase();
if (!index.has(lowerName)) {
index.set(lowerName, []);
}
index.get(lowerName).push(fullPath);
count++;
}
} else if (stat.isDirectory()) {
walk(fullPath, depth + 1);
}
} catch (e) {
// ignore
}
}
} catch (e) {
// ignore
}
}
walk(baseDir);
return index;
}
// Endpoint: get missing media clips status and scan workspace for relocations
app.get('/api/media-relink-status', (req, res) => {
const { songPath, customSearchDir, scanSplice } = req.query;
if (!songPath || !fs.existsSync(songPath)) {
return res.status(404).json({ error: 'Song file not found.' });
}
try {
const zip = new AdmZip(songPath);
const mediapoolEntry = zip.getEntry('Song/mediapool.xml');
if (!mediapoolEntry) {
return res.json({ success: true, missingClips: [] });
}
const xmlText = mediapoolEntry.getData().toString('utf8').replace(/^\uFEFF/, '');
// Find all file:/// URLs
const fileUrls = new Set();
let match;
const urlRegex = /url="(file:\/\/[^"]+)"/gi;
while ((match = urlRegex.exec(xmlText)) !== null) {
fileUrls.add(match[1]);
}
// Index the workspace
const index = buildWorkspaceIndex(WORKSPACE_DIR);
// Index project directory if it is different
const projDir = path.dirname(songPath);
if (!projDir.startsWith(WORKSPACE_DIR)) {
const projIndex = buildWorkspaceIndex(projDir);
for (const [key, paths] of projIndex.entries()) {
if (!index.has(key)) {
index.set(key, []);
}
paths.forEach(p => {
if (!index.get(key).includes(p)) {
index.get(key).push(p);
}