๐Ÿ“ฆ navidrome / website

๐Ÿ“„ convert-app-images.js ยท 266 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#!/usr/bin/env node

/**
 * Convert App Images Script
 *
 * Converts app images to WebP with max dimension of 1200px
 * Usage: node convert-app-images.js [app-name]
 * If no app-name is provided, converts all apps
 */

const fs = require("fs");
const path = require("path");
const sharp = require("sharp");

const MAX_SIZE = 1200;
const QUALITY = 80;

// 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 ImageConverter {
  constructor() {
    this.appsDir = path.join(process.cwd(), "assets", "apps");
  }

  log(message, color = "reset") {
    if (isCI) {
      console.log(message);
    } else {
      console.log(`${colors[color]}${message}${colors.reset}`);
    }
  }

  // Get image dimensions using sharp
  async getImageDimensions(imagePath) {
    try {
      const metadata = await sharp(imagePath).metadata();
      return { width: metadata.width, height: metadata.height };
    } catch (err) {
      this.log(`Error getting dimensions for ${imagePath}: ${err.message}`, "red");
      return null;
    }
  }

  // Update YAML file to replace old filename with new filename
  updateYaml(yamlPath, oldName, newName) {
    if (!fs.existsSync(yamlPath)) {
      return;
    }

    try {
      let content = fs.readFileSync(yamlPath, "utf8");
      const updated = content.replace(new RegExp(oldName, "g"), newName);

      if (content !== updated) {
        fs.writeFileSync(yamlPath, updated, "utf8");
        this.log(`  โœ“ Updated ${path.basename(yamlPath)}: ${oldName} โ†’ ${newName}`, "green");
      }
    } catch (err) {
      this.log(`  Error updating YAML: ${err.message}`, "yellow");
    }
  }

  // Convert a single image
  async convertImage(inputFile) {
    const ext = path.extname(inputFile).toLowerCase();
    const outputFile = inputFile.replace(/\.(png|jpg|jpeg)$/i, ".webp");

    // Get image dimensions
    const dimensions = await this.getImageDimensions(inputFile);
    if (!dimensions) return;

    const { width, height } = dimensions;
    const maxDimension = Math.max(width, height);

    // Skip ONLY if already webp AND smaller than MAX_SIZE
    if (ext === ".webp" && maxDimension <= MAX_SIZE) {
      this.log(
        `  โŠ˜ Skipping ${path.basename(inputFile)} (${width}x${height}) - already WebP and smaller than ${MAX_SIZE}px`,
        "cyan"
      );
      return;
    }

    // If already webp but too large, resize it in place
    if (ext === ".webp") {
      this.log(`  โ†’ Resizing ${path.basename(inputFile)} (${width}x${height})`, "blue");
      try {
        await sharp(inputFile)
          .resize(MAX_SIZE, MAX_SIZE, {
            fit: "inside",
            withoutEnlargement: true,
          })
          .webp({ quality: QUALITY })
          .toFile(inputFile + ".tmp");
        
        fs.renameSync(inputFile + ".tmp", inputFile);
        this.log(`  โœ“ Resized ${path.basename(inputFile)}`, "green");
      } catch (err) {
        this.log(`  Error resizing: ${err.message}`, "red");
        if (fs.existsSync(inputFile + ".tmp")) {
          fs.unlinkSync(inputFile + ".tmp");
        }
      }
      return;
    }

    // For non-webp files: check if output already exists
    if (fs.existsSync(outputFile)) {
      this.log(`  โœ“ ${path.basename(outputFile)} already exists, skipping`, "green");
      return;
    }

    // Process non-webp image
    try {
      if (maxDimension > MAX_SIZE) {
        this.log(
          `  โ†’ Resizing and converting ${path.basename(inputFile)} (${width}x${height})`,
          "blue"
        );
      } else {
        this.log(
          `  โ†’ Converting ${path.basename(inputFile)} (${width}x${height})`,
          "blue"
        );
      }

      await sharp(inputFile)
        .resize(MAX_SIZE, MAX_SIZE, {
          fit: "inside",
          withoutEnlargement: true,
        })
        .webp({ quality: QUALITY })
        .toFile(outputFile);

      this.log(`  โœ“ Created ${path.basename(outputFile)}`, "green");

      // Update index.yaml if it exists
      const appDir = path.dirname(inputFile);
      const yamlFile = path.join(appDir, "index.yaml");
      const oldFilename = path.basename(inputFile);
      const newFilename = path.basename(outputFile);

      this.updateYaml(yamlFile, oldFilename, newFilename);

      // Remove the original file after successful conversion
      fs.unlinkSync(inputFile);
      this.log(`  โœ“ Removed original file ${path.basename(inputFile)}`, "green");
    } catch (err) {
      this.log(`  Error converting: ${err.message}`, "red");
    }
  }

  // Process a single app
  async processApp(appName) {
    const appDir = path.join(this.appsDir, appName);

    if (!fs.existsSync(appDir)) {
      this.log(`Error: App directory not found: ${appDir}`, "red");
      return;
    }

    this.log(`Processing app: ${appName}`, "cyan");

    // Find all image files (png, jpg, jpeg)
    const imageFiles = this.findImages(appDir);

    if (imageFiles.length === 0) {
      this.log(`  No images found in ${appName}`, "yellow");
    } else {
      for (const image of imageFiles) {
        await this.convertImage(image);
      }
    }

    this.log("", "reset");
  }

  // Recursively find image files in a directory
  findImages(dir) {
    const images = [];
    const imageExtensions = [".png", ".jpg", ".jpeg", ".webp"];

    const walk = (currentDir) => {
      const items = fs.readdirSync(currentDir);

      items.forEach((item) => {
        const fullPath = path.join(currentDir, item);
        const stat = fs.statSync(fullPath);

        if (stat.isDirectory()) {
          walk(fullPath);
        } else if (imageExtensions.includes(path.extname(item).toLowerCase())) {
          images.push(fullPath);
        }
      });
    };

    walk(dir);
    return images;
  }

  // Process all apps
  async processAllApps() {
    this.log("Converting all app images to WebP format...", "cyan");
    this.log(`Max dimension: ${MAX_SIZE}px, Quality: ${QUALITY}`, "cyan");
    this.log("", "reset");

    const apps = fs
      .readdirSync(this.appsDir)
      .filter((item) => {
        const itemPath = path.join(this.appsDir, item);
        return (
          fs.statSync(itemPath).isDirectory() &&
          item !== "_template"
        );
      });

    for (const appName of apps) {
      await this.processApp(appName);
    }

    this.log("Done!", "green");
  }

  // Main execution
  async run(appName = null) {
    if (appName) {
      await this.processApp(appName);
    } else {
      await this.processAllApps();
    }
  }
}

// CLI execution
if (require.main === module) {
  const appName = process.argv[2];
  const converter = new ImageConverter();
  converter.run(appName).catch((err) => {
    console.error("Fatal error:", err);
    process.exit(1);
  });
}

module.exports = ImageConverter;