-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathalbums.ts
More file actions
317 lines (289 loc) · 8.32 KB
/
Copy pathalbums.ts
File metadata and controls
317 lines (289 loc) · 8.32 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
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
import type { MaxInt } from '@spotify/web-api-ts-sdk';
import { z } from 'zod';
import type { SpotifyHandlerExtra, tool } from './types.js';
import { createSpotifyApi, formatDuration, handleSpotifyRequest, loadSpotifyConfig } from './utils.js';
const getAlbums: tool<{
albumIds: z.ZodUnion<[z.ZodString, z.ZodArray<z.ZodString>]>;
}> = {
name: 'getAlbums',
description:
'Get detailed information about one or more albums by their Spotify IDs',
schema: {
albumIds: z
.union([z.string(), z.array(z.string()).max(20)])
.describe('A single album ID or array of album IDs (max 20)'),
},
handler: async (args, _extra: SpotifyHandlerExtra) => {
const { albumIds } = args;
const ids = Array.isArray(albumIds) ? albumIds : [albumIds];
if (ids.length === 0) {
return {
content: [
{
type: 'text',
text: 'Error: No album IDs provided',
},
],
};
}
try {
const albums = await handleSpotifyRequest(async (spotifyApi) => {
return ids.length === 1
? [await spotifyApi.albums.get(ids[0])]
: await spotifyApi.albums.get(ids);
});
if (albums.length === 0) {
return {
content: [
{
type: 'text',
text: 'No albums found for the provided IDs',
},
],
};
}
if (albums.length === 1) {
const album = albums[0];
const artists = album.artists.map((a) => a.name).join(', ');
const releaseDate = album.release_date;
const totalTracks = album.total_tracks;
const albumType = album.album_type;
return {
content: [
{
type: 'text',
text: `# Album Details\n\n**Name**: "${album.name}"\n**Artists**: ${artists}\n**Release Date**: ${releaseDate}\n**Type**: ${albumType}\n**Total Tracks**: ${totalTracks}\n**ID**: ${album.id}`,
},
],
};
}
const formattedAlbums = albums
.map((album, i) => {
if (!album) return `${i + 1}. [Album not found]`;
const artists = album.artists.map((a) => a.name).join(', ');
return `${i + 1}. "${album.name}" by ${artists} (${album.release_date}) - ${album.total_tracks} tracks - ID: ${album.id}`;
})
.join('\n');
return {
content: [
{
type: 'text',
text: `# Multiple Albums\n\n${formattedAlbums}`,
},
],
};
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error getting albums: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
},
};
const getAlbumTracks: tool<{
albumId: z.ZodString;
limit: z.ZodOptional<z.ZodNumber>;
offset: z.ZodOptional<z.ZodNumber>;
}> = {
name: 'getAlbumTracks',
description: 'Get tracks from a specific album with pagination support',
schema: {
albumId: z.string().describe('The Spotify ID of the album'),
limit: z
.number()
.min(1)
.max(50)
.optional()
.describe('Maximum number of tracks to return (1-50)'),
offset: z
.number()
.min(0)
.optional()
.describe('Offset for pagination (0-based index)'),
},
handler: async (args, _extra: SpotifyHandlerExtra) => {
const { albumId, limit = 20, offset = 0 } = args;
try {
const tracks = await handleSpotifyRequest(async (spotifyApi) => {
return await spotifyApi.albums.tracks(
albumId,
undefined,
limit as MaxInt<50>,
offset,
);
});
if (tracks.items.length === 0) {
return {
content: [
{
type: 'text',
text: 'No tracks found in this album',
},
],
};
}
const formattedTracks = tracks.items
.map((track, i) => {
if (!track) return `${i + 1}. [Track not found]`;
const artists = track.artists.map((a) => a.name).join(', ');
const duration = formatDuration(track.duration_ms);
return `${offset + i + 1}. "${track.name}" by ${artists} (${duration}) - ID: ${track.id}`;
})
.join('\n');
return {
content: [
{
type: 'text',
text: `# Album Tracks (${offset + 1}-${offset + tracks.items.length} of ${tracks.total})\n\n${formattedTracks}`,
},
],
};
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error getting album tracks: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
},
};
const saveOrRemoveAlbumForUser: tool<{
albumIds: z.ZodArray<z.ZodString>;
action: z.ZodEnum<['save', 'remove']>;
}> = {
name: 'saveOrRemoveAlbumForUser',
description: 'Save or remove albums from the user\'s "Your Music" library',
schema: {
albumIds: z
.array(z.string())
.max(20)
.describe('Array of Spotify album IDs (max 20)'),
action: z
.enum(['save', 'remove'])
.describe('Action to perform: save or remove albums'),
},
handler: async (args, _extra: SpotifyHandlerExtra) => {
const { albumIds, action } = args;
if (albumIds.length === 0) {
return {
content: [
{
type: 'text',
text: 'Error: No album IDs provided',
},
],
};
}
try {
await createSpotifyApi();
const config = loadSpotifyConfig();
const uris = albumIds.map((id) => `spotify:album:${id}`).join(',');
const response = await fetch(
`https://api.spotify.com/v1/me/library?uris=${encodeURIComponent(uris)}`,
{
method: action === 'save' ? 'PUT' : 'DELETE',
headers: {
Authorization: `Bearer ${config.accessToken}`,
},
},
);
if (!response.ok) {
const errorData = await response.text();
throw new Error(`Spotify API error ${response.status}: ${errorData}`);
}
const actionPastTense = action === 'save' ? 'saved' : 'removed';
const preposition = action === 'save' ? 'to' : 'from';
return {
content: [
{
type: 'text',
text: `Successfully ${actionPastTense} ${albumIds.length} album${albumIds.length === 1 ? '' : 's'} ${preposition} your library`,
},
],
};
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error ${action === 'save' ? 'saving' : 'removing'} albums: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
},
};
const checkUsersSavedAlbums: tool<{
albumIds: z.ZodArray<z.ZodString>;
}> = {
name: 'checkUsersSavedAlbums',
description: 'Check if albums are saved in the user\'s "Your Music" library',
schema: {
albumIds: z
.array(z.string())
.max(20)
.describe('Array of Spotify album IDs to check (max 20)'),
},
handler: async (args, _extra: SpotifyHandlerExtra) => {
const { albumIds } = args;
if (albumIds.length === 0) {
return {
content: [
{
type: 'text',
text: 'Error: No album IDs provided',
},
],
};
}
try {
const savedStatus = await handleSpotifyRequest(async (spotifyApi) => {
return await spotifyApi.currentUser.albums.hasSavedAlbums(albumIds);
});
const formattedResults = albumIds
.map((albumId, i) => {
const isSaved = savedStatus[i];
return `${i + 1}. ${albumId}: ${isSaved ? 'Saved' : 'Not saved'}`;
})
.join('\n');
return {
content: [
{
type: 'text',
text: `# Album Save Status\n\n${formattedResults}`,
},
],
};
} catch (error) {
return {
content: [
{
type: 'text',
text: `Error checking saved albums: ${
error instanceof Error ? error.message : String(error)
}`,
},
],
};
}
},
};
export const albumTools = [
getAlbums,
getAlbumTracks,
saveOrRemoveAlbumForUser,
checkUsersSavedAlbums,
];