-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjxa.ts
73 lines (62 loc) · 1.7 KB
/
jxa.ts
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
import { run as runJxa } from "@jxa/run";
declare function Application(applicationName: "Music"): {
running(): boolean;
playerState(): string;
currentTrack(): {
properties(): {
title: string;
artist?: string;
year?: number;
[key: string]: any;
};
year(): number;
releaseDate(): string;
name(): string;
artist(): string;
};
};
type CurrentTrackResponse = {
title: string;
artist?: string;
year?: number;
paused: boolean;
};
export async function getCurrentTrack(): Promise<CurrentTrackResponse | null> {
// Using native macOS JavaScript for Automation (JXA), we
// ask the Music app for its current track then return it.
return await runJxa<CurrentTrackResponse | null>((format) => {
const musicApp = Application("Music");
if (!musicApp.running()) {
return null;
}
let title, artist, year, paused;
try {
let currentTrack = musicApp.currentTrack().properties();
title = currentTrack.name;
artist = currentTrack.artist;
year = currentTrack.year;
paused = musicApp.playerState() === "paused";
} catch (err) {
// If there's no current track or there's an error retrieving it,
// fall back to "Nothing is playing"
return null;
}
return { title, artist, year, paused };
});
}
export function formatTrack(
details: CurrentTrackResponse | null,
options?: { withYear?: boolean; pauseOverride?: boolean }
) {
if (!details) {
return `Nothing is playing`;
}
const withYear = options?.withYear ?? false;
const pauseOverride = options?.pauseOverride ?? false;
const { title, artist, year, paused } = details;
return pauseOverride && paused
? "Paused"
: `${artist ? `${artist} – ` : ""}${title}${
withYear && year ? ` (${year})` : ""
}`;
}