Repository navigation
Expand file tree
/
Copy pathNativeAppIconResolver.ts
More file actions
279 lines (256 loc) · 9.71 KB
/
Copy pathNativeAppIconResolver.ts
File metadata and controls
279 lines (256 loc) · 9.71 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
import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
import type { NativeAppIconReference } from "@t3tools/contracts";
import * as Cache from "effect/Cache";
import * as Cause from "effect/Cause";
import * as Digest from "effect/crypto/Digest";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as Clock from "effect/Clock";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Exit from "effect/Exit";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Path from "effect/Path";
import * as PlatformError from "effect/PlatformError";
import * as Semaphore from "effect/Semaphore";
import * as Hex from "effect/encoding/Hex";
import { ChildProcess, ChildProcessSpawner } from "effect/process";
import * as HostProcess from "@t3tools/shared/HostProcess";
import * as ServerConfig from "../config.ts";
const ICON_SIZE = 64;
const COMMAND_TIMEOUT = "5 seconds";
const RESOLUTION_CACHE_TTL = Duration.hours(1);
const RESOLUTION_CACHE_MAX_ENTRIES = 256;
export class NativeAppIconResolver extends Context.Service<
NativeAppIconResolver,
{
readonly resolve: (app: NativeAppIconReference) => Effect.Effect<string | null>;
}
>()("t3/assets/NativeAppIconResolver") {}
function appCacheKey(app: NativeAppIconReference): string {
return JSON.stringify(app);
}
function appFromCacheKey(key: string): NativeAppIconReference {
return JSON.parse(key) as NativeAppIconReference;
}
const existingFile = Effect.fn("NativeAppIconResolver.existingFile")(function* (filePath: string) {
const fileSystem = yield* FileSystem.FileSystem;
const info = yield* fileSystem.stat(filePath).pipe(
Effect.asSome,
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeedNone : Effect.fail(error),
}),
);
return Option.isSome(info) && info.value.type === "File" ? filePath : null;
});
const commandOutput = Effect.fn("NativeAppIconResolver.commandOutput")(function* (
command: string,
args: ReadonlyArray<string>,
) {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
return yield* spawner
.string(ChildProcess.make(command, args, { stdin: "ignore", stderr: "ignore" }))
.pipe(Effect.timeout(COMMAND_TIMEOUT));
});
const plistValue = Effect.fn("NativeAppIconResolver.plistValue")(function* (
infoPlistPath: string,
key: string,
) {
return yield* commandOutput("/usr/bin/plutil", [
"-extract",
key,
"raw",
"-o",
"-",
infoPlistPath,
]).pipe(
Effect.map((value) => value.trim()),
Effect.orElseSucceed(() => ""),
);
});
function escapeSpotlightString(value: string): string {
return value.replace(/([\\'*?])/gu, "\\$1");
}
function containsControlCharacter(value: string): boolean {
return [...value].some((character) => {
const codePoint = character.codePointAt(0) ?? 0;
return codePoint <= 31 || codePoint === 127;
});
}
const resolveApplicationPath = Effect.fn("NativeAppIconResolver.resolveApplicationPath")(function* (
app: NativeAppIconReference,
) {
const path = yield* Path.Path;
if (app._tag === "app-path") {
const appPath = expandHomePath(app.path, yield* HostProcess.HomeDirectory);
return path.isAbsolute(appPath) && appPath.endsWith(".app") ? appPath : null;
}
const query =
app._tag === "app-id"
? `kMDItemCFBundleIdentifier == '${app.appId}'`
: `kMDItemContentType == 'com.apple.application-bundle' && kMDItemDisplayName == '${escapeSpotlightString(app.displayName)}'`;
const spotlightOutput = yield* commandOutput("/usr/bin/mdfind", [query]);
const candidates = spotlightOutput
.split(/\r?\n/u)
.map((value) => value.trim())
.filter((value) => value.endsWith(".app"));
const matchingCandidates =
app._tag === "app-id"
? candidates
: candidates.filter(
(value) =>
path.basename(value, ".app").toLocaleLowerCase() ===
app.displayName.toLocaleLowerCase(),
);
const rankedCandidates = matchingCandidates.length > 0 ? matchingCandidates : candidates;
let mostRecentlyUsed: { readonly path: string; readonly lastUsed: string } | null = null;
for (const candidate of rankedCandidates) {
const lastUsed = yield* commandOutput("/usr/bin/mdls", [
"-raw",
"-name",
"kMDItemLastUsedDate",
candidate,
]).pipe(
Effect.map((value) => value.trim()),
Effect.orElseSucceed(() => ""),
);
if (!mostRecentlyUsed || lastUsed > mostRecentlyUsed.lastUsed) {
mostRecentlyUsed = { path: candidate, lastUsed };
}
}
return mostRecentlyUsed?.path ?? null;
});
const resolveNativeAppIconUncached = Effect.fn("NativeAppIconResolver.resolveUncached")(function* (
app: NativeAppIconReference,
) {
const fileSystem = yield* FileSystem.FileSystem;
const path = yield* Path.Path;
const config = yield* ServerConfig.ServerConfig;
const appPath = yield* resolveApplicationPath(app);
if (!appPath) return null;
const canonicalAppPath = yield* fileSystem.realPath(appPath);
const infoPlistPath = path.join(canonicalAppPath, "Contents", "Info.plist");
const resourcesDirectory = path.join(canonicalAppPath, "Contents", "Resources");
const iconName =
(yield* plistValue(infoPlistPath, "CFBundleIconFile")) ||
(yield* plistValue(infoPlistPath, "CFBundleIconName"));
if (iconName && path.basename(iconName) !== iconName) return null;
const iconFileName = iconName ? (path.extname(iconName) ? iconName : `${iconName}.icns`) : null;
const resourceEntries = yield* fileSystem
.readDirectory(resourcesDirectory)
.pipe(Effect.orElseSucceed(() => []));
const sourceIconCandidate =
(iconFileName ? yield* existingFile(path.join(resourcesDirectory, iconFileName)) : null) ??
(yield* existingFile(path.join(resourcesDirectory, "AppIcon.icns"))) ??
(resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))
? yield* existingFile(
path.join(
resourcesDirectory,
resourceEntries.find((entry) => entry.toLowerCase().endsWith(".icns"))!,
),
)
: null);
if (!sourceIconCandidate) return null;
const sourceIconPath = yield* fileSystem.realPath(sourceIconCandidate);
const relativeSource = path.relative(resourcesDirectory, sourceIconPath);
if (
relativeSource === ".." ||
relativeSource.startsWith(`..${path.sep}`) ||
path.isAbsolute(relativeSource)
) {
return null;
}
const appVersion =
(yield* plistValue(infoPlistPath, "CFBundleVersion")) ||
(yield* plistValue(infoPlistPath, "CFBundleShortVersionString"));
const random = yield* SecureRandom.SecureRandom;
const digest = yield* Digest.Digest;
const cacheKey = yield* digest
.digest(
Digest.sha256,
new TextEncoder().encode(`${canonicalAppPath}\0${appVersion}\0${sourceIconPath}`),
)
.pipe(Effect.map(Hex.encode), Effect.orDie);
const cacheDirectory = path.join(config.providerStatusCacheDir, "native-app-icons");
const cachePath = path.join(cacheDirectory, `${cacheKey}.png`);
if (yield* existingFile(cachePath)) return cachePath;
yield* fileSystem.makeDirectory(cacheDirectory, { recursive: true });
const temporaryPath = path.join(
cacheDirectory,
`.${cacheKey}-${process.pid}-${(yield* Clock.currentTimeMillis).toString(36)}-${yield* random.uuidV4()}.png`,
);
yield* commandOutput("/usr/bin/sips", [
"-z",
String(ICON_SIZE),
String(ICON_SIZE),
"-s",
"format",
"png",
sourceIconPath,
"--out",
temporaryPath,
]).pipe(
Effect.tap(() => fileSystem.rename(temporaryPath, cachePath)),
Effect.ensuring(
fileSystem.remove(temporaryPath).pipe(Effect.catchTags({ PlatformError: () => Effect.void })),
),
);
return yield* existingFile(cachePath);
});
/** @public */
export const make = Effect.gen(function* () {
const fileSystem = yield* FileSystem.FileSystem;
const hostPlatform = yield* HostProcess.Platform;
const resolutionSemaphore = yield* Semaphore.make(2);
const resolutionCache: Cache.Cache<
string,
string | null,
PlatformError.PlatformError | Cause.TimeoutError
> = yield* Cache.makeWith(
(key: string) =>
resolutionSemaphore.withPermits(1)(resolveNativeAppIconUncached(appFromCacheKey(key))),
{
capacity: RESOLUTION_CACHE_MAX_ENTRIES,
timeToLive: Exit.match({
onSuccess: () => RESOLUTION_CACHE_TTL,
onFailure: () => Duration.zero,
}),
},
);
const cachedFileExists = (filePath: string) =>
fileSystem.stat(filePath).pipe(
Effect.map((info) => info.type === "File"),
Effect.catchTags({
PlatformError: (error) =>
error.reason._tag === "NotFound" ? Effect.succeed(false) : Effect.fail(error),
}),
);
const resolveAttempt = Effect.fn("NativeAppIconResolver.resolve")(function* (
app: NativeAppIconReference,
) {
if (
hostPlatform !== "darwin" ||
(app._tag === "display-name" && containsControlCharacter(app.displayName))
) {
return null;
}
const key = appCacheKey(app);
const cached = yield* Cache.get(resolutionCache, key);
if (cached === null) return null;
if (yield* cachedFileExists(cached)) return cached;
yield* Cache.invalidate(resolutionCache, key);
return yield* Cache.get(resolutionCache, key);
});
const resolve: NativeAppIconResolver["Service"]["resolve"] = (app) =>
resolveAttempt(app).pipe(
Effect.tapError((cause) =>
Effect.logDebug("Failed to resolve native application icon.", { app, cause }),
),
Effect.orElseSucceed(() => null),
);
return NativeAppIconResolver.of({ resolve });
});
export const layer = Layer.effect(NativeAppIconResolver, make);