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
|
import { execAsync, Gio, GLib } from "astal";
import { pathToFileName } from "./strings";
export default class Thumbnailer {
static readonly thumbnailDir = `${CACHE}/thumbnails`;
static lazy = true;
static thumbWidth = 500;
static thumbHeight = 250;
static maxAttempts = 5;
static timeBetweenAttempts = 300;
static readonly #running = new Set<string>();
static getThumbPath(path: string) {
return `${this.thumbnailDir}/${pathToFileName(path, "png")}`;
}
static async shouldThumbnail(path: string) {
const [width, height] = (await execAsync(`identify -ping -format "%w %h" ${path}`)).split(" ").map(parseInt);
return width > this.thumbWidth || height > this.thumbHeight;
}
static async #thumbnail(path: string, attempts: number): Promise<string> {
const thumbPath = this.getThumbPath(path);
try {
await execAsync(
`magick -define jpeg:size=${this.thumbWidth * 2}x${this.thumbHeight * 2} ${path} -thumbnail ${
this.thumbWidth
}x${this.thumbHeight} -unsharp 0x.5 ${thumbPath}`
);
} catch {
if (attempts >= this.maxAttempts) {
console.error(`Failed to generate thumbnail for ${path}`);
return path;
}
await new Promise(r => setTimeout(r, this.timeBetweenAttempts));
return this.#thumbnail(path, attempts + 1);
}
return thumbPath;
}
static async thumbnail(path: string): Promise<string> {
if (!(await this.shouldThumbnail(path))) return path;
let thumbPath = this.getThumbPath(path);
// If not lazy (i.e. force gen), delete existing thumbnail
if (!this.lazy) Gio.File.new_for_path(thumbPath).delete(null);
// Wait for existing thumbnail for path to finish
while (this.#running.has(path)) await new Promise(r => setTimeout(r, 100));
// If no thumbnail, generate
if (!GLib.file_test(thumbPath, GLib.FileTest.EXISTS)) {
this.#running.add(path);
thumbPath = await this.#thumbnail(path, 0);
this.#running.delete(path);
}
return thumbPath;
}
// Static class
private constructor() {}
static {
GLib.mkdir_with_parents(this.thumbnailDir, 0o755);
}
}
|