[feature] can now launch beat saber from shortcut

This commit is contained in:
MathieuG-P
2023-07-14 14:18:23 +02:00
parent 8a7ffdc264
commit 2f3b5bf610
32 changed files with 2119 additions and 347 deletions
+6
View File
@@ -1,3 +1,6 @@
import { app } from "electron";
import path from "path";
export const BS_EXECUTABLE = "Beat Saber.exe";
export const OCULUS_BS_DIR = "hyperbolic-magnetism-beat-saber";
export const BS_APP_ID = "620980";
@@ -5,3 +8,6 @@ export const BS_DEPOT = "620981";
export const APP_NAME = "BSManager";
export const STEAMVR_APP_ID = "250820";
export const IMAGE_CACHE_FOLDER = "imagescache";
export const IMAGE_CACHE_PATH = path.join(path.dirname(app.getPath("exe")), IMAGE_CACHE_FOLDER);
+13
View File
@@ -0,0 +1,13 @@
import { ProviderPlatform } from "shared/models/provider-platform.enum";
export function execOnOs<T>(executions: { [key in ProviderPlatform]?: () => T }, noError = false): T {
if(executions[process.platform as ProviderPlatform]) {
return executions[process.platform as ProviderPlatform]();
}
if(!noError) {
throw new Error(`No execution found for platform ${process.platform}`);
}
return undefined;
}
+8
View File
@@ -3,8 +3,11 @@ import { WindowManagerService } from "../services/window-manager.service";
import { IpcRequest } from "shared/models/ipc";
import { AppWindow } from "shared/models/window-manager/app-window.model";
import { BSLauncherService } from "../services/bs-launcher.service";
import { IpcService } from "../services/ipc.service";
import { from } from "rxjs";
const launcher = BSLauncherService.getInstance();
const ipc = IpcService.getInstance();
ipcMain.on("open-window-then-close-all", async (event, request: IpcRequest<AppWindow>) => {
const windowManager = WindowManagerService.getInstance();
@@ -25,3 +28,8 @@ ipcMain.on("close-windows", async (event, request: IpcRequest<AppWindow[]>) => {
const windowManager = WindowManagerService.getInstance();
windowManager.close(...request.args);
});
ipc.on<AppWindow>("open-window-or-focus", (req, reply) => {
const windowManager = WindowManagerService.getInstance();
reply(from(windowManager.openWindowOrFocus(req.args)));
});
+6 -2
View File
@@ -88,7 +88,11 @@ if (!gotTheLock) {
initServicesMustBeInitialized();
// DeepLinkService.getInstance().dispatchLinkOpened("bsmanager://launch/?launchOptions=%7B%22debug%22%3Afalse%2C%22oculus%22%3Atrue%2C%22desktop%22%3Atrue%2C%22version%22%3A%7B%22BSVersion%22%3A%221.29.0%22%2C%22BSManifest%22%3A%223341527958186345367%22%2C%22ReleaseURL%22%3A%22https%3A%2F%2Fsteamcommunity.com%2Fgames%2F620980%2Fannouncements%2Fdetail%2F6169409105082976092%22%2C%22ReleaseImg%22%3A%22https%3A%2F%2Fcdn.cloudflare.steamstatic.com%2Fsteamcommunity%2Fpublic%2Fimages%2Fclans%2F%2F32055887%2F255fd49cd96042b97089f754609be291293e783f.png%22%2C%22ReleaseDate%22%3A%221680188760%22%2C%22year%22%3A%222023%22%2C%22name%22%3A%221.29.0+%281%29%22%7D%7D");
// TODO : to remove
setTimeout(() => {
// DeepLinkService.getInstance().dispatchLinkOpened("bsmanager://launch?version=1.29.1&versionName=Hi+Twitter&versionIno=2533274792493431&oculusMode=true&desktopMode=true&additionalArgs=--nowait&additionalArgs=-omgargs");
}, 3000);
const deepLink = process.argv.find(arg => DeepLinkService.getInstance().isDeepLink(arg));
@@ -124,7 +128,7 @@ if (!gotTheLock) {
year: '2023',
name: 'Hi Twitter',
ino: 2533274792493431,
color: '#6545ff af'
color: '#6545ff'
},
additionalArgs: [ '--nowait', '-omgargs' ]
});
+6 -6
View File
@@ -1,6 +1,6 @@
import { BS_APP_ID, BS_DEPOT } from "../constants";
import path from "path";
import { BSVersion, PartialBSVersion } from "shared/bs-version.interface";
import { BSVersion } from "shared/bs-version.interface";
import { UtilsService } from "./utils.service";
import { ChildProcessWithoutNullStreams, spawn, spawnSync } from "child_process";
import log from "electron-log";
@@ -194,18 +194,18 @@ export class BSInstallerService {
return destPath;
}
public async importVersion(path: string): Promise<PartialBSVersion> {
const rawBsVersion = await this.localVersionService.getVersionOfBSFolder(path);
public async importVersion(path: string): Promise<BSVersion> {
const version = await this.localVersionService.getVersionOfBSFolder(path);
if (!rawBsVersion) {
if (!version) {
throw new Error("NOT_BS_FOLDER");
}
const destPath = await this.getPathNotAleardyExist(await this.localVersionService.getVersionPath(rawBsVersion));
const destPath = await this.getPathNotAleardyExist(await this.localVersionService.getVersionPath(version));
await copy(path, destPath, { dereference: true });
return rawBsVersion;
return version;
}
}
+133 -52
View File
@@ -1,7 +1,7 @@
import path from "path";
import { LaunchOption, BSLaunchEvent, BSLaunchErrorEvent, BSLaunchErrorType, BSLaunchEventType } from "../../shared/models/bs-launch";
import { LaunchOption, BSLaunchEvent, BSLaunchEventData, BSLaunchWarning, BSLaunchErrorData, BSLaunchError } from "../../shared/models/bs-launch";
import { UtilsService } from "./utils.service";
import { BS_EXECUTABLE, BS_APP_ID, STEAMVR_APP_ID } from "../constants";
import { BS_EXECUTABLE, BS_APP_ID, STEAMVR_APP_ID, IMAGE_CACHE_PATH } from "../constants";
import { ChildProcessWithoutNullStreams, SpawnOptionsWithoutStdio, spawn } from "child_process";
import { SteamService } from "./steam.service";
import { BSLocalVersionService } from "./bs-local-version.service";
@@ -9,10 +9,17 @@ import { OculusService } from "./oculus.service";
import { pathExist } from "../helpers/fs.helpers";
import { rename } from "fs/promises";
import log from "electron-log";
import { Observable, lastValueFrom, timer } from "rxjs";
import { Observable, lastValueFrom, of, timer } from "rxjs";
import { BsmProtocolService } from "./bsm-protocol.service";
import { app, shell } from "electron";
import { app} from "electron";
import { Resvg } from "@resvg/resvg-js";
import Color from "color";
import { ensureDir, writeFile } from "fs-extra";
import toIco from "to-ico";
import { objectFromEntries } from "../../shared/helpers/object.helpers";
import { WindowManagerService } from "./window-manager.service";
import { IpcService } from "./ipc.service";
import { BSVersionLibService } from "./bs-version-lib.service";
export class BSLauncherService {
private static instance: BSLauncherService;
@@ -22,8 +29,9 @@ export class BSLauncherService {
private readonly oculusService: OculusService;
private readonly localVersionService: BSLocalVersionService;
private readonly bsmProtocolService: BsmProtocolService;
private bsProcess: ChildProcessWithoutNullStreams;
private readonly windows: WindowManagerService;
private readonly ipc: IpcService;
private readonly remoteVersion: BSVersionLibService;
public static getInstance(): BSLauncherService {
if (!BSLauncherService.instance) {
@@ -38,11 +46,14 @@ export class BSLauncherService {
this.oculusService = OculusService.getInstance();
this.localVersionService = BSLocalVersionService.getInstance();
this.bsmProtocolService = BsmProtocolService.getInstance();
this.windows = WindowManagerService.getInstance();
this.ipc = IpcService.getInstance();
this.remoteVersion = BSVersionLibService.getInstance();
this.bsmProtocolService.on("launch", link => {
log.info("Launch from bsm protocol", link.toString());
if(!link.searchParams.has("launchOptions")){ return; }
this.launch(JSON.parse(link.searchParams.get("launchOptions"))).subscribe();
const shortcutParams = objectFromEntries(link.searchParams.entries()) as ShortcutParams;
this.openShortcutLaunchWindow(shortcutParams);
});
}
@@ -93,11 +104,7 @@ export class BSLauncherService {
return Array.from(new Set(launchArgs).values());
}
private launchBSProcess(bsExePath: string, args: string[], debug = false): Promise<void>{
if(this.bsProcess?.connected){
return Promise.reject("Beat Saber process already running");
}
private launchBSProcess(bsExePath: string, args: string[], debug = false): ChildProcessWithoutNullStreams{
const spawnOptions: SpawnOptionsWithoutStdio = { shell: true, cwd: path.dirname(bsExePath), env: {...process.env, "SteamAppId": BS_APP_ID} };
@@ -106,54 +113,44 @@ export class BSLauncherService {
spawnOptions.windowsVerbatimArguments = true;
}
this.bsProcess = spawn(`\"${bsExePath}\"`, args, spawnOptions);
return new Promise((resolve, reject) => {
this.bsProcess.on('error', e => { log.error(e); reject(e); });
this.bsProcess.once('exit', code => {
if(code !== 0){
log.error(`Beat Saber process exited with code ${code}`);
}
resolve();
});
});
return spawn(`\"${bsExePath}\"`, args, spawnOptions);
}
public launch(launchOptions: LaunchOption): Observable<BSLaunchEvent>{
public launch(launchOptions: LaunchOption): Observable<BSLaunchEventData>{
// const t = new URL("bsmanager://launch");
// t.searchParams.set("launchOptions", JSON.stringify(launchOptions));
// console.log(t.toString());
return new Observable<BSLaunchEventData>(obs => {(async () => {
console.log(launchOptions);
return new Observable<BSLaunchEvent>(obs => {(async () => {
if(await this.isBsRunning()){
return obs.error({type: BSLaunchErrorType.BS_ALREADY_RUNNING} as BSLaunchErrorEvent);
if(launchOptions.skipAlreadyRunning !== true && await this.isBsRunning()){
return obs.error({type: BSLaunchError.BS_ALREADY_RUNNING} as BSLaunchErrorData);
}
if(launchOptions.version.oculus && (await this.oculusService.oculusRunning())){
return obs.error({type: BSLaunchErrorType.OCULUS_NOT_RUNNING} as BSLaunchErrorEvent);
return obs.error({type: BSLaunchError.OCULUS_NOT_RUNNING} as BSLaunchErrorData);
}
const bsFolderPath = await this.localVersionService.getInstalledVersionPath(launchOptions.version);
const exePath = path.join(bsFolderPath, BS_EXECUTABLE);
if(!(await pathExist(exePath))){
return obs.error({type: BSLaunchErrorType.BS_NOT_FOUND} as BSLaunchErrorEvent);
return obs.error({type: BSLaunchError.BS_NOT_FOUND} as BSLaunchErrorData);
}
// Open Steam if not running
if(!launchOptions.version.oculus && !(await this.steamService.steamRunning())){
obs.next({type: BSLaunchEventType.STEAM_LAUNCHING});
await this.steamService.openSteam().catch(log.error);
obs.next({type: BSLaunchEvent.STEAM_LAUNCHING});
await this.steamService.openSteam().then(() => {
obs.next({type: BSLaunchEvent.STEAM_LAUNCHED});
}).catch(e => {
log.error(e);
obs.next({type: BSLaunchWarning.UNABLE_TO_LAUNCH_STEAM});
});
}
// Backup SteamVR when desktop mode is enabled
if(!launchOptions.version.oculus && launchOptions.desktop){
await this.backupSteamVR().catch(e => {
await this.backupSteamVR().catch(() => {
return this.restoreSteamVR();
});
await lastValueFrom(timer(2_000));
@@ -163,22 +160,52 @@ export class BSLauncherService {
const launchArgs = this.buildBsLaunchArgs(launchOptions);
obs.next({type: BSLaunchEventType.BS_LAUNCHING});
obs.next({type: BSLaunchEvent.BS_LAUNCHING});
await this.launchBSProcess(exePath, launchArgs, launchOptions.debug).catch(err => {
obs.error({type: BSLaunchErrorType.BS_EXIT_ERROR, data: err} as BSLaunchErrorEvent);
}).finally(() => {
if(!launchOptions.desktop || launchOptions.version.oculus){ return; }
this.restoreSteamVR();
await new Promise<number>((resolve, reject) => {
const bsProcess = this.launchBSProcess(exePath, launchArgs, launchOptions.debug);
bsProcess.on("error", reject);
bsProcess.on("exit", resolve);
setTimeout(() => {
bsProcess.removeAllListeners("error");
bsProcess.removeAllListeners("exit");
resolve(-1);
}, 4000);
}).then(exitCode => {
log.info("BS process exit code", exitCode);
}).catch(err => {
log.error(err);
obs.error({type: BSLaunchError.BS_EXIT_ERROR, data: err} as BSLaunchErrorData);
});
})().then(() => {
obs.complete();
}).catch(err => {
obs.error({type: BSLaunchErrorType.UNKNOWN_ERROR, data: err} as BSLaunchErrorEvent);
obs.error({type: BSLaunchError.UNKNOWN_ERROR, data: err} as BSLaunchErrorData);
})});
}
private shortcutParamsToLaunchOption(params: ShortcutParams): LaunchOption{
const res: LaunchOption = {
version: {
BSVersion: params.version,
name: params.versionName,
steam: params.versionSteam === "true",
oculus: params.versionOculus === "true",
ino: +params.versionIno
},
oculus: params.oculusMode === "true",
desktop: params.desktopMode === "true",
debug: params.debug === "true",
additionalArgs: params.additionalArgs
};
return res;
}
private launchOptionToShortcutParams(launchOptions: LaunchOption): ShortcutParams{
const res: ShortcutParams = { version: launchOptions.version.BSVersion };
@@ -195,19 +222,73 @@ export class BSLauncherService {
return res;
}
/**
* Create .ico file for the shortcut with the given color
* @param {Color} color
* @returns {Promise<string>} Path of the icon
*/
private async createShortcutIco(color: Color): Promise<string>{
const svgIcon = `
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 406.4 406.4" height="406.4" width="406.4">
<rect rx="69.453" height="406.4" width="406.4" fill="${color.hex()}"/>
<path d="M65.467 60.6H336.4v33.867L200.933 162.2 65.467 94.467z" fill="#fff"/>
</svg>
`;
const pngBuffer = new Resvg(svgIcon, {
fitTo: { mode: "width", value: 256 }
}).render().asPng();
const icoBuffer = await toIco([pngBuffer]);
await ensureDir(IMAGE_CACHE_PATH);
const iconPath = path.join(IMAGE_CACHE_PATH, `launch_shortcut_${color.hex()}.ico`);
await writeFile(iconPath, icoBuffer);
return iconPath;
}
private createInternetShortcut(options: { url: string, output: string, iconFile?: string, iconIndex?: number }): Promise<void>{
const data = [
"[InternetShortcut]",
`URL=${options.url}`,
options.iconFile ? `IconFile=${options.iconFile}` : null,
`IconIndex=${options.iconIndex ?? 0}`
].join("\r\n");
return writeFile(options.output, data);
}
public async createLaunchShortcut(launchOptions: LaunchOption): Promise<void>{
const shortcutParams = this.launchOptionToShortcutParams(launchOptions);
const shortcutUrl = this.bsmProtocolService.buildLink("launch", shortcutParams);
console.log(objectFromEntries(shortcutUrl.searchParams.entries()));
const shortcutName = ["Beat Saber", launchOptions.version.BSVersion, launchOptions.version.name].join(" ")
// shell.writeShortcutLink(path.join(app.getPath("desktop"), "test.lnk"), "create", {
// target: shortcutUrl.toString(),
// description: "test allo allo",
// });
return this.createInternetShortcut({
output: path.join(app.getPath("desktop"), `${shortcutName}.url`),
url: shortcutUrl.toString(),
iconFile: await this.createShortcutIco(new Color(launchOptions.version.color, "hex")),
});
}
private async openShortcutLaunchWindow(launchOptions: ShortcutParams): Promise<void>{
const launchOption = this.shortcutParamsToLaunchOption(launchOptions);
launchOption.version = await this.localVersionService.getVersionOfBSFolder(await this.localVersionService.getInstalledVersionPath(launchOption.version));
launchOption.version = {...(await this.remoteVersion.getVersionDetails(launchOption.version.BSVersion)), ...launchOption.version};
this.ipc.once("shortcut-launch-options", (_data, reply) => {
reply(of(launchOption));
});
this.windows.openWindow("shortcut-launch.html");
}
}
+49 -52
View File
@@ -1,5 +1,5 @@
import { BSVersionLibService } from "./bs-version-lib.service";
import { BSVersion, PartialBSVersion } from "shared/bs-version.interface";
import { BSVersion } from "shared/bs-version.interface";
import { InstallationLocationService } from "./installation-location.service";
import { SteamService } from "./steam.service";
import { BS_APP_ID, OCULUS_BS_DIR } from "../constants";
@@ -45,50 +45,55 @@ export class BSLocalVersionService {
public async getVersionOfBSFolder(bsPath: string): Promise<PartialBSVersion>{
public async getVersionOfBSFolder(bsPath: string): Promise<BSVersion>{
const versionFilePath = path.join(bsPath, 'Beat Saber_Data', 'globalgamemanagers');
if(!(await pathExist(versionFilePath))){ return null; }
const versionsAvailable = await this.remoteVersionService.getAvailableVersions();
const versionsDict = await this.remoteVersionService.getAvailableVersions();
return new Promise<PartialBSVersion>(async (resolve, reject) => {
const folderVersion = await new Promise<BSVersion>(async (resolve, reject) => {
const stream = createReadStream(versionFilePath);
stream.on('data', async line => {
stream.on('data', line => {
line = line.toString();
for(const version of versionsAvailable){
if(!line.includes(version.BSVersion)){ continue; }
const findVersion: PartialBSVersion = {BSVersion: version.BSVersion};
if(findVersion.BSVersion !== path.basename(bsPath)){
findVersion.name = path.basename(bsPath);
}
for(const bsVersion of versionsDict){
const folderStats = await lstat(bsPath);
if(folderStats.ino){
findVersion.ino = folderStats.ino;
}
if(!line.includes(bsVersion.BSVersion)){ continue; }
resolve({...bsVersion});
stream.close();
stream.destroy();
return resolve(findVersion);
return;
}
});
stream.on("close", () => {
resolve(null);
});
stream.on("error", e => {
reject(e);
});
stream.on("close", () => { resolve(null); });
stream.on("error", e => { log.error(e); reject(e); });
});
if(!folderVersion){ return null; }
if(folderVersion.BSVersion !== path.basename(bsPath)){
folderVersion.name = path.basename(bsPath);
}
const folderStats = await lstat(bsPath);
if(folderStats.ino){
folderVersion.ino = folderStats.ino;
}
const customVersion = this.getCustomVersions().find(customVersion => {
return customVersion.BSVersion === folderVersion.BSVersion && customVersion.name === folderVersion.name;
});
folderVersion.color = customVersion?.color;
return folderVersion;
}
private setCustomVersions(versions: BSVersion[]): void{
@@ -165,35 +170,38 @@ export class BSLocalVersionService {
private async getSteamVersion(): Promise<BSVersion> {
const steamBsFolder = await this.steamService.getGameFolder(BS_APP_ID, "Beat Saber");
if (!steamBsFolder || !(await pathExist(steamBsFolder))) {
return null;
}
const steamBsVersion = await this.getVersionOfBSFolder(steamBsFolder);
if (!steamBsVersion) {
if(!steamBsVersion){
return null;
}
const version = await this.remoteVersionService.getVersionDetails(steamBsVersion.BSVersion);
if (!version) {
return null;
}
return { ...version, steam: true };
steamBsVersion.name = undefined;
steamBsVersion.steam = true;
return steamBsVersion;
}
private async getOculusVersion(): Promise<BSVersion> {
const oculusBsFolder = await this.oculusService.getGameFolder(OCULUS_BS_DIR);
if (!oculusBsFolder) {
return null;
}
const oculusBsVersion = await this.getVersionOfBSFolder(oculusBsFolder);
if(!oculusBsVersion){ return null; }
const version = await this.remoteVersionService.getVersionDetails(oculusBsVersion.BSVersion);
if (!version) {
return null;
}
return { ...version, oculus: true };
oculusBsVersion.name = undefined;
oculusBsVersion.oculus = true;
return oculusBsVersion;
}
public async getInstalledVersions(): Promise<BSVersion[]> {
@@ -217,23 +225,12 @@ export class BSLocalVersionService {
for (const f of folderInInstallation) {
log.info("try get version from folder", f);
const rawVersion = await this.getVersionOfBSFolder(f);
if(!rawVersion){ continue; }
const version = await this.getVersionOfBSFolder(f);
const vertionDetails = await this.remoteVersionService.getVersionDetails(rawVersion.BSVersion);
if(!version){ continue; }
if(!vertionDetails){ continue; }
const bsVersion: BSVersion = {...vertionDetails, ...rawVersion};
const customVersion = this.getCustomVersions().find(custom => custom.BSVersion === bsVersion.BSVersion && custom.name === bsVersion.name);
if (customVersion) {
bsVersion.color = customVersion.color;
}
versions.push(bsVersion);
versions.push(version);
};
this.setCustomVersions(versions.filter(v => !!v.color));
+5 -5
View File
@@ -39,11 +39,11 @@ export class BsmProtocolService {
}
public buildLink(host: string, params?: Record<string, string|string[]>): URL {
return buildUrl({
protocol: this.BSM_PROTOCOL,
host,
search: params
});
return buildUrl({
protocol: this.BSM_PROTOCOL,
host,
search: params
});
}
}
@@ -18,6 +18,7 @@ export class WindowManagerService {
"oneclick-download-map.html": { width: 350, height: 400, minWidth: 350, minHeight: 400, resizable: false },
"oneclick-download-playlist.html": { width: 350, height: 400, minWidth: 350, minHeight: 400, resizable: false },
"oneclick-download-model.html": { width: 350, height: 400, minWidth: 350, minHeight: 400, resizable: false },
"shortcut-launch.html": { width: 600, height: 300, minWidth: 600, minHeight: 300, resizable: false },
};
private readonly baseWindowOption: BrowserWindowConstructorOptions = {
@@ -89,4 +90,15 @@ export class WindowManagerService {
public getAppWindowFromWebContents(sender: Electron.WebContents): AppWindow {
return Array.from(this.windows.entries()).find(([, value]) => value.webContents.id === sender.id)[0];
}
public openWindowOrFocus(window: AppWindow): Promise<void> {
const win = this.getWindow(window);
if (win) {
win.focus();
return Promise.resolve();
}
return this.openWindow(window).then(() => {});
}
}