SongBrowserModel.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  1. using SongBrowser.DataAccess;
  2. using SongBrowser.Internals;
  3. using SongBrowser.UI;
  4. using SongCore.OverrideClasses;
  5. using SongCore.Utilities;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Text.RegularExpressions;
  12. using UnityEngine;
  13. using static StandardLevelInfoSaveData;
  14. using Logger = SongBrowser.Logging.Logger;
  15. namespace SongBrowser
  16. {
  17. public class SongBrowserModel
  18. {
  19. private readonly String CUSTOM_SONGS_DIR = Path.Combine("Beat Saber_Data", "CustomLevels");
  20. private readonly DateTime EPOCH = new DateTime(1970, 1, 1);
  21. // song_browser_settings.xml
  22. private SongBrowserSettings _settings;
  23. // song list management
  24. private double _customSongDirLastWriteTime = 0;
  25. private Dictionary<String, CustomPreviewBeatmapLevel> _levelIdToCustomLevel;
  26. private Dictionary<String, double> _cachedLastWriteTimes;
  27. private Dictionary<string, int> _weights;
  28. private Dictionary<BeatmapDifficulty, int> _difficultyWeights;
  29. private Dictionary<string, ScrappedSong> _levelHashToDownloaderData = null;
  30. private Dictionary<string, int> _levelIdToPlayCount;
  31. public BeatmapCharacteristicSO CurrentBeatmapCharacteristicSO;
  32. public static Func<IBeatmapLevelPack, List<IPreviewBeatmapLevel>> CustomFilterHandler;
  33. public static Action<Dictionary<string, CustomPreviewBeatmapLevel>> didFinishProcessingSongs;
  34. /// <summary>
  35. /// Get the settings the model is using.
  36. /// </summary>
  37. public SongBrowserSettings Settings
  38. {
  39. get
  40. {
  41. return _settings;
  42. }
  43. }
  44. /// <summary>
  45. /// Get the last selected (stored in settings) level id.
  46. /// </summary>
  47. public String LastSelectedLevelId
  48. {
  49. get
  50. {
  51. return _settings.currentLevelId;
  52. }
  53. set
  54. {
  55. _settings.currentLevelId = value;
  56. _settings.Save();
  57. }
  58. }
  59. private Playlist _currentPlaylist;
  60. /// <summary>
  61. /// Manage the current playlist if one exists.
  62. /// </summary>
  63. public Playlist CurrentPlaylist
  64. {
  65. get
  66. {
  67. if (_currentPlaylist == null)
  68. {
  69. _currentPlaylist = Playlist.LoadPlaylist(this._settings.currentPlaylistFile);
  70. }
  71. return _currentPlaylist;
  72. }
  73. set
  74. {
  75. _settings.currentPlaylistFile = value.fileLoc;
  76. _currentPlaylist = value;
  77. }
  78. }
  79. /// <summary>
  80. /// Current editing playlist
  81. /// </summary>
  82. public Playlist CurrentEditingPlaylist;
  83. /// <summary>
  84. /// HashSet of LevelIds for quick lookup
  85. /// </summary>
  86. public HashSet<String> CurrentEditingPlaylistLevelIds;
  87. /// <summary>
  88. /// Constructor.
  89. /// </summary>
  90. public SongBrowserModel()
  91. {
  92. _levelIdToCustomLevel = new Dictionary<string, CustomPreviewBeatmapLevel>();
  93. _cachedLastWriteTimes = new Dictionary<String, double>();
  94. _levelIdToPlayCount = new Dictionary<string, int>();
  95. CurrentEditingPlaylistLevelIds = new HashSet<string>();
  96. // Weights used for keeping the original songs in order
  97. // Invert the weights from the game so we can order by descending and make LINQ work with us...
  98. /* Level4, Level2, Level9, Level5, Level10, Level6, Level7, Level1, Level3, Level8, Level11 */
  99. _weights = new Dictionary<string, int>
  100. {
  101. ["OneHopeLevel"] = 12,
  102. ["100Bills"] = 11,
  103. ["Escape"] = 10,
  104. ["Legend"] = 9,
  105. ["BeatSaber"] = 8,
  106. ["AngelVoices"] = 7,
  107. ["CountryRounds"] = 6,
  108. ["BalearicPumping"] = 5,
  109. ["Breezer"] = 4,
  110. ["CommercialPumping"] = 3,
  111. ["TurnMeOn"] = 2,
  112. ["LvlInsane"] = 1,
  113. ["100BillsOneSaber"] = 12,
  114. ["EscapeOneSaber"] = 11,
  115. ["LegendOneSaber"] = 10,
  116. ["BeatSaberOneSaber"] = 9,
  117. ["CommercialPumpingOneSaber"] = 8,
  118. ["TurnMeOnOneSaber"] = 8,
  119. };
  120. _difficultyWeights = new Dictionary<BeatmapDifficulty, int>
  121. {
  122. [BeatmapDifficulty.Easy] = 1,
  123. [BeatmapDifficulty.Normal] = 2,
  124. [BeatmapDifficulty.Hard] = 4,
  125. [BeatmapDifficulty.Expert] = 8,
  126. [BeatmapDifficulty.ExpertPlus] = 16,
  127. };
  128. }
  129. /// <summary>
  130. /// Init this model.
  131. /// </summary>
  132. /// <param name="songSelectionMasterView"></param>
  133. /// <param name="songListViewController"></param>
  134. public void Init()
  135. {
  136. _settings = SongBrowserSettings.Load();
  137. Logger.Info("Settings loaded, sorting mode is: {0}", _settings.sortMode);
  138. }
  139. /// <summary>
  140. /// Easy invert of toggling.
  141. /// </summary>
  142. public void ToggleInverting()
  143. {
  144. this.Settings.invertSortResults = !this.Settings.invertSortResults;
  145. }
  146. /// <summary>
  147. /// Get the song cache from the game.
  148. /// </summary>
  149. public void UpdateLevelRecords()
  150. {
  151. Stopwatch timer = new Stopwatch();
  152. timer.Start();
  153. // Calculate some information about the custom song dir
  154. String customSongsPath = Path.Combine(Environment.CurrentDirectory, CUSTOM_SONGS_DIR);
  155. String revSlashCustomSongPath = customSongsPath.Replace('\\', '/');
  156. double currentCustomSongDirLastWriteTIme = (File.GetLastWriteTimeUtc(customSongsPath) - EPOCH).TotalMilliseconds;
  157. bool customSongDirChanged = false;
  158. if (_customSongDirLastWriteTime != currentCustomSongDirLastWriteTIme)
  159. {
  160. customSongDirChanged = true;
  161. _customSongDirLastWriteTime = currentCustomSongDirLastWriteTIme;
  162. }
  163. if (!Directory.Exists(customSongsPath))
  164. {
  165. Logger.Error("CustomSong directory is missing...");
  166. return;
  167. }
  168. // Map some data for custom songs
  169. Regex r = new Regex(@"(\d+-\d+)", RegexOptions.IgnoreCase);
  170. Stopwatch lastWriteTimer = new Stopwatch();
  171. lastWriteTimer.Start();
  172. foreach (KeyValuePair<string, CustomPreviewBeatmapLevel> level in SongCore.Loader.CustomLevels)
  173. {
  174. // If we already know this levelID, don't both updating it.
  175. // SongLoader should filter duplicates but in case of failure we don't want to crash
  176. if (!_cachedLastWriteTimes.ContainsKey(level.Value.levelID) || customSongDirChanged)
  177. {
  178. double lastWriteTime = GetSongUserDate(level.Value);
  179. _cachedLastWriteTimes[level.Value.levelID] = lastWriteTime;
  180. }
  181. if (!_levelIdToCustomLevel.ContainsKey(level.Value.levelID))
  182. {
  183. _levelIdToCustomLevel.Add(level.Value.levelID, level.Value);
  184. }
  185. }
  186. lastWriteTimer.Stop();
  187. Logger.Info("Determining song download time and determining mappings took {0}ms", lastWriteTimer.ElapsedMilliseconds);
  188. // Update song Infos, directory tree, and sort
  189. this.UpdatePlayCounts();
  190. // Check if we need to upgrade settings file favorites
  191. try
  192. {
  193. this.Settings.ConvertFavoritesToPlaylist(_levelIdToCustomLevel);
  194. }
  195. catch (Exception e)
  196. {
  197. Logger.Exception("FAILED TO CONVERT FAVORITES TO PLAYLIST!", e);
  198. }
  199. // load the current editing playlist or make one
  200. if (CurrentEditingPlaylist == null && !String.IsNullOrEmpty(this.Settings.currentEditingPlaylistFile))
  201. {
  202. Logger.Debug("Loading playlist for editing: {0}", this.Settings.currentEditingPlaylistFile);
  203. CurrentEditingPlaylist = Playlist.LoadPlaylist(this.Settings.currentEditingPlaylistFile);
  204. PlaylistsCollection.MatchSongsForPlaylist(CurrentEditingPlaylist, true);
  205. }
  206. if (CurrentEditingPlaylist == null)
  207. {
  208. Logger.Debug("Current editing playlist does not exit, create...");
  209. CurrentEditingPlaylist = new Playlist
  210. {
  211. playlistTitle = "Song Browser Favorites",
  212. playlistAuthor = "SongBrowser",
  213. fileLoc = this.Settings.currentEditingPlaylistFile,
  214. image = Base64Sprites.SpriteToBase64(Base64Sprites.BeastSaberLogo),
  215. songs = new List<PlaylistSong>(),
  216. };
  217. }
  218. CurrentEditingPlaylistLevelIds = new HashSet<string>();
  219. foreach (PlaylistSong ps in CurrentEditingPlaylist.songs)
  220. {
  221. // Sometimes we cannot match a song
  222. string levelId = null;
  223. if (ps.level != null)
  224. {
  225. levelId = ps.level.levelID;
  226. }
  227. else if (!String.IsNullOrEmpty(ps.levelId))
  228. {
  229. levelId = ps.levelId;
  230. }
  231. else
  232. {
  233. //Logger.Debug("MISSING SONG {0}", ps.songName);
  234. continue;
  235. }
  236. CurrentEditingPlaylistLevelIds.Add(levelId);
  237. }
  238. // Signal complete
  239. if (SongCore.Loader.CustomLevels.Count > 0)
  240. {
  241. didFinishProcessingSongs?.Invoke(SongCore.Loader.CustomLevels);
  242. }
  243. timer.Stop();
  244. Logger.Info("Updating songs infos took {0}ms", timer.ElapsedMilliseconds);
  245. }
  246. /// <summary>
  247. /// Try to get the date from the cover file, likely the most reliable.
  248. /// Fall back on the folders creation date.
  249. /// </summary>
  250. /// <param name="level"></param>
  251. /// <returns></returns>
  252. private double GetSongUserDate(CustomPreviewBeatmapLevel level)
  253. {
  254. var coverPath = Path.Combine(level.customLevelPath, level.standardLevelInfoSaveData.coverImageFilename);
  255. var lastTime = EPOCH;
  256. if (File.Exists(coverPath))
  257. {
  258. var lastWriteTime = File.GetLastWriteTimeUtc(coverPath);
  259. var lastCreateTime = File.GetCreationTimeUtc(coverPath);
  260. lastTime = lastWriteTime > lastCreateTime ? lastWriteTime : lastCreateTime;
  261. }
  262. else
  263. {
  264. var lastCreateTime = File.GetCreationTimeUtc(level.customLevelPath);
  265. lastTime = lastCreateTime;
  266. }
  267. return (lastTime - EPOCH).TotalMilliseconds;
  268. }
  269. /// <summary>
  270. /// SongLoader doesn't fire event when we delete a song.
  271. /// </summary>
  272. /// <param name="levelPack"></param>
  273. /// <param name="levelId"></param>
  274. public void RemoveSongFromLevelPack(IBeatmapLevelPack levelPack, String levelId)
  275. {
  276. levelPack.beatmapLevelCollection.beatmapLevels.ToList().RemoveAll(x => x.levelID == levelId);
  277. }
  278. /// <summary>
  279. /// Update the gameplay play counts.
  280. /// </summary>
  281. /// <param name="gameplayMode"></param>
  282. private void UpdatePlayCounts()
  283. {
  284. // Reset current playcounts
  285. _levelIdToPlayCount = new Dictionary<string, int>();
  286. // Build a map of levelId to sum of all playcounts and sort.
  287. PlayerDataModelSO playerData = Resources.FindObjectsOfTypeAll<PlayerDataModelSO>().FirstOrDefault();
  288. foreach (var levelData in playerData.currentLocalPlayer.levelsStatsData)
  289. {
  290. if (!_levelIdToPlayCount.ContainsKey(levelData.levelID))
  291. {
  292. _levelIdToPlayCount.Add(levelData.levelID, 0);
  293. }
  294. _levelIdToPlayCount[levelData.levelID] += levelData.playCount;
  295. }
  296. }
  297. /// <summary>
  298. /// Map the downloader data for quick lookup.
  299. /// </summary>
  300. /// <param name="songs"></param>
  301. public void UpdateDownloaderDataMapping(List<ScrappedSong> songs)
  302. {
  303. _levelHashToDownloaderData = new Dictionary<string, ScrappedSong>();
  304. foreach (ScrappedSong song in songs)
  305. {
  306. if (_levelHashToDownloaderData.ContainsKey(song.Hash))
  307. {
  308. continue;
  309. }
  310. _levelHashToDownloaderData.Add(song.Hash, song);
  311. }
  312. }
  313. /// <summary>
  314. /// Add Song to Editing Playlist
  315. /// </summary>
  316. /// <param name="songInfo"></param>
  317. public void AddSongToEditingPlaylist(IBeatmapLevel songInfo)
  318. {
  319. if (this.CurrentEditingPlaylist == null)
  320. {
  321. return;
  322. }
  323. this.CurrentEditingPlaylist.songs.Add(new PlaylistSong()
  324. {
  325. songName = songInfo.songName,
  326. levelId = songInfo.levelID,
  327. hash = CustomHelpers.GetSongHash(songInfo.levelID),
  328. });
  329. this.CurrentEditingPlaylistLevelIds.Add(songInfo.levelID);
  330. this.CurrentEditingPlaylist.SavePlaylist();
  331. }
  332. /// <summary>
  333. /// Remove Song from editing playlist
  334. /// </summary>
  335. /// <param name="levelId"></param>
  336. public void RemoveSongFromEditingPlaylist(IBeatmapLevel songInfo)
  337. {
  338. if (this.CurrentEditingPlaylist == null)
  339. {
  340. return;
  341. }
  342. this.CurrentEditingPlaylist.songs.RemoveAll(x => x.level != null && x.level.levelID == songInfo.levelID);
  343. this.CurrentEditingPlaylistLevelIds.RemoveWhere(x => x == songInfo.levelID);
  344. this.CurrentEditingPlaylist.SavePlaylist();
  345. }
  346. /// <summary>
  347. /// Overwrite the current level pack.
  348. /// </summary>
  349. private void OverwriteCurrentLevelPack(IBeatmapLevelPack pack, List<IPreviewBeatmapLevel> sortedLevels)
  350. {
  351. Logger.Debug("Overwriting levelPack [{0}] beatmapLevelCollection.levels", pack);
  352. if (pack.packID == PluginConfig.CUSTOM_SONG_LEVEL_PACK_ID || (pack as SongCoreCustomBeatmapLevelPack) != null)
  353. {
  354. Logger.Debug("Overwriting SongCore Level Pack collection...");
  355. var newLevels = sortedLevels.Select(x => x as CustomPreviewBeatmapLevel);
  356. ReflectionUtil.SetPrivateField(pack.beatmapLevelCollection, "_customPreviewBeatmapLevels", newLevels.ToArray());
  357. }
  358. else
  359. {
  360. // Hack to see if level pack is purchased or not.
  361. BeatmapLevelPackSO beatmapLevelPack = pack as BeatmapLevelPackSO;
  362. if ((pack as BeatmapLevelPackSO) != null)
  363. {
  364. Logger.Debug("Owned level pack...");
  365. var newLevels = sortedLevels.Select(x => x as BeatmapLevelSO);
  366. ReflectionUtil.SetPrivateField(pack.beatmapLevelCollection, "_beatmapLevels", newLevels.ToArray());
  367. }
  368. else
  369. {
  370. Logger.Debug("Unowned DLC Detected...");
  371. var newLevels = sortedLevels.Select(x => x as PreviewBeatmapLevelSO);
  372. ReflectionUtil.SetPrivateField(pack.beatmapLevelCollection, "_beatmapLevels", newLevels.ToArray());
  373. }
  374. Logger.Debug("Overwriting Regular Collection...");
  375. }
  376. }
  377. /// <summary>
  378. /// Sort the song list based on the settings.
  379. /// </summary>
  380. public void ProcessSongList(IBeatmapLevelPack pack)
  381. {
  382. Logger.Trace("ProcessSongList()");
  383. List<IPreviewBeatmapLevel> unsortedSongs = null;
  384. List<IPreviewBeatmapLevel> filteredSongs = null;
  385. List<IPreviewBeatmapLevel> sortedSongs = null;
  386. // This has come in handy many times for debugging issues with Newest.
  387. /*foreach (BeatmapLevelSO level in _originalSongs)
  388. {
  389. if (_levelIdToCustomLevel.ContainsKey(level.levelID))
  390. {
  391. Logger.Debug("HAS KEY {0}: {1}", _levelIdToCustomLevel[level.levelID].customSongInfo.path, level.levelID);
  392. }
  393. else
  394. {
  395. Logger.Debug("Missing KEY: {0}", level.levelID);
  396. }
  397. }*/
  398. // Abort
  399. if (pack == null)
  400. {
  401. Logger.Debug("Cannot process songs yet, no level pack selected...");
  402. return;
  403. }
  404. // fetch unsorted songs.
  405. if (this._settings.filterMode == SongFilterMode.Playlist && this.CurrentPlaylist != null)
  406. {
  407. unsortedSongs = null;
  408. }
  409. else
  410. {
  411. Logger.Debug("Using songs from level pack: {0}", pack.packID);
  412. unsortedSongs = pack.beatmapLevelCollection.beatmapLevels.ToList();
  413. }
  414. // filter
  415. Logger.Debug("Starting filtering songs...");
  416. Stopwatch stopwatch = Stopwatch.StartNew();
  417. switch (_settings.filterMode)
  418. {
  419. case SongFilterMode.Favorites:
  420. filteredSongs = FilterFavorites(pack);
  421. break;
  422. case SongFilterMode.Search:
  423. filteredSongs = FilterSearch(unsortedSongs);
  424. break;
  425. case SongFilterMode.Playlist:
  426. filteredSongs = FilterPlaylist(pack);
  427. break;
  428. case SongFilterMode.Custom:
  429. Logger.Info("Song filter mode set to custom. Deferring filter behaviour to another mod.");
  430. filteredSongs = CustomFilterHandler != null ? CustomFilterHandler.Invoke(pack) : unsortedSongs;
  431. break;
  432. case SongFilterMode.None:
  433. default:
  434. Logger.Info("No song filter selected...");
  435. filteredSongs = unsortedSongs;
  436. break;
  437. }
  438. stopwatch.Stop();
  439. Logger.Info("Filtering songs took {0}ms", stopwatch.ElapsedMilliseconds);
  440. // sort
  441. Logger.Debug("Starting to sort songs...");
  442. stopwatch = Stopwatch.StartNew();
  443. switch (_settings.sortMode)
  444. {
  445. case SongSortMode.Original:
  446. sortedSongs = SortOriginal(filteredSongs);
  447. break;
  448. case SongSortMode.Newest:
  449. sortedSongs = SortNewest(filteredSongs);
  450. break;
  451. case SongSortMode.Author:
  452. sortedSongs = SortAuthor(filteredSongs);
  453. break;
  454. case SongSortMode.UpVotes:
  455. sortedSongs = SortUpVotes(filteredSongs);
  456. break;
  457. case SongSortMode.PlayCount:
  458. sortedSongs = SortBeatSaverPlayCount(filteredSongs);
  459. break;
  460. case SongSortMode.Rating:
  461. sortedSongs = SortBeatSaverRating(filteredSongs);
  462. break;
  463. case SongSortMode.YourPlayCount:
  464. sortedSongs = SortPlayCount(filteredSongs);
  465. break;
  466. case SongSortMode.PP:
  467. sortedSongs = SortPerformancePoints(filteredSongs);
  468. break;
  469. case SongSortMode.Stars:
  470. sortedSongs = SortStars(filteredSongs);
  471. break;
  472. case SongSortMode.Difficulty:
  473. sortedSongs = SortDifficulty(filteredSongs);
  474. break;
  475. case SongSortMode.Random:
  476. sortedSongs = SortRandom(filteredSongs);
  477. break;
  478. case SongSortMode.Default:
  479. default:
  480. sortedSongs = SortSongName(filteredSongs);
  481. break;
  482. }
  483. if (this.Settings.invertSortResults && _settings.sortMode != SongSortMode.Random)
  484. {
  485. sortedSongs.Reverse();
  486. }
  487. stopwatch.Stop();
  488. Logger.Info("Sorting songs took {0}ms", stopwatch.ElapsedMilliseconds);
  489. this.OverwriteCurrentLevelPack(pack, sortedSongs);
  490. //_sortedSongs.ForEach(x => Logger.Debug(x.levelID));
  491. }
  492. /// <summary>
  493. /// For now the editing playlist will be considered the favorites playlist.
  494. /// Users can edit the settings file themselves.
  495. /// </summary>
  496. private List<IPreviewBeatmapLevel> FilterFavorites(IBeatmapLevelPack pack)
  497. {
  498. Logger.Info("Filtering song list as favorites playlist...");
  499. if (this.CurrentEditingPlaylist != null)
  500. {
  501. this.CurrentPlaylist = this.CurrentEditingPlaylist;
  502. }
  503. return this.FilterPlaylist(pack);
  504. }
  505. /// <summary>
  506. /// Filter for a search query.
  507. /// </summary>
  508. /// <param name="levels"></param>
  509. /// <returns></returns>
  510. private List<IPreviewBeatmapLevel> FilterSearch(List<IPreviewBeatmapLevel> levels)
  511. {
  512. // Make sure we can actually search.
  513. if (this._settings.searchTerms.Count <= 0)
  514. {
  515. Logger.Error("Tried to search for a song with no valid search terms...");
  516. SortSongName(levels);
  517. return levels;
  518. }
  519. string searchTerm = this._settings.searchTerms[0];
  520. if (String.IsNullOrEmpty(searchTerm))
  521. {
  522. Logger.Error("Empty search term entered.");
  523. SortSongName(levels);
  524. return levels;
  525. }
  526. Logger.Info("Filtering song list by search term: {0}", searchTerm);
  527. var terms = searchTerm.Split(' ');
  528. foreach (var term in terms)
  529. {
  530. levels = levels.Intersect(
  531. levels
  532. .Where(x => $"{x.songName} {x.songSubName} {x.songAuthorName} {x.levelAuthorName}".ToLower().Contains(term.ToLower()))
  533. .ToList(
  534. )
  535. ).ToList();
  536. }
  537. return levels;
  538. }
  539. /// <summary>
  540. /// Filter for a playlist (favorites uses this).
  541. /// </summary>
  542. /// <param name="pack"></param>
  543. /// <returns></returns>
  544. private List<IPreviewBeatmapLevel> FilterPlaylist(IBeatmapLevelPack pack)
  545. {
  546. // bail if no playlist, usually means the settings stored one the user then moved.
  547. if (this.CurrentPlaylist == null)
  548. {
  549. Logger.Error("Trying to load a null playlist...");
  550. this.Settings.filterMode = SongFilterMode.None;
  551. return null;
  552. }
  553. // Get song keys
  554. PlaylistsCollection.MatchSongsForPlaylist(this.CurrentPlaylist, true);
  555. Logger.Debug("Filtering songs for playlist: {0}", this.CurrentPlaylist.playlistTitle);
  556. Dictionary<String, IPreviewBeatmapLevel> levelDict = new Dictionary<string, IPreviewBeatmapLevel>();
  557. foreach (var level in pack.beatmapLevelCollection.beatmapLevels)
  558. {
  559. if (!levelDict.ContainsKey(level.levelID))
  560. {
  561. levelDict.Add(level.levelID, level);
  562. }
  563. }
  564. List<IPreviewBeatmapLevel> songList = new List<IPreviewBeatmapLevel>();
  565. foreach (PlaylistSong ps in this.CurrentPlaylist.songs)
  566. {
  567. if (ps.level != null && levelDict.ContainsKey(ps.level.levelID))
  568. {
  569. songList.Add(levelDict[ps.level.levelID]);
  570. }
  571. else
  572. {
  573. Logger.Debug("Could not find song in playlist: {0}", ps.songName);
  574. }
  575. }
  576. Logger.Debug("Playlist filtered song count: {0}", songList.Count);
  577. return songList;
  578. }
  579. /// <summary>
  580. /// Sorting returns original list.
  581. /// </summary>
  582. /// <param name="levels"></param>
  583. /// <returns></returns>
  584. private List<IPreviewBeatmapLevel> SortOriginal(List<IPreviewBeatmapLevel> levels)
  585. {
  586. Logger.Info("Sorting song list as original");
  587. return levels;
  588. }
  589. /// <summary>
  590. /// Sorting by newest (file time, creation+modified).
  591. /// </summary>
  592. /// <param name="levels"></param>
  593. /// <returns></returns>
  594. private List<IPreviewBeatmapLevel> SortNewest(List<IPreviewBeatmapLevel> levels)
  595. {
  596. Logger.Info("Sorting song list as newest.");
  597. return levels
  598. .OrderBy(x => _weights.ContainsKey(x.levelID) ? _weights[x.levelID] : 0)
  599. .ThenByDescending(x => !_levelIdToCustomLevel.ContainsKey(x.levelID) ? (_weights.ContainsKey(x.levelID) ? _weights[x.levelID] : 0) : _cachedLastWriteTimes[x.levelID])
  600. .ToList();
  601. }
  602. /// <summary>
  603. /// Sorting by the song author.
  604. /// </summary>
  605. /// <param name="levelIds"></param>
  606. /// <returns></returns>
  607. private List<IPreviewBeatmapLevel> SortAuthor(List<IPreviewBeatmapLevel> levelIds)
  608. {
  609. Logger.Info("Sorting song list by author");
  610. return levelIds
  611. .OrderBy(x => x.songAuthorName)
  612. .ThenBy(x => x.songName)
  613. .ToList();
  614. }
  615. /// <summary>
  616. /// Sorting by song users play count.
  617. /// </summary>
  618. /// <param name="levels"></param>
  619. /// <returns></returns>
  620. private List<IPreviewBeatmapLevel> SortPlayCount(List<IPreviewBeatmapLevel> levels)
  621. {
  622. Logger.Info("Sorting song list by playcount");
  623. return levels
  624. .OrderByDescending(x => _levelIdToPlayCount.ContainsKey(x.levelID) ? _levelIdToPlayCount[x.levelID] : 0)
  625. .ThenBy(x => x.songName)
  626. .ToList();
  627. }
  628. /// <summary>
  629. /// Sorting by PP.
  630. /// </summary>
  631. /// <param name="levels"></param>
  632. /// <returns></returns>
  633. private List<IPreviewBeatmapLevel> SortPerformancePoints(List<IPreviewBeatmapLevel> levels)
  634. {
  635. Logger.Info("Sorting song list by performance points...");
  636. if (ScoreSaberDatabaseDownloader.ScoreSaberDataFile == null)
  637. {
  638. return levels;
  639. }
  640. return levels
  641. .OrderByDescending(x =>
  642. {
  643. var hash = CustomHelpers.GetSongHash(x.levelID);
  644. if (ScoreSaberDatabaseDownloader.ScoreSaberDataFile.SongHashToScoreSaberData.ContainsKey(hash))
  645. {
  646. return ScoreSaberDatabaseDownloader.ScoreSaberDataFile.SongHashToScoreSaberData[hash].diffs.Max(y => y.pp);
  647. }
  648. else
  649. {
  650. return 0;
  651. }
  652. })
  653. .ToList();
  654. }
  655. /// <summary>
  656. /// Sorting by star rating.
  657. /// </summary>
  658. /// <param name="levels"></param>
  659. /// <returns></returns>
  660. private List<IPreviewBeatmapLevel> SortStars(List<IPreviewBeatmapLevel> levels)
  661. {
  662. Logger.Info("Sorting song list by star points...");
  663. if (ScoreSaberDatabaseDownloader.ScoreSaberDataFile == null)
  664. {
  665. return levels;
  666. }
  667. return levels
  668. .OrderByDescending(x =>
  669. {
  670. var hash = CustomHelpers.GetSongHash(x.levelID);
  671. var stars = 0.0;
  672. if (ScoreSaberDatabaseDownloader.ScoreSaberDataFile.SongHashToScoreSaberData.ContainsKey(hash))
  673. {
  674. var diffs = ScoreSaberDatabaseDownloader.ScoreSaberDataFile.SongHashToScoreSaberData[hash].diffs;
  675. stars = diffs.Max(y => y.star);
  676. }
  677. //Logger.Debug("Stars={0}", stars);
  678. if (stars != 0)
  679. {
  680. return stars;
  681. }
  682. if (_settings.invertSortResults)
  683. {
  684. return double.MaxValue;
  685. }
  686. else
  687. {
  688. return double.MinValue;
  689. }
  690. })
  691. .ToList();
  692. }
  693. /// <summary>
  694. /// Attempt to sort by songs containing easy first
  695. /// </summary>
  696. /// <param name="levels"></param>
  697. /// <returns></returns>
  698. private List<IPreviewBeatmapLevel> SortDifficulty(List<IPreviewBeatmapLevel> levels)
  699. {
  700. Logger.Info("Sorting song list by difficulty...");
  701. IEnumerable<BeatmapDifficulty> difficultyIterator = Enum.GetValues(typeof(BeatmapDifficulty)).Cast<BeatmapDifficulty>();
  702. Dictionary<string, int> levelIdToDifficultyValue = new Dictionary<string, int>();
  703. foreach (IPreviewBeatmapLevel level in levels)
  704. {
  705. // only need to process a level once
  706. if (levelIdToDifficultyValue.ContainsKey(level.levelID))
  707. {
  708. continue;
  709. }
  710. // TODO - fix, not honoring beatmap characteristic.
  711. int difficultyValue = 0;
  712. if (level as BeatmapLevelSO != null)
  713. {
  714. var beatmapSet = (level as BeatmapLevelSO).difficultyBeatmapSets;
  715. difficultyValue = beatmapSet
  716. .SelectMany(x => x.difficultyBeatmaps)
  717. .Sum(x => _difficultyWeights[x.difficulty]);
  718. }
  719. else if (_levelIdToCustomLevel.ContainsKey(level.levelID))
  720. {
  721. var beatmapSet = (_levelIdToCustomLevel[level.levelID] as CustomPreviewBeatmapLevel).standardLevelInfoSaveData.difficultyBeatmapSets;
  722. difficultyValue = beatmapSet
  723. .SelectMany(x => x.difficultyBeatmaps)
  724. .Sum(x => _difficultyWeights[(BeatmapDifficulty)Enum.Parse(typeof(BeatmapDifficulty), x.difficulty)]);
  725. }
  726. levelIdToDifficultyValue.Add(level.levelID, difficultyValue);
  727. }
  728. return levels
  729. .OrderBy(x => levelIdToDifficultyValue[x.levelID])
  730. .ThenBy(x => x.songName)
  731. .ToList();
  732. }
  733. /// <summary>
  734. /// Randomize the sorting.
  735. /// </summary>
  736. /// <param name="levelIds"></param>
  737. /// <returns></returns>
  738. private List<IPreviewBeatmapLevel> SortRandom(List<IPreviewBeatmapLevel> levelIds)
  739. {
  740. Logger.Info("Sorting song list by random (seed={0})...", this.Settings.randomSongSeed);
  741. System.Random rnd = new System.Random(this.Settings.randomSongSeed);
  742. return levelIds
  743. .OrderBy(x => rnd.Next())
  744. .ToList();
  745. }
  746. /// <summary>
  747. /// Sorting by the song name.
  748. /// </summary>
  749. /// <param name="levels"></param>
  750. /// <returns></returns>
  751. private List<IPreviewBeatmapLevel> SortSongName(List<IPreviewBeatmapLevel> levels)
  752. {
  753. Logger.Info("Sorting song list as default (songName)");
  754. return levels
  755. .OrderBy(x => x.songName)
  756. .ThenBy(x => x.songAuthorName)
  757. .ToList();
  758. }
  759. /// <summary>
  760. /// Sorting by BeatSaver UpVotes.
  761. /// </summary>
  762. /// <param name="levelIds"></param>
  763. /// <returns></returns>
  764. private List<IPreviewBeatmapLevel> SortUpVotes(List<IPreviewBeatmapLevel> levelIds)
  765. {
  766. Logger.Info("Sorting song list by BeatSaver UpVotes");
  767. // Do not always have data when trying to sort by UpVotes
  768. if (_levelHashToDownloaderData == null)
  769. {
  770. return levelIds;
  771. }
  772. return levelIds
  773. .OrderByDescending(x => {
  774. var hash = CustomHelpers.GetSongHash(x.levelID);
  775. if (_levelHashToDownloaderData.ContainsKey(hash))
  776. {
  777. return _levelHashToDownloaderData[hash].Upvotes;
  778. }
  779. else
  780. {
  781. return int.MinValue;
  782. }
  783. })
  784. .ToList();
  785. }
  786. /// <summary>
  787. /// Sorting by BeatSaver playcount stat.
  788. /// </summary>
  789. /// <param name="levelIds"></param>
  790. /// <returns></returns>
  791. private List<IPreviewBeatmapLevel> SortBeatSaverPlayCount(List<IPreviewBeatmapLevel> levelIds)
  792. {
  793. Logger.Info("Sorting song list by BeatSaver PlayCount");
  794. // Do not always have data when trying to sort by UpVotes
  795. if (_levelHashToDownloaderData == null)
  796. {
  797. return levelIds;
  798. }
  799. return levelIds
  800. .OrderByDescending(x => {
  801. var hash = CustomHelpers.GetSongHash(x.levelID);
  802. if (_levelHashToDownloaderData.ContainsKey(hash))
  803. {
  804. return _levelHashToDownloaderData[hash].PlayedCount;
  805. }
  806. else
  807. {
  808. return int.MinValue;
  809. }
  810. })
  811. .ToList();
  812. }
  813. /// <summary>
  814. /// Sorting by BeatSaver rating stat.
  815. /// </summary>
  816. /// <param name="levelIds"></param>
  817. /// <returns></returns>
  818. private List<IPreviewBeatmapLevel> SortBeatSaverRating(List<IPreviewBeatmapLevel> levelIds)
  819. {
  820. Logger.Info("Sorting song list by BeatSaver Rating");
  821. // Do not always have data when trying to sort by UpVotes
  822. if (_levelHashToDownloaderData == null)
  823. {
  824. return levelIds;
  825. }
  826. return levelIds
  827. .OrderByDescending(x => {
  828. var hash = CustomHelpers.GetSongHash(x.levelID);
  829. if (_levelHashToDownloaderData.ContainsKey(hash))
  830. {
  831. return _levelHashToDownloaderData[hash].Rating;
  832. }
  833. else
  834. {
  835. return int.MinValue;
  836. }
  837. })
  838. .ToList();
  839. }
  840. }
  841. }