This repository was archived by the owner on Feb 9, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtoolset.js
More file actions
1117 lines (935 loc) · 45.2 KB
/
toolset.js
File metadata and controls
1117 lines (935 loc) · 45.2 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
(async () => {
require('dotenv').config()
const asar = require('@electron/asar');
const minimist = require('minimist');
const fs = require('fs');
const fsp = require('fs').promises;
const path = require('path');
const semver = require('semver');
const crypto = require('crypto');
const plist = require('plist');
const { minify } = require('terser');
const { Octokit } = await import('@octokit/rest');
const { execSync } = require('child_process');
const { exec, spawn } = require('child_process');
const { promisify } = require('util');
const archiver = require("archiver");
const execAsync = promisify(exec);
const spawnAsync = promisify(spawn);
const SRC_PATH = path.join(process.argv[1], '../src');
const DEFAULT_DIST_PATH = path.join(process.argv[1], '../builds/latest/app.asar');
const DEFAULT_PATCHED_DIST_PATH = path.join(process.argv[1], '../builds/patched/app.asar');
const EXTRACTED_DIR_PATH = path.join(process.argv[1], '../extracted');
const MAC_APP_PATH = '/Applications/Яндекс Музыка.app';
const WINDOWS_APP_PATH = path.join(process.env?.LOCALAPPDATA ?? '', '/Programs/YandexMusic');
const WINDOWS_EXE_PATH = path.join(WINDOWS_APP_PATH ?? '', 'Яндекс Музыка.exe');
const DIRECT_DIST_PATH = process.platform === 'darwin' ? path.join(MAC_APP_PATH, '/Contents/Resources/app.asar') : path.join(WINDOWS_APP_PATH, "resources/app.asar");
const INFO_PLIST_PATH = path.join(MAC_APP_PATH, '/Contents/Info.plist');
if(process.platform === 'darwin') {
if(!fs.existsSync(DIRECT_DIST_PATH)) {
console.warn('Не удалось найти директорию с Яндекс Музыкой:', DIRECT_DIST_PATH, '\nПереопределите MAC_APP_PATH в toolset.js');
}
if(!fs.existsSync(INFO_PLIST_PATH)) {
console.warn('Не удалось найти Info.plist:', INFO_PLIST_PATH, '\nПереопределите MAC_APP_PATH в toolset.js');
}
}
if(!fs.existsSync(DIRECT_DIST_PATH)) {
console.warn('Не удалось найти директорию с Яндекс Музыкой:', DIRECT_DIST_PATH, '\nПереопределите WINDOWS_APP_PATH в toolset.js');
}
const MINIFIED_SRC_PATH = path.join(process.argv[1], "../minified/src");
const TEMP_DIR = path.join(process.argv[1], "../temp");
if(!fs.existsSync(TEMP_DIR)) {
fs.mkdirSync(TEMP_DIR, { recursive: true });
console.log('Создана временная директория:', TEMP_DIR);
}
const EXTRACTED_ENTITLEMENTS_PATH = path.join(TEMP_DIR, "extracted_entitlements.xml");
const PATCH_NOTES_PATH = path.join(process.argv[1], "../PATCHNOTES.md");
const GITHUB_TOKEN = process.env.GITHUB_TOKEN;
const gitOwner = 'TheKing-OfTime';
const gitRepo = 'YandexMusicModClient';
const webhookUrl = process.env.DISCORD_WEBHOOK_URL;
const patchNoteStringMD = fs.readFileSync(PATCH_NOTES_PATH, { encoding: "utf8"});
const octokit = new Octokit({ auth: GITHUB_TOKEN });
let oldYMHash;
let oldYMHashOverride;
class PatchNote {
static forSpoofPatch(ymVersion, version, previousYmVersion) {
return new PatchNote(ymVersion, version, `# Что нового\n- Версия спуфнута c ${previousYmVersion} до ${ymVersion}`)
}
constructor(ymVersion, version, patchNoteString) {
this.ymVersion = ymVersion;
this.version = version;
this.patchNoteString = patchNoteString;
}
toDiscord(){
return `# Client ${this.version}\n\n${this.patchNoteString}`
}
toGitHub(){
return `## Патч для Яндекс Музыки ${this.ymVersion}\n\n${this.patchNoteString}\n\n`
}
}
/**
* Архивирует папку в zip
* @param {String} folderPath - путь к папке
* @param {String} outputZipPath - путь для сохранения архива
* @returns {Promise<String>} - путь к архиву
*/
function zipFolder(folderPath, outputZipPath) {
return new Promise((resolve, reject) => {
const output = fs.createWriteStream(outputZipPath);
const archive = archiver("zip", { zlib: { level: 9 } });
output.on("close", () => resolve(outputZipPath));
archive.on("error", reject);
archive.pipe(output);
archive.directory(folderPath, false);
archive.finalize();
});
}
/**
*
* @param {PatchNote} patchNote
* @return {Promise<void>}
*/
async function sendPatchNoteToDiscord(patchNote) {
const webhookResponse = await fetch(webhookUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
"content": patchNote.toDiscord(),
}),
});
if (!webhookResponse.ok) {
throw new Error(`Не удалось отправить webhook: ${webhookResponse.statusText}`);
}
console.log('Патчноут отправлен в Discord')
}
async function getLatestExtractedSrcDir(toPatched = false) {
let version = '1.0.0'
const versions = (await fsp.readdir(EXTRACTED_DIR_PATH, { withFileTypes: true })).filter(
(dirent) => {
return dirent.isDirectory() && dirent.name.endsWith('@pure');
},
).map(dirstr => dirstr.name.replace('@pure',''));
versions.forEach(ver=>{if(semver.gt(ver, version)) version = ver});
if(version === '1.0.0') return console.log('Не удалось получить последний релиз из ./extracted/')
return path.join(EXTRACTED_DIR_PATH, `/${version}${toPatched ? '' : '@pure'}`);
}
async function getLatestYMVersion(type='direct', srcPath=undefined) {
let packageFileBuffer;
switch (type) {
default:
case 'direct':
packageFileBuffer = asar.extractFile(DIRECT_DIST_PATH, 'package.json').toString();
break;
case 'extracted':
let extractedPathDir = await getLatestExtractedSrcDir();
if(!extractedPathDir) return console.log('Не удалось получить последнюю версию YM')
packageFileBuffer = await fsp.readFile(path.join(extractedPathDir, '/package.json'), 'utf8')
break;
case 'src':
packageFileBuffer = await fsp.readFile(path.join(SRC_PATH, '/package.json'), 'utf8')
break;
case 'customSrc':
packageFileBuffer = await fsp.readFile(path.join(srcPath, '/package.json'), 'utf8')
break;
case 'customAsar':
packageFileBuffer = asar.extractFile(srcPath, 'package.json').toString();
break;
}
const packageFileJson = JSON.parse(packageFileBuffer);
return { version: packageFileJson.version, buildInfo: packageFileJson.buildInfo, modification: packageFileJson.modification };
}
function getModVersion() {
return require(path.join(SRC_PATH, "/main/config.js")).config.modification
.version;
}
async function modifyPackage({src = SRC_PATH, version=undefined, buildInfo=undefined, modVersion=undefined, appConfig=undefined }) {
let packageJson = JSON.parse(await fsp.readFile(path.join(src, '/package.json'), 'utf8'));
const oldVersion = packageJson.version;
if (version) packageJson.version = version;
if (buildInfo || version) packageJson.buildInfo = buildInfo ?? { "VERSION": version, "BRANCH": "c3903938d4df76688c4639330c6834cd5ea664f2", "BUILD_TIME": "2025-11-13T15:37:20Z"}; // TODO: Поразмыслить как сделать по нормальному для сборки мейна через Роллап
if (modVersion) packageJson.modification.version = modVersion;
if (appConfig) packageJson.appConfig = {...packageJson.appConfig, ...appConfig};
await fsp.writeFile(path.join(src, '/package.json'), JSON.stringify(packageJson, null, 2), 'utf8');
return { oldVersion: oldVersion, newVersion: version }
}
async function getLatestRelease() {
const response = await octokit.rest.repos.getLatestRelease({
owner: gitOwner,
repo: gitRepo,
});
if (!response.status.toString().startsWith('2')) return console.log("Не удалось получить последний релиз:", response.data);
return response.data;
}
async function createAndPushSpoofCommit(oldVersion=undefined, newVersion=undefined) {
const currentCommit = await octokit.repos.getCommit({
owner: gitOwner,
repo: gitRepo,
ref: 'master'
});
const modifiedFiles = [
{ path: 'src/main/config.js' },
{ path: 'src/package.json' }
];
const createBlobPromises = modifiedFiles.map(file => {
const content = fs.readFileSync(path.join(SRC_PATH, '..', file.path), 'utf8');
return octokit.git.createBlob({
owner: gitOwner,
repo: gitRepo,
content: content,
encoding: 'utf-8'
});
});
const blobs = await Promise.all(createBlobPromises);
const tree = await octokit.git.createTree({
owner: gitOwner,
repo: gitRepo,
base_tree: currentCommit.data.commit.tree.sha,
tree: blobs.map((blob, index) => ({
path: modifiedFiles[index].path,
mode: '100644',
type: 'blob',
sha: blob.data.sha
}))
});
const commitResponse = await octokit.git.createCommit({
owner: gitOwner,
repo: gitRepo,
message: (oldVersion && newVersion) ? `chore: Spoof version from ${oldVersion} to ${newVersion}` : 'chore: Spoof version',
tree: tree.data.sha,
parents: [currentCommit.data.sha]
});
await octokit.git.updateRef({
owner: gitOwner,
repo: gitRepo,
ref: 'heads/master',
sha: commitResponse.data.sha,
force: true
});
if (!commitResponse.status.toString().startsWith('2')) return console.log("Не удалось создать коммит:", commitResponse.data);
console.log("Коммит успешно создан и отправлен в репозиторий");
}
/**
* Загружает ассет в GitHub релиз с ретраями
* @param {Object} octokit
* @param {String} gitOwner
* @param {String} gitRepo
* @param {Number} releaseId
* @param {String} asarPath
* @param {Number} [maxRetries=3]
* @returns {Promise<Object>} uploadResponse
*/
async function uploadReleaseAssetWithRetry(octokit, gitOwner, gitRepo, releaseId, asarPath, maxRetries = 3) {
const assetData = fs.readFileSync(asarPath);
let uploadResponse = undefined;
const assetName = path.basename(asarPath);
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
console.time(`Ассет успешно загружен ${assetName}`);
console.log(`Загрузка ассета ${assetName}...`);
uploadResponse = await octokit.repos.uploadReleaseAsset({
owner: gitOwner,
repo: gitRepo,
release_id: releaseId,
name: assetName,
data: assetData,
headers: {
"content-type": "application/octet-stream",
"content-length": assetData.length,
},
});
console.timeEnd(`Ассет успешно загружен ${assetName}`);
break;
} catch (err) {
console.warn(`Попытка #${attempt} загрузки ассета ${assetName} не удалась:`, err.message);
if (attempt === maxRetries) throw err;
console.warn(`Повторная попытка загрузки ассета через ${(2000 * attempt) / 1000} секунды...`);
await new Promise(res => setTimeout(res, 2000 * attempt));
}
}
return uploadResponse;
}
/**
* Загружает папку как asset (архивирует и загружает)
* @param {Object} octokit
* @param {String} gitOwner
* @param {String} gitRepo
* @param {Number} releaseId
* @param {String} folderPath
* @param {String} assetName - имя ассета (например, "build.zip")
* @param {Number} [maxRetries=3]
*/
async function uploadFolderAsAssetWithRetry(octokit, gitOwner, gitRepo, releaseId, folderPath, assetName, maxRetries = 3) {
if (!fs.existsSync(folderPath)) return undefined;
const tmpZipPath = path.join(path.dirname(folderPath), assetName); // например, build.zip
await zipFolder(folderPath, tmpZipPath);
const assetData = fs.readFileSync(tmpZipPath);
let uploadResponse = undefined;
for (let attempt = 1; attempt <= maxRetries; attempt++) {
try {
console.time(`Ассет успешно загружен ${assetName}`);
console.log(`Загрузка ассета ${assetName}...`);
uploadResponse = await octokit.repos.uploadReleaseAsset({
owner: gitOwner,
repo: gitRepo,
release_id: releaseId,
name: assetName,
data: assetData,
headers: {
"content-type": "application/zip",
"content-length": assetData.length,
},
});
console.timeEnd(`Ассет успешно загружен ${assetName}`);
break;
} catch (err) {
console.warn(`Попытка #${attempt} загрузки ассета ${assetName} не удалась:`, err.message);
if (attempt === maxRetries) throw err;
console.warn(`Повторная попытка загрузки ассета через ${(2000 * attempt) / 1000} секунды...`);
await new Promise(res => setTimeout(res, 2000 * attempt));
}
}
fs.unlinkSync(tmpZipPath); // удаляем временный архив
return uploadResponse;
}
/**
*
* @param {String} version
* @param {String} asarPath
* @param {PatchNote} patchNote
* @return {Promise<void>}
*/
async function createGitHubRelease(version, asarPath, patchNote) {
const tagCreateResponse = await octokit.git.createRef({
owner: gitOwner,
repo: gitRepo,
ref: `refs/tags/onlyDiscordRPC@${version}`,
sha: (await octokit.repos.getCommit({ owner: gitOwner, repo: gitRepo, ref: 'master' })).data.sha,
});
if (!tagCreateResponse.status.toString().startsWith('2'))
return console.log("Не удалось создать тег", tagCreateResponse.data);
console.log("Тег успешно создан");
const releaseResponse = await octokit.rest.repos.createRelease({
owner: gitOwner,
repo: gitRepo,
tag_name: `onlyDiscordRPC@${version}`,
name: version,
draft: true,
prerelease: false,
body: patchNote.toGitHub()
});
if (!releaseResponse.status.toString().startsWith('2'))
return console.log("Не удалось создать драфт:", releaseResponse.data);
console.log("Драфт успешно создан");
const assetName = path.basename(asarPath);
const dirPath = path.dirname(asarPath);
const asarUnpackedPath = path.join(dirPath, 'app.asar.unpacked');
const asarUploadResponse = await uploadReleaseAssetWithRetry(
octokit,
gitOwner,
gitRepo,
releaseResponse.data.id,
asarPath
);
if (!asarUploadResponse.status.toString().startsWith('2'))
return console.log(`Не удалось загрузить ассет ${assetName}:`, releaseResponse.data);
const asarUnpackedUploadResponse = await uploadFolderAsAssetWithRetry(
octokit,
gitOwner,
gitRepo,
releaseResponse.data.id,
asarUnpackedPath, // путь к папке
"app.asar.unpacked.zip" // имя ассета
);
if (!asarUnpackedUploadResponse.status.toString().startsWith('2'))
return console.log('Не удалось загрузить ассет app.asar.unpacked:', releaseResponse.data);
const updatedRelease = await octokit.repos.updateRelease({
owner: gitOwner,
repo: gitRepo,
release_id: releaseResponse.data.id,
draft: false,
});
if (!updatedRelease.status.toString().startsWith('2'))
return console.log("Не удалось опубликовать релиз:", releaseResponse.data);
console.log("Релиз опубликован");
}
async function minifyDir(srcDir, destDir) {
await fsp.mkdir(destDir, { recursive: true });
const items = await fsp.readdir(srcDir);
for (const item of items) {
const srcPath = path.join(srcDir, item);
const destPath = path.join(destDir, item);
const stat = await fsp.stat(srcPath);
if (stat.isFile() && srcPath.endsWith('.js')) {
try {
console.time(` Минифицирован: ${destPath}`);
const code = await fsp.readFile(srcPath, 'utf8');
const result = await minify(code);
if (result.error) {
console.error(` Ошибка минификации ${destPath}:`, result.error);
continue;
}
await fsp.writeFile(destPath, result.code, 'utf8');
console.timeEnd(` Минифицирован: ${destPath}`);
} catch (err) {
console.warn(` Ошибка при минификации ${destPath}:`, err);
await fsp.cp(srcPath, destPath, { recursive: true })
console.log(` Пропущен и скопирован: ${destPath}`);
}
} else if (stat.isDirectory()) {
await minifyDir(srcPath, destPath);
} else {
await fsp.cp(srcPath, destPath, { recursive: true })
console.log(` Скопирован: ${destPath}`);
}
}
}
function hashDirFiltered(
dir,
ignore = [
'node_modules',
'dist',
'build',
'.build-meta.json',
'.git',
'.DS_Store'
]
) {
const hash = crypto.createHash('sha256');
function walk(p) {
const entries = fs.readdirSync(p, { withFileTypes: true });
for (const e of entries) {
if (ignore.includes(e.name)) continue;
const full = path.join(p, e.name);
if (e.isDirectory()) {
walk(full);
} else {
hash.update(e.name);
hash.update(fs.readFileSync(full));
}
}
}
walk(dir);
return hash.digest('hex');
}
function getNativeBuildKey(nativeDir) {
return crypto
.createHash('sha256')
.update(JSON.stringify({
sourcesHash: hashDirFiltered(nativeDir),
abi: process.versions.modules,
platform: process.platform,
arch: process.arch
}))
.digest('hex');
}
/**
* Сборка и копирование нативного модуля
* @param {string} moduleName - имя папки с модулем (например, setIconicThumbnail)
*/
async function buildNativeModule(moduleName) {
const nativeDir = path.join(__dirname, 'native', moduleName);
const gypPath = path.join(nativeDir, 'binding.gyp');
if (!fs.existsSync(gypPath)) throw new Error(`Не найден binding.gyp в ${nativeDir}`);
const gyp = JSON.parse(
fs.readFileSync(gypPath, 'utf8')
.replace(/\/\/.*$/mg, '')
.replace(/,\s*]/g, ']')
.replace(/,\s*}/g, '}')
);
const targetName = gyp.targets?.[0]?.target_name;
if (!targetName) throw new Error('Не удалось получить target_name');
const destDir = path.join(__dirname, 'src', 'main', 'native_modules', targetName);
const destNode = path.join(destDir, `${targetName}.node`);
const metaPath = path.join(destDir, '.build-meta.json');
const buildKey = getNativeBuildKey(nativeDir);
if (
fs.existsSync(destNode) &&
fs.existsSync(metaPath) &&
JSON.parse(fs.readFileSync(metaPath, 'utf8')).buildKey === buildKey
) {
console.log(`⏩ Нативный модуль ${targetName} актуален — сборка пропущена`);
return;
}
console.log(`🔨 Сборка нативного модуля: ${targetName}`);
execSync('npm run build', { cwd: nativeDir, stdio: 'inherit' });
const builtNode = path.join(nativeDir, 'build', 'Release', `${targetName}.node`);
await fsp.mkdir(destDir, { recursive: true });
await fsp.copyFile(builtNode, destNode);
// JS wrapper
const jsDir = path.join(nativeDir, 'js');
if (fs.existsSync(jsDir)) {
for (const file of await fsp.readdir(jsDir)) {
await fsp.copyFile(
path.join(jsDir, file),
path.join(destDir, file)
);
}
}
fs.writeFileSync(metaPath, JSON.stringify({
buildKey,
builtAt: new Date().toISOString()
}, null, 2));
console.log(`✅ Модуль ${targetName} собран`);
}
async function buildNativeModules() {
console.log('Собираю нативные модули');
const nativeDir = path.join(__dirname, 'native');
const modules = (await fsp.readdir(nativeDir, {withFileTypes: true})).filter(dirent => dirent.isDirectory()).map(dirent => dirent.name);
for (const module of modules) {
await buildNativeModule(module)
}
}
async function buildMiniPlayer(force = false) {
const miniPlayerDir = path.join(__dirname, 'miniplayer');
const metaPath = path.join(miniPlayerDir, '.build-meta.json');
if (!fs.existsSync(miniPlayerDir)) {
console.log('Миниплеер не найден, сборка пропущена');
return;
}
const buildKey = crypto
.createHash('sha256')
.update(JSON.stringify({
sourcesHash: hashDirFiltered(miniPlayerDir),
node: process.version,
platform: process.platform,
arch: process.arch
}))
.digest('hex');
if (
!force &&
fs.existsSync(metaPath)
) {
const meta = JSON.parse(fs.readFileSync(metaPath, 'utf8'));
if (meta.buildKey === buildKey) {
console.log('⏩ Миниплеер актуален — сборка пропущена');
return;
}
}
console.log('🎵 Сборка миниплеера...');
console.time('Миниплеер собран');
execSync('npm install', {
cwd: miniPlayerDir,
stdio: 'inherit'
});
execSync('npm run build', {
cwd: miniPlayerDir,
stdio: 'inherit'
});
console.timeEnd('Миниплеер собран');
fs.writeFileSync(metaPath, JSON.stringify({
buildKey,
builtAt: new Date().toISOString()
}, null, 2));
console.log('✅ Миниплеер успешно собран');
}
async function build({ srcPath = SRC_PATH, destDir = DEFAULT_DIST_PATH, noMinify = false, noNativeModules = false } = { srcPath: SRC_PATH, destDir: DEFAULT_DIST_PATH, noMinify: false }) {
await buildMiniPlayer();
if (!noNativeModules) await buildNativeModules();
if (!noMinify) {
console.log("Минификация...");
console.time("Минификация завершена");
await minifyDir(srcPath, MINIFIED_SRC_PATH);
console.timeEnd("Минификация завершена");
}
console.log("Архивация из " + (noMinify ? srcPath : MINIFIED_SRC_PATH) + " в " + destDir);
console.time("Архивация завершена");
await asar.createPackageWithOptions(noMinify ? srcPath : MINIFIED_SRC_PATH, destDir, { unpackDir: "**/node_modules/{sharp,@img}/**/*" });
console.timeEnd("Архивация завершена");
if (!noMinify) {
await fsp.rm(MINIFIED_SRC_PATH, { recursive: true });
console.log("Минифицированный код отчищен");
}
}
async function buildDirectly(src, noMinify=false, noNativeModules=false, forceOpen=false) {
if (process.platform === "darwin" && checkIfSystemIntegrityProtectionEnabled()) {
console.log("System Integrity Protection включён. Обход невозможен, пожалуйста, отключите SIP для File System и попробуйте снова.");
return false;
}
oldYMHash = calcASARHeaderHash(DIRECT_DIST_PATH).hash;
const shouldReopen = await closeYandexMusic();
await build({srcPath: src, destDir: DIRECT_DIST_PATH, noMinify: noMinify, noNativeModules: noNativeModules });
await new Promise(resolve => setTimeout(resolve, 1000)); // Dirty delay. To make sure YM is closed
await bypassAsarIntegrity();
if( shouldReopen || forceOpen ) {
console.log('Запуск Яндекс Музыки...');
launchYandexMusic();
console.log('Яндекс Музыка запущена');
};
}
async function spoof(type='extracted', shouldRelease=false) {
console.log('Спуфинг...');
console.time('Спуфинг завершён');
let latestRelease, modVersion;
const versions = await getLatestYMVersion(type);
if (shouldRelease) {
latestRelease = await getLatestRelease();
modVersion = (await getLatestYMVersion('src')).modification.version;
}
console.log('Последняя версия ЯМ', versions);
const result = await modifyPackage({ version: versions.version, buildInfo: versions.buildInfo });
if(latestRelease) {
if(semver.lte(modVersion, latestRelease.name)) {
const nextVersion = semver.inc(latestRelease.name, 'patch');
await modifyPackage({ modVersion: nextVersion });
console.log('Версия мода изменена с', modVersion, 'на', nextVersion);
await createAndPushSpoofCommit(result.oldVersion, result.newVersion);
}
}
console.timeEnd('Спуфинг завершён');
console.log('Спуфнуто с', result.oldVersion, 'до', result.newVersion);
return result
}
async function release(dest, versions=undefined) {
const version = await getModVersion();
const {version: ymVersion} = await getLatestYMVersion();
const patchNote = (versions ? PatchNote.forSpoofPatch(versions.newVersion, version, versions.oldVersion) : new PatchNote(ymVersion, version, patchNoteStringMD));
await createGitHubRelease(version, dest, patchNote);
await sendPatchNoteToDiscord(patchNote);
}
async function extractIfNotExist(version, force=false, src=undefined) {
const extractedPathDir = path.join(EXTRACTED_DIR_PATH, version);
if(!force && fs.existsSync(extractedPathDir)) return console.log('Папка под ' + version + ' уже существует:', extractedPathDir);
await fsp.mkdir(extractedPathDir, { recursive: true });
await asar.extractAll(src ?? DIRECT_DIST_PATH, extractedPathDir);
console.log('Релиз ' + version + ' успешно извлечён в', extractedPathDir);
return extractedPathDir;
}
async function extractBuild(force=false, src=undefined, type='direct', withPure=true) {
if(!fs.existsSync(EXTRACTED_DIR_PATH)) {
await fsp.mkdir(EXTRACTED_DIR_PATH, { recursive: true });
}
const latestYMVersion = await getLatestYMVersion(type, src);
const pathToExtractedBuild = await extractIfNotExist(latestYMVersion.version, force, src);
if (withPure) {
const pathToPureExtractedBuild = await extractIfNotExist(`${latestYMVersion.version}@pure`, force);
return { pureExtracted: pathToPureExtractedBuild, extracted: pathToExtractedBuild }
}
return { extracted: pathToExtractedBuild }
}
async function replaceInFilesRecursively(dir, rules) {
const entries = await fsp.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
await replaceInFilesRecursively(fullPath, rules);
} else if (entry.isFile()) {
let content = await fsp.readFile(fullPath, 'utf8');
let newContent = content;
for (const { regex, replacement } of rules) {
newContent = newContent.replace(regex, replacement);
}
if (newContent !== content) {
await fsp.writeFile(fullPath, newContent, 'utf8');
console.log(`Вхождение найдено и заменено в: ${fullPath}`);
}
}
}
}
async function patchExtractedBuild(extractedPath, options = { unlockDevtools: true, unlockDevPanel: true }) {
console.log('Патчинг извлечённого релиза', extractedPath);
if (options.unlockDevtools) {
// Old way (Using it again because new YM version bundles all main files into main/index.js)
let indexJs = await fsp.readFile(path.join(extractedPath, "/index.js"),"utf8",);
indexJs = indexJs.replace(/const\s?webPreferences\s?=\s?\{/i, "const webPreferences = { devTools: true,",);
await fsp.writeFile(path.join(extractedPath, "/index.js"), indexJs, "utf8",);
// await modifyPackage({src: extractedPath, appConfig: { enableDevTools: true, enableUpdateByProbability: false } });
// console.log("Devtools Разблокированы", extractedPath);
}
if (options.unlockDevPanel) {
const rules = [
// Old way
// { regex: /panel: ?!1, ?allowOverwriteExperiments: ?!1/g, replacement: 'panel:!0,allowOverwriteExperiments:!0' },
// { regex: /exposeSonataStateInWindow: ?!1/g, replacement: 'exposeSonataStateInWindow:!0' },
{ regex: /e\.set\(c.qV, ?![10]\), ?e\.set\(c.yc, ?![10]\), ?e\.set\(c.W4, ?![10]\)/g, replacement: 'e.set(c.qV,!0),e.set(c.yc,!0),e.set(c.W4,!0)' },
]
console.log('Применяю regex патчи', extractedPath, rules);
await replaceInFilesRecursively(path.join(extractedPath, '/app/'), rules);
console.log('Regex патчи применены', extractedPath);
}
}
function calcASARHeaderHash(archivePath) {
const headerString = asar.getRawHeader(archivePath).headerString;
const hash = crypto.createHash('sha256').update(headerString).digest('hex');
return { algorithm: 'SHA256', hash };
}
function dumpEntitlements(appPath) {
try {
execSync(`codesign -d --entitlements :- '${appPath}' > '${EXTRACTED_ENTITLEMENTS_PATH}'`);
console.log(`Упакованы entitlements из ${appPath} в ${EXTRACTED_ENTITLEMENTS_PATH}`);
} catch (error) {
console.error(`Не удалось упаковать entitlements из ${appPath} в ${EXTRACTED_ENTITLEMENTS_PATH}.`, error);
}
}
function checkIfElectronAsarIntegrityIsUsed() {
try {
execSync(`plutil -p '${INFO_PLIST_PATH}' | grep -q ElectronAsarIntegrity`);
return true;
} catch {
return false;
}
}
function checkIfSystemIntegrityProtectionEnabled() {
try {
const response = execSync(`csrutil status`);
return response.includes('enabled');
} catch {
return false;
}
}
async function bypassWinAsarIntegrity(appPath) {
console.log(`Подготовка к замене хеша`);
try {
const exePath = appPath;
if (!fs.existsSync(exePath)) {
return console.log(`Файл не найден по пути: ${exePath}`);
}
// // 2) Создание резервной копии
// const backupPath = exePath + '.backup';
// if (!fs.existsSync(backupPath)) {
// fs.copyFileSync(exePath, backupPath);
// console.log(`Резервная копия создана: ${backupPath}`);
// } else {
// console.log(`Резервная копия уже существует: ${backupPath}`);
// }
// 3) Шаблоны (ASCII‑hex)
const oldHexStr = oldYMHashOverride ?? oldYMHash;
const newHexStr = calcASARHeaderHash(DIRECT_DIST_PATH).hash;
console.log(`Хеши: ${oldHexStr} ${newHexStr} ${oldHexStr.length} ${newHexStr.length}`);
if (oldHexStr.length !== newHexStr.length) {
return console.log('Длины старого и нового хеша не совпадают');
}
if (oldHexStr === newHexStr) {
return console.log('Старый и новый хеши совпадают, изменения не требуется');
}
const oldBuf = Buffer.from(oldHexStr, 'ascii');
const newBuf = Buffer.from(newHexStr, 'ascii');
// 4) Чтение, замена, запись
const fileBuf = fs.readFileSync(exePath);
let count = 0;
let offset = 0;
while (true) {
const idx = fileBuf.indexOf(oldBuf, offset);
if (idx === -1) break;
newBuf.copy(fileBuf, idx);
count++;
offset = idx + oldBuf.length;
}
if (count === 0) {
console.log('Шаблон не найден, изменений не внесено.');
} else {
fs.writeFileSync(exePath, fileBuf);
console.log(`Успешно заменено вхождений: ${count}.`);
}
} catch (err) {
console.log('Ошибка: ' + err.message);
}
}
async function bypassDarwinAsarIntegrity(appPath) {
if (process.platform !== 'darwin') {
console.log("Не удалось обойти asar integrity: Доступно только для macOS");
return false;
}
if (checkIfSystemIntegrityProtectionEnabled()) {
console.log("System Integrity Protection включён. Обход невозможен, пожалуйста, отключите SIP для File System и попробуйте снова.");
return false;
}
try {
if (checkIfElectronAsarIntegrityIsUsed()) {
console.log("Asar integrity включено. Обход");
const newHash = calcASARHeaderHash(DIRECT_DIST_PATH).hash;
console.log(`Хеш модифицированного asar: ${newHash}`);
console.log("Подменяю хеш в Info.plist");
const plistContent = fs.readFileSync(INFO_PLIST_PATH, 'utf8');
const plistData = plist.parse(plistContent);
plistData.ElectronAsarIntegrity["Resources/app.asar"].hash = newHash;
fs.writeFileSync(INFO_PLIST_PATH, plist.build(plistData));
}
console.log("Подменяю подпись");
dumpEntitlements(appPath);
execSync(`codesign --force --entitlements ${EXTRACTED_ENTITLEMENTS_PATH} --sign - '${appPath}'`);
fs.unlinkSync(EXTRACTED_ENTITLEMENTS_PATH);
console.log("Кеш очищен");
console.log("Обход asar integrity завершён");
} catch (error) {
console.error("Не удалось обойти asar integrity", error);
fs.unlinkSync(EXTRACTED_ENTITLEMENTS_PATH);
console.log("Кеш очищен");
}
}
async function bypassAsarIntegrity(dest=undefined) {
if (process.platform === "darwin") await bypassDarwinAsarIntegrity(dest ?? MAC_APP_PATH);
if (process.platform === "win32") await bypassWinAsarIntegrity(dest ?? WINDOWS_EXE_PATH);
}
// Copied from https://github.com/PulseSync-LLC/PulseSync-client/blob/dev/src/main/utils/appUtils.ts
async function getYandexMusicProcesses() {
if (process.platform === "darwin") {
try {
const command = `pgrep -f "Яндекс Музыка"`
const { stdout } = await execAsync(command, { encoding: 'utf8' })
const processes = stdout.split('\n').filter(line => line.trim() !== '')
return processes.map(pid => ({ pid: parseInt(pid, 10) })).filter(proc => !isNaN(proc.pid))
} catch (error) {
console.error('Ошибка выявления процесса Яндекс Музыки на Mac:', error)
return []
}
} else if (process.platform === "linux") {
try {
const command = `pgrep -fa "yandexmusic"`
const { stdout } = await execAsync(command, { encoding: 'utf8' })
const processes = stdout.split('\n')
.filter(line => line.trim() !== '')
.filter(line => !['pgrep', 'yandexmusicmodpatcher', 'YandexMusicModPatcher'].some(keyword => line.includes(keyword)))
return processes.map(line => {
const parts = line.split(' ');
const pid = parseInt(parts[0], 10);
return { pid };
}).filter(proc => !isNaN(proc.pid));
} catch (error) {
console.error('Ошибка выявления процесса Яндекс Музыки на Linux:', error)
return []
}
} else {
try {
const command = `tasklist /FI "IMAGENAME eq Яндекс Музыка.exe" /FO CSV /NH`
const { stdout } = await execAsync(command, { encoding: 'utf8' })
const processes = stdout.split('\n').filter(line => line.trim() !== '')
const yandexProcesses = []
processes.forEach(line => {
const parts = line.split('","')
if (parts.length > 1) {
const pidStr = parts[1].replace(/"/g, '').trim()
const pid = parseInt(pidStr, 10)
if (!isNaN(pid)) {
yandexProcesses.push({ pid })
}
}
})
return yandexProcesses
} catch (error) {
console.error('Ошибка выявления процесса Яндекс Музыки:', error)
return []
}
}
}
async function isYandexMusicRunning() {
return (await getYandexMusicProcesses())?.length > 0;
}
async function closeYandexMusic() {
const yandexProcesses = await getYandexMusicProcesses();
if (yandexProcesses.length === 0) {
console.log('Яндекс Музыка не запущена. Закрытие не требуется.');
return false;
}
console.log('Закрываю Яндекс Музыку...');
for (const proc of yandexProcesses) {
try {
process.kill(proc.pid)
console.log(`Процесс Яндекс Музыки с PID ${proc.pid} был завершён.`)
} catch (error) {
console.error(`Не удалось завершить процесс ${proc.pid}:`, error)
}
}
return true;