-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs.template
More file actions
317 lines (268 loc) · 11.4 KB
/
Program.cs.template
File metadata and controls
317 lines (268 loc) · 11.4 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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using SpotifyAPI.Web;
using SpotifyAPI.Web.Auth;
namespace SpotifyGenreOrganizer
{
class Program
{
private static IConfiguration? _configuration;
private static SpotifyClient? _spotify;
private static string? _userId;
static async Task Main(string[] args)
{
Console.WriteLine("=== Spotify Genre Organizer ===\n");
// Load configuration
LoadConfiguration();
// Authenticate with Spotify
await AuthenticateAsync();
// Get user profile
var profile = await _spotify!.UserProfile.Current();
_userId = profile.Id;
Console.WriteLine($"Logged in as: {profile.DisplayName}\n");
// Fetch all saved tracks
Console.WriteLine("Fetching your saved tracks...");
var savedTracks = await FetchAllSavedTracksAsync();
Console.WriteLine($"Found {savedTracks.Count} saved tracks\n");
// Analyze genres
Console.WriteLine("Analyzing genres...");
var tracksByGenre = await CategorizeTracksByGenreAsync(savedTracks);
// Display genre statistics
Console.WriteLine("\nGenre Distribution:");
foreach (var genre in tracksByGenre.OrderByDescending(g => g.Value.Count))
{
Console.WriteLine($" {genre.Key}: {genre.Value.Count} tracks");
}
// Get target genres from configuration
var targetGenres = _configuration.GetSection("GenreFilters").Get<List<string>>()
?? new List<string>();
if (!targetGenres.Any())
{
Console.WriteLine("\nNo genres specified in appsettings.json!");
Console.WriteLine("Please add genres to the 'GenreFilters' section.");
return;
}
Console.WriteLine($"\nTarget genres: {string.Join(", ", targetGenres)}");
Console.Write("\nProceed with playlist creation? (y/n): ");
var response = Console.ReadLine()?.ToLower();
if (response != "y" && response != "yes")
{
Console.WriteLine("Cancelled.");
return;
}
// Create playlists for each genre
await CreateGenrePlaylistsAsync(tracksByGenre, targetGenres);
Console.WriteLine("\n✓ Complete! Your genre playlists have been created.");
}
static void LoadConfiguration()
{
_configuration = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
}
static async Task AuthenticateAsync()
{
var clientId = _configuration!["Spotify:ClientId"];
var clientSecret = _configuration["Spotify:ClientSecret"];
var redirectUri = _configuration["Spotify:RedirectUri"] ?? "http://localhost:5009/callback";
if (string.IsNullOrEmpty(clientId) || string.IsNullOrEmpty(clientSecret))
{
throw new Exception("Spotify ClientId and ClientSecret must be configured in appsettings.json");
}
// Start local server for OAuth callback
var server = new EmbedIOAuthServer(new Uri(redirectUri), 5009);
await server.Start();
server.AuthorizationCodeReceived += async (sender, response) =>
{
await server.Stop();
var config = SpotifyClientConfig.CreateDefault();
var tokenResponse = await new OAuthClient(config).RequestToken(
new AuthorizationCodeTokenRequest(
clientId,
clientSecret,
response.Code,
new Uri(redirectUri)
)
);
_spotify = new SpotifyClient(tokenResponse.AccessToken);
};
var loginRequest = new LoginRequest(
new Uri(redirectUri),
clientId,
LoginRequest.ResponseType.Code
)
{
Scope = new[]
{
Scopes.UserLibraryRead,
Scopes.PlaylistModifyPublic,
Scopes.PlaylistModifyPrivate
}
};
var uri = loginRequest.ToUri();
Console.WriteLine("Please authorize the application:");
Console.WriteLine(uri);
Console.WriteLine("\nOpening browser...");
// Open browser
OpenBrowser(uri.ToString());
// Wait for authentication
while (_spotify == null)
{
await Task.Delay(100);
}
Console.WriteLine("✓ Authentication successful!\n");
}
static void OpenBrowser(string url)
{
try
{
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = url,
UseShellExecute = true
});
}
catch
{
// Fallback for systems where UseShellExecute doesn't work
Console.WriteLine($"Please open this URL in your browser: {url}");
}
}
static async Task<List<SavedTrack>> FetchAllSavedTracksAsync()
{
var allTracks = new List<SavedTrack>();
var offset = 0;
const int limit = 50;
while (true)
{
var tracks = await _spotify!.Library.GetTracks(new LibraryTracksRequest
{
Limit = limit,
Offset = offset
});
if (tracks.Items == null || !tracks.Items.Any())
break;
allTracks.AddRange(tracks.Items!);
Console.Write($"\rFetched {allTracks.Count} tracks...");
if (tracks.Items.Count < limit)
break;
offset += limit;
}
Console.WriteLine();
return allTracks;
}
static async Task<Dictionary<string, List<FullTrack>>> CategorizeTracksByGenreAsync(
List<SavedTrack> savedTracks)
{
var tracksByGenre = new Dictionary<string, List<FullTrack>>(StringComparer.OrdinalIgnoreCase);
var processedCount = 0;
var multiGenreBehavior = _configuration!["MultiGenreBehavior"] ?? "AddToAll";
foreach (var savedTrack in savedTracks)
{
processedCount++;
if (processedCount % 50 == 0)
{
Console.Write($"\rAnalyzing track {processedCount}/{savedTracks.Count}...");
}
var track = savedTrack.Track;
var genres = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
// Get genres from all artists on the track
foreach (var artist in track.Artists)
{
try
{
var fullArtist = await _spotify!.Artists.Get(artist.Id);
if (fullArtist.Genres != null)
{
foreach (var genre in fullArtist.Genres)
{
genres.Add(genre);
}
}
}
catch (Exception ex)
{
Console.WriteLine($"\nWarning: Could not fetch artist {artist.Name}: {ex.Message}");
}
// Add small delay to avoid rate limiting
await Task.Delay(50);
}
// If no genres found, categorize as "Unknown"
if (!genres.Any())
{
genres.Add("Unknown");
}
// Add track to genre categories
if (multiGenreBehavior == "PrimaryOnly" && genres.Any())
{
var primaryGenre = genres.First();
if (!tracksByGenre.ContainsKey(primaryGenre))
tracksByGenre[primaryGenre] = new List<FullTrack>();
tracksByGenre[primaryGenre].Add(track);
}
else // AddToAll
{
foreach (var genre in genres)
{
if (!tracksByGenre.ContainsKey(genre))
tracksByGenre[genre] = new List<FullTrack>();
tracksByGenre[genre].Add(track);
}
}
}
Console.WriteLine($"\rAnalyzing track {processedCount}/{savedTracks.Count}... Done!");
return tracksByGenre;
}
static async Task CreateGenrePlaylistsAsync(
Dictionary<string, List<FullTrack>> tracksByGenre,
List<string> targetGenres)
{
foreach (var targetGenre in targetGenres)
{
// Find matching genre (case-insensitive, partial match)
var matchingGenres = tracksByGenre.Keys
.Where(g => g.Contains(targetGenre, StringComparison.OrdinalIgnoreCase))
.ToList();
if (!matchingGenres.Any())
{
Console.WriteLine($"\n⚠ No tracks found for genre: {targetGenre}");
continue;
}
// Combine all matching genre tracks
var tracks = matchingGenres
.SelectMany(g => tracksByGenre[g])
.DistinctBy(t => t.Id)
.ToList();
Console.WriteLine($"\nCreating playlist for '{targetGenre}' ({tracks.Count} tracks)...");
// Create playlist
var playlistName = $"{targetGenre.ToUpper()} - Auto Generated";
var playlist = await _spotify!.Playlists.Create(
_userId!,
new PlaylistCreateRequest(playlistName)
{
Description = $"Auto-generated playlist containing {targetGenre} tracks from your saved library.",
Public = false
}
);
Console.WriteLine($"✓ Created playlist: {playlistName}");
// Add tracks to playlist (Spotify allows max 100 tracks per request)
var trackUris = tracks.Select(t => t.Uri).ToList();
for (int i = 0; i < trackUris.Count; i += 100)
{
var batch = trackUris.Skip(i).Take(100).ToList();
await _spotify.Playlists.AddItems(
playlist.Id!,
new PlaylistAddItemsRequest(batch)
);
Console.WriteLine($" Added {Math.Min(i + 100, trackUris.Count)}/{trackUris.Count} tracks");
}
Console.WriteLine($"✓ Completed playlist: {playlistName}");
}
}
}
}