forked from JohnnyCrazy/SpotifyAPI-NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
280 lines (250 loc) · 11.6 KB
/
Program.cs
File metadata and controls
280 lines (250 loc) · 11.6 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
using SpotifyAPI.Web;
using SpotifyAPI.Web.Auth;
using SpotifyAPI.Web.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
namespace SpotifyAPI.AlbumMetadataSearch
{
class Program
{
static void Main(string[] args)
{
string path = args[0];
int depth = 0;
DirectoryInfo dir = new DirectoryInfo(path);
DirectoryInfo[] children = dir.GetDirectories();
while (children.Length > 0)
{
depth++;
children = children[0].GetDirectories();
}
if (depth > 0)
{
Console.WriteLine($"Child directories found, detected depth is {depth}. Press Y to continue");
if (!Console.ReadLine().Trim().Equals("Y", StringComparison.InvariantCultureIgnoreCase))
{
return;
}
Console.WriteLine();
}
CredentialsAuth auth = new CredentialsAuth("c04cdb49f2e34e25989458ff1653e194", "e8c464ee20d1453aa03330669f4ed2d9");
Task<Token> task = auth.GetToken();
task.Wait();
var api = new SpotifyWebAPI()
{
TokenType = "Bearer",
AccessToken = task.Result.AccessToken
};
ProcessDirectory(api, dir, depth);
}
private static SearchItem artistSearch = null;
public static SearchItem GetArtistSearch(SpotifyWebAPI api, string artistName)
{
if (artistSearch == null)
{
artistSearch = api.SearchItems(artistName, Web.Enums.SearchType.Artist, market: "US");
}
return artistSearch;
}
public static Dictionary<string, List<SimpleAlbum>> artistAlbums = new Dictionary<string, List<SimpleAlbum>>(StringComparer.InvariantCultureIgnoreCase);
public static List<SimpleAlbum> GetArtistAlbums(SpotifyWebAPI api, string id)
{
if (!artistAlbums.TryGetValue(id, out List<SimpleAlbum> albums))
{
albums = api.GetArtistsAlbums(id, SpotifyAPI.Web.Enums.AlbumType.Album, limit: 250, market: "US").Items;
artistAlbums[id] = albums;
}
return albums;
}
public static Dictionary<string, FullAlbum> fullAlbums = new Dictionary<string, FullAlbum>();
public static FullAlbum GetFullAlbum(SpotifyWebAPI api, string id)
{
if (!fullAlbums.TryGetValue(id, out FullAlbum fullAlbum))
{
fullAlbum = api.GetAlbum(id);
}
return fullAlbum;
}
public static void ProcessDirectory(SpotifyWebAPI api, DirectoryInfo dir, int depth)
{
if (depth != 0)
{
depth--;
foreach (DirectoryInfo di in dir.GetDirectories())
{
ProcessDirectory(api, di, depth);
}
return;
}
string path = dir.FullName;
string[] paths = path.Split(new char[] { Path.DirectorySeparatorChar });
string artistName = paths[paths.Length - 2];
string albumName = paths[paths.Length - 1];
Console.WriteLine($"Searching for {artistName} - {albumName}");
List<KeyValuePair<FullAlbum, FullArtist>> albums = new List<KeyValuePair<FullAlbum, FullArtist>>();
var search = GetArtistSearch(api, artistName);
bool hasExactMatch = false;
bool hasQualifyingMatch = false;
foreach (FullArtist a in search.Artists.Items)
{
List<SimpleAlbum> searchAlbums = GetArtistAlbums(api, a.Id);
if (searchAlbums == null)
{
continue;
}
foreach (SimpleAlbum album in searchAlbums)
{
if (a.Name.Equals(artistName, StringComparison.InvariantCultureIgnoreCase) &&
album.Name.Equals(albumName, StringComparison.InvariantCultureIgnoreCase))
{
hasExactMatch = true;
break;
}
else if (
(artistName.StartsWith(a.Name, StringComparison.InvariantCultureIgnoreCase) || a.Name.StartsWith(artistName, StringComparison.InvariantCultureIgnoreCase)) &&
(albumName.StartsWith(album.Name, StringComparison.InvariantCultureIgnoreCase) || album.Name.StartsWith(albumName, StringComparison.InvariantCultureIgnoreCase)))
{
hasQualifyingMatch = true;
}
}
foreach (SimpleAlbum album in searchAlbums)
{
bool exactMatch =
a.Name.Equals(artistName, StringComparison.InvariantCultureIgnoreCase) &&
album.Name.Equals(albumName, StringComparison.InvariantCultureIgnoreCase);
bool qualifyingMatch =
(artistName.StartsWith(a.Name, StringComparison.InvariantCultureIgnoreCase) || a.Name.StartsWith(artistName, StringComparison.InvariantCultureIgnoreCase)) &&
(albumName.StartsWith(album.Name, StringComparison.InvariantCultureIgnoreCase) || album.Name.StartsWith(albumName, StringComparison.InvariantCultureIgnoreCase));
if (hasExactMatch)
{
if (!exactMatch)
{
continue;
}
Console.WriteLine("Exact Match");
}
else if (hasQualifyingMatch)
{
if (!qualifyingMatch)
{
continue;
}
Console.WriteLine("Qualifying Match");
}
Console.WriteLine($"#{albums.Count + 1} - {a.Name} - \"{album.Name}\" - {album.ReleaseDate} - {album.Type}");
FullAlbum fullAlbum = GetFullAlbum(api, album.Id);
albums.Add(new KeyValuePair<FullAlbum, FullArtist>(fullAlbum, a));
foreach (SimpleTrack track in fullAlbum.Tracks.Items)
{
Console.WriteLine($" D:{track.DiscNumber} T:{track.TrackNumber} - {track.Name}, MS:{track.DurationMs}");
}
}
}
FullAlbum selectedAlbum = null;
FullArtist selectedArtist = null;
if (albums.Count > 0)
{
Console.WriteLine("Type album number to accept album info");
if (int.TryParse(Console.ReadLine(), out int id) && id > 0 && id <= albums.Count)
{
selectedAlbum = albums[id - 1].Key;
selectedArtist = albums[id - 1].Value;
}
}
if (selectedAlbum != null)
{
string pictureFile = null;
if (selectedAlbum.Images.Count > 0)
{
Console.WriteLine("Downloading album images");
List<string> sizes = new List<string>()
{
"Small",
"Large"
};
foreach (string size in sizes)
{
Image i = selectedAlbum.Images.OrderBy(im => im.Height).FirstOrDefault(
im => size == "Small" ? im.Height <= 300 && im.Height > 64 : im.Height > 300);
if (i != null)
{
try
{
using (WebClient webClient = new WebClient())
{
string name = "AlbumArt_" + size + ".jpg";
if (File.Exists(Path.Combine(path, name)))
{
File.Delete(Path.Combine(path, name));
}
webClient.DownloadFile(i.Url, Path.Combine(path, name));
if (pictureFile == null)
{
pictureFile = Path.Combine(path, name);
}
}
}
catch (Exception e)
{
Console.WriteLine("Error saving thumbnail: " + e.Message);
}
}
}
}
int index = -1;
foreach (string file in Directory.EnumerateFiles(path, "*.mp3").OrderBy(f => f).ToList())
{
if (selectedAlbum.Tracks.Items.Count > ++index)
{
SimpleTrack track = selectedAlbum.Tracks.Items[index];
string safeName = track.Name + ".mp3";
foreach (char c in Path.GetInvalidFileNameChars())
{
safeName = safeName.Replace(c, '_');
}
string moveTo = Path.Combine(Path.GetDirectoryName(file), $"{track.TrackNumber:00} {safeName}");
Console.WriteLine($"Updating {Path.GetFileName(file)} to {Path.GetFileName(moveTo)}");
try
{
File.Move(file, moveTo);
}
catch (Exception e)
{
Console.WriteLine($"Error: {e.Message}");
}
TagLib.File tagFile = TagLib.File.Create(moveTo);
tagFile.Tag.Title = track.Name;
tagFile.Tag.Performers = track.Artists.Select(a => a.Name).ToArray();
tagFile.Tag.AlbumArtists = new string[] { artistName };
tagFile.Tag.Album = selectedAlbum.Name;
tagFile.Tag.Track = (uint)track.TrackNumber;
tagFile.Tag.Disc = (uint)track.DiscNumber;
if (DateTime.TryParse(selectedAlbum.ReleaseDate, out DateTime release))
{
tagFile.Tag.Year = (uint)release.Year;
}
tagFile.Tag.Genres = selectedAlbum.Genres.ToArray();
tagFile.Tag.Copyright = string.Join(", ", selectedAlbum.Copyrights.Select(c => $"{c.Type} - {c.Text}"));
if (pictureFile != null)
{
tagFile.Tag.Pictures = new TagLib.IPicture[] { new TagLib.Picture(pictureFile) };
}
tagFile.Save();
}
else
{
Console.WriteLine($"{Path.GetFileName(file)} not in track listing");
}
}
Console.WriteLine($"{artistName} - {albumName} Complete");
Console.WriteLine("-------------------------------------");
Console.WriteLine();
//Console.Clear();
}
}
}
}