-
-
Notifications
You must be signed in to change notification settings - Fork 39
/
music-rpc.ts
executable file
·362 lines (312 loc) · 10.2 KB
/
music-rpc.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
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
#!/usr/bin/env deno run --allow-env --allow-run --allow-net --allow-read --allow-write --allow-ffi --allow-import --unstable-kv
import type { Activity } from "https://deno.land/x/[email protected]/mod.ts";
import { Client } from "https://deno.land/x/[email protected]/mod.ts";
import type {} from "https://raw.githubusercontent.com/NextFire/jxa/v0.0.5/run/global.d.ts";
import { run } from "https://raw.githubusercontent.com/NextFire/jxa/v0.0.5/run/mod.ts";
import type { iTunes } from "https://raw.githubusercontent.com/NextFire/jxa/v0.0.5/run/types/core.d.ts";
//#region RPC
class AppleMusicDiscordRPC {
static readonly CLIENT_IDS: Record<iTunesAppName, string> = {
iTunes: "979297966739300416",
Music: "773825528921849856",
};
static readonly KV_VERSION = 0;
private constructor(
public readonly appName: iTunesAppName,
public readonly rpc: Client,
public readonly kv: Deno.Kv,
public readonly defaultTimeout: number,
) {}
async run(): Promise<void> {
while (true) {
try {
await this.setActivityLoop();
} catch (err) {
console.error(err);
}
console.log("Reconnecting in %dms", this.defaultTimeout);
await sleep(this.defaultTimeout);
}
}
async setActivityLoop(): Promise<void> {
try {
await this.rpc.connect();
console.log("Connected to Discord RPC");
while (true) {
const timeout = await this.setActivity();
console.log("Next setActivity in %dms", timeout);
await sleep(timeout);
}
} finally {
// Ensure the connection is properly closed
if (this.rpc.ipc) {
console.log("Closing connection to Discord RPC");
this.rpc.close();
this.rpc.ipc = undefined;
}
}
}
async setActivity(): Promise<number> {
const open = await isMusicOpen(this.appName);
console.log("open:", open);
if (!open) {
await this.rpc.clearActivity();
return this.defaultTimeout;
}
const state = await getMusicState(this.appName);
console.log("state:", state);
switch (state) {
case "playing": {
const props = await getMusicProps(this.appName);
console.log("props:", props);
let delta, start, end;
if (props.duration) {
delta = (props.duration - props.playerPosition) * 1000;
end = Math.ceil(Date.now() + delta);
start = Math.ceil(Date.now() - props.playerPosition * 1000);
}
// EVERYTHING must be less than or equal to 128 chars long
const activity: Activity = {
// @ts-ignore: "listening to" is allowed in recent Discord versions
type: 2,
details: AppleMusicDiscordRPC.truncateString(props.name),
timestamps: { start, end },
assets: { large_image: "appicon" },
};
if (props.artist) {
activity.state = AppleMusicDiscordRPC.truncateString(props.artist);
}
if (props.album) {
const infos = await this.cachedTrackExtras(props);
console.log("infos:", infos);
activity.assets = {
large_image: infos.artworkUrl ?? "appicon",
large_text: AppleMusicDiscordRPC.truncateString(props.album),
};
const buttons = [];
if (infos.iTunesUrl) {
buttons.push({
label: "Play on Apple Music",
url: infos.iTunesUrl,
});
}
const query = encodeURIComponent(
`artist:${props.artist} track:${props.name}`,
);
const spotifyUrl = `https://open.spotify.com/search/${query}?si`;
if (spotifyUrl.length <= 512) {
buttons.push({
label: "Search on Spotify",
url: spotifyUrl,
});
}
if (buttons.length > 0) {
activity.buttons = buttons;
}
}
await this.rpc.setActivity(activity);
return Math.min(
(delta ?? this.defaultTimeout) + 1000,
this.defaultTimeout,
);
}
case "paused":
case "stopped": {
await this.rpc.clearActivity();
return this.defaultTimeout;
}
default:
throw new Error(`Unknown state: ${state}`);
}
}
async cachedTrackExtras(props: iTunesProps): Promise<TrackExtras> {
const { name, artist, album } = props;
const cacheIndex = `${name} ${artist} ${album}`;
const entry = await this.kv.get<TrackExtras>(["extras", cacheIndex]);
let infos = entry.value;
if (!infos) {
infos = await fetchTrackExtras(props);
await this.kv.set(["extras", cacheIndex], infos);
}
return infos;
}
static async create(defaultTimeout = 15e3): Promise<AppleMusicDiscordRPC> {
const macOSVersion = await this.getMacOSVersion();
const appName: iTunesAppName = macOSVersion >= 10.15 ? "Music" : "iTunes";
const rpc = new Client({ id: this.CLIENT_IDS[appName] });
const kv = await Deno.openKv(`cache_v${this.KV_VERSION}.sqlite3`);
return new this(appName, rpc, kv, defaultTimeout);
}
static async getMacOSVersion(): Promise<number> {
const cmd = new Deno.Command("sw_vers", { args: ["-productVersion"] });
const output = await cmd.output();
const decoded = new TextDecoder().decode(output.stdout);
const version = parseFloat(decoded.match(/\d+\.\d+/)![0]);
return version;
}
static truncateString(value: string, maxLength = 128): string {
return value.length <= maxLength
? value
: `${value.slice(0, maxLength - 3)}...`;
}
}
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const client = await AppleMusicDiscordRPC.create();
await client.run();
//#endregion
//#region JXA
function isMusicOpen(appName: iTunesAppName): Promise<boolean> {
return run((appName: iTunesAppName) => {
return Application("System Events").processes[appName].exists();
}, appName);
}
function getMusicState(appName: iTunesAppName): Promise<string> {
return run((appName: iTunesAppName) => {
const music = Application(appName) as unknown as iTunes;
return music.playerState();
}, appName);
}
function getMusicProps(appName: iTunesAppName): Promise<iTunesProps> {
return run((appName: iTunesAppName) => {
const music = Application(appName) as unknown as iTunes;
return {
...music.currentTrack().properties(),
playerPosition: music.playerPosition(),
};
}, appName);
}
//#endregion
//#region Extras
async function fetchTrackExtras(props: iTunesProps): Promise<TrackExtras> {
const json = await iTunesSearch(props);
let result: iTunesSearchResult | undefined;
if (json && json.resultCount === 1) {
result = json.results[0];
} else if (json && json.resultCount > 1) {
// If there are multiple results, find the right album
// Use includes as imported songs may format it differently
// Also put them all to lowercase in case of differing capitalisation
result = json.results.find(
(r) =>
r.collectionName.toLowerCase().includes(props.album.toLowerCase()) &&
r.trackName.toLowerCase().includes(props.name.toLowerCase()),
);
} else if (props.album.match(/\(.*\)$/)) {
// If there are no results, try to remove the part
// of the album name in parentheses (e.g. "Album (Deluxe Edition)")
return await fetchTrackExtras({
...props,
album: props.album.replace(/\(.*\)$/, "").trim(),
});
}
return {
artworkUrl: result?.artworkUrl100 ?? (await musicBrainzArtwork(props)),
iTunesUrl: result?.trackViewUrl,
};
}
async function iTunesSearch(
{ name, artist, album }: iTunesProps,
retryCount: number = 3,
): Promise<iTunesSearchResponse | undefined> {
// Asterisks tend to result in no songs found, and songs are usually able to be found without it
const query = `${name} ${artist} ${album}`.replace("*", "");
const params = new URLSearchParams({
media: "music",
entity: "song",
term: query,
});
const url = `https://itunes.apple.com/search?${params}`;
for (let i = 0; i < retryCount; i++) {
const resp = await fetch(url);
if (!resp.ok) {
console.error(
"Failed to fetch from iTunes API: %s %s (Attempt %d/%d)",
resp.statusText,
url,
i + 1,
retryCount,
);
resp.body?.cancel();
await sleep(200);
continue;
}
return (await resp.json()) as iTunesSearchResponse;
}
}
async function musicBrainzArtwork({
name,
artist,
album,
}: iTunesProps): Promise<string | undefined> {
const MB_EXCLUDED_NAMES = ["", "Various Artist"];
const queryTerms = [];
if (!MB_EXCLUDED_NAMES.every((elem) => artist.includes(elem))) {
queryTerms.push(
`artist:"${luceneEscape(removeParenthesesContent(artist))}"`,
);
}
if (!MB_EXCLUDED_NAMES.every((elem) => album.includes(elem))) {
queryTerms.push(`release:"${luceneEscape(album)}"`);
} else {
queryTerms.push(`recording:"${luceneEscape(name)}"`);
}
const query = queryTerms.join(" ");
const params = new URLSearchParams({
fmt: "json",
limit: "10",
query,
});
const resp = await fetch(`https://musicbrainz.org/ws/2/release?${params}`);
const json = (await resp.json()) as MBReleaseLookupResponse;
for (const release of json.releases) {
const resp = await fetch(
`https://coverartarchive.org/release/${release.id}/front`,
{ method: "HEAD" },
);
await resp.body?.cancel();
if (resp.ok) {
return resp.url;
}
}
}
function luceneEscape(term: string): string {
return term.replace(/([+\-&|!(){}\[\]^"~*?:\\])/g, "\\$1");
}
function removeParenthesesContent(term: string): string {
return term.replace(/\([^)]*\)/g, "").trim();
}
//#endregion
//#region TypeScript
type iTunesAppName = "iTunes" | "Music";
interface iTunesProps {
id: number;
name: string;
artist: string;
album: string;
year: number;
duration?: number;
playerPosition: number;
}
interface TrackExtras {
artworkUrl?: string;
iTunesUrl?: string;
}
interface iTunesSearchResponse {
resultCount: number;
results: iTunesSearchResult[];
}
interface iTunesSearchResult {
trackName: string;
collectionName: string;
artworkUrl100: string;
trackViewUrl: string;
}
interface MBReleaseLookupResponse {
releases: MBRelease[];
}
interface MBRelease {
id: string;
}
//#endregion