[feature-107] lot of changes but mainly, maps now use a cache and load almost instantly after first load

This commit is contained in:
MathieuG-P
2024-02-18 22:24:57 +01:00
parent 9a3ebf2971
commit b42231b134
43 changed files with 1256 additions and 305 deletions
+6 -2
View File
@@ -1,4 +1,5 @@
import { app } from "electron";
import { constants } from "http2";
import path from "path";
export const BS_EXECUTABLE = "Beat Saber.exe";
@@ -10,5 +11,8 @@ export const APP_NAME = "BSManager";
export const STEAMVR_APP_ID = "250820";
export const IMAGE_CACHE_FOLDER = "imagescache";
export const IMAGE_CACHE_PATH = path.join(app.getPath("userData"), IMAGE_CACHE_FOLDER);
export const CACHE_PATH = path.join(app.getPath("userData"), "CachedData");
export const IMAGE_CACHE_PATH = path.join(CACHE_PATH, "imagescache");
export const HTTP_STATUS_CODES = constants;
+3 -2
View File
@@ -175,7 +175,7 @@ export async function dirSize(dirPath: string): Promise<number>{
const realPath = await realpath(fullPath);
const stat = await lstat(realPath);
if (stat.isDirectory()) {
if (stat.isDirectory()) {
return dirSize(fullPath);
}
@@ -244,9 +244,10 @@ export function resolveGUIDPath(guidPath: string): string {
return path.join(driveLetter, path.relative(guidVolume, guidPath));
}
export interface Progression<T = unknown> {
export interface Progression<T = unknown, D = unknown> {
total: number;
current: number;
diff?: number;
data?: T;
extra?: D;
}
+1 -1
View File
@@ -1,4 +1,4 @@
import { LocalMapsManagerService } from "../services/additional-content/local-maps-manager.service";
import { LocalMapsManagerService } from "../services/additional-content/maps/local-maps-manager.service";
import { UtilsService } from "../services/utils.service";
import { BSVersion } from "shared/bs-version.interface";
import { IpcRequest } from "shared/models/ipc";
+13 -8
View File
@@ -5,36 +5,41 @@ import { of, throwError } from "rxjs";
const ipc = IpcService.getInstance();
ipc.on<string>("one-click-install-playlist", (req, reply) => {
const mapsManager = LocalPlaylistsManagerService.getInstance();
reply(mapsManager.oneClickInstallPlaylist(req.args));
const playlists = LocalPlaylistsManagerService.getInstance();
reply(playlists.oneClickInstallPlaylist(req.args));
});
ipc.on("register-playlists-deep-link", (_, reply) => {
const maps = LocalPlaylistsManagerService.getInstance();
const playlists = LocalPlaylistsManagerService.getInstance();
try {
reply(of(maps.enableDeepLinks()));
reply(of(playlists.enableDeepLinks()));
} catch (e) {
reply(throwError(() => e));
}
});
ipc.on("unregister-playlists-deep-link", (_, reply) => {
const maps = LocalPlaylistsManagerService.getInstance();
const playlists = LocalPlaylistsManagerService.getInstance();
try {
reply(of(maps.disableDeepLinks()));
reply(of(playlists.disableDeepLinks()));
} catch (e) {
reply(throwError(() => e));
}
});
ipc.on("is-playlists-deep-links-enabled", (_, reply) => {
const maps = LocalPlaylistsManagerService.getInstance();
const playlists = LocalPlaylistsManagerService.getInstance();
try {
reply(of(maps.isDeepLinksEnabled()));
reply(of(playlists.isDeepLinksEnabled()));
} catch (e) {
reply(throwError(() => e));
}
});
ipc.on("get-version-playlists", (req, reply) => {
const playlists = LocalPlaylistsManagerService.getInstance();
reply(playlists.getVersionPlaylists(req.args));
});
+1 -1
View File
@@ -10,7 +10,7 @@ import { from } from "rxjs";
import path from "path";
import { pathExist } from "../helpers/fs.helpers";
import { FolderLinkerService, LinkOptions } from "../services/folder-linker.service";
import { LocalMapsManagerService } from "../services/additional-content/local-maps-manager.service";
import { LocalMapsManagerService } from "../services/additional-content/maps/local-maps-manager.service";
import { readJSON, writeJSON } from "fs-extra";
import log from "electron-log";
import { VersionLinkerAction } from "renderer/services/version-folder-linker.service";
+5 -1
View File
@@ -13,7 +13,7 @@ import "./ipcs";
import { WindowManagerService } from "./services/window-manager.service";
import { DeepLinkService } from "./services/deep-link.service";
import { AppWindow } from "shared/models/window-manager/app-window.model";
import { LocalMapsManagerService } from "./services/additional-content/local-maps-manager.service";
import { LocalMapsManagerService } from "./services/additional-content/maps/local-maps-manager.service";
import { LocalPlaylistsManagerService } from "./services/additional-content/local-playlists-manager.service";
import { LocalModelsManagerService } from "./services/additional-content/local-models-manager.service";
import { APP_NAME } from "./constants";
@@ -22,6 +22,7 @@ import { IpcRequest } from "shared/models/ipc";
import { LivShortcut } from "./services/liv/liv-shortcut.service";
import { SteamLauncherService } from "./services/bs-launcher/steam-launcher.service";
import { FileAssociationService } from "./services/file-association.service";
import { SongDetailsCacheService } from "./services/additional-content/maps/song-details-cache.service";
const isDebug = process.env.NODE_ENV === "development" || process.env.DEBUG_PROD === "true";
@@ -68,6 +69,7 @@ const initServicesMustBeInitialized = () => {
LocalModelsManagerService.getInstance();
LivShortcut.getInstance();
BSLauncherService.getInstance();
SongDetailsCacheService.getInstance();
}
const findDeepLinkInArgs = (args: string[]): string => {
@@ -102,6 +104,8 @@ if (!gotTheLock) {
app.whenReady().then(() => {
// C:\\Users\\Mathieu\\Desktop\\BSManager\\BSInstances\\My Version\\UserData\\SongDetailsCache.proto
app.setAppUserModelId(APP_NAME);
initServicesMustBeInitialized();
+77
View File
@@ -0,0 +1,77 @@
import { writeFileSync } from "fs-extra";
import { tryit } from "shared/helpers/error.helpers";
import log from "electron-log";
import { Subject, debounceTime } from "rxjs";
export class JsonCache<T = unknown> {
private cache: Record<string, T> = {};
private readonly setEvent: Subject<void> = new Subject<void>();
public constructor(
private readonly jsonPath: string,
private readonly options: JsonCacheOptions = { autoSave: true, saveDebounce: 1000}
){
this.load();
if(this.options.autoSave){
this.setEvent = new Subject<void>();
this.setEvent.pipe(debounceTime(this.options.saveDebounce ?? 1000)).subscribe(() => this.save());
}
}
private load(): void {
try {
this.cache = require(this.jsonPath);
} catch (error) {
log.warn("Failed to load cache or file cache not exist yet", this.jsonPath, error);
} finally {
this.cache ??= {};
}
}
public save(): void {
const res = tryit(() => writeFileSync(this.jsonPath, JSON.stringify(this.cache), { flush: true }));
if(res.error){
log.error("Failed to save cache", this.jsonPath, res.error);
}
}
public get(key: string): T {
return this.cache[key];
}
public set(key: string, value: T): void {
this.cache[key] = value;
this.setEvent?.next();
}
public delete(key: string): void {
delete this.cache[key];
this.setEvent?.next();
}
public clear(): void {
this.cache = {};
this.setEvent?.next();
}
}
export type JsonCacheOptions = {
/**
* Load the cache immediately after creating the instance
* @default true
*/
loadImmediately?: boolean;
/**
* Auto save the cache after a change
* @default true
*/
autoSave?: boolean;
/**
* Time in ms to wait before saving the cache after a change
* @default 1000
*/
saveDebounce?: number;
};
@@ -4,13 +4,13 @@ import { BSVersion } from "shared/bs-version.interface";
import { BSLocalVersionService } from "../bs-local-version.service";
import { DeepLinkService } from "../deep-link.service";
import { RequestService } from "../request.service";
import { LocalMapsManagerService } from "./local-maps-manager.service";
import { LocalMapsManagerService } from "./maps/local-maps-manager.service";
import log from "electron-log";
import { WindowManagerService } from "../window-manager.service";
import { BPList, DownloadPlaylistProgressionData } from "shared/models/playlists/playlist.interface";
import { readFileSync } from "fs";
import { BeatSaverService } from "../thrid-party/beat-saver/beat-saver.service";
import { copy, copyFile, pathExists, realpath } from "fs-extra";
import { copy, copyFile, pathExists, pathExistsSync, readdirSync, realpath } from "fs-extra";
import { Progression, ensureFolderExist, pathExist } from "../../helpers/fs.helpers";
import { FileAssociationService } from "../file-association.service";
@@ -100,6 +100,37 @@ export class LocalPlaylistsManagerService {
this.windows.openWindow(`oneclick-download-playlist.html?playlistUrl=${downloadUrl}`);
}
private getReadBPListOfFolder(folerPath: string): Observable<Progression<BPList[]>> {
return new Observable<Progression<BPList[]>>(obs => {
const progress: Progression<BPList[]> = { current: 0, total: 0, data: [] };
(async () => {
if(!pathExistsSync(folerPath)) {
throw new Error(`Playlists folder not found ${folerPath}`);
}
const playlists = readdirSync(folerPath).filter(file => path.extname(file) === ".bplist");
progress.total = playlists.length;
for (const playlist of playlists) {
const playlistPath = path.join(folerPath, playlist);
const playlistContent = await this.readPlaylistFile(playlistPath);
progress.data.push(playlistContent);
progress.current += 1;
obs.next(progress);
}
})().catch(err => obs.error(err)).finally(() => obs.complete());
});
}
public getVersionPlaylists(version: BSVersion): Observable<Progression<BPList[]>> {
return new Observable<Progression<BPList[]>>(obs => {
this.getPlaylistsFolder(version)
.then(folder => this.getReadBPListOfFolder(folder).subscribe(obs))
});
}
public downloadPlaylist(bpListUrl: string, version: BSVersion): Observable<Progression<DownloadPlaylistProgressionData>> {
return new Observable<Progression<DownloadPlaylistProgressionData>>(obs => {
@@ -2,26 +2,29 @@ import path from "path";
import { BSVersion } from "shared/bs-version.interface";
import { BsvMapDetail, RawMapInfoData } from "shared/models/maps";
import { BsmLocalMap, BsmLocalMapsProgress, DeleteMapsProgress } from "shared/models/maps/bsm-local-map.interface";
import { BSLocalVersionService } from "../bs-local-version.service";
import { InstallationLocationService } from "../installation-location.service";
import { UtilsService } from "../utils.service";
import { BSLocalVersionService } from "../../bs-local-version.service";
import { InstallationLocationService } from "../../installation-location.service";
import { UtilsService } from "../../utils.service";
import crypto from "crypto";
import { lstatSync } from "fs";
import { copy, createReadStream, ensureDir, pathExists, realpath, unlink } from "fs-extra";
import StreamZip from "node-stream-zip";
import { RequestService } from "../request.service";
import { RequestService } from "../../request.service";
import sanitize from "sanitize-filename";
import { DeepLinkService } from "../deep-link.service";
import { DeepLinkService } from "../../deep-link.service";
import log from "electron-log";
import { WindowManagerService } from "../window-manager.service";
import { WindowManagerService } from "../../window-manager.service";
import { Observable, lastValueFrom, of } from "rxjs";
import { Archive } from "../../models/archive.class";
import { deleteFolder, ensureFolderExist, getFilesInFolder, getFoldersInFolder, pathExist } from "../../helpers/fs.helpers";
import { Archive } from "../../../models/archive.class";
import { deleteFolder, ensureFolderExist, getFilesInFolder, getFoldersInFolder, pathExist } from "../../../helpers/fs.helpers";
import { readFile } from "fs/promises";
import { FolderLinkerService } from "../folder-linker.service";
import { allSettled } from "../../../shared/helpers/promise.helpers";
import { splitIntoChunk } from "../../../shared/helpers/array.helpers";
import { IpcService } from "../ipc.service";
import { FolderLinkerService } from "../../folder-linker.service";
import { allSettled } from "../../../../shared/helpers/promise.helpers";
import { splitIntoChunk } from "../../../../shared/helpers/array.helpers";
import { IpcService } from "../../ipc.service";
import { SongDetailsCacheService } from "./song-details-cache.service";
import { sToMs } from "shared/helpers/time.helpers";
import { SongCacheService } from "./song-cache.service";
export class LocalMapsManagerService {
private static instance: LocalMapsManagerService;
@@ -49,7 +52,9 @@ export class LocalMapsManagerService {
private readonly deepLink: DeepLinkService;
private readonly windows: WindowManagerService;
private readonly ipc: IpcService;
private readonly linker = FolderLinkerService.getInstance();
private readonly linker: FolderLinkerService;
private readonly songDetailsCache: SongDetailsCacheService;
private readonly songCache: SongCacheService;
private constructor() {
this.localVersion = BSLocalVersionService.getInstance();
@@ -60,6 +65,8 @@ export class LocalMapsManagerService {
this.windows = WindowManagerService.getInstance();
this.linker = FolderLinkerService.getInstance();
this.ipc = IpcService.getInstance();
this.songDetailsCache = SongDetailsCacheService.getInstance();
this.songCache = SongCacheService.getInstance();
this.deepLink.addLinkOpenedListener(this.DEEP_LINKS.BeatSaver, link => {
log.info("DEEP-LINK RECEIVED FROM", this.DEEP_LINKS.BeatSaver, link);
@@ -87,7 +94,7 @@ export class LocalMapsManagerService {
const mapRawInfo: RawMapInfoData = JSON.parse(rawInfoString);
const shasum = crypto.createHash("sha1");
shasum.update(rawInfoString);
const hashFile = (filePath: string): Promise<void> => {
return new Promise<void>((resolve, reject) => {
const stream = createReadStream(filePath);
@@ -103,11 +110,24 @@ export class LocalMapsManagerService {
await hashFile(diffFilePath);
}
}
return shasum.digest("hex");
}
private async loadMapInfoFromPath(mapPath: string): Promise<BsmLocalMap> {
const getUrlsAndReturn = (rawInfo: RawMapInfoData, hash: string, mapPath: string) => {
const coverUrl = new URL(`file:///${path.join(mapPath, rawInfo._coverImageFilename)}`).href;
const songUrl = new URL(`file:///${path.join(mapPath, rawInfo._songFilename)}`).href;
return { rawInfo, coverUrl, songUrl, hash, path: mapPath, songDetails: this.songDetailsCache.getSongDetails(hash) } as BsmLocalMap;
};
const cachedInfos = this.songCache.getMapInfoFromDirname(path.basename(mapPath));
if (cachedInfos) {
return getUrlsAndReturn(cachedInfos.rawInfo, cachedInfos.hash, mapPath);
}
const files = await getFilesInFolder(mapPath);
const infoFile = files.find(file => path.basename(file).toLowerCase() === "info.dat");
@@ -116,14 +136,10 @@ export class LocalMapsManagerService {
}
const rawInfoString = await readFile(infoFile, { encoding: "utf-8" });
const rawInfo: RawMapInfoData = JSON.parse(rawInfoString);
const coverUrl = new URL(`file:///${path.join(mapPath, rawInfo._coverImageFilename)}`).href;
const songUrl = new URL(`file:///${path.join(mapPath, rawInfo._songFilename)}`).href;
const hash = await this.computeMapHash(mapPath, rawInfoString);
return { rawInfo, coverUrl, songUrl, hash, path: mapPath };
return getUrlsAndReturn(rawInfo, hash, mapPath);
}
private async downloadMapZip(zipUrl: string): Promise<{ zip: StreamZip.StreamZipAsync; zipPath: string }> {
@@ -132,6 +148,7 @@ export class LocalMapsManagerService {
await ensureFolderExist(this.utils.getTempPath());
const dest = path.join(tempPath, fileName);
const zipPath = (await lastValueFrom(this.reqService.downloadFile(zipUrl, dest))).data;
const zip = new StreamZip.async({ file: zipPath });
@@ -140,14 +157,10 @@ export class LocalMapsManagerService {
private openOneClickDownloadMapWindow(mapId: string, isHash = false): void {
this.windows.openWindow("oneclick-download-map.html").then(window => {
this.ipc.once("one-click-map-info", async (_, reply) => {
reply(of({ id: mapId, isHash }));
}, window.webContents.ipc);
});
}
public getMaps(version?: BSVersion): Observable<BsmLocalMapsProgress> {
@@ -159,6 +172,8 @@ export class LocalMapsManagerService {
return new Observable<BsmLocalMapsProgress>(observer => {
(async () => {
await this.songDetailsCache.waitLoaded(sToMs(30));
const levelsFolder = await this.getMapsFolderPath(version);
if(!(await pathExist(levelsFolder))) {
@@ -180,6 +195,8 @@ export class LocalMapsManagerService {
return null;
}
this.songCache.setMapInfoFromDirname(path.basename(mapPath), { rawInfo: mapInfo.rawInfo, hash: mapInfo.hash });
progression.loaded++;
observer.next(progression);
return mapInfo;
@@ -235,6 +252,7 @@ export class LocalMapsManagerService {
continue;
}
await deleteFolder(folder);
this.songCache.deleteMapInfoFromDirname(path.basename(folder));
progress.deleted++;
observer.next(progress);
}
@@ -248,7 +266,7 @@ export class LocalMapsManagerService {
public async downloadMap(map: BsvMapDetail, version?: BSVersion): Promise<BsmLocalMap> {
if (!map.versions.at(0).hash) {
throw "Cannot download map, no hash found";
throw new Error("Cannot download map, no hash found");
}
const zipUrl = map.versions.at(0).downloadURL;
@@ -261,7 +279,7 @@ export class LocalMapsManagerService {
if(!exists){ return null; }
return this.loadMapInfoFromPath(mapPath);
}).catch(() => null);
if(map.versions.every(version => version.hash === installedMap?.hash)) {
return installedMap;
}
@@ -269,7 +287,7 @@ export class LocalMapsManagerService {
const { zip, zipPath } = await this.downloadMapZip(zipUrl);
if (!zip) {
throw `Cannot download ${zipUrl}`;
throw new Error(`Cannot download ${zipUrl}`);
}
await ensureFolderExist(mapPath);
@@ -279,7 +297,7 @@ export class LocalMapsManagerService {
await unlink(zipPath);
const localMap = await this.loadMapInfoFromPath(mapPath);
localMap.bsaverInfo = map;
localMap.songDetails = this.songDetailsCache.getSongDetails(localMap.hash);
return localMap;
}
@@ -0,0 +1,42 @@
import { CACHE_PATH } from "main/constants";
import { JsonCache } from "main/models/json-cache.class";
import path from "path";
import { RawMapInfoData } from "shared/models/maps";
export class SongCacheService {
private static instance: SongCacheService;
public static getInstance(): SongCacheService {
if (!SongCacheService.instance) {
SongCacheService.instance = new SongCacheService();
}
return SongCacheService.instance;
}
private readonly RAW_INFOS_CACHE_PATH = path.join(CACHE_PATH, "song-raw-info-cache.json");
private readonly rawInfosCache: JsonCache<CachedRawInfoWithHash>;
private constructor(){
this.rawInfosCache = new JsonCache(this.RAW_INFOS_CACHE_PATH);
}
public getMapInfoFromDirname(dirname: string): CachedRawInfoWithHash {
return this.rawInfosCache.get(dirname);
}
public setMapInfoFromDirname(dirname: string, info: CachedRawInfoWithHash): void {
this.rawInfosCache.set(dirname, info);
}
public deleteMapInfoFromDirname(dirname: string): void {
this.rawInfosCache.delete(dirname);
}
}
export type CachedRawInfoWithHash = {
hash: string;
rawInfo: RawMapInfoData;
};
@@ -0,0 +1,167 @@
import path from "path";
import { ensureDirSync, existsSync, readFile, writeFile } from "fs-extra";
import { BehaviorSubject, Observable, catchError, filter, lastValueFrom, of, take, timeout } from "rxjs";
import { ConfigurationService } from "../../configuration.service";
import { RequestService } from "../../request.service";
import { tryit } from "shared/helpers/error.helpers";
import { CACHE_PATH, HTTP_STATUS_CODES } from "main/constants";
import log from "electron-log";
import protobuf from "protobufjs";
import { UtilsService } from "../../utils.service";
import { SongDetails, SongDetailsCache } from "shared/models/maps/song-details-cache.model";
import { inflate } from "pako";
export class SongDetailsCacheService {
private static instance: SongDetailsCacheService;
public static getInstance(): SongDetailsCacheService {
if (!SongDetailsCacheService.instance) {
SongDetailsCacheService.instance = new SongDetailsCacheService();
}
return SongDetailsCacheService.instance;
}
private readonly dataSource = [
"https://raw.githubusercontent.com/Zagrios/beat-saber-scraped-maps/master/song_details_cache_v1.gz",
"https://cdn.jsdelivr.net/gh/Zagrios/beat-saber-scraped-maps@master/song_details_cache_v1.gz",
]
private readonly PROTO_CACHE_PATH = path.join(CACHE_PATH, "song-details-cache");
private readonly etagKey = "song-details-cache-etag";
private readonly config: ConfigurationService;
private readonly request: RequestService;
private readonly utils: UtilsService;
private songDetailsCache: Record<string, SongDetails> = {};
private readonly _loaded$ = new BehaviorSubject<boolean>(null);
private constructor(){
this.config = ConfigurationService.getInstance();
this.request = RequestService.getInstance();
this.utils = UtilsService.getInstance();
this.loadCache()
}
private async loadCache(): Promise<void> {
const protoCacheExists = existsSync(this.PROTO_CACHE_PATH);
const etag = protoCacheExists ? this.config.get<string>(this.etagKey) : null;
await this.downloadCacheFile(etag).then(etag => {
this.config.set(this.etagKey, etag);
}).catch(err => {
log.error("Unable to download cache file", err);
});
this.readProtoMessageCacheFile(this.PROTO_CACHE_PATH).then(cache => {
this.songDetailsCache = cache;
log.info("SongDetailsCache loaded");
}).catch(err => {
log.error("Failed to read cache file", this.PROTO_CACHE_PATH, err);
}).finally(() => {
this._loaded$.next(true);
})
}
private async readProtoMessageCacheFile(filePath: string): Promise<Record<string, SongDetails>> {
const protobufRoot = await protobuf.load(this.getProtoShemaPath());
const cacheMessage = protobufRoot.lookupType("SongDetailsCache");
const buffer = await readFile(filePath);
const messageBuffer = cacheMessage.decode(buffer);
const messageObj = cacheMessage.toObject(messageBuffer) as SongDetailsCache;
const res: Record<string, SongDetails> = {};
for(const song of messageObj.songs){
res[song.hash.toLocaleLowerCase()] = song;
}
return res;
}
/**
* Download the GZipped Proto file and write it to the cache destination
* @param etag
* @returns {string} new etag or the same if the file is the same
*/
private async downloadCacheFile(etag?: string): Promise<string> {
const { buffer, etag: newEtag } = await this.downloadGZCacheFile(etag);
if(!buffer) { return etag; }
ensureDirSync(path.dirname(this.PROTO_CACHE_PATH));
await writeFile(this.PROTO_CACHE_PATH, inflate(buffer), { encoding: "binary" });
return newEtag;
}
/**
* Download the GZipped Proto file from the sources
* @returns {Promise<{ buffer: Buffer, etag: string }>} {\
* buffer: GZipper Buffer, will be empty if etag is the same\
* etag: ETag of the file, should be never empty\
* }
*/
private async downloadGZCacheFile(etag?: string): Promise<{ buffer: Buffer, etag: string }> {
let lastError: Error;
for(const sourceUrl of this.dataSource){
const { result, error } = await tryit(() => {
return lastValueFrom(this.request.downloadBuffer(sourceUrl, {
headers: etag ? { "If-None-Match": etag } : {},
decompress: false
})).then(res => ({ buffer: res.data, request: res.extra}));
});
if(error) {
lastError = error;
continue;
}
log.info("Downloaded SongDetailCache file from source:", sourceUrl, "ETAG:", result.request.headers.etag, result.request.statusCode);
return {
buffer: result.request.statusCode === HTTP_STATUS_CODES.HTTP_STATUS_NOT_MODIFIED ? null : result.buffer,
etag: result.request.headers.etag
}
}
log.error("Failed to download SongDetailCache file", etag, lastError);
throw lastError;
}
private getProtoShemaPath(): string {
return this.utils.getAssetsPath(path.join("protos", "song_details_cache_v1.proto"))
}
public get loaded$(): Observable<boolean> {
return this._loaded$.pipe(filter(val => typeof val === "boolean"));
}
/**
* Promise that resolves when the cache is loaded (loaded does not mean cache contains data, just the all load process is done)
* @param timeoutMs in milliseconds
* @throws {TimeoutError} if the cache is not ready after the provided timeout
*/
public waitLoaded(timeoutMs: number): Promise<boolean> {
const obs = this.loaded$.pipe(take(1));
return lastValueFrom(obs.pipe(timeout(timeoutMs), catchError((err => {
log.error("Wait loaded SongDetailsCache timed out", err);
return of(false);
}))));
}
public getSongDetails(hash: string): any {
return this.songDetailsCache[hash.toLocaleLowerCase()];
}
}
+10 -10
View File
@@ -92,7 +92,7 @@ export class BSLocalVersionService {
}
public async getVersionOfBSFolder(
bsPath: string,
bsPath: string,
options?: {
steam?: boolean;
oculus?: boolean;
@@ -126,7 +126,7 @@ export class BSLocalVersionService {
// Will be removed in future version. It just to prepare future features
if(!metadata?.id){
metadata = await this.initVersionMetadata(folderVersion, metadata ?? { store: BsStore.STEAM });
metadata = await this.initVersionMetadata(folderVersion, metadata ?? { store: BsStore.STEAM });
}
folderVersion.metadata = metadata;
@@ -182,8 +182,8 @@ export class BSLocalVersionService {
/**
* Return path of a version even if it's not installed.
* @param {BSVersion} version
* Return path of a version even if it's not installed.
* @param {BSVersion} version
* @returns {Promise<string>}
*/
public async getVersionPath(version: BSVersion): Promise<string>{
@@ -191,25 +191,25 @@ export class BSLocalVersionService {
if(version.oculus){ return this.oculusService.tryGetGameFolder([OCULUS_BS_DIR, OCULUS_BS_BACKUP_DIR]); }
return path.join(
await this.installLocationService.versionsDirectory(),
this.installLocationService.versionsDirectory(),
this.getVersionFolder(version)
);
}
/**
* Return path of an installed version. Returns null if not found.
* @param {BSVersion} version
* @param {BSVersion} version
* @returns {Promise<string>}
*/
public async getInstalledVersionPath(version: BSVersion): Promise<string>{
const versionPath = await this.getVersionPath(version);
if(await pathExists(versionPath)){ return versionPath; }
const versionFolders = await getFoldersInFolder(await this.installLocationService.versionsDirectory());
const versionFolders = await getFoldersInFolder(this.installLocationService.versionsDirectory());
for(const folder of versionFolders){
const stats = await lstat(folder);
if(stats.ino === version.ino){
if(stats.ino === version.ino){
return folder;
}
}
@@ -270,11 +270,11 @@ export class BSLocalVersionService {
versions.push(oculusVersion);
}
if (!(await pathExists(await this.installLocationService.versionsDirectory()))) {
if (!(await pathExists(this.installLocationService.versionsDirectory()))) {
return versions;
}
const folderInInstallation = await getFoldersInFolder(await this.installLocationService.versionsDirectory());
const folderInInstallation = await getFoldersInFolder(this.installLocationService.versionsDirectory());
log.info("Finded versions folders", folderInInstallation);
@@ -82,7 +82,7 @@ export class BsSteamDownloaderService {
qr
}
await ensureDir(await this.installLocationService.versionsDirectory());
await ensureDir(this.installLocationService.versionsDirectory());
const isLinux = process.platform === 'linux';
const exePath = this.getDepotDownloaderExePath();
@@ -91,7 +91,7 @@ export class BsSteamDownloaderService {
const depotDownloader = new DepotDownloader({
command: isLinux ? 'dotnet' : exePath,
args: isLinux ? [exePath, ...args] : args,
options: { cwd: await this.installLocationService.versionsDirectory() },
options: { cwd: this.installLocationService.versionsDirectory() },
echoStartData: downloadVersion
}, log);
+2 -1
View File
@@ -23,11 +23,12 @@ export class ConfigurationService {
}
private async initStore() {
const contentPath = await this.locations.installationDirectory();
const contentPath = this.locations.installationDirectory();
this.store = new ElectronStore({
cwd: contentPath,
name: "config",
fileExtension: "cfg",
accessPropertiesByDotNotation: false,
});
}
@@ -1,7 +1,8 @@
import path from "path";
import { app } from "electron";
import ElectronStore from "electron-store";
import { copyDirectoryWithJunctions, deleteFolder, ensureFolderExist, pathExist } from "../helpers/fs.helpers";
import { copyDirectoryWithJunctions, deleteFolder, ensureFolderExist } from "../helpers/fs.helpers";
import { pathExistsSync } from "fs-extra";
export class InstallationLocationService {
private static instance: InstallationLocationService;
@@ -17,6 +18,7 @@ export class InstallationLocationService {
public readonly VERSIONS_FOLDER = "BSInstances";
private readonly SHARED_CONTENT_FOLDER = "SharedContent";
private readonly CACHE_FOLDER = "cache";
private readonly STORE_INSTALLATION_PATH_KEY = "installation-folder";
@@ -39,7 +41,7 @@ export class InstallationLocationService {
public async setInstallationDirectory(newDir: string): Promise<string> {
newDir = path.basename(newDir) === this.INSTALLATION_FOLDER ? path.join(newDir, "..") : newDir;
const oldDir = await this.installationDirectory();
const oldDir = this.installationDirectory();
await ensureFolderExist(oldDir);
await copyDirectoryWithJunctions(oldDir, path.join(newDir, this.INSTALLATION_FOLDER), { overwrite: true });
@@ -56,9 +58,9 @@ export class InstallationLocationService {
this.updateListeners.add(fn);
}
public async installationDirectory(): Promise<string> {
public installationDirectory(): string {
const installParentPath = async () => {
const installParentPath = () => {
if(this._installationDirectory) {
return this._installationDirectory;
}
@@ -68,24 +70,28 @@ export class InstallationLocationService {
}
const oldPath = path.join(app.getPath("documents"), this.INSTALLATION_FOLDER);
if(await pathExist(oldPath)){
if(pathExistsSync(oldPath)){
return app.getPath("documents");
}
return app.getPath("home");
};
this._installationDirectory = await installParentPath();
this._installationDirectory = installParentPath();
return path.join(this._installationDirectory, this.INSTALLATION_FOLDER);
}
public async versionsDirectory(): Promise<string> {
return path.join(await this.installationDirectory(), this.VERSIONS_FOLDER);
public versionsDirectory(): string {
return path.join(this.installationDirectory(), this.VERSIONS_FOLDER);
}
public async sharedContentPath(): Promise<string> {
return path.join(await this.installationDirectory(), this.SHARED_CONTENT_FOLDER);
public sharedContentPath(): string {
return path.join(this.installationDirectory(), this.SHARED_CONTENT_FOLDER);
}
public cachePath(): string {
return path.join(this.installationDirectory(), this.CACHE_FOLDER);
}
}
+2 -2
View File
@@ -1,5 +1,5 @@
import { IpcRequest } from "shared/models/ipc";
import { BrowserWindow, ipcMain } from "electron";
import { BrowserWindow, IpcMainEvent, ipcMain } from "electron";
import { Observable } from "rxjs";
import { IpcCompleteChannel, IpcErrorChannel, IpcTearDownChannel } from "shared/models/ipc/ipc-response.interface";
import { IpcReplier } from "shared/models/ipc/ipc-request.interface";
@@ -31,7 +31,7 @@ export class IpcService {
}
private buildProxyListener<T>(listener: IpcListener<T>) {
return (event: Electron.IpcMainEvent, req: IpcRequest<T>) => {
return (event: IpcMainEvent, req: IpcRequest<T>) => {
const window = BrowserWindow.fromWebContents(event.sender);
const replier = (data: Observable<unknown>) => this.connectStream(req.responceChannel, window, data);
listener(req, replier);
+34 -17
View File
@@ -4,6 +4,8 @@ import { Progression } from "main/helpers/fs.helpers";
import { Observable, shareReplay, tap } from "rxjs";
import log from "electron-log";
import fetch, { RequestInfo, RequestInit } from "node-fetch";
import got, { GotOptions } from "got";
import { IncomingMessage } from "http";
export class RequestService {
private static instance: RequestService;
@@ -30,7 +32,7 @@ export class RequestService {
throw new Error(`HTTP error! status: ${response.status} ${url}`);
}
return await response.json();
return await response.json() as T;
} catch (err) {
log.error(err);
throw err;
@@ -67,7 +69,7 @@ export class RequestService {
}).pipe(tap({ error: e => log.error(e, url, dest) }), shareReplay(1));
}
public downloadBuffer(url: string): Observable<Progression<Buffer>> {
public downloadBuffer(url: string, options?: GotOptions<string>): Observable<Progression<Buffer, IncomingMessage>> {
return new Observable<Progression<Buffer>>(subscriber => {
const progress: Progression<Buffer> = {
current: 0,
@@ -75,27 +77,42 @@ export class RequestService {
data: null,
};
const allChunks: Buffer[] = [];
const req = got.stream(url, options);
const req = get(url, { agent: this.ipv4Agent }, res => {
progress.total = parseInt(res.headers?.["content-length"] || "0", 10);
let data = Buffer.alloc(0);
let response: IncomingMessage;
res.on("data", chunk => {
allChunks.push(chunk);
progress.current += chunk.length;
subscriber.next(progress);
});
res.on("end", () => {
progress.data = Buffer.concat(allChunks);
subscriber.next(progress);
subscriber.complete();
});
res.on("error", err => subscriber.error(err));
req.once("response", res => {
response = res;
});
req.on("error", err => {
req.on("data", (chunk: Buffer) => {
data = Buffer.concat([data, chunk]);
})
req.on("downloadProgress", ({ transferred, total }) => {
progress.current = transferred;
progress.total = total;
subscriber.next(progress);
});
req.once("error", err => {
subscriber.error(err);
});
req.once("end", () => {
progress.data = data;
progress.extra = response;
subscriber.next(progress);
subscriber.complete();
});
req.resume();
return () => {
req.destroy();
}
}).pipe(tap({ error: e => log.error(e) }), shareReplay(1));
}
}
@@ -2,7 +2,7 @@ import { getFoldersInFolder } from "../helpers/fs.helpers";
import path from "path";
import { VersionLinkerAction, VersionLinkFolderAction, VersionUnlinkFolderAction } from "renderer/services/version-folder-linker.service";
import { BSVersion } from "shared/bs-version.interface";
import { LocalMapsManagerService } from "./additional-content/local-maps-manager.service";
import { LocalMapsManagerService } from "./additional-content/maps/local-maps-manager.service";
import { BSLocalVersionService } from "./bs-local-version.service";
import { FolderLinkerService, LinkOptions } from "./folder-linker.service";
import { allSettled } from "../../shared/helpers/promise.helpers";
@@ -3,13 +3,11 @@ import { BSVersion } from "shared/bs-version.interface";
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
import { BsmLocalMap } from "shared/models/maps/bsm-local-map.interface";
import { Subscription, BehaviorSubject } from "rxjs";
import { MapFilter } from "shared/models/maps/beat-saver.model";
import { MapFilter, MapTag } from "shared/models/maps/beat-saver.model";
import { MapsDownloaderService } from "renderer/services/maps-downloader.service";
import { VariableSizeList } from "react-window";
import { MapsRow } from "./maps-row.component";
import { debounceTime, last, mergeMap, tap } from "rxjs/operators";
import { BeatSaverService } from "renderer/services/thrird-partys/beat-saver.service";
import { OsDiagnosticService } from "renderer/services/os-diagnostic.service";
import { debounceTime, last, tap } from "rxjs/operators";
import { useTranslation } from "renderer/hooks/use-translation.hook";
import BeatWaitingImg from "../../../../../assets/images/apngs/beat-waiting.png";
import BeatConflict from "../../../../../assets/images/apngs/beat-conflict.png";
@@ -33,8 +31,6 @@ type Props = {
export const LocalMapsListPanel = forwardRef(({ version, className, filter, search, linkedState, isActive }: Props, forwardRef) => {
const mapsManager = useService(MapsManagerService);
const mapsDownloader = useService(MapsDownloaderService);
const bsaver = useService(BeatSaverService);
const os = useService(OsDiagnosticService);
const t = useTranslation();
const ref = useRef(null);
@@ -43,7 +39,7 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
const [selectedMaps$] = useState(new BehaviorSubject<BsmLocalMap[]>([]));
const [itemPerRow, setItemPerRow] = useState(2);
const [listHeight, setListHeight] = useState(0);
const isActiveOnce = useChangeUntilEqual(isActive, { untilEqual: true, emitOnEqual: true });
const isActiveOnce = useChangeUntilEqual(isActive, { untilEqual: true });
const [linked, setLinked] = useState(false);
const [loadPercent$] = useState(new BehaviorSubject(0));
@@ -135,21 +131,10 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
loadMapsObs$
.pipe(
tap(progress => loadPercent$.next(Math.floor((progress.loaded / progress.total) * 100))),
last(),
mergeMap(async progress => {
if (os.isOffline) {
return progress.maps;
}
const { maps } = progress;
const details = await bsaver.getMapDetailsFromHashs(maps.map(map => map.hash));
return maps.map(map => {
map.bsaverInfo = details.find(d => d.versions.at(0).hash === map.hash);
return map;
});
})
last()
)
.subscribe({
next: maps => setMaps(() => maps),
next: progress => setMaps(() => progress.maps),
complete: () => loadPercent$.next(0),
})
);
@@ -194,13 +179,14 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
// Can be more clean and optimized i think
const fitEnabledTags = (() => {
if (!filter?.enabledTags || filter.enabledTags.size === 0) {
return true;
}
if (!map?.bsaverInfo?.tags) {
if (!map?.songDetails?.tags) {
return false;
}
return Array.from(filter.enabledTags.values()).every(tag => map.bsaverInfo.tags.some(mapTag => mapTag === tag));
return Array.from(filter.enabledTags.values()).every(tag => map.songDetails.tags.some(mapTag => mapTag === tag));
})();
if (!fitEnabledTags) {
@@ -211,10 +197,10 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
if (!filter?.excludedTags || filter.excludedTags.size === 0) {
return true;
}
if (!map?.bsaverInfo?.tags) {
if (!map?.songDetails?.tags) {
return true;
}
return !map.bsaverInfo.tags.some(tag => filter.excludedTags.has(tag));
return !map.songDetails?.tags.some(tag => filter.excludedTags.has(tag as MapTag));
})();
if (!fitExcluedTags) {
@@ -225,12 +211,8 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
if (!filter?.minNps) {
return true;
}
if (!map?.bsaverInfo?.versions?.at(0)) {
return false;
}
return !map.bsaverInfo.versions.some(version => {
return version.diffs.some(diff => diff.nps < filter.minNps);
});
return map.songDetails?.difficulties.some(diff => diff.nps > filter.minNps);
})();
if (!fitMinNps) {
@@ -241,12 +223,8 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
if (!filter?.maxNps) {
return true;
}
if (!map?.bsaverInfo?.versions?.at(0)) {
return false;
}
return !map.bsaverInfo.versions.some(version => {
return version.diffs.some(diff => diff.nps > filter.maxNps);
});
return map.songDetails?.difficulties.some(diff => diff.nps < filter.maxNps);
})();
if (!fitMaxNps) {
@@ -258,10 +236,10 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
return true;
}
if (!map?.bsaverInfo?.metadata?.duration) {
if (!map?.songDetails?.metadata?.duration) {
return false;
}
return map.bsaverInfo.metadata.duration >= filter.minDuration;
return map.songDetails?.metadata.duration >= filter.minDuration;
})();
if (!fitMinDuration) {
@@ -272,10 +250,10 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
if (!filter?.maxDuration) {
return true;
}
if (!map?.bsaverInfo?.metadata?.duration) {
if (!map?.songDetails?.metadata?.duration) {
return false;
}
return map.bsaverInfo.metadata.duration <= filter.maxDuration;
return map.songDetails?.metadata.duration <= filter.maxDuration;
})();
if (!fitMaxDuration) {
@@ -286,10 +264,7 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
if (!filter?.noodle) {
return true;
}
if (!map?.bsaverInfo?.versions?.at(0)) {
return false;
}
return map.bsaverInfo.versions.some(version => version.diffs.some(diff => !!diff.ne));
return map.songDetails?.difficulties.some(diff => !!diff.ne);
})();
if (!fitNoodle) {
@@ -300,10 +275,8 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
if (!filter?.me) {
return true;
}
if (!map?.bsaverInfo?.versions?.at(0)) {
return false;
}
return map.bsaverInfo.versions.some(version => version.diffs.some(diff => !!diff.me));
return map.songDetails?.difficulties.some(diff => !!diff.me);
})();
if (!fitMe) {
@@ -314,10 +287,8 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
if (!filter?.cinema) {
return true;
}
if (!map?.bsaverInfo?.versions?.at(0)) {
return false;
}
return map.bsaverInfo.versions.some(version => version.diffs.some(diff => !!diff.cinema));
return map.songDetails?.difficulties.some(diff => !!diff.cinema);
})();
if (!fitCinema) {
@@ -328,10 +299,8 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
if (!filter?.chroma) {
return true;
}
if (!map?.bsaverInfo?.versions?.at(0)) {
return false;
}
return map.bsaverInfo.versions.some(version => version.diffs.some(diff => !!diff.chroma));
return map.songDetails?.difficulties.some(diff => !!diff.chroma);
})();
if (!fitChroma) {
@@ -342,31 +311,29 @@ export const LocalMapsListPanel = forwardRef(({ version, className, filter, sear
if (!filter?.fullSpread) {
return true;
}
if (!map?.bsaverInfo?.versions?.at(0)) {
return false;
}
return map.bsaverInfo.versions.some(version => version?.diffs?.length >= 5);
return map.songDetails?.difficulties.length >= 5;
})();
if (!fitFullSpread) {
return false;
}
if (!(filter?.automapper ? map.bsaverInfo?.automapper === filter.automapper : true)) {
if (filter?.automapper && (map.songDetails && !map.songDetails?.automapper)) {
return false;
}
if (!(filter?.ranked ? map.bsaverInfo?.ranked === filter.ranked : true)) {
if (!(filter?.ranked ? map.songDetails?.ranked === filter.ranked : true)) {
return false;
}
if (!(filter?.curated ? !!map.bsaverInfo?.curatedAt : true)) {
if (!(filter?.curated ? !!map.songDetails?.curated === filter.curated : true)) {
return false;
}
if (!(filter?.verified ? !!map.bsaverInfo?.uploader?.verifiedMapper : true)) {
if (!(filter?.verified ? !!map.songDetails?.uploader?.verified : true)) {
return false;
}
const searchCheck = (() => {
return ((map.rawInfo?._songName ?? map.bsaverInfo?.name) || "")?.toLowerCase().includes(search.toLowerCase()) || ((map.rawInfo?._songAuthorName ?? map.bsaverInfo?.metadata?.songAuthorName) || "")?.toLowerCase().includes(search.toLowerCase()) || ((map.rawInfo?._levelAuthorName ?? map.bsaverInfo?.metadata?.levelAuthorName) || "")?.toLowerCase().includes(search.toLowerCase());
return ((map.rawInfo?._songName ?? map.songDetails?.name) || "")?.toLowerCase().includes(search.toLowerCase()) || ((map.rawInfo?._songAuthorName ?? map.songDetails?.metadata?.songAuthorName) || "")?.toLowerCase().includes(search.toLowerCase()) || ((map.rawInfo?._levelAuthorName ?? map.songDetails?.metadata?.levelAuthorName) || "")?.toLowerCase().includes(search.toLowerCase());
})();
if (!searchCheck) {
@@ -1,5 +1,5 @@
import { BsmImage } from "../../shared/bsm-image.component";
import { BsvMapCharacteristic, BsvMapDifficultyType } from "shared/models/maps/beat-saver.model";
import { BsvMapDifficultyType } from "shared/models/maps/beat-saver.model";
import { useThemeColor } from "renderer/hooks/use-theme-color.hook";
import { BsmLink } from "../../shared/bsm-link.component";
import { BsmIcon } from "../../svgs/bsm-icon.component";
@@ -22,8 +22,9 @@ import { GlowEffect } from "../../shared/glow-effect.component";
import { useDelayedState } from "renderer/hooks/use-delayed-state.hook";
import { useService } from "renderer/hooks/use-service.hook";
import Tippy from "@tippyjs/react";
import { SongDetailDiffCharactertistic, SongDiffName } from "shared/models/maps";
export type ParsedMapDiff = { type: BsvMapDifficultyType; name: string; stars: number };
export type ParsedMapDiff = { type: SongDiffName; name: string; stars: number };
export type MapItemProps<T = unknown> = {
hash: string;
@@ -34,12 +35,12 @@ export type MapItemProps<T = unknown> = {
songUrl: string;
autorId: number;
mapId: string;
diffs: Map<BsvMapCharacteristic, ParsedMapDiff[]>;
diffs: Map<SongDetailDiffCharactertistic, ParsedMapDiff[]>;
ranked: boolean;
bpm: number;
duration: number;
likes: number;
createdAt: string;
createdAt: number;
selected?: boolean;
downloading?: boolean;
showOwned?: boolean;
@@ -165,7 +166,7 @@ export const MapItem = memo(({ hash, title, autor, songAutor, coverUrl, songUrl,
<li key={`${type}${name}${stars}`} className="w-full h-4 flex items-center gap-1">
<BsmIcon className="h-full w-fit p-px" icon={charac} />
<span className="h-full px-2 flex items-center text-xs font-bold bg-current rounded-full" style={{ color: MAP_DIFFICULTIES_COLORS[type] }}>
{stars ? <span className="h-full block brightness-[.25]">★ {stars}</span> : <span className="h-full brightness-[.25] leading-4 pb-[2px] capitalize">{parseDiffLabel(type)}</span>}
{stars ? <span className="h-full block brightness-[.25]">★ {stars.toFixed(2)}</span> : <span className="h-full brightness-[.25] leading-4 pb-[2px] capitalize">{parseDiffLabel(type)}</span>}
</span>
<span className="text-sm leading-4 pb-[2px] capitalize">{parseDiffLabel(name)}</span>
</li>
@@ -2,10 +2,10 @@ import { CSSProperties, memo } from "react";
import { useObservable } from "renderer/hooks/use-observable.hook";
import { distinctUntilChanged, map } from "rxjs/operators";
import { BehaviorSubject } from "rxjs";
import { BsvMapCharacteristic } from "shared/models/maps/beat-saver.model";
import { BsmLocalMap } from "shared/models/maps/bsm-local-map.interface";
import { ParsedMapDiff, MapItem } from "./map-item.component";
import equal from "fast-deep-equal/es6";
import { SongDetailDiffCharactertistic } from "shared/models/maps/song-details-cache.model";
type Props = {
maps: BsmLocalMap[];
@@ -21,10 +21,10 @@ export const MapsRow = memo(({ maps, style, selectedMaps$, onMapSelect, onMapDel
distinctUntilChanged(equal),
), []);
const extractMapDiffs = (map: BsmLocalMap): Map<BsvMapCharacteristic, ParsedMapDiff[]> => {
const res = new Map<BsvMapCharacteristic, ParsedMapDiff[]>();
if (map.bsaverInfo?.versions[0]?.diffs) {
map.bsaverInfo.versions[0].diffs.forEach(diff => {
const extractMapDiffs = (map: BsmLocalMap): Map<SongDetailDiffCharactertistic, ParsedMapDiff[]> => {
const res = new Map<SongDetailDiffCharactertistic, ParsedMapDiff[]>();
if (map.songDetails?.difficulties) {
map.songDetails?.difficulties.forEach(diff => {
const arr = res.get(diff.characteristic) || [];
const diffName = map.rawInfo._difficultyBeatmapSets.find(set => set._beatmapCharacteristicName === diff.characteristic)._difficultyBeatmaps.find(rawDiff => rawDiff._difficulty === diff.difficulty)?._customData?._difficultyLabel || diff.difficulty;
arr.push({ name: diffName, type: diff.difficulty, stars: diff.stars });
@@ -45,24 +45,26 @@ export const MapsRow = memo(({ maps, style, selectedMaps$, onMapSelect, onMapDel
};
const renderMapItem = (map: BsmLocalMap) => {
return <MapItem
key={map.hash}
hash={map.hash}
title={map.rawInfo._songName}
coverUrl={map.coverUrl}
songUrl={map.songUrl}
autor={map.rawInfo._levelAuthorName}
songAutor={map.rawInfo._songAuthorName}
bpm={map.rawInfo._beatsPerMinute}
duration={map.bsaverInfo?.metadata?.duration}
selected={selectedMaps.some(selected => selected.hash === map.hash)}
diffs={extractMapDiffs(map)} mapId={map.bsaverInfo?.id}
ranked={map.bsaverInfo?.ranked}
autorId={map.bsaverInfo?.uploader?.id}
likes={map.bsaverInfo?.stats?.upvotes}
createdAt={map.bsaverInfo?.createdAt}
onDelete={onMapDelete}
onSelected={onMapSelect}
return <MapItem
key={map.hash}
hash={map.hash}
title={map.rawInfo._songName}
coverUrl={map.coverUrl}
songUrl={map.songUrl}
autor={map.rawInfo._levelAuthorName}
songAutor={map.rawInfo._songAuthorName}
bpm={map.rawInfo._beatsPerMinute}
duration={map.songDetails?.metadata.duration}
selected={selectedMaps.some(selected => selected.hash === map.hash)}
diffs={extractMapDiffs(map)}
mapId={map.songDetails?.id}
ranked={map.songDetails?.ranked}
autorId={map.songDetails?.uploader.id}
likes={map.songDetails?.upVotes}
createdAt={map.songDetails?.uploadedAt}
onDelete={onMapDelete}
onSelected={onMapSelect}
callBackParam={map}
/>;
};
@@ -1,5 +1,8 @@
import { useChangeUntilEqual } from "renderer/hooks/use-change-until-equal.hook";
import { useOnUpdate } from "renderer/hooks/use-on-update.hook";
import { FolderLinkState } from "renderer/services/version-folder-linker.service";
import { BSVersion } from "shared/bs-version.interface";
import { noop } from "shared/helpers/function.helpers";
type Props = {
version: BSVersion;
@@ -9,6 +12,17 @@ type Props = {
};
export function LocalPlaylistsListPanel({ version, className, isActive, linkedState }: Props) {
const isActiveOnce = useChangeUntilEqual(isActive, { untilEqual: true });
useOnUpdate(() => {
if(!isActiveOnce){ return noop(); }
// load playlists
}, [isActiveOnce]);
return (
<div>local-playlists-list-panel.component</div>
)
@@ -3,32 +3,31 @@ import { useEffect, useRef, useState } from "react";
type Options<T = unknown> = {
untilEqual: T;
emitOnEqual?: boolean;
}
export function useChangeUntilEqual<T = unknown>(variableValue: T, { untilEqual, emitOnEqual }: Options<T>): T {
export function useChangeUntilEqual<T = unknown>(variableValue: T, { untilEqual }: Options<T> ): T {
const [value, setValue] = useState(variableValue);
const untilEqualRef = useRef(untilEqual);
const emitOnEqualRef = useRef(emitOnEqual);
const hasBeenEqual = useRef(false);
useEffect(() => {
if(hasBeenEqual.current) {
return;
}
const isEqual = equal(variableValue, untilEqualRef.current);
console.log("isEqual", isEqual, variableValue, untilEqualRef.current);
if(!isEqual){
console.log("setValue", variableValue);
return setValue(variableValue);
}
hasBeenEqual.current = true;
if(emitOnEqualRef.current) {
setValue(variableValue);
}
setValue(variableValue);
}, [variableValue]);
return value;
@@ -1,3 +1,3 @@
import { MapStyle } from "shared/models/maps/beat-saver.model";
export const MAP_STYLES: MapStyle[] = ["dance", "swing", "nightcore", "folk", "family", "ambient", "funk", "jazz", "soul", "speedcore", "punk", "rb", "holiday", "vocaloid", "jrock", "trance", "drumbass", "comedy", "instrumental", "hardcore", "kpop", "indie", "techno", "house", "game", "film", "alt", "dubstep", "metal", "anime", "hiphop", "jpop", "rock", "pop", "electronic", "classical-orchestral"];
export const MAP_STYLES: MapStyle[] = ["dance", "swing", "nightcore", "folk", "family", "ambient", "funk", "jazz", "soul", "speedcore", "punk", "rb", "holiday", "vocaloid", "j-rock", "trance", "drumbass", "comedy", "instrumental", "hardcore", "k-pop", "indie", "techno", "house", "game", "film", "alt", "dubstep", "metal", "anime", "hiphop", "j-pop", "rock", "pop", "electronic", "classical-orchestral"];
@@ -23,6 +23,10 @@ export class PlaylistsManagerService {
this.linker = VersionFolderLinkerService.getInstance();
}
public getVersionPlaylists(version: BSVersion): Promise {
return this.ipc.sendV2("get-version-playlists", version);
}
public isDeepLinksEnabled(): Promise<boolean> {
return lastValueFrom(this.ipc.sendV2<boolean>("is-playlists-deep-links-enabled"));
}
+2
View File
@@ -1,3 +1,5 @@
export function isFunction(value: any): value is Function {
return !!(value && value.constructor && value.call && value.apply)
}
export function noop() {}
+1 -1
View File
@@ -143,7 +143,7 @@ export interface BsvMapParitySummary {
export type BsvMapCharacteristic = "Standard" | "OneSaber" | "NoArrows" | "90Degree" | "360Degree" | "Lightshow" | "Lawless";
export type BsvMapDifficultyType = "Easy" | "Normal" | "Hard" | "Expert" | "ExpertPlus";
export type MapStyle = "dance" | "swing" | "nightcore" | "folk" | "family" | "ambient" | "funk" | "jazz" | "soul" | "speedcore" | "punk" | "rb" | "holiday" | "vocaloid" | "jrock" | "trance" | "drumbass" | "comedy" | "instrumental" | "hardcore" | "kpop" | "indie" | "techno" | "house" | "game" | "film" | "alt" | "dubstep" | "metal" | "anime" | "hiphop" | "jpop" | "rock" | "pop" | "electronic" | "classical-orchestral";
export type MapStyle = "dance" | "swing" | "nightcore" | "folk" | "family" | "ambient" | "funk" | "jazz" | "soul" | "speedcore" | "punk" | "rb" | "holiday" | "vocaloid" | "j-rock" | "trance" | "drumbass" | "comedy" | "instrumental" | "hardcore" | "k-pop" | "indie" | "techno" | "house" | "game" | "film" | "alt" | "dubstep" | "metal" | "anime" | "hiphop" | "j-pop" | "rock" | "pop" | "electronic" | "classical-orchestral";
export type MapType = "accuracy" | "balanced" | "challenge" | "dancestyle" | "fitness" | "speed" | "tech";
export type MapTag = MapStyle | MapType;
@@ -1,12 +1,12 @@
import { BsvMapDetail } from "./beat-saver.model";
import { RawMapInfoData } from "./raw-map.model";
import { SongDetails } from "./song-details-cache.model";
export interface BsmLocalMap {
hash: string;
coverUrl: string;
songUrl: string;
rawInfo: RawMapInfoData;
bsaverInfo?: BsvMapDetail;
songDetails?: SongDetails;
path: string;
}
+1
View File
@@ -1,2 +1,3 @@
export { RawMapInfoData, RawMapDifficulty, RawDifficultySet } from "./raw-map.model";
export { BsvInstant, BsvMapDetail, BsvMapDetailMetadata, BsvMapDifficulty, BsvMapParitySummary, BsvMapStats, BsvMapTestplay, BsvMapVersion, BsvUserDetail } from "./beat-saver.model";
export { SongDetailsCache, SongDetails, Difficulty, MapDetailMetadata, Uploader, SongDetailDiffCharactertistic, SongDiffName } from "./song-details-cache.model";
+3 -3
View File
@@ -1,4 +1,4 @@
import { BsvMapCharacteristic, BsvMapDifficultyType } from "./beat-saver.model";
import { SongDetailDiffCharactertistic, SongDiffName } from "./song-details-cache.model";
export interface RawMapInfoData<T = unknown> {
_version: string;
@@ -21,12 +21,12 @@ export interface RawMapInfoData<T = unknown> {
}
export interface RawDifficultySet {
_beatmapCharacteristicName: BsvMapCharacteristic;
_beatmapCharacteristicName: SongDetailDiffCharactertistic;
_difficultyBeatmaps: RawMapDifficulty[];
}
export interface RawMapDifficulty {
_difficulty: BsvMapDifficultyType;
_difficulty: SongDiffName;
_difficultyRank: string;
_beatmapFilename: string;
_noteJumpMovementSpeed: number;
@@ -0,0 +1,82 @@
export interface SongDetailsCache {
songs: SongDetails[];
lastUpdated: number; // int64 in protobuf is represented as number in TypeScript, but consider using BigInt for precise representation
total: number; // uint32
}
export interface SongDetails {
id: string;
hash: string;
name: string;
metadata: MapDetailMetadata;
uploader: Uploader;
uploadedAt: number; // int32
tags: string[];
bpm: number; // float
ranked: boolean;
qualified: boolean;
curated: boolean;
rankedBL: boolean;
nominatedBL: boolean;
qualifiedBL: boolean;
upVotes: number; // int32
downVotes: number; // int32
downloads: number; // int32
duration: number; // int32
automapper: boolean;
difficulties: Difficulty[];
}
export interface Difficulty {
difficulty: SongDiffName;
characteristic: SongDetailDiffCharactertistic;
label: string;
stars: number; // float
starsBL: number; // float
njs: number; // float
nps: number; // float
offset: number; // float
chroma: boolean;
cinema: boolean;
me: boolean;
ne: boolean;
bombs: number; // int32
notes: number; // int32
obstacles: number; // int32
}
export interface Uploader {
name: string;
id: number; // int32
verified: boolean;
}
export interface MapDetailMetadata {
bpm: number; // float
duration: number; // int32
levelAuthorName: string;
songAuthorName: string;
songName: string;
songSubName: string;
}
export enum SongDiffName {
Easy = "Easy",
Normal = "Normal",
Hard = "Hard",
Expert = "Expert",
ExpertPlus = "ExpertPlus",
}
export enum SongDetailDiffCharactertistic {
Standard = "Standard",
OneSaber = "OneSaber",
NoArrows = "NoArrows",
Lawless = "Lawless",
Lightshow = "Lightshow",
Legacy = "Legacy",
_90Degree = "90Degree",
_360Degree = "360Degree",
}