๐Ÿ“ฆ navidrome / website

๐Ÿ“„ validate-app-entry.js ยท 457 lines
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#!/usr/bin/env node

/**
 * Validate App Entry Script
 *
 * Usage: node validate-app-entry.js <app-name>
 * Example: node validate-app-entry.js dsub
 */

const fs = require("fs");
const path = require("path");
const https = require("https");
const http = require("http");

// Detect if running in CI environment
const isCI = process.env.CI === "true" || process.env.GITHUB_ACTIONS === "true";

// Color codes for terminal output (disabled in CI)
const colors = isCI
  ? {
      reset: "",
      red: "",
      green: "",
      yellow: "",
      blue: "",
      cyan: "",
    }
  : {
      reset: "\x1b[0m",
      red: "\x1b[31m",
      green: "\x1b[32m",
      yellow: "\x1b[33m",
      blue: "\x1b[34m",
      cyan: "\x1b[36m",
    };

class AppValidator {
  constructor(appName, options = {}) {
    this.appName = appName;
    this.appDir = path.join(process.cwd(), "assets", "apps", appName);
    this.yamlPath = path.join(this.appDir, "index.yaml");
    this.schemaPath = path.join(
      process.cwd(),
      "assets",
      "apps",
      "app-schema.json"
    );
    this.errors = [];
    this.warnings = [];
    this.quiet = options.quiet || false;
  }

  log(message, color = "reset") {
    if (isCI) {
      // In CI, just output plain text
      console.log(message);
    } else {
      console.log(`${colors[color]}${message}${colors.reset}`);
    }
  }

  addError(message) {
    this.errors.push(message);
  }

  addWarning(message) {
    this.warnings.push(message);
  }

  // Check if app directory exists
  checkDirectory() {
    if (!fs.existsSync(this.appDir)) {
      this.addError(`App directory not found: ${this.appDir}`);
      return false;
    }
    return true;
  }

  // Check if index.yaml exists and is valid YAML
  async validateYaml() {
    if (!fs.existsSync(this.yamlPath)) {
      this.addError("index.yaml file not found");
      return null;
    }

    try {
      const yaml = require("js-yaml");
      const content = fs.readFileSync(this.yamlPath, "utf8");
      const data = yaml.load(content);
      return data;
    } catch (err) {
      this.addError(`Invalid YAML syntax: ${err.message}`);
      return null;
    }
  }

  // Validate against JSON Schema
  async validateSchema(data) {
    if (!data) return;

    try {
      const Ajv = require("ajv");
      const addFormats = require("ajv-formats");

      const ajv = new Ajv({ allErrors: true, strict: false });
      addFormats(ajv);

      const schema = JSON.parse(fs.readFileSync(this.schemaPath, "utf8"));
      const validate = ajv.compile(schema);
      const valid = validate(data);

      if (!valid) {
        validate.errors.forEach((err) => {
          const field = err.instancePath || "root";
          const message = err.message;
          const detail = err.params ? JSON.stringify(err.params) : "";
          this.addError(
            `Schema validation: ${field} ${message} ${detail}`.trim()
          );
        });
      }
    } catch (err) {
      this.addError(`Schema validation failed: ${err.message}`);
    }
  }

  // Check if image files exist
  validateImages(data) {
    if (!data || !data.screenshots) return;

    // Check thumbnail
    if (data.screenshots.thumbnail) {
      const thumbnailPath = path.join(this.appDir, data.screenshots.thumbnail);
      if (!fs.existsSync(thumbnailPath)) {
        this.addError(
          `Thumbnail image not found: ${data.screenshots.thumbnail}`
        );
      } else {
        // Check file size (warn if > 500KB)
        const stats = fs.statSync(thumbnailPath);
        const sizeInKB = stats.size / 1024;
        if (sizeInKB > 500) {
          this.addWarning(
            `Thumbnail is ${Math.round(sizeInKB)}KB (recommended: < 500KB)`
          );
        }
      }
    }

    // Check gallery images
    if (data.screenshots.gallery && Array.isArray(data.screenshots.gallery)) {
      data.screenshots.gallery.forEach((imgPath) => {
        const fullPath = path.join(this.appDir, imgPath);
        if (!fs.existsSync(fullPath)) {
          this.addError(`Gallery image not found: ${imgPath}`);
        } else {
          // Check file size
          const stats = fs.statSync(fullPath);
          const sizeInKB = stats.size / 1024;
          if (sizeInKB > 500) {
            this.addWarning(
              `Gallery image ${imgPath} is ${Math.round(
                sizeInKB
              )}KB (recommended: < 500KB)`
            );
          }
        }
      });
    }
  }

  // Validate URL (checks if it's reachable)
  validateUrl(url, description) {
    return new Promise((resolve) => {
      if (!url) {
        resolve();
        return;
      }

      // Basic URL format check
      let parsedUrl;
      try {
        parsedUrl = new URL(url);
      } catch (err) {
        this.addError(`Invalid URL format for ${description}: ${url}`);
        resolve();
        return;
      }

      const protocol = parsedUrl.protocol === "https:" ? https : http;
      const timeout = 5000; // 5 seconds

      const options = {
        method: "HEAD", // Use HEAD instead of GET for faster response
        headers: {
          "User-Agent": "Navidrome-App-Validator/1.0",
        },
      };

      const req = protocol.request(url, options, (res) => {
        // Follow redirects (3xx) silently
        if (res.statusCode >= 300 && res.statusCode < 400) {
          resolve();
          return;
        }

        if (res.statusCode >= 400) {
          this.addWarning(
            `${description} returned status ${res.statusCode}: ${url}`
          );
        }
        resolve();
      });

      // Set timeout properly
      req.setTimeout(timeout, () => {
        req.destroy();
        this.addWarning(`${description} request timed out: ${url}`);
        resolve();
      });

      req.on("error", (err) => {
        if (err.code === "ENOTFOUND" || err.code === "ECONNREFUSED") {
          this.addWarning(`${description} appears unreachable: ${url}`);
        } else if (err.code !== "ETIMEDOUT" && err.code !== "ECONNRESET") {
          this.addWarning(`${description} validation failed: ${err.message}`);
        }
        resolve();
      });

      req.end();
    });
  }

  // Validate all URLs in the app data
  async validateUrls(data) {
    if (!data) return;

    const urlChecks = [];

    // Main app URL
    if (data.url) {
      urlChecks.push(this.validateUrl(data.url, "App URL"));
    }

    // Repository URL
    if (data.repoUrl) {
      urlChecks.push(this.validateUrl(data.repoUrl, "Repository URL"));
    }

    // Platform store URLs
    if (data.platforms) {
      ["android", "ios", "macos"].forEach((platform) => {
        if (
          data.platforms[platform] &&
          typeof data.platforms[platform] === "object"
        ) {
          if (data.platforms[platform].store) {
            urlChecks.push(
              this.validateUrl(
                data.platforms[platform].store,
                `${platform} store URL`
              )
            );
          }
        }
      });
    }

    await Promise.all(urlChecks);
  }

  // Main validation method
  async validate() {
    if (!this.quiet) {
      if (isCI) {
        console.log(`App: ${this.appName}`);
      } else {
        this.log(
          `\nValidating app: ${colors.cyan}${this.appName}${colors.reset}\n`
        );
      }
    }

    // Check directory
    if (!this.checkDirectory()) {
      return this.printResults();
    }

    // Validate YAML
    const data = await this.validateYaml();

    // Validate against schema
    await this.validateSchema(data);

    // Validate images
    this.validateImages(data);

    // Validate URLs
    if (!isCI && !this.quiet) {
      this.log("Checking URLs (this may take a moment)...", "blue");
    }
    await this.validateUrls(data);

    return this.printResults();
  }

  // Print validation results
  printResults() {
    if (this.errors.length === 0 && this.warnings.length === 0) {
      if (!this.quiet) {
        if (isCI) {
          console.log("Status: PASSED โœ…");
        } else {
          console.log("");
          this.log(
            "โœ… Validation passed! No errors or warnings found.",
            "green"
          );
        }
      }
      return 0;
    }

    if (isCI) {
      console.log("Status: FAILED โŒ\n");
    }

    if (this.errors.length > 0) {
      if (isCI) {
        console.log(`Errors (${this.errors.length}):`);
        this.errors.forEach((error, index) => {
          console.log(`  ${index + 1}. ${error}`);
        });
      } else {
        this.log(`\nโŒ Found ${this.errors.length} error(s):`, "red");
        this.errors.forEach((error, index) => {
          this.log(`  ${index + 1}. ${error}`, "red");
        });
      }
    }

    if (this.warnings.length > 0) {
      if (isCI) {
        console.log(`\nWarnings (${this.warnings.length}):`);
        this.warnings.forEach((warning, index) => {
          console.log(`  ${index + 1}. ${warning}`);
        });
      } else {
        this.log(`\nโš ๏ธ  Found ${this.warnings.length} warning(s):`, "yellow");
        this.warnings.forEach((warning, index) => {
          this.log(`  ${index + 1}. ${warning}`, "yellow");
        });
      }
    }

    console.log("");
    return this.errors.length > 0 ? 1 : 0;
  }
}

// Main execution
async function main() {
  // Parse arguments
  const args = process.argv.slice(2);
  const quiet = args.includes("-q") || args.includes("--quiet");
  const appName = args.find((arg) => !arg.startsWith("-"));

  // Check for required dependencies
  const requiredModules = ["js-yaml", "ajv", "ajv-formats"];
  const missingModules = [];

  for (const mod of requiredModules) {
    try {
      require.resolve(mod);
    } catch (e) {
      missingModules.push(mod);
    }
  }

  if (missingModules.length > 0) {
    console.error(
      `${colors.red}Error: Missing required dependencies${colors.reset}`
    );
    console.log(`\nPlease install the following packages:`);
    console.log(`  npm install ${missingModules.join(" ")}\n`);
    process.exit(1);
  }

  // If no app name provided, validate all apps
  if (!appName) {
    const appsDir = path.join(process.cwd(), "assets", "apps");

    if (!fs.existsSync(appsDir)) {
      console.error(
        `${colors.red}Error: Apps directory not found: ${appsDir}${colors.reset}`
      );
      process.exit(1);
    }

    const appDirs = fs
      .readdirSync(appsDir, { withFileTypes: true })
      .filter((dirent) => dirent.isDirectory() && dirent.name !== "_template")
      .map((dirent) => dirent.name)
      .sort();

    if (appDirs.length === 0) {
      console.log("No app entries found to validate");
      process.exit(0);
    }

    if (!quiet) {
      console.log(`Validating ${appDirs.length} app(s)...\n`);
    }

    let totalErrors = 0;
    let failedApps = [];

    for (const app of appDirs) {
      const validator = new AppValidator(app, { quiet });
      const exitCode = await validator.validate();

      if (exitCode !== 0) {
        totalErrors++;
        failedApps.push(app);
      }

      // Add separator between apps (except for last one) when not quiet
      if (!quiet && app !== appDirs[appDirs.length - 1]) {
        console.log("\n" + "=".repeat(60) + "\n");
      }
    }

    console.log("\n" + "=".repeat(60));
    console.log("\nValidation Summary:");
    console.log(`  Total apps: ${appDirs.length}`);
    console.log(`  Passed: ${appDirs.length - totalErrors}`);
    console.log(`  Failed: ${totalErrors}`);

    if (failedApps.length > 0) {
      console.log(`\nFailed apps: ${failedApps.join(", ")}`);
    }

    process.exit(totalErrors > 0 ? 1 : 0);
  }

  // Single app validation
  const validator = new AppValidator(appName, { quiet });
  const exitCode = await validator.validate();
  process.exit(exitCode);
}

main().catch((err) => {
  console.error(`${colors.red}Unexpected error: ${err.message}${colors.reset}`);
  process.exit(1);
});