Playlist.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  1. using Newtonsoft.Json;
  2. using SimpleJSON;
  3. using SongBrowser.DataAccess.BeatSaverApi;
  4. using SongBrowser.Internals;
  5. using System;
  6. using System.Collections;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Threading.Tasks;
  12. using UnityEngine;
  13. using Logger = SongBrowser.Logging.Logger;
  14. using Sprites = SongBrowser.UI.Base64Sprites;
  15. namespace SongBrowser.DataAccess
  16. {
  17. public static class PlaylistsCollection
  18. {
  19. public static List<Playlist> loadedPlaylists = new List<Playlist>();
  20. public static void ReloadPlaylists(bool fullRefresh = true)
  21. {
  22. try
  23. {
  24. List<string> playlistFiles = new List<string>();
  25. if (PluginConfig.beatDropInstalled)
  26. {
  27. String beatDropPath = Path.Combine(PluginConfig.beatDropPlaylistsLocation, "playlists");
  28. if (Directory.Exists(beatDropPath))
  29. {
  30. string[] beatDropJSONPlaylists = Directory.GetFiles(beatDropPath, "*.json");
  31. string[] beatDropBPLISTPlaylists = Directory.GetFiles(beatDropPath, "*.bplist");
  32. playlistFiles.AddRange(beatDropJSONPlaylists);
  33. playlistFiles.AddRange(beatDropBPLISTPlaylists);
  34. Logger.Log($"Found {beatDropJSONPlaylists.Length + beatDropBPLISTPlaylists.Length} playlists in BeatDrop folder");
  35. }
  36. }
  37. string[] localJSONPlaylists = Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "Playlists"), "*.json");
  38. string[] localBPLISTPlaylists = Directory.GetFiles(Path.Combine(Environment.CurrentDirectory, "Playlists"), "*.bplist");
  39. playlistFiles.AddRange(localJSONPlaylists);
  40. playlistFiles.AddRange(localBPLISTPlaylists);
  41. Logger.Log($"Found {localJSONPlaylists.Length + localBPLISTPlaylists.Length} playlists in Playlists folder");
  42. if (fullRefresh)
  43. {
  44. loadedPlaylists.Clear();
  45. foreach (string path in playlistFiles)
  46. {
  47. try
  48. {
  49. Playlist playlist = Playlist.LoadPlaylist(path);
  50. if (Path.GetFileName(path) == "favorites.json" && playlist.playlistTitle == "Your favorite songs")
  51. continue;
  52. loadedPlaylists.Add(playlist);
  53. Logger.Log($"Found \"{playlist.playlistTitle}\" by {playlist.playlistAuthor}");
  54. }
  55. catch (Exception e)
  56. {
  57. Logger.Log($"Unable to parse playlist @ {path}! Exception: {e}");
  58. }
  59. }
  60. }
  61. else
  62. {
  63. foreach (string path in playlistFiles)
  64. {
  65. if (!loadedPlaylists.Any(x => x.fileLoc == path))
  66. {
  67. Logger.Log("Found new playlist! Path: " + path);
  68. try
  69. {
  70. Playlist playlist = Playlist.LoadPlaylist(path);
  71. if (Path.GetFileName(path) == "favorites.json" && playlist.playlistTitle == "Your favorite songs")
  72. continue;
  73. loadedPlaylists.Add(playlist);
  74. Logger.Log($"Found \"{playlist.playlistTitle}\" by {playlist.playlistAuthor}");
  75. if (SongCore.Loader.AreSongsLoaded)
  76. {
  77. MatchSongsForPlaylist(playlist);
  78. }
  79. }
  80. catch (Exception e)
  81. {
  82. Logger.Log($"Unable to parse playlist @ {path}! Exception: {e}");
  83. }
  84. }
  85. }
  86. }
  87. }
  88. catch (Exception e)
  89. {
  90. Logger.Exception("Unable to load playlists! Exception: " + e);
  91. }
  92. }
  93. public static void AddSongToPlaylist(Playlist playlist, PlaylistSong song)
  94. {
  95. playlist.songs.Add(song);
  96. if (playlist.playlistTitle == "Your favorite songs")
  97. {
  98. playlist.SavePlaylist();
  99. }
  100. }
  101. public static void RemoveLevelFromPlaylists(string levelId)
  102. {
  103. foreach (Playlist playlist in loadedPlaylists)
  104. {
  105. if (playlist.songs.Where(y => y.level != null).Any(x => x.level.levelID == levelId))
  106. {
  107. PlaylistSong song = playlist.songs.First(x => x.level != null && x.level.levelID == levelId);
  108. song.level = null;
  109. song.levelId = "";
  110. }
  111. if (playlist.playlistTitle == "Your favorite songs")
  112. {
  113. playlist.SavePlaylist();
  114. }
  115. }
  116. }
  117. public static void RemoveLevelFromPlaylist(Playlist playlist, string levelId)
  118. {
  119. if (playlist.songs.Where(y => y.level != null).Any(x => x.level.levelID == levelId))
  120. {
  121. PlaylistSong song = playlist.songs.First(x => x.level != null && x.level.levelID == levelId);
  122. song.level = null;
  123. song.levelId = "";
  124. }
  125. if (playlist.playlistTitle == "Your favorite songs")
  126. {
  127. playlist.SavePlaylist();
  128. }
  129. }
  130. public static void MatchSongsForPlaylist(Playlist playlist, bool matchAll = false)
  131. {
  132. if (!SongCore.Loader.AreSongsLoaded || SongCore.Loader.AreSongsLoading || playlist.playlistTitle == "All songs" || playlist.playlistTitle == "Your favorite songs") return;
  133. Dictionary<string, CustomPreviewBeatmapLevel> songMap = new Dictionary<string, CustomPreviewBeatmapLevel>(StringComparer.OrdinalIgnoreCase);
  134. foreach (var kp in SongCore.Loader.CustomLevels)
  135. {
  136. var songHash = CustomHelpers.GetSongHash(kp.Value.levelID);
  137. if (songMap.ContainsKey(songHash))
  138. {
  139. continue;
  140. }
  141. songMap.Add(songHash, kp.Value);
  142. }
  143. if (!playlist.songs.All(x => x.level != null) || matchAll)
  144. {
  145. playlist.songs.AsParallel().ForAll(x =>
  146. {
  147. if (x.level == null || matchAll)
  148. {
  149. try
  150. {
  151. // try to use levelID
  152. if (!string.IsNullOrEmpty(x.levelId))
  153. {
  154. string songHash = CustomHelpers.GetSongHash(x.levelId);
  155. if (songMap.ContainsKey(songHash))
  156. {
  157. x.level = songMap[songHash];
  158. x.hash = songHash;
  159. }
  160. }
  161. // failed, try again using hash
  162. if (x.level == null && !string.IsNullOrEmpty(x.hash))
  163. {
  164. // fix broken playlists from a bug in song browser
  165. if (x.hash.Contains("custom_level"))
  166. {
  167. x.hash = CustomHelpers.GetSongHash(x.hash);
  168. }
  169. if (songMap.ContainsKey(x.hash))
  170. {
  171. x.level = songMap[x.hash];
  172. }
  173. }
  174. if (x.level == null && !string.IsNullOrEmpty(x.key))
  175. {
  176. x.level = SongCore.Loader.CustomLevels.FirstOrDefault(y => y.Value.customLevelPath.Contains(x.key)).Value;
  177. if (x.level != null && !String.IsNullOrEmpty(x.level.levelID))
  178. {
  179. x.hash = CustomHelpers.GetSongHash(x.level.levelID);
  180. }
  181. }
  182. }
  183. catch (Exception e)
  184. {
  185. Logger.Warning($"Unable to match song with {(string.IsNullOrEmpty(x.key) ? " unknown key!" : ("key " + x.key + " !"))}");
  186. }
  187. }
  188. });
  189. }
  190. }
  191. public static void MatchSongsForAllPlaylists(bool matchAll = false)
  192. {
  193. Logger.Log("Matching songs for all playlists!");
  194. Task.Run(() =>
  195. {
  196. for (int i = 0; i < loadedPlaylists.Count; i++)
  197. {
  198. MatchSongsForPlaylist(loadedPlaylists[i], matchAll);
  199. }
  200. });
  201. }
  202. }
  203. public class PlaylistSong
  204. {
  205. public string key { get; set; }
  206. public string songName { get; set; }
  207. public string hash { get; set; }
  208. [NonSerialized]
  209. public string levelId;
  210. [NonSerialized]
  211. public CustomPreviewBeatmapLevel level;
  212. [NonSerialized]
  213. public bool oneSaber;
  214. [NonSerialized]
  215. public string path;
  216. public IEnumerator MatchKey()
  217. {
  218. if (!string.IsNullOrEmpty(key) || level == null || !(level is CustomPreviewBeatmapLevel))
  219. yield break;
  220. string songHash = null;
  221. if (!string.IsNullOrEmpty(hash))
  222. {
  223. songHash = hash;
  224. }
  225. else if (!string.IsNullOrEmpty(levelId))
  226. {
  227. songHash = CustomHelpers.GetSongHash(level.levelID);
  228. }
  229. if (songHash != null && SongDataCore.Plugin.BeatSaver.Data.Songs.ContainsKey(hash))
  230. {
  231. var song = SongDataCore.Plugin.BeatSaver.Data.Songs[hash];
  232. key = song.key;
  233. }
  234. else
  235. {
  236. // no more hitting api just to match a key. We know the song hash.
  237. //yield return SongDownloader.Instance.RequestSongByLevelIDCoroutine(level.levelID.Split('_')[2], (Song bsSong) => { if (bsSong != null) key = bsSong.key; });
  238. }
  239. }
  240. }
  241. public class Playlist
  242. {
  243. public string playlistTitle { get; set; }
  244. public string playlistAuthor { get; set; }
  245. public string image { get; set; }
  246. public int playlistSongCount { get; set; }
  247. public List<PlaylistSong> songs { get; set; }
  248. public string fileLoc { get; set; }
  249. public string customDetailUrl { get; set; }
  250. public string customArchiveUrl { get; set; }
  251. [NonSerialized]
  252. public Sprite icon;
  253. public Playlist()
  254. {
  255. }
  256. public Playlist(JSONNode playlistNode)
  257. {
  258. string image = playlistNode["image"].Value;
  259. if (!string.IsNullOrEmpty(image))
  260. {
  261. try
  262. {
  263. icon = Sprites.Base64ToSprite(image.Substring(image.IndexOf(",") + 1));
  264. }
  265. catch
  266. {
  267. Logger.Exception("Unable to convert playlist image to sprite!");
  268. icon = Sprites.BeastSaberLogo;
  269. }
  270. }
  271. else
  272. {
  273. icon = Sprites.BeastSaberLogo;
  274. }
  275. playlistTitle = playlistNode["playlistTitle"];
  276. playlistAuthor = playlistNode["playlistAuthor"];
  277. customDetailUrl = playlistNode["customDetailUrl"];
  278. customArchiveUrl = playlistNode["customArchiveUrl"];
  279. if (!string.IsNullOrEmpty(customDetailUrl))
  280. {
  281. if (!customDetailUrl.EndsWith("/"))
  282. customDetailUrl += "/";
  283. Logger.Log("Found playlist with customDetailUrl! Name: " + playlistTitle + ", CustomDetailUrl: " + customDetailUrl);
  284. }
  285. if (!string.IsNullOrEmpty(customArchiveUrl) && customArchiveUrl.Contains("[KEY]"))
  286. {
  287. Logger.Log("Found playlist with customArchiveUrl! Name: " + playlistTitle + ", CustomArchiveUrl: " + customArchiveUrl);
  288. }
  289. songs = new List<PlaylistSong>();
  290. foreach (JSONNode node in playlistNode["songs"].AsArray)
  291. {
  292. PlaylistSong song = new PlaylistSong();
  293. song.key = node["key"];
  294. song.songName = node["songName"];
  295. song.hash = node["hash"];
  296. song.levelId = node["levelId"];
  297. songs.Add(song);
  298. }
  299. if (playlistNode["playlistSongCount"] != null)
  300. {
  301. playlistSongCount = playlistNode["playlistSongCount"].AsInt;
  302. }
  303. if (playlistNode["fileLoc"] != null)
  304. fileLoc = playlistNode["fileLoc"];
  305. if (playlistNode["playlistURL"] != null)
  306. fileLoc = playlistNode["playlistURL"];
  307. }
  308. public static Playlist LoadPlaylist(string path)
  309. {
  310. Playlist playlist = new Playlist(JSON.Parse(File.ReadAllText(path)));
  311. playlist.fileLoc = path;
  312. return playlist;
  313. }
  314. public void SavePlaylist(string path = "")
  315. {
  316. SharedCoroutineStarter.instance.StartCoroutine(SavePlaylistCoroutine(path));
  317. }
  318. public IEnumerator SavePlaylistCoroutine(string path = "")
  319. {
  320. Logger.Log($"Saving playlist \"{playlistTitle}\"...");
  321. try
  322. {
  323. if (icon != null)
  324. {
  325. image = Sprites.SpriteToBase64(icon);
  326. }
  327. else
  328. {
  329. image = null;
  330. }
  331. playlistSongCount = songs.Count;
  332. }
  333. catch (Exception e)
  334. {
  335. Logger.Exception("Unable to save playlist! Exception: " + e);
  336. yield break;
  337. }
  338. // match key if we can, not really that important anymore
  339. if (SongDataCore.Plugin.BeatSaver.Data.Songs.Count > 0)
  340. {
  341. foreach (PlaylistSong song in songs)
  342. {
  343. yield return song.MatchKey();
  344. }
  345. }
  346. try
  347. {
  348. if (!string.IsNullOrEmpty(path))
  349. {
  350. fileLoc = Path.GetFullPath(path);
  351. }
  352. File.WriteAllText(fileLoc, JsonConvert.SerializeObject(this, Formatting.Indented));
  353. Logger.Log("Playlist saved!");
  354. }
  355. catch (Exception e)
  356. {
  357. Logger.Exception("Unable to save playlist! Exception: " + e);
  358. yield break;
  359. }
  360. }
  361. public bool PlaylistEqual(object obj)
  362. {
  363. if (obj == null) return false;
  364. var playlist = obj as Playlist;
  365. if (playlist == null) return false;
  366. int songCountThis = (songs != null ? (songs.Count > 0 ? songs.Count : playlistSongCount) : playlistSongCount);
  367. int songCountObj = (playlist.songs != null ? (playlist.songs.Count > 0 ? playlist.songs.Count : playlist.playlistSongCount) : playlist.playlistSongCount);
  368. return playlistTitle == playlist.playlistTitle &&
  369. playlistAuthor == playlist.playlistAuthor &&
  370. songCountThis == songCountObj;
  371. }
  372. public void CreateNew(String fileLoc)
  373. {
  374. File.WriteAllText(fileLoc, JsonConvert.SerializeObject(this, Formatting.Indented));
  375. }
  376. }
  377. }