codeplay-common 2.1.51 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,891 +1,891 @@
1
- /*
2
- Can be run like
3
- node finalrelease
4
- node finalrelease 1
5
- node finalrelease "1,2,7"
6
- */
7
-
8
- import { existsSync, readFileSync, readdirSync, promises, constants, writeFileSync, unlinkSync, mkdirSync, renameSync } from 'fs';
9
- import { join, resolve } from 'path';
10
- import { execSync } from 'child_process';
11
- import { createInterface } from 'readline';
12
-
13
- import { fileURLToPath } from 'url';
14
- import { dirname } from 'path';
15
-
16
- /* const path = require('path');
17
- const fs = require('fs'); */
18
-
19
- import fs from 'fs';
20
- import path from 'path';
21
-
22
- // Define a mapping between store IDs and store names
23
- /* const storeNames = {
24
- "1": "PlayStore",
25
- "2": "SamsungStore",
26
- "7": "AmazonStore"
27
- }; */
28
-
29
- const storeNames = {
30
- "1": "PlayStore",
31
- "2": "SamsungStore",
32
- "7": "AmazonStore",
33
-
34
- "3": "MiStore",
35
- "4": "HuaweiStore",
36
- "5": "OppoStore",
37
- //"6": "iOSStore",
38
- "8": "VivoStore"
39
- };
40
-
41
-
42
- //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore
43
-
44
-
45
-
46
-
47
-
48
-
49
-
50
- let isAdmobFound = false;
51
-
52
- const amazonMinSdkVersion=24;
53
-
54
- const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
55
-
56
-
57
- const configPath = path.join(process.cwd(), 'capacitor.config.json');
58
- const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
59
-
60
- const _appUniqueId = config.android?.APP_UNIQUE_ID;
61
- const _appName=config.appName;
62
- const _appPackageId=config.appId;
63
-
64
-
65
-
66
- const __filename = fileURLToPath(import.meta.url);
67
- const __dirname = dirname(__filename);
68
-
69
- function fileExists(filePath) {
70
- return existsSync(filePath);
71
- }
72
-
73
-
74
- const ffmpegPluginXmlPath = path.join(__dirname, 'node_modules', 'codeplay-fmpg', 'plugin.xml');
75
- const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
76
-
77
-
78
-
79
- function isFfmpegUsed() {
80
- try {
81
- const xmlContent = fs.readFileSync(ffmpegPluginXmlPath, 'utf8');
82
- // Simple check: if plugin.xml exists and contains <plugin> tag (or any FFmpeg-specific tag)
83
- return /<plugin\b/.test(xmlContent);
84
- } catch (err) {
85
- console.log('⚠️ FFmpeg plugin not found:', err.message);
86
- return false;
87
- }
88
- }
89
-
90
- const _isffmpegUsed = isFfmpegUsed();
91
-
92
- function getAdMobConfig() {
93
- if (!fileExists(capacitorConfigPath)) {
94
- throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
95
- }
96
-
97
- const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
98
- const admobConfig = config.plugins?.AdMob;
99
-
100
- //_appPackageId=config.appId;
101
-
102
- if (!admobConfig) {
103
- throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
104
- }
105
-
106
- // Default to true if ADMOB_ENABLED is not specified
107
- const isEnabled = admobConfig.ADMOB_ENABLED !== false;
108
-
109
- if (!isEnabled) {
110
- return { ADMOB_ENABLED: false }; // Skip further validation
111
- }
112
-
113
- if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
114
- throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
115
- }
116
-
117
- return {
118
- ADMOB_ENABLED: true,
119
- APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
120
- APP_ID_IOS: admobConfig.APP_ID_IOS,
121
- USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
122
- };
123
- }
124
-
125
-
126
-
127
- const _capacitorConfig = getAdMobConfig();
128
-
129
- const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
130
-
131
- // Proceed only if ADMOB_ENABLED is true
132
- //if (_capacitorConfig.ADMOB_ENABLED)
133
-
134
-
135
- const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration.json');
136
- let admobConfig;
137
-
138
- if (_isADMOB_ENABLED)
139
- {
140
- try
141
- {
142
- admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
143
- }
144
- catch (err)
145
- {
146
- console.error("❌ Failed to read admob-ad-configuration.json", err);
147
- process.exit(1);
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
- const checkCommonFileStoreId=()=>{
173
- const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
174
- let viteConfigPath;
175
- for (const configFile of possibleConfigFiles) {
176
- const fullPath = resolve( configFile);
177
- if (existsSync(fullPath)) {
178
- viteConfigPath = fullPath;
179
- break;
180
- }
181
- }
182
-
183
- if (!viteConfigPath) {
184
- console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
185
- process.exit(1);
186
- }
187
-
188
- try {
189
- // Read vite config file
190
- const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
191
-
192
- // Extract @common alias path
193
- const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
194
- const match = viteConfigContent.match(aliasPattern);
195
-
196
- if (!match) {
197
- console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
198
- process.exit(1);
199
- }
200
-
201
- const commonFilePath = match[1];
202
- const resolvedCommonPath = resolve(__dirname, commonFilePath);
203
-
204
- // Read the common file content
205
- if (!existsSync(resolvedCommonPath)) {
206
- console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
207
- process.exit(1);
208
- }
209
-
210
- const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
211
-
212
- // Check for the _storeid export line
213
- const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
214
- if (!storeIdPattern.test(commonFileContent)) {
215
- console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
216
- process.exit(1);
217
- }
218
-
219
- console.log(commonFilePath,'Success - No problem found');
220
- } catch (error) {
221
- console.error('❌ Error:', error);
222
- process.exit(1);
223
- }
224
-
225
- }
226
-
227
- const checkIsTestingInAdmob=()=>{
228
-
229
- if (admobConfig.config && admobConfig.config.isTesting === true) {
230
- console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration.json" file.`);
231
- process.exit(1); // Exit with an error code to halt the process
232
- } else {
233
- console.log('✅ No problem found. "isTesting" is either already false or not defined.');
234
- }
235
- }
236
-
237
- const checkIsAdsDisableByReturnStatement=()=>{
238
-
239
-
240
- const adsFolder = join('src', 'js', 'Ads');
241
- const filePattern = /^admob-emi-(\d+\.)+\d+\.js$/;
242
-
243
- // Step 1: Find the admob file
244
- const files = readdirSync(adsFolder);
245
- const admobFile = files.find(f => filePattern.test(f));
246
-
247
- if (!admobFile) {
248
- console.log('❌ No Admob file found.');
249
- process.exit(1);
250
- }
251
-
252
- const filePath = join(adsFolder, admobFile);
253
- const content = readFileSync(filePath, 'utf-8');
254
-
255
- // Step 2: Extract the adsOnDeviceReady function body
256
- const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
257
- const match = content.match(functionRegex);
258
-
259
- if (!match) {
260
- console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
261
- process.exit(1);
262
- }
263
-
264
- const body = match[1];
265
- const lines = body.split('\n').map(line => line.trim());
266
-
267
- // Step 3: Skip blank lines and comments, get the first real code line
268
- let firstCodeLine = '';
269
- for (const line of lines) {
270
- if (line === '' || line.startsWith('//')) continue;
271
- firstCodeLine = line;
272
- break;
273
- }
274
-
275
- // Step 4: Block if it's any of the unwanted returns
276
- const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
277
-
278
- if (badReturnPattern.test(firstCodeLine)) {
279
- console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
280
- process.exit(2);
281
- } else {
282
- console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
283
- }
284
- }
285
-
286
-
287
-
288
- const addPermission_AD_ID=async()=>{
289
-
290
- const admobPluginXmlPath = join('node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
291
-
292
-
293
- //let isAdmobFound = false;
294
- try {
295
- await promises.access(admobPluginXmlPath, constants.F_OK);
296
- isAdmobFound = true;
297
- } catch (err) {
298
- isAdmobFound = false;
299
- }
300
-
301
-
302
-
303
- if (isAdmobFound) {
304
- if (existsSync(androidManifestPath)) {
305
- let manifestContent = readFileSync(androidManifestPath, 'utf8');
306
- let modified = false;
307
-
308
- // --- Step 1: Ensure AD_ID permission exists ---
309
- const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
310
- if (!manifestContent.includes(adIdPermission)) {
311
- console.log("📄 AD_ID permission not found. Adding to AndroidManifest.xml.");
312
- manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
313
- console.log("✅ AD_ID permission added successfully.");
314
- modified = true;
315
- } else {
316
- console.log("ℹ️ AD_ID permission already exists in AndroidManifest.xml.");
317
- }
318
-
319
- // --- Step 2: Ensure OPTIMIZE_AD_LOADING meta-data exists ---
320
- const optimizeAdMeta = `<meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING" android:value="true" />`;
321
-
322
- if (!manifestContent.includes(optimizeAdMeta)) {
323
- console.log("📄 OPTIMIZE_AD_LOADING meta-data not found. Adding to AndroidManifest.xml.");
324
-
325
- const appTagPattern = /<application[^>]*>/;
326
- if (appTagPattern.test(manifestContent)) {
327
- manifestContent = manifestContent.replace(appTagPattern, match => `${match}\n ${optimizeAdMeta}`);
328
- console.log("✅ OPTIMIZE_AD_LOADING meta-data added successfully.");
329
- modified = true;
330
- } else {
331
- console.error("❌ <application> tag not found in AndroidManifest.xml.");
332
- }
333
- } else {
334
- console.log("ℹ️ OPTIMIZE_AD_LOADING meta-data already exists in AndroidManifest.xml.");
335
- }
336
-
337
- // --- Step 3: Write only if modified ---
338
- if (modified) {
339
- writeFileSync(androidManifestPath, manifestContent, 'utf8');
340
- console.log("💾 AndroidManifest.xml updated successfully.");
341
- } else {
342
- console.log("✅ No changes needed. AndroidManifest.xml is up to date.");
343
- }
344
-
345
- } else {
346
- console.error("❌ AndroidManifest.xml not found at the specified path.");
347
- }
348
- } else {
349
- console.log("\x1b[33m%s\x1b[0m", "⚠️ No AdMob found, so AD_ID permission and meta-data were not added");
350
- }
351
-
352
-
353
-
354
-
355
-
356
-
357
- }
358
-
359
-
360
-
361
-
362
-
363
-
364
-
365
-
366
-
367
-
368
-
369
- checkCommonFileStoreId();
370
-
371
-
372
-
373
- if (_isADMOB_ENABLED)
374
- {
375
- checkIsTestingInAdmob();
376
- checkIsAdsDisableByReturnStatement()
377
-
378
- await addPermission_AD_ID()
379
- }
380
-
381
-
382
-
383
- let originalReleaseType, originalSigningType;
384
-
385
- function readCapacitorConfig() {
386
- return JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
387
- }
388
-
389
- function writeCapacitorConfig(config) {
390
- fs.writeFileSync(capacitorConfigPath, JSON.stringify(config, null, 2), 'utf8');
391
- }
392
-
393
- function updateCapacitorConfig(releaseType, signingType) {
394
- const config = readCapacitorConfig();
395
-
396
- // Save original values once
397
- if (originalReleaseType === undefined) originalReleaseType = config.android?.buildOptions?.releaseType || '';
398
- if (originalSigningType === undefined) originalSigningType = config.android?.buildOptions?.signingType || '';
399
-
400
- // Update values
401
- config.android = config.android || {};
402
- config.android.buildOptions = config.android.buildOptions || {};
403
- config.android.buildOptions.releaseType = releaseType;
404
- config.android.buildOptions.signingType = signingType;
405
-
406
- writeCapacitorConfig(config);
407
- console.log(`ℹ️ capacitor.config.json updated: releaseType=${releaseType}, signingType=${signingType}`);
408
- }
409
-
410
- function restoreCapacitorConfig() {
411
- const config = readCapacitorConfig();
412
- if (originalReleaseType !== undefined) config.android.buildOptions.releaseType = originalReleaseType;
413
- if (originalSigningType !== undefined) config.android.buildOptions.signingType = originalSigningType;
414
- writeCapacitorConfig(config);
415
- console.log(`✅ capacitor.config.json restored to original values.`);
416
- }
417
-
418
- process.on('SIGINT', () => {
419
- console.log('\n⚠️ Detected Ctrl+C, restoring capacitor.config.json...');
420
- restoreCapacitorConfig();
421
- process.exit(0);
422
- });
423
-
424
- process.on('exit', () => {
425
- restoreCapacitorConfig();
426
- });
427
-
428
-
429
-
430
- const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
431
- console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
432
-
433
-
434
-
435
-
436
-
437
-
438
- // Get the store ID from the command line arguments
439
- /* const storeIdArg = ["2","3"]//process.argv[2]; // Get the store ID from the command line
440
- const storeIds = storeIdArg ? storeIdArg : Object.keys(storeNames);//["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
441
-
442
- debugger; */
443
-
444
- let storeIdArg = process.argv[2]; // command-line argument
445
- let storeIds;
446
-
447
- if (storeIdArg) {
448
- try {
449
- // Try parsing as JSON array first
450
- const parsed = JSON.parse(storeIdArg);
451
- if (Array.isArray(parsed)) {
452
- storeIds = parsed.map(String); // ensure strings
453
- } else {
454
- storeIds = [parsed.toString()];
455
- }
456
- } catch (e) {
457
- // Not JSON, assume comma-separated string
458
- storeIds = storeIdArg.split(",").map(s => s.trim());
459
- }
460
- } else {
461
- // No argument, use all store IDs
462
- storeIds = Object.keys(storeNames);
463
- }
464
-
465
-
466
- // Store the original minSdkVersion globally
467
- let originalMinSdkVersion;
468
-
469
- // Remove any existing AAB files before starting the build process
470
- const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
471
- if (existsSync(aabDirectory)) {
472
- const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
473
- files.forEach(file => {
474
- const filePath = join(aabDirectory, file);
475
- unlinkSync(filePath);
476
- console.log(`ℹ️ Deleted existing AAB file: ${file}`);
477
- });
478
- }
479
-
480
- const aabOutputDir = join("AAB");
481
- if (!existsSync(aabOutputDir)) {
482
- mkdirSync(aabOutputDir);
483
- console.log(`Created directory: ${aabOutputDir}`);
484
- }
485
-
486
- if (existsSync(aabOutputDir)) {
487
- const files = readdirSync(aabOutputDir).filter(
488
- file => file.endsWith('.aab') || file.endsWith('.apk')
489
- );
490
-
491
- files.forEach(file => {
492
- const filePath = join(aabOutputDir, file);
493
- unlinkSync(filePath);
494
- console.log(`Deleted existing build file: ${file}`);
495
- });
496
- }
497
-
498
-
499
- // Extract version code and version name from build.gradle
500
- const gradleFilePath = join("android", "app", "build.gradle");
501
- const gradleContent = readFileSync(gradleFilePath, 'utf8');
502
-
503
- const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
504
- const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
505
-
506
- const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
507
- const versionName = versionNameMatch ? versionNameMatch[1] : '';
508
-
509
- // Display the current versionCode and versionName
510
- console.log(`Current versionCode: ${versionCode}`);
511
- console.log(`Current versionName: ${versionName}`);
512
-
513
- // Create an interface for user input
514
- const rl = createInterface({
515
- input: process.stdin,
516
- output: process.stdout
517
- });
518
-
519
- // Ask for new versionCode
520
- rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
521
- const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
522
-
523
- // Ask for new versionName
524
- rl.question('Enter new versionName (press enter to keep current): ', (newVersionName) => {
525
- const finalVersionName = newVersionName || versionName; // Use existing if no input
526
-
527
- // Log the final version details
528
- console.log(`📦 Final versionCode: ${finalVersionCode}`);
529
- console.log(`📝 Final versionName: ${finalVersionName}`);
530
-
531
-
532
-
533
- // Update build.gradle with the new version details
534
- let updatedGradleContent = gradleContent
535
- .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
536
- .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
537
-
538
- // Check if resConfigs "en" already exists
539
- const resConfigsLine = ' resConfigs "en"';
540
- if (!updatedGradleContent.includes(resConfigsLine)) {
541
- // Add resConfigs "en" below versionName
542
- updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
543
- } else {
544
- console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
545
- }
546
-
547
-
548
-
549
- // List of package IDs for which minify should be false
550
-
551
-
552
- // Determine desired minify value
553
- const desiredMinify = !_isffmpegUsed;
554
-
555
- // Check if minifyEnabled is already present
556
- if (/minifyEnabled\s+(true|false)/.test(updatedGradleContent)) {
557
- // Replace existing value with desired
558
- updatedGradleContent = updatedGradleContent.replace(/minifyEnabled\s+(true|false)/, `minifyEnabled ${desiredMinify}`);
559
- console.log(`Replaced minifyEnabled with ${desiredMinify}.`);
560
- } else if (/buildTypes\s*{[\s\S]*?release\s*{/.test(updatedGradleContent)) {
561
- // Insert minifyEnabled if not present
562
- updatedGradleContent = updatedGradleContent.replace(
563
- /(buildTypes\s*{[\s\S]*?release\s*{)/,
564
- `$1\n minifyEnabled ${desiredMinify}`
565
- );
566
- console.log(`✅ Inserted minifyEnabled ${desiredMinify} into release block.`);
567
- } else {
568
- console.log('⚠️ Warning: buildTypes > release block not found. minifyEnabled was not added.');
569
- }
570
-
571
-
572
-
573
-
574
-
575
-
576
- // Write the updated gradle content back to build.gradle
577
- writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
578
- console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en" and "minifyEnabled true"`);
579
-
580
- storeIds.forEach((id) => {
581
- console.log(`ℹ️ Building for Store ID ${id}`);
582
-
583
- // Set the environment variable for store ID
584
- process.env.VITE_STORE_ID = id;
585
-
586
- // Conditionally set the new file name
587
- let newFileName;
588
- let storeName = storeNames[id];
589
-
590
- debugger;
591
-
592
-
593
- managePackages(storeName);
594
-
595
- if (storeName === "SamsungStore") {
596
- // For SamsungStore, rename to versionCode value only
597
- //newFileName = `${finalVersionCode}.aab`;
598
- newFileName=`${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`
599
- } else {
600
- // For other stores, use the standard naming format
601
- //newFileName = `app-release-signed-${storeName}-b${finalVersionCode}-v${finalVersionName}.aab`;
602
-
603
- newFileName=`${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName}.aab`
604
-
605
-
606
- /*
607
- const _appUniqueId = config.android?.APP_UNIQUE_ID;
608
- const _appName=config.appName;
609
- const _appPackageId=config.appId;
610
- */
611
-
612
- }
613
-
614
- //storeName="amazon"
615
- const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
616
-
617
- // Modify minSdkVersion in variables.gradle for SamsungStore
618
- const variablesGradleFilePath = join("android", "variables.gradle");
619
- let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
620
-
621
- // Extract the current minSdkVersion
622
- const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
623
- const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
624
-
625
- // Store the original minSdkVersion (only on the first iteration)
626
- if (!originalMinSdkVersion) {
627
- originalMinSdkVersion = currentMinSdkVersion;
628
- }
629
- try {
630
- // Modify the minSdkVersion based on the store
631
-
632
-
633
- if(currentMinSdkVersion==23 || currentMinSdkVersion==24)
634
- {
635
- if (storeName === "SamsungStore" || storeName === "PlayStore" ||
636
- //_appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker"
637
-
638
- //ffmpegUsedPackages.includes(_appPackageId)
639
- _isffmpegUsed
640
- ) {
641
- if (currentMinSdkVersion !== 24) {
642
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
643
- console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
644
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
645
- }
646
- } else {
647
- // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
648
- //if (currentMinSdkVersion !== originalMinSdkVersion) {
649
- variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
650
- console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
651
- writeFileSync(variablesGradleFilePath, variablesGradleContent);
652
- //}
653
- }
654
- }
655
-
656
-
657
- // Run the Node.js script to modify plugin.xml
658
- if (isAdmobFound) {
659
- execSync('node buildCodeplay/modify-plugin-xml.js', { stdio: 'inherit' });
660
- } else {
661
- console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
662
- }
663
-
664
- // Run the Vite build
665
- execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
666
-
667
-
668
-
669
- // Copy the built files to the appropriate folder
670
- const src = join("www", "*");
671
- const dest = join("android", "app", "src", "main", "assets", "public");
672
-
673
- // Use 'xcopy' command for Windows
674
- execSync(`xcopy ${src} ${dest} /E /I /Y`, { stdio: 'inherit' });
675
-
676
- // Build Android AAB file
677
- //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
678
-
679
-
680
- // Build Android AAB or APK file based on store
681
- console.log(`🏗️ Building release for ${storeName}...`);
682
-
683
- /* let buildType = "AAB";
684
- if (["VivoStore", "OppoStore", "MiStore"].includes(storeName)) {
685
- buildType = "APK";
686
- } */
687
-
688
-
689
- // Determine build type and signing type per store
690
- let buildType = ["VivoStore","OppoStore","MiStore"].includes(storeName) ? "APK" : "AAB";
691
- let signingType = buildType === "APK" ? "apksigner" : "jarsigner";
692
-
693
- // Update capacitor.config.json for this store
694
- updateCapacitorConfig(buildType, signingType);
695
-
696
-
697
-
698
- execSync('npx cap sync android', { stdio: 'inherit' });
699
- execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' });
700
-
701
- // Determine output paths
702
- let oldFilePath;
703
- let newExt = buildType === "APK" ? "apk" : "aab";
704
-
705
- if (buildType === "APK") {
706
- oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release-signed.apk");
707
- } else {
708
- oldFilePath = join("android", "app", "build", "outputs", "bundle", "release", "app-release-signed.aab");
709
- }
710
-
711
- const checkFullPath = join("AAB", newFileName.replace(/\.aab$/, `.${newExt}`));
712
-
713
- // Rename the output file
714
- if (existsSync(oldFilePath)) {
715
- renameSync(oldFilePath, checkFullPath);
716
- console.log(`✅ Renamed output ${newExt.toUpperCase()} file to: ${path.basename(checkFullPath)}`);
717
- } else {
718
- console.error(`❌ ${newExt.toUpperCase()} file not found after build.`);
719
- }
720
-
721
- } catch (error) {
722
- console.error(`❌ Error during build for Store ID ${id}:`, error);
723
- process.exit(1);
724
- }
725
- });
726
-
727
- rl.close(); // Close the readline interface after all operations
728
- });
729
- });
730
-
731
-
732
-
733
-
734
-
735
- function managePackages(store) {
736
- console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
737
-
738
- let install = "";
739
- let uninstall = "";
740
-
741
-
742
-
743
- let manifestContent = readFileSync(androidManifestPath, 'utf-8');
744
-
745
- const permissionsToRemove = [
746
- 'com.android.vending.BILLING',
747
- 'com.samsung.android.iap.permission.BILLING'
748
- ];
749
-
750
-
751
- permissionsToRemove.forEach(permission => {
752
- const permissionRegex = new RegExp(`^\\s*<uses-permission\\s+android:name="${permission}"\\s*/?>\\s*[\r\n]?`, 'm');
753
- if (permissionRegex.test(manifestContent)) {
754
- manifestContent = manifestContent.replace(permissionRegex, '');
755
- console.log(`✅ Removed <uses-permission android:name="${permission}" /> from AndroidManifest.xml`);
756
- }
757
- });
758
-
759
- // Write the updated content back to the file
760
- writeFileSync(androidManifestPath, manifestContent, 'utf-8');
761
-
762
-
763
-
764
- if ((playstore && store === "PlayStore") || (amazon && store === "AmazonStore")) {
765
- install = '@revenuecat/purchases-capacitor';
766
- uninstall = 'cordova-plugin-samsungiap';
767
-
768
- // Update AndroidManifest.xml for PlayStore
769
- if(playstore)
770
- updateAndroidManifest(store,
771
- '<uses-permission android:name="com.android.vending.BILLING" />');
772
-
773
- } else if (samsung && store === "SamsungStore") {
774
- install = 'cordova-plugin-samsungiap';
775
- uninstall = '@revenuecat/purchases-capacitor';
776
-
777
- // Update AndroidManifest.xml for SamsungStore
778
- updateAndroidManifest(store,
779
- '<uses-permission android:name="com.samsung.android.iap.permission.BILLING" />');
780
-
781
- } else {
782
- console.log("No valid store specified or no configurations found. Both plugins will be uninstalled.");
783
- try {
784
- execSync(`npm uninstall cordova-plugin-samsungiap`, { stdio: 'inherit' });
785
- execSync(`npm uninstall @revenuecat/purchases-capacitor`, { stdio: 'inherit' });
786
- console.log(`✅ Both plugins uninstalled successfully.`);
787
- } catch (err) {
788
- console.error("❌ Error uninstalling plugins:", err);
789
- }
790
- return;
791
- }
792
-
793
- console.log(`⚠️ Installing ${install} and uninstalling ${uninstall} for ${store}...`);
794
- try {
795
- if (install) {
796
- execSync(`npm install ${install}`, { stdio: 'inherit' });
797
- }
798
- if (uninstall) {
799
- execSync(`npm uninstall ${uninstall}`, { stdio: 'inherit' });
800
- }
801
- console.log(`✅ ${install} installed and ${uninstall} uninstalled successfully.`);
802
- } catch (err) {
803
- console.error(`❌ Error managing packages for ${store}:`, err);
804
- }
805
- }
806
-
807
-
808
-
809
- function updateAndroidManifest(store, addPermission) {
810
- try {
811
- if (!existsSync(androidManifestPath)) {
812
- console.error("❌ AndroidManifest.xml file not found!");
813
- return;
814
- }
815
-
816
- // Read the content of the AndroidManifest.xml
817
- let manifestContent = readFileSync(androidManifestPath, 'utf-8');
818
-
819
- // Normalize line endings to `\n` for consistent processing
820
- manifestContent = manifestContent.replace(/\r\n/g, '\n');
821
-
822
- // Check if the permission is already present
823
- if (manifestContent.includes(addPermission.trim())) {
824
- console.log(`${addPermission} is already in the AndroidManifest.xml. Skipping addition.`);
825
- return; // Skip if the permission is already present
826
- }
827
-
828
- // Insert the permission before the closing </manifest> tag
829
- const closingTag = '</manifest>';
830
- const formattedPermission = ` ${addPermission.trim()}\n`;
831
- if (manifestContent.includes(closingTag)) {
832
- manifestContent = manifestContent.replace(
833
- closingTag,
834
- `${formattedPermission}${closingTag}`
835
- );
836
- console.log(`✅ Added ${addPermission} before </manifest> tag.`);
837
- } else {
838
- console.warn(`⚠️ </manifest> tag not found. Adding ${addPermission} at the end of the file.`);
839
- manifestContent += `\n${formattedPermission}`;
840
- }
841
-
842
- // Normalize line endings back to `\r\n` and write the updated content
843
- manifestContent = manifestContent.replace(/\n/g, '\r\n');
844
- writeFileSync(androidManifestPath, manifestContent, 'utf-8');
845
- console.log(`✅ AndroidManifest.xml updated successfully for ${store}`);
846
- } catch (err) {
847
- console.error(`❌ Error updating AndroidManifest.xml for ${store}:`, err);
848
- }
849
- }
850
-
851
- restoreCapacitorConfig();
852
- console.log("🏁 All builds completed, capacitor.config.json restored.");
853
-
854
-
855
- /* function updateAndroidManifest1(store, addPermission) {
856
- try {
857
- if (!fs.existsSync(androidManifestPath)) {
858
- console.error("AndroidManifest.xml file not found!");
859
- return;
860
- }
861
-
862
- let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
863
-
864
-
865
-
866
- // Add the required permission if not already present
867
- if (!manifestContent.includes(addPermission)) {
868
- const manifestLines = manifestContent.split('\n');
869
- const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
870
- if (insertIndex > -1) {
871
- manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
872
- manifestContent = manifestLines.join('\n');
873
- console.log(`Added ${addPermission} to AndroidManifest.xml`);
874
- }
875
- }
876
-
877
- // Write the updated content back to the file
878
- fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
879
- console.log(`AndroidManifest.xml updated successfully for ${store}`);
880
- } catch (err) {
881
- console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
882
- }
883
- } */
884
-
885
-
886
-
887
-
888
-
889
-
890
-
891
-
1
+ /*
2
+ Can be run like
3
+ node finalrelease
4
+ node finalrelease 1
5
+ node finalrelease "1,2,7"
6
+ */
7
+
8
+ import { existsSync, readFileSync, readdirSync, promises, constants, writeFileSync, unlinkSync, mkdirSync, renameSync } from 'fs';
9
+ import { join, resolve } from 'path';
10
+ import { execSync } from 'child_process';
11
+ import { createInterface } from 'readline';
12
+
13
+ import { fileURLToPath } from 'url';
14
+ import { dirname } from 'path';
15
+
16
+ /* const path = require('path');
17
+ const fs = require('fs'); */
18
+
19
+ import fs from 'fs';
20
+ import path from 'path';
21
+
22
+ // Define a mapping between store IDs and store names
23
+ /* const storeNames = {
24
+ "1": "PlayStore",
25
+ "2": "SamsungStore",
26
+ "7": "AmazonStore"
27
+ }; */
28
+
29
+ const storeNames = {
30
+ "1": "PlayStore",
31
+ "2": "SamsungStore",
32
+ "7": "AmazonStore",
33
+
34
+ "3": "MiStore",
35
+ "4": "HuaweiStore",
36
+ "5": "OppoStore",
37
+ //"6": "iOSStore",
38
+ "8": "VivoStore"
39
+ };
40
+
41
+
42
+ //1=> PlayStore 2=> SamsungStore 3=>MiStore 4=>HuaweiStore 5=>OppoStore 6=>iOSStore 7=> AmazonStore 8=> VivoStore
43
+
44
+
45
+
46
+
47
+
48
+
49
+
50
+ let isAdmobFound = false;
51
+
52
+ const amazonMinSdkVersion=24;
53
+
54
+ const androidManifestPath = join("android", "app", "src", "main", "AndroidManifest.xml");
55
+
56
+
57
+ const configPath = path.join(process.cwd(), 'capacitor.config.json');
58
+ const config = JSON.parse(fs.readFileSync(configPath, 'utf8'));
59
+
60
+ const _appUniqueId = config.android?.APP_UNIQUE_ID;
61
+ const _appName=config.appName;
62
+ const _appPackageId=config.appId;
63
+
64
+
65
+
66
+ const __filename = fileURLToPath(import.meta.url);
67
+ const __dirname = dirname(__filename);
68
+
69
+ function fileExists(filePath) {
70
+ return existsSync(filePath);
71
+ }
72
+
73
+
74
+ const ffmpegPluginXmlPath = path.join(__dirname, 'node_modules', 'codeplay-fmpg', 'plugin.xml');
75
+ const capacitorConfigPath = join(process.cwd(), 'capacitor.config.json');
76
+
77
+
78
+
79
+ function isFfmpegUsed() {
80
+ try {
81
+ const xmlContent = fs.readFileSync(ffmpegPluginXmlPath, 'utf8');
82
+ // Simple check: if plugin.xml exists and contains <plugin> tag (or any FFmpeg-specific tag)
83
+ return /<plugin\b/.test(xmlContent);
84
+ } catch (err) {
85
+ console.log('⚠️ FFmpeg plugin not found:', err.message);
86
+ return false;
87
+ }
88
+ }
89
+
90
+ const _isffmpegUsed = isFfmpegUsed();
91
+
92
+ function getAdMobConfig() {
93
+ if (!fileExists(capacitorConfigPath)) {
94
+ throw new Error('❌ capacitor.config.json not found. Ensure this is a Capacitor project.');
95
+ }
96
+
97
+ const config = JSON.parse(readFileSync(capacitorConfigPath, 'utf8'));
98
+ const admobConfig = config.plugins?.AdMob;
99
+
100
+ //_appPackageId=config.appId;
101
+
102
+ if (!admobConfig) {
103
+ throw new Error('❌ AdMob configuration is missing in capacitor.config.json.');
104
+ }
105
+
106
+ // Default to true if ADMOB_ENABLED is not specified
107
+ const isEnabled = admobConfig.ADMOB_ENABLED !== false;
108
+
109
+ if (!isEnabled) {
110
+ return { ADMOB_ENABLED: false }; // Skip further validation
111
+ }
112
+
113
+ if (!admobConfig.APP_ID_ANDROID || !admobConfig.APP_ID_IOS) {
114
+ throw new Error(' ❌ AdMob configuration is incomplete. Ensure APP_ID_ANDROID and APP_ID_IOS are defined.');
115
+ }
116
+
117
+ return {
118
+ ADMOB_ENABLED: true,
119
+ APP_ID_ANDROID: admobConfig.APP_ID_ANDROID,
120
+ APP_ID_IOS: admobConfig.APP_ID_IOS,
121
+ USE_LITE_ADS: admobConfig.USE_LITE_ADS === "lite",
122
+ };
123
+ }
124
+
125
+
126
+
127
+ const _capacitorConfig = getAdMobConfig();
128
+
129
+ const _isADMOB_ENABLED=_capacitorConfig.ADMOB_ENABLED;
130
+
131
+ // Proceed only if ADMOB_ENABLED is true
132
+ //if (_capacitorConfig.ADMOB_ENABLED)
133
+
134
+
135
+ const admobConfigPath = join('src', 'js','Ads', 'admob-ad-configuration.json');
136
+ let admobConfig;
137
+
138
+ if (_isADMOB_ENABLED)
139
+ {
140
+ try
141
+ {
142
+ admobConfig = JSON.parse(readFileSync(admobConfigPath, 'utf8'));
143
+ }
144
+ catch (err)
145
+ {
146
+ console.error("❌ Failed to read admob-ad-configuration.json", err);
147
+ process.exit(1);
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
+ const checkCommonFileStoreId=()=>{
173
+ const possibleConfigFiles = ['vite.config.mjs', 'vite.config.js'];
174
+ let viteConfigPath;
175
+ for (const configFile of possibleConfigFiles) {
176
+ const fullPath = resolve( configFile);
177
+ if (existsSync(fullPath)) {
178
+ viteConfigPath = fullPath;
179
+ break;
180
+ }
181
+ }
182
+
183
+ if (!viteConfigPath) {
184
+ console.error('❌ Error: No vite.config.mjs or vite.config.js file found.');
185
+ process.exit(1);
186
+ }
187
+
188
+ try {
189
+ // Read vite config file
190
+ const viteConfigContent = readFileSync(viteConfigPath, 'utf-8');
191
+
192
+ // Extract @common alias path
193
+ const aliasPattern = /'@common':\s*path\.resolve\(__dirname,\s*'(.+?)'\)/;
194
+ const match = viteConfigContent.match(aliasPattern);
195
+
196
+ if (!match) {
197
+ console.error(`❌ Error: @common alias not found in ${viteConfigPath}`);
198
+ process.exit(1);
199
+ }
200
+
201
+ const commonFilePath = match[1];
202
+ const resolvedCommonPath = resolve(__dirname, commonFilePath);
203
+
204
+ // Read the common file content
205
+ if (!existsSync(resolvedCommonPath)) {
206
+ console.error(`❌ Error: Resolved common file does not exist: ${resolvedCommonPath}`);
207
+ process.exit(1);
208
+ }
209
+
210
+ const commonFileContent = readFileSync(resolvedCommonPath, 'utf-8');
211
+
212
+ // Check for the _storeid export line
213
+ const storeIdPattern = /export\s+let\s+_storeid\s*=\s*import\.meta\.env\.VITE_STORE_ID\s*\|\|\s*1\s*;/;
214
+ if (!storeIdPattern.test(commonFileContent)) {
215
+ console.error(`❌ Error: _storeid value is wrong in ${commonFilePath}`);
216
+ process.exit(1);
217
+ }
218
+
219
+ console.log(commonFilePath,'Success - No problem found');
220
+ } catch (error) {
221
+ console.error('❌ Error:', error);
222
+ process.exit(1);
223
+ }
224
+
225
+ }
226
+
227
+ const checkIsTestingInAdmob=()=>{
228
+
229
+ if (admobConfig.config && admobConfig.config.isTesting === true) {
230
+ console.error(`❌ Problem found while generating the AAB file. Please change "isTesting: true" to "isTesting: false" in the "admob-ad-configuration.json" file.`);
231
+ process.exit(1); // Exit with an error code to halt the process
232
+ } else {
233
+ console.log('✅ No problem found. "isTesting" is either already false or not defined.');
234
+ }
235
+ }
236
+
237
+ const checkIsAdsDisableByReturnStatement=()=>{
238
+
239
+
240
+ const adsFolder = join('src', 'js', 'Ads');
241
+ const filePattern = /^admob-emi-(\d+\.)+\d+\.js$/;
242
+
243
+ // Step 1: Find the admob file
244
+ const files = readdirSync(adsFolder);
245
+ const admobFile = files.find(f => filePattern.test(f));
246
+
247
+ if (!admobFile) {
248
+ console.log('❌ No Admob file found.');
249
+ process.exit(1);
250
+ }
251
+
252
+ const filePath = join(adsFolder, admobFile);
253
+ const content = readFileSync(filePath, 'utf-8');
254
+
255
+ // Step 2: Extract the adsOnDeviceReady function body
256
+ const functionRegex = /async\s+function\s+adsOnDeviceReady\s*\([^)]*\)\s*{([\s\S]*?)^}/m;
257
+ const match = content.match(functionRegex);
258
+
259
+ if (!match) {
260
+ console.log(`❌ Function 'adsOnDeviceReady' not found in file: ${admobFile}`);
261
+ process.exit(1);
262
+ }
263
+
264
+ const body = match[1];
265
+ const lines = body.split('\n').map(line => line.trim());
266
+
267
+ // Step 3: Skip blank lines and comments, get the first real code line
268
+ let firstCodeLine = '';
269
+ for (const line of lines) {
270
+ if (line === '' || line.startsWith('//')) continue;
271
+ firstCodeLine = line;
272
+ break;
273
+ }
274
+
275
+ // Step 4: Block if it's any of the unwanted returns
276
+ const badReturnPattern = /^return\s*(true|false)?\s*;?$/;
277
+
278
+ if (badReturnPattern.test(firstCodeLine)) {
279
+ console.log(`❌ BLOCKED in file '${admobFile}': First active line in 'adsOnDeviceReady' is '${firstCodeLine}'`);
280
+ process.exit(2);
281
+ } else {
282
+ console.log(`✅ Safe: No early return (true/false) found in 'adsOnDeviceReady' of file '${admobFile}'.`);
283
+ }
284
+ }
285
+
286
+
287
+
288
+ const addPermission_AD_ID=async()=>{
289
+
290
+ const admobPluginXmlPath = join('node_modules', 'emi-indo-cordova-plugin-admob', 'plugin.xml');
291
+
292
+
293
+ //let isAdmobFound = false;
294
+ try {
295
+ await promises.access(admobPluginXmlPath, constants.F_OK);
296
+ isAdmobFound = true;
297
+ } catch (err) {
298
+ isAdmobFound = false;
299
+ }
300
+
301
+
302
+
303
+ if (isAdmobFound) {
304
+ if (existsSync(androidManifestPath)) {
305
+ let manifestContent = readFileSync(androidManifestPath, 'utf8');
306
+ let modified = false;
307
+
308
+ // --- Step 1: Ensure AD_ID permission exists ---
309
+ const adIdPermission = '<uses-permission android:name="com.google.android.gms.permission.AD_ID" />';
310
+ if (!manifestContent.includes(adIdPermission)) {
311
+ console.log("📄 AD_ID permission not found. Adding to AndroidManifest.xml.");
312
+ manifestContent = manifestContent.replace('</manifest>', ` ${adIdPermission}\n</manifest>`);
313
+ console.log("✅ AD_ID permission added successfully.");
314
+ modified = true;
315
+ } else {
316
+ console.log("ℹ️ AD_ID permission already exists in AndroidManifest.xml.");
317
+ }
318
+
319
+ // --- Step 2: Ensure OPTIMIZE_AD_LOADING meta-data exists ---
320
+ const optimizeAdMeta = `<meta-data android:name="com.google.android.gms.ads.flag.OPTIMIZE_AD_LOADING" android:value="true" />`;
321
+
322
+ if (!manifestContent.includes(optimizeAdMeta)) {
323
+ console.log("📄 OPTIMIZE_AD_LOADING meta-data not found. Adding to AndroidManifest.xml.");
324
+
325
+ const appTagPattern = /<application[^>]*>/;
326
+ if (appTagPattern.test(manifestContent)) {
327
+ manifestContent = manifestContent.replace(appTagPattern, match => `${match}\n ${optimizeAdMeta}`);
328
+ console.log("✅ OPTIMIZE_AD_LOADING meta-data added successfully.");
329
+ modified = true;
330
+ } else {
331
+ console.error("❌ <application> tag not found in AndroidManifest.xml.");
332
+ }
333
+ } else {
334
+ console.log("ℹ️ OPTIMIZE_AD_LOADING meta-data already exists in AndroidManifest.xml.");
335
+ }
336
+
337
+ // --- Step 3: Write only if modified ---
338
+ if (modified) {
339
+ writeFileSync(androidManifestPath, manifestContent, 'utf8');
340
+ console.log("💾 AndroidManifest.xml updated successfully.");
341
+ } else {
342
+ console.log("✅ No changes needed. AndroidManifest.xml is up to date.");
343
+ }
344
+
345
+ } else {
346
+ console.error("❌ AndroidManifest.xml not found at the specified path.");
347
+ }
348
+ } else {
349
+ console.log("\x1b[33m%s\x1b[0m", "⚠️ No AdMob found, so AD_ID permission and meta-data were not added");
350
+ }
351
+
352
+
353
+
354
+
355
+
356
+
357
+ }
358
+
359
+
360
+
361
+
362
+
363
+
364
+
365
+
366
+
367
+
368
+
369
+ checkCommonFileStoreId();
370
+
371
+
372
+
373
+ if (_isADMOB_ENABLED)
374
+ {
375
+ checkIsTestingInAdmob();
376
+ checkIsAdsDisableByReturnStatement()
377
+
378
+ await addPermission_AD_ID()
379
+ }
380
+
381
+
382
+
383
+ let originalReleaseType, originalSigningType;
384
+
385
+ function readCapacitorConfig() {
386
+ return JSON.parse(fs.readFileSync(capacitorConfigPath, 'utf8'));
387
+ }
388
+
389
+ function writeCapacitorConfig(config) {
390
+ fs.writeFileSync(capacitorConfigPath, JSON.stringify(config, null, 2), 'utf8');
391
+ }
392
+
393
+ function updateCapacitorConfig(releaseType, signingType) {
394
+ const config = readCapacitorConfig();
395
+
396
+ // Save original values once
397
+ if (originalReleaseType === undefined) originalReleaseType = config.android?.buildOptions?.releaseType || '';
398
+ if (originalSigningType === undefined) originalSigningType = config.android?.buildOptions?.signingType || '';
399
+
400
+ // Update values
401
+ config.android = config.android || {};
402
+ config.android.buildOptions = config.android.buildOptions || {};
403
+ config.android.buildOptions.releaseType = releaseType;
404
+ config.android.buildOptions.signingType = signingType;
405
+
406
+ writeCapacitorConfig(config);
407
+ console.log(`ℹ️ capacitor.config.json updated: releaseType=${releaseType}, signingType=${signingType}`);
408
+ }
409
+
410
+ function restoreCapacitorConfig() {
411
+ const config = readCapacitorConfig();
412
+ if (originalReleaseType !== undefined) config.android.buildOptions.releaseType = originalReleaseType;
413
+ if (originalSigningType !== undefined) config.android.buildOptions.signingType = originalSigningType;
414
+ writeCapacitorConfig(config);
415
+ console.log(`✅ capacitor.config.json restored to original values.`);
416
+ }
417
+
418
+ process.on('SIGINT', () => {
419
+ console.log('\n⚠️ Detected Ctrl+C, restoring capacitor.config.json...');
420
+ restoreCapacitorConfig();
421
+ process.exit(0);
422
+ });
423
+
424
+ process.on('exit', () => {
425
+ restoreCapacitorConfig();
426
+ });
427
+
428
+
429
+
430
+ const { playstore, samsung, amazon } = (_isADMOB_ENABLED && admobConfig.IAP) ? admobConfig.IAP : { playstore: false, samsung: false, amazon: false };
431
+ console.log(`ℹ️ IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
432
+
433
+
434
+
435
+
436
+
437
+
438
+ // Get the store ID from the command line arguments
439
+ /* const storeIdArg = ["2","3"]//process.argv[2]; // Get the store ID from the command line
440
+ const storeIds = storeIdArg ? storeIdArg : Object.keys(storeNames);//["1", "2", "7"]; // If a specific ID is provided, use it; otherwise, use all store IDs
441
+
442
+ debugger; */
443
+
444
+ let storeIdArg = process.argv[2]; // command-line argument
445
+ let storeIds;
446
+
447
+ if (storeIdArg) {
448
+ try {
449
+ // Try parsing as JSON array first
450
+ const parsed = JSON.parse(storeIdArg);
451
+ if (Array.isArray(parsed)) {
452
+ storeIds = parsed.map(String); // ensure strings
453
+ } else {
454
+ storeIds = [parsed.toString()];
455
+ }
456
+ } catch (e) {
457
+ // Not JSON, assume comma-separated string
458
+ storeIds = storeIdArg.split(",").map(s => s.trim());
459
+ }
460
+ } else {
461
+ // No argument, use all store IDs
462
+ storeIds = Object.keys(storeNames);
463
+ }
464
+
465
+
466
+ // Store the original minSdkVersion globally
467
+ let originalMinSdkVersion;
468
+
469
+ // Remove any existing AAB files before starting the build process
470
+ const aabDirectory = join("android", "app", "build", "outputs", "bundle", "release");
471
+ if (existsSync(aabDirectory)) {
472
+ const files = readdirSync(aabDirectory).filter(file => file.endsWith('.aab'));
473
+ files.forEach(file => {
474
+ const filePath = join(aabDirectory, file);
475
+ unlinkSync(filePath);
476
+ console.log(`ℹ️ Deleted existing AAB file: ${file}`);
477
+ });
478
+ }
479
+
480
+ const aabOutputDir = join("AAB");
481
+ if (!existsSync(aabOutputDir)) {
482
+ mkdirSync(aabOutputDir);
483
+ console.log(`Created directory: ${aabOutputDir}`);
484
+ }
485
+
486
+ if (existsSync(aabOutputDir)) {
487
+ const files = readdirSync(aabOutputDir).filter(
488
+ file => file.endsWith('.aab') || file.endsWith('.apk')
489
+ );
490
+
491
+ files.forEach(file => {
492
+ const filePath = join(aabOutputDir, file);
493
+ unlinkSync(filePath);
494
+ console.log(`Deleted existing build file: ${file}`);
495
+ });
496
+ }
497
+
498
+
499
+ // Extract version code and version name from build.gradle
500
+ const gradleFilePath = join("android", "app", "build.gradle");
501
+ const gradleContent = readFileSync(gradleFilePath, 'utf8');
502
+
503
+ const versionCodeMatch = gradleContent.match(/versionCode\s+(\d+)/);
504
+ const versionNameMatch = gradleContent.match(/versionName\s+"([^"]+)"/);
505
+
506
+ const versionCode = versionCodeMatch ? versionCodeMatch[1] : '';
507
+ const versionName = versionNameMatch ? versionNameMatch[1] : '';
508
+
509
+ // Display the current versionCode and versionName
510
+ console.log(`Current versionCode: ${versionCode}`);
511
+ console.log(`Current versionName: ${versionName}`);
512
+
513
+ // Create an interface for user input
514
+ const rl = createInterface({
515
+ input: process.stdin,
516
+ output: process.stdout
517
+ });
518
+
519
+ // Ask for new versionCode
520
+ rl.question('Enter new versionCode (press enter to keep current): ', (newVersionCode) => {
521
+ const finalVersionCode = newVersionCode || versionCode; // Use existing if no input
522
+
523
+ // Ask for new versionName
524
+ rl.question('Enter new versionName (press enter to keep current): ', (newVersionName) => {
525
+ const finalVersionName = newVersionName || versionName; // Use existing if no input
526
+
527
+ // Log the final version details
528
+ console.log(`📦 Final versionCode: ${finalVersionCode}`);
529
+ console.log(`📝 Final versionName: ${finalVersionName}`);
530
+
531
+
532
+
533
+ // Update build.gradle with the new version details
534
+ let updatedGradleContent = gradleContent
535
+ .replace(/versionCode\s+\d+/, `versionCode ${finalVersionCode}`)
536
+ .replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"`);
537
+
538
+ // Check if resConfigs "en" already exists
539
+ const resConfigsLine = ' resConfigs "en"';
540
+ if (!updatedGradleContent.includes(resConfigsLine)) {
541
+ // Add resConfigs "en" below versionName
542
+ updatedGradleContent = updatedGradleContent.replace(/versionName\s+"[^"]+"/, `versionName "${finalVersionName}"\n${resConfigsLine}`);
543
+ } else {
544
+ console.log('ℹ️ resConfigs "en" already exists in build.gradle.');
545
+ }
546
+
547
+
548
+
549
+ // List of package IDs for which minify should be false
550
+
551
+
552
+ // Determine desired minify value
553
+ const desiredMinify = !_isffmpegUsed;
554
+
555
+ // Check if minifyEnabled is already present
556
+ if (/minifyEnabled\s+(true|false)/.test(updatedGradleContent)) {
557
+ // Replace existing value with desired
558
+ updatedGradleContent = updatedGradleContent.replace(/minifyEnabled\s+(true|false)/, `minifyEnabled ${desiredMinify}`);
559
+ console.log(`Replaced minifyEnabled with ${desiredMinify}.`);
560
+ } else if (/buildTypes\s*{[\s\S]*?release\s*{/.test(updatedGradleContent)) {
561
+ // Insert minifyEnabled if not present
562
+ updatedGradleContent = updatedGradleContent.replace(
563
+ /(buildTypes\s*{[\s\S]*?release\s*{)/,
564
+ `$1\n minifyEnabled ${desiredMinify}`
565
+ );
566
+ console.log(`✅ Inserted minifyEnabled ${desiredMinify} into release block.`);
567
+ } else {
568
+ console.log('⚠️ Warning: buildTypes > release block not found. minifyEnabled was not added.');
569
+ }
570
+
571
+
572
+
573
+
574
+
575
+
576
+ // Write the updated gradle content back to build.gradle
577
+ writeFileSync(gradleFilePath, updatedGradleContent, 'utf8');
578
+ console.log(`✅ Updated build.gradle with versionCode: ${finalVersionCode}, versionName: ${finalVersionName}, resConfigs "en" and "minifyEnabled true"`);
579
+
580
+ storeIds.forEach((id) => {
581
+ console.log(`ℹ️ Building for Store ID ${id}`);
582
+
583
+ // Set the environment variable for store ID
584
+ process.env.VITE_STORE_ID = id;
585
+
586
+ // Conditionally set the new file name
587
+ let newFileName;
588
+ let storeName = storeNames[id];
589
+
590
+ debugger;
591
+
592
+
593
+ managePackages(storeName);
594
+
595
+ if (storeName === "SamsungStore") {
596
+ // For SamsungStore, rename to versionCode value only
597
+ //newFileName = `${finalVersionCode}.aab`;
598
+ newFileName=`${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName.replace(/\./g,'_')}.aab`
599
+ } else {
600
+ // For other stores, use the standard naming format
601
+ //newFileName = `app-release-signed-${storeName}-b${finalVersionCode}-v${finalVersionName}.aab`;
602
+
603
+ newFileName=`${_appUniqueId}_${_appName.replaceAll(" ","_")}-${(storeName.toUpperCase()).replace("STORE","")}-b${finalVersionCode}-v${finalVersionName}.aab`
604
+
605
+
606
+ /*
607
+ const _appUniqueId = config.android?.APP_UNIQUE_ID;
608
+ const _appName=config.appName;
609
+ const _appPackageId=config.appId;
610
+ */
611
+
612
+ }
613
+
614
+ //storeName="amazon"
615
+ const checkFullPath = join("AAB", newFileName); // Update to point to the new AAB directory
616
+
617
+ // Modify minSdkVersion in variables.gradle for SamsungStore
618
+ const variablesGradleFilePath = join("android", "variables.gradle");
619
+ let variablesGradleContent = readFileSync(variablesGradleFilePath, 'utf8');
620
+
621
+ // Extract the current minSdkVersion
622
+ const minSdkVersionMatch = variablesGradleContent.match(/minSdkVersion\s*=\s*(\d+)/);
623
+ const currentMinSdkVersion = minSdkVersionMatch ? parseInt(minSdkVersionMatch[1], 10) : null;
624
+
625
+ // Store the original minSdkVersion (only on the first iteration)
626
+ if (!originalMinSdkVersion) {
627
+ originalMinSdkVersion = currentMinSdkVersion;
628
+ }
629
+ try {
630
+ // Modify the minSdkVersion based on the store
631
+
632
+
633
+ if(currentMinSdkVersion==23 || currentMinSdkVersion==24)
634
+ {
635
+ if (storeName === "SamsungStore" || storeName === "PlayStore" ||
636
+ //_appPackageId=="vfx.green.editor" || _appPackageId=="audio.music.sound.editor" || _appPackageId=="video.to.gif.maker"
637
+
638
+ //ffmpegUsedPackages.includes(_appPackageId)
639
+ _isffmpegUsed
640
+ ) {
641
+ if (currentMinSdkVersion !== 24) {
642
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, 'minSdkVersion = 24');
643
+ console.log('minSdkVersion updated to 24 for SamsungStore & PlayStore');
644
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
645
+ }
646
+ } else {
647
+ // For PlayStore and AmazonStore, ensure minSdkVersion is originalMinSdkVersion
648
+ //if (currentMinSdkVersion !== originalMinSdkVersion) {
649
+ variablesGradleContent = variablesGradleContent.replace(/minSdkVersion\s*=\s*\d+/, `minSdkVersion = ${amazonMinSdkVersion}`);
650
+ console.log(`minSdkVersion reverted to ${amazonMinSdkVersion} for ${storeName}`);
651
+ writeFileSync(variablesGradleFilePath, variablesGradleContent);
652
+ //}
653
+ }
654
+ }
655
+
656
+
657
+ // Run the Node.js script to modify plugin.xml
658
+ if (isAdmobFound) {
659
+ execSync('node buildCodeplay/modify-plugin-xml.js', { stdio: 'inherit' });
660
+ } else {
661
+ console.log("\x1b[33m%s\x1b[0m", "Seems to Pro Version [No ads found]");
662
+ }
663
+
664
+ // Run the Vite build
665
+ execSync(`npm run build:storeid${id}`, { stdio: 'inherit' });
666
+
667
+
668
+
669
+ // Copy the built files to the appropriate folder
670
+ const src = join("www", "*");
671
+ const dest = join("android", "app", "src", "main", "assets", "public");
672
+
673
+ // Use 'xcopy' command for Windows
674
+ execSync(`xcopy ${src} ${dest} /E /I /Y`, { stdio: 'inherit' });
675
+
676
+ // Build Android AAB file
677
+ //child_process.execSync('cd android && ./gradlew bundleRelease', { stdio: 'inherit' });
678
+
679
+
680
+ // Build Android AAB or APK file based on store
681
+ console.log(`🏗️ Building release for ${storeName}...`);
682
+
683
+ /* let buildType = "AAB";
684
+ if (["VivoStore", "OppoStore", "MiStore"].includes(storeName)) {
685
+ buildType = "APK";
686
+ } */
687
+
688
+
689
+ // Determine build type and signing type per store
690
+ let buildType = ["VivoStore","OppoStore","MiStore"].includes(storeName) ? "APK" : "AAB";
691
+ let signingType = buildType === "APK" ? "apksigner" : "jarsigner";
692
+
693
+ // Update capacitor.config.json for this store
694
+ updateCapacitorConfig(buildType, signingType);
695
+
696
+
697
+
698
+ execSync('npx cap sync android', { stdio: 'inherit' });
699
+ execSync(`npx cap build android --androidreleasetype=${buildType}`, { stdio: 'inherit' });
700
+
701
+ // Determine output paths
702
+ let oldFilePath;
703
+ let newExt = buildType === "APK" ? "apk" : "aab";
704
+
705
+ if (buildType === "APK") {
706
+ oldFilePath = join("android", "app", "build", "outputs", "apk", "release", "app-release-signed.apk");
707
+ } else {
708
+ oldFilePath = join("android", "app", "build", "outputs", "bundle", "release", "app-release-signed.aab");
709
+ }
710
+
711
+ const checkFullPath = join("AAB", newFileName.replace(/\.aab$/, `.${newExt}`));
712
+
713
+ // Rename the output file
714
+ if (existsSync(oldFilePath)) {
715
+ renameSync(oldFilePath, checkFullPath);
716
+ console.log(`✅ Renamed output ${newExt.toUpperCase()} file to: ${path.basename(checkFullPath)}`);
717
+ } else {
718
+ console.error(`❌ ${newExt.toUpperCase()} file not found after build.`);
719
+ }
720
+
721
+ } catch (error) {
722
+ console.error(`❌ Error during build for Store ID ${id}:`, error);
723
+ process.exit(1);
724
+ }
725
+ });
726
+
727
+ rl.close(); // Close the readline interface after all operations
728
+ });
729
+ });
730
+
731
+
732
+
733
+
734
+
735
+ function managePackages(store) {
736
+ console.log(`IAP Configurations - PlayStore: ${playstore}, Samsung: ${samsung}, Amazon: ${amazon}`);
737
+
738
+ let install = "";
739
+ let uninstall = "";
740
+
741
+
742
+
743
+ let manifestContent = readFileSync(androidManifestPath, 'utf-8');
744
+
745
+ const permissionsToRemove = [
746
+ 'com.android.vending.BILLING',
747
+ 'com.samsung.android.iap.permission.BILLING'
748
+ ];
749
+
750
+
751
+ permissionsToRemove.forEach(permission => {
752
+ const permissionRegex = new RegExp(`^\\s*<uses-permission\\s+android:name="${permission}"\\s*/?>\\s*[\r\n]?`, 'm');
753
+ if (permissionRegex.test(manifestContent)) {
754
+ manifestContent = manifestContent.replace(permissionRegex, '');
755
+ console.log(`✅ Removed <uses-permission android:name="${permission}" /> from AndroidManifest.xml`);
756
+ }
757
+ });
758
+
759
+ // Write the updated content back to the file
760
+ writeFileSync(androidManifestPath, manifestContent, 'utf-8');
761
+
762
+
763
+
764
+ if ((playstore && store === "PlayStore") || (amazon && store === "AmazonStore")) {
765
+ install = '@revenuecat/purchases-capacitor';
766
+ uninstall = 'cordova-plugin-samsungiap';
767
+
768
+ // Update AndroidManifest.xml for PlayStore
769
+ if(playstore)
770
+ updateAndroidManifest(store,
771
+ '<uses-permission android:name="com.android.vending.BILLING" />');
772
+
773
+ } else if (samsung && store === "SamsungStore") {
774
+ install = 'cordova-plugin-samsungiap';
775
+ uninstall = '@revenuecat/purchases-capacitor';
776
+
777
+ // Update AndroidManifest.xml for SamsungStore
778
+ updateAndroidManifest(store,
779
+ '<uses-permission android:name="com.samsung.android.iap.permission.BILLING" />');
780
+
781
+ } else {
782
+ console.log("No valid store specified or no configurations found. Both plugins will be uninstalled.");
783
+ try {
784
+ execSync(`npm uninstall cordova-plugin-samsungiap`, { stdio: 'inherit' });
785
+ execSync(`npm uninstall @revenuecat/purchases-capacitor`, { stdio: 'inherit' });
786
+ console.log(`✅ Both plugins uninstalled successfully.`);
787
+ } catch (err) {
788
+ console.error("❌ Error uninstalling plugins:", err);
789
+ }
790
+ return;
791
+ }
792
+
793
+ console.log(`⚠️ Installing ${install} and uninstalling ${uninstall} for ${store}...`);
794
+ try {
795
+ if (install) {
796
+ execSync(`npm install ${install}`, { stdio: 'inherit' });
797
+ }
798
+ if (uninstall) {
799
+ execSync(`npm uninstall ${uninstall}`, { stdio: 'inherit' });
800
+ }
801
+ console.log(`✅ ${install} installed and ${uninstall} uninstalled successfully.`);
802
+ } catch (err) {
803
+ console.error(`❌ Error managing packages for ${store}:`, err);
804
+ }
805
+ }
806
+
807
+
808
+
809
+ function updateAndroidManifest(store, addPermission) {
810
+ try {
811
+ if (!existsSync(androidManifestPath)) {
812
+ console.error("❌ AndroidManifest.xml file not found!");
813
+ return;
814
+ }
815
+
816
+ // Read the content of the AndroidManifest.xml
817
+ let manifestContent = readFileSync(androidManifestPath, 'utf-8');
818
+
819
+ // Normalize line endings to `\n` for consistent processing
820
+ manifestContent = manifestContent.replace(/\r\n/g, '\n');
821
+
822
+ // Check if the permission is already present
823
+ if (manifestContent.includes(addPermission.trim())) {
824
+ console.log(`${addPermission} is already in the AndroidManifest.xml. Skipping addition.`);
825
+ return; // Skip if the permission is already present
826
+ }
827
+
828
+ // Insert the permission before the closing </manifest> tag
829
+ const closingTag = '</manifest>';
830
+ const formattedPermission = ` ${addPermission.trim()}\n`;
831
+ if (manifestContent.includes(closingTag)) {
832
+ manifestContent = manifestContent.replace(
833
+ closingTag,
834
+ `${formattedPermission}${closingTag}`
835
+ );
836
+ console.log(`✅ Added ${addPermission} before </manifest> tag.`);
837
+ } else {
838
+ console.warn(`⚠️ </manifest> tag not found. Adding ${addPermission} at the end of the file.`);
839
+ manifestContent += `\n${formattedPermission}`;
840
+ }
841
+
842
+ // Normalize line endings back to `\r\n` and write the updated content
843
+ manifestContent = manifestContent.replace(/\n/g, '\r\n');
844
+ writeFileSync(androidManifestPath, manifestContent, 'utf-8');
845
+ console.log(`✅ AndroidManifest.xml updated successfully for ${store}`);
846
+ } catch (err) {
847
+ console.error(`❌ Error updating AndroidManifest.xml for ${store}:`, err);
848
+ }
849
+ }
850
+
851
+ restoreCapacitorConfig();
852
+ console.log("🏁 All builds completed, capacitor.config.json restored.");
853
+
854
+
855
+ /* function updateAndroidManifest1(store, addPermission) {
856
+ try {
857
+ if (!fs.existsSync(androidManifestPath)) {
858
+ console.error("AndroidManifest.xml file not found!");
859
+ return;
860
+ }
861
+
862
+ let manifestContent = fs.readFileSync(androidManifestPath, 'utf-8');
863
+
864
+
865
+
866
+ // Add the required permission if not already present
867
+ if (!manifestContent.includes(addPermission)) {
868
+ const manifestLines = manifestContent.split('\n');
869
+ const insertIndex = manifestLines.findIndex(line => line.trim().startsWith('<application'));
870
+ if (insertIndex > -1) {
871
+ manifestLines.splice(insertIndex, 0, ` ${addPermission}`);
872
+ manifestContent = manifestLines.join('\n');
873
+ console.log(`Added ${addPermission} to AndroidManifest.xml`);
874
+ }
875
+ }
876
+
877
+ // Write the updated content back to the file
878
+ fs.writeFileSync(androidManifestPath, manifestContent, 'utf-8');
879
+ console.log(`AndroidManifest.xml updated successfully for ${store}`);
880
+ } catch (err) {
881
+ console.error(`Error updating AndroidManifest.xml for ${store}:`, err);
882
+ }
883
+ } */
884
+
885
+
886
+
887
+
888
+
889
+
890
+
891
+