-
-
Notifications
You must be signed in to change notification settings - Fork 419
/
BeatSaver.cs
389 lines (351 loc) · 15.7 KB
/
BeatSaver.cs
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Windows;
using static ModAssistant.Http;
namespace ModAssistant.API
{
public class BeatSaver
{
private const string BeatSaverURLPrefix = "https://api.beatsaver.com";
private static readonly string CustomSongsFolder = Path.Combine("Beat Saber_Data", "CustomLevels");
private const bool BypassDownloadCounter = false;
public static async Task<BeatSaverMap> GetFromKey(string Key, bool showNotification = true)
{
if (showNotification && App.OCIWindow != "No") OneClickInstaller.Status.Show();
return await GetMap(Key, "key", showNotification);
}
public static async Task<BeatSaverMap> GetFromHash(string Hash, bool showNotification = true)
{
if (showNotification && App.OCIWindow != "No") OneClickInstaller.Status.Show();
return await GetMap(Hash, "hash", showNotification);
}
private static async Task<BeatSaverMap> GetMap(string id, string type, bool showNotification)
{
string urlSegment;
switch (type)
{
case "hash":
urlSegment = "/maps/hash/";
break;
case "key":
urlSegment = "/maps/id/";
break;
default:
return null;
}
BeatSaverMap map = new BeatSaverMap
{
Success = false
};
if (showNotification) Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:Installing"), id)}");
try
{
BeatSaverApiResponse beatsaver = await GetResponse(BeatSaverURLPrefix + urlSegment + id);
if (beatsaver != null && beatsaver.map != null)
{
map.response = beatsaver;
if (type == "hash")
{
map.HashToDownload = id.ToLower();
}
else
{
BeatSaverApiResponseMap.BeatsaverMapVersion mapVersion = null;
foreach (var version in map.response.map.versions)
{
if (mapVersion == null || version.createdAt > mapVersion.createdAt) mapVersion = version;
}
map.HashToDownload = mapVersion.hash;
}
map.Name = await InstallMap(map, showNotification);
map.Success = true;
}
}
catch (Exception e)
{
ModAssistant.Utils.Log($"Failed downloading BeatSaver map: {id} | Error: {e.Message}", "ERROR");
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:Failed"), (map.Name ?? id))}");
App.CloseWindowOnFinish = false;
}
return map;
}
private static async Task<BeatSaverApiResponse> GetResponse(string url, bool showNotification = true, int retries = 3)
{
if (retries == 0)
{
ModAssistant.Utils.Log($"Max tries reached: Skipping {url}", "ERROR");
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:RatelimitSkip"), url)}");
App.CloseWindowOnFinish = false;
throw new Exception("Max retries allowed");
}
BeatSaverApiResponse response = new BeatSaverApiResponse();
try
{
var resp = await HttpClient.GetAsync(url);
response.statusCode = resp.StatusCode;
response.ratelimit = GetRatelimit(resp.Headers);
string body = await resp.Content.ReadAsStringAsync();
if ((int)resp.StatusCode == 429)
{
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:RatelimitHit"), response.ratelimit.ResetTime.ToLocalTime())}");
await response.ratelimit.Wait();
return await GetResponse(url, showNotification, retries - 1);
}
if (response.statusCode == HttpStatusCode.OK)
{
response.map = JsonSerializer.Deserialize<BeatSaverApiResponseMap>(body);
return response;
}
else
{
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:Failed"), url)}");
App.CloseWindowOnFinish = false;
return response;
}
}
catch (Exception e)
{
if (showNotification)
{
MessageBox.Show($"{Application.Current.FindResource("OneClick:MapDownloadFailed")}\n\n" + e);
}
return null;
}
}
public static async Task<string> InstallMap(BeatSaverMap Map, bool showNotification = true)
{
BeatSaverApiResponseMap responseMap = Map.response.map;
BeatSaverApiResponseMap.BeatsaverMapVersion mapVersion = responseMap.versions.Where(r => r.hash == Map.HashToDownload).First();
if (mapVersion == null)
{
throw new Exception("Could not find map version.");
}
string zip = Path.Combine(Utils.BeatSaberPath, CustomSongsFolder, Map.HashToDownload) + ".zip";
string mapName = string.Concat(($"{responseMap.id} ({responseMap.metadata.songName} - {responseMap.metadata.levelAuthorName})")
.Split(ModAssistant.Utils.Constants.IllegalCharacters));
string directory = Path.Combine(Utils.BeatSaberPath, CustomSongsFolder, mapName);
#pragma warning disable CS0162 // Unreachable code detected
if (BypassDownloadCounter)
{
await Utils.DownloadAsset(mapVersion.downloadURL, CustomSongsFolder, Map.HashToDownload + ".zip", mapName, showNotification, true);
}
else
{
await Utils.DownloadAsset(mapVersion.downloadURL, CustomSongsFolder, Map.HashToDownload + ".zip", mapName, showNotification, true);
}
#pragma warning restore CS0162 // Unreachable code detected
if (File.Exists(zip))
{
string mimeType = MimeMapping.GetMimeMapping(zip);
if (!mimeType.StartsWith("application/x-zip"))
{
ModAssistant.Utils.Log($"Failed extracting BeatSaver map: {zip} \n| Content: {string.Join("\n", File.ReadAllLines(zip))}", "ERROR");
throw new Exception("File not a zip.");
}
try
{
using (FileStream stream = new FileStream(zip, FileMode.Open))
using (ZipArchive archive = new ZipArchive(stream))
{
foreach (ZipArchiveEntry file in archive.Entries)
{
string fileDirectory = Path.GetDirectoryName(Path.Combine(directory, file.FullName));
if (!Directory.Exists(fileDirectory))
{
Directory.CreateDirectory(fileDirectory);
}
if (!string.IsNullOrEmpty(file.Name))
{
file.ExtractToFile(Path.Combine(directory, file.FullName), true);
}
}
}
}
catch (Exception e)
{
File.Delete(zip);
ModAssistant.Utils.Log($"Failed extracting BeatSaver map: {zip} | Error: {e} \n| Content: {string.Join("\n", File.ReadAllLines(zip))}", "ERROR");
throw new Exception("File extraction failed.");
}
File.Delete(zip);
}
else
{
if (showNotification)
{
string line1 = (string)Application.Current.FindResource("OneClick:SongDownload:Failed");
string line2 = (string)Application.Current.FindResource("OneClick:SongDownload:NetworkIssues");
string title = (string)Application.Current.FindResource("OneClick:SongDownload:FailedTitle");
MessageBox.Show($"{line1}\n{line2}", title);
}
throw new Exception("Zip file not found.");
}
return mapName;
}
public static BeatSaverRatelimit GetRatelimit(HttpResponseHeaders headers)
{
BeatSaverRatelimit ratelimit = new BeatSaverRatelimit();
if (headers.TryGetValues("Rate-Limit-Remaining", out IEnumerable<string> _remaining))
{
var Remaining = _remaining.GetEnumerator();
Remaining.MoveNext();
ratelimit.Remaining = int.Parse(Remaining.Current);
Remaining.Dispose();
}
if (headers.TryGetValues("Rate-Limit-Reset", out IEnumerable<string> _reset))
{
var Reset = _reset.GetEnumerator();
Reset.MoveNext();
ratelimit.Reset = int.Parse(Reset.Current);
ratelimit.ResetTime = UnixTimestampToDateTime((long)ratelimit.Reset);
Reset.Dispose();
}
if (headers.TryGetValues("Rate-Limit-Total", out IEnumerable<string> _total))
{
var Total = _total.GetEnumerator();
Total.MoveNext();
ratelimit.Total = int.Parse(Total.Current);
Total.Dispose();
}
return ratelimit;
}
public static DateTime UnixTimestampToDateTime(double unixTime)
{
DateTime unixStart = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
long unixTimeStampInTicks = (long)(unixTime * TimeSpan.TicksPerSecond);
return new DateTime(unixStart.Ticks + unixTimeStampInTicks, DateTimeKind.Utc);
}
public static async Task Download(string url, string output, int retries = 3)
{
if (retries == 0)
{
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:RatelimitSkip"), url)}");
App.CloseWindowOnFinish = false;
ModAssistant.Utils.Log($"Max tries reached: Couldn't download {url}", "ERROR");
throw new Exception("Max retries allowed");
}
var resp = await HttpClient.GetAsync(url);
if ((int)resp.StatusCode == 429)
{
var ratelimit = GetRatelimit(resp.Headers);
Utils.SetMessage($"{string.Format((string)Application.Current.FindResource("OneClick:RatelimitHit"), ratelimit.ResetTime.ToLocalTime())}");
await ratelimit.Wait();
await Download(url, output, retries - 1);
}
using (var stream = await resp.Content.ReadAsStreamAsync())
using (var fs = new FileStream(output, FileMode.OpenOrCreate, FileAccess.Write))
{
await stream.CopyToAsync(fs);
}
}
#pragma warning disable IDE1006 // Naming Styles
public class BeatSaverMap
{
public BeatSaverApiResponse response { get; set; }
public bool Success { get; set; }
public string Name { get; set; }
public string HashToDownload { get; set; }
}
public class BeatSaverApiResponse
{
public HttpStatusCode statusCode { get; set; }
public BeatSaverRatelimit ratelimit { get; set; }
public BeatSaverApiResponseMap map { get; set; }
}
public class BeatSaverRatelimit
{
public int? Remaining { get; set; }
public int? Total { get; set; }
public int? Reset { get; set; }
public DateTime ResetTime { get; set; }
public async Task Wait()
{
await Task.Delay(new TimeSpan(Math.Max(ResetTime.Ticks - DateTime.UtcNow.Ticks, 0)));
}
}
public class BeatSaverApiResponseMap
{
public string id { get; set; }
public string name { get; set; }
public string description { get; set; }
public Uploader uploader { get; set; }
public Metadata metadata { get; set; }
public Stats stats { get; set; }
public DateTime uploaded { get; set; }
public bool automapper { get; set; }
public bool ranked { get; set; }
public bool qualified { get; set; }
public BeatsaverMapVersion[] versions { get; set; }
public class Metadata
{
public double bpm { get; set; }
public int duration { get; set; }
public string songName { get; set; }
public string songSubName { get; set; }
public string songAuthorName { get; set; }
public string levelAuthorName { get; set; }
}
public class Uploader
{
public int id { get; set; }
public string name { get; set; }
public string hash { get; set; }
public string avatar { get; set; }
}
public class Stats
{
public int plays { get; set; }
public int downloads { get; set; }
public int upvotes { get; set; }
public int downvotes { get; set; }
public double score { get; set; }
}
public class BeatsaverMapVersion
{
public string hash { get; set; }
public string key { get; set; }
public string state { get; set; }
public DateTime createdAt { get; set; }
public int sageScore { get; set; }
public Difficulty[] diffs { get; set; }
public string downloadURL { get; set; }
public string coverURL { get; set; }
public string previewURL { get; set; }
}
public class Difficulty
{
public double njs { get; set; }
public double offset { get; set; }
public int notes { get; set; }
public int bombs { get; set; }
public int obstacles { get; set; }
public double nps { get; set; }
public double length { get; set; }
public string characteristic { get; set; }
public string difficulty { get; set; }
public int events { get; set; }
public bool chroma { get; set; }
public bool me { get; set; }
public bool ne { get; set; }
public bool cinema { get; set; }
public double seconds { get; set; }
public ParitySummary paritySummary { get; set; }
public double stars { get; set; }
}
public class ParitySummary
{
public int errors { get; set; }
public int warns { get; set; }
public int resets { get; set; }
}
}
}
}
#pragma warning restore IDE1006 // Naming Styles