Merge branch 'master' into feat/663

This commit is contained in:
LiamillionSS
2024-11-25 16:35:23 +11:00
committed by GitHub
47 changed files with 965 additions and 250 deletions
+1 -1
View File
@@ -59,7 +59,7 @@ module.exports = {
"react/function-component-definition": "off",
"jsx-a11y/control-has-associated-label": "off",
"react/button-has-type": "off",
"no-labels": ["error", { "allowLoop": true }]
"max-classes-per-file": "off",
},
parserOptions: {
ecmaVersion: 2020,
+1
View File
@@ -16,3 +16,4 @@
*.woff binary
*.woff2 binary
assets/scripts/* binary
*.zip binary
+5 -4
View File
@@ -13,7 +13,7 @@ jobs:
build:
strategy:
matrix:
os: [ubuntu-latest, windows-latest, macos-latest]
os: [ubuntu-latest, windows-latest]
runs-on: ${{ matrix.os }}
@@ -26,6 +26,7 @@ jobs:
cache: "npm"
- run: npm ci
- run: npm run build
- run: npm test
# Currently typescript, eslint, and prettier are unhappy
continue-on-error: true
- name: Unit tests
run: npm run test:unit
+11 -3
View File
@@ -785,8 +785,7 @@
"ReleaseURL": "https://steamcommunity.com/games/620980/announcements/detail/4669760442595134838",
"ReleaseImg": "https://clan.akamai.steamstatic.com/images/32055887/57cfa043407c091e67b7e0a8ae86fe5590deae33.png",
"ReleaseDate": "1728399815",
"year": "2024",
"recommended": true
"year": "2024"
},
{
"BSVersion": "1.39.0",
@@ -796,5 +795,14 @@
"ReleaseImg": "https://clan.cloudflare.steamstatic.com/images/32055887/fd8e2c783e46decdf5e10fed1e16f124616d9321.png",
"ReleaseDate": "1731426932",
"year": "2024"
},
{
"BSVersion": "1.39.1",
"BSManifest": "2179614296547473280",
"OculusBinaryId": "8189133517853022",
"ReleaseURL": "https://steamcommunity.com/games/620980/announcements/detail/4451340304252928024",
"ReleaseDate": "1732107748",
"year": "2024",
"recommended": true
}
]
]
+11 -1
View File
@@ -38,6 +38,7 @@
"desktop-description": "Auf diese Weise kannst du WASD und die Maus verwenden, um im Spiel durch das Menü zu navigieren. Dies erleichtert das Testen erheblich, da du dein Headset nicht aufsetzen musst!",
"debug": "Debug Modus",
"debug-description": "Aktiviert das Ausgabeprotokollfenster für IPA. Dies zeigt die Debug-Konsole, welche die Mods verwenden.",
"outdated-tippy": "Diese Version ist veraltet, und einige Mods oder Funktionen funktionieren möglicherweise nicht wie erwartet. Es wird empfohlen, die empfohlene Version ({recommendedVersion}) von Beat Saber zu verwenden, um die neuesten Funktionen und Fehlerbehebungen zu genießen.",
"advanced-launch": {
"button": "Erweiterter Start",
"placeholder": "Weitere Argumente, bspw: --revert; --nowait"
@@ -107,7 +108,8 @@
"latest": "Neueste",
"description": "Beschreibung",
"dropdown": {
"uninstall-all": "Alle deinstallieren"
"uninstall-all": "Alle deinstallieren",
"unselect-all": "Alle abwählen"
}
}
},
@@ -594,6 +596,14 @@
"error": {
"msg": "Beim Erstellen der Verknüpfung ist ein Fehler aufgetreten."
}
},
"bs-version-oudated": {
"title": "Veraltete Version",
"msg": "Diese Version von Beat Saber ist veraltet. Verwenden Sie die empfohlene Version, um die neuesten Funktionen und Fehlerbehebungen zu nutzen.",
"actions": {
"do-not-remind": "Nicht mehr daran erinnern",
"ok": "Ok"
}
}
},
"modals": {
+11 -1
View File
@@ -38,6 +38,7 @@
"desktop-description": "First Person Flying Controller mode allows you to use WASD and the mouse to navigate around the menu in game. This makes testing much easier, because you don't have to put on your headset!",
"debug": "Debug Mode",
"debug-description": "Enables the output log window for IPA. This will show the debug console that mods use.",
"outdated-tippy": "This version is outdated, and some mods or features may no longer work as expected. Prefer using the recommended version ({recommendedVersion}) of Beat Saber to enjoy the latest features and bugfixes.",
"advanced-launch": {
"button": "Advanced launch",
"placeholder": "Additional arguments ex: --revert; --nowait"
@@ -107,7 +108,8 @@
"latest": "Latest",
"description": "Description",
"dropdown": {
"uninstall-all": "Uninstall all"
"uninstall-all": "Uninstall all",
"unselect-all": "Unselect all"
}
}
},
@@ -594,6 +596,14 @@
"error": {
"msg": "An error occurred while creating the shortcut."
}
},
"bs-version-oudated": {
"title": "Version Outdated",
"msg": "This Beat Saber version is outdated, use the recommended version to enjoy the latest features and bugfixes",
"actions": {
"do-not-remind": "Do not remind me",
"ok": "Ok"
}
}
},
"modals": {
+11 -1
View File
@@ -38,6 +38,7 @@
"desktop-description": "El modo FPFC te permite usar WASD y el mouse para navegar por el menú en juego. Esto hace que las pruebas sean mucho más fáciles, ¡porque no tienes que ponerte las gafas VR!",
"debug": "Modo Depuración",
"debug-description": "Habilita la ventana de registro de salida para IPA. Esto mostrará la consola de depuración que usan los mods.",
"outdated-tippy": "Esta versión está desactualizada, y algunos mods o funciones pueden no funcionar como se espera. Es mejor usar la versión recomendada ({recommendedVersion}) de Beat Saber para disfrutar de las últimas características y correcciones.",
"advanced-launch": {
"button": "Opciones avanzadas",
"placeholder": "Argumentos adicionales ej: --revert; --no-wait"
@@ -107,7 +108,8 @@
"latest": "Último",
"description": "Descripción",
"dropdown": {
"uninstall-all": "Desinstalar todos"
"uninstall-all": "Desinstalar todos",
"unselect-all": "Deseleccionar todo"
}
}
},
@@ -594,6 +596,14 @@
"error": {
"msg": "Se produjo un error al crear el acceso directo."
}
},
"bs-version-oudated": {
"title": "Versión desactualizada",
"msg": "Esta versión de Beat Saber está desactualizada. Usa la versión recomendada para disfrutar de las últimas características y correcciones.",
"actions": {
"do-not-remind": "No volver a recordármelo",
"ok": "Ok"
}
}
},
"modals": {
+11 -1
View File
@@ -38,6 +38,7 @@
"desktop-description": "Cela vous permet d'utiliser WASD et la souris pour naviguer dans le menu en jeu. Cela rend les tests beaucoup plus faciles, car vous n'avez pas à mettre votre casque!",
"debug": "Mode Debug",
"debug-description": "Active la fenêtre de log pour IPA. Cela affichera la console de débogage utilisée par les mods.",
"outdated-tippy": "Cette version est obsolète et certains mods ou fonctionnalités peuvent ne plus fonctionner comme prévu. Préférez utiliser la version recommandée ({recommendedVersion}) de Beat Saber pour profiter des dernières fonctionnalités et correctifs.",
"advanced-launch": {
"button": "Lancement avancé",
"placeholder": "Arguments supplémentaires ex: --revert; --nowait"
@@ -107,7 +108,8 @@
"latest": "Récent",
"description": "Description",
"dropdown": {
"uninstall-all": "Tout désinstaller"
"uninstall-all": "Tout désinstaller",
"unselect-all": "Tout désélectionner"
}
}
},
@@ -595,6 +597,14 @@
"error": {
"msg": "Une erreur s'est produite lors de la création du raccourci."
}
},
"bs-version-oudated": {
"title": "Version obsolète",
"msg": "Cette version de Beat Saber est obsolète. Utilisez la version recommandée pour profiter des dernières fonctionnalités et correctifs.",
"actions": {
"do-not-remind": "Ne plus me rappeler",
"ok": "Ok"
}
}
},
"modals": {
+11 -1
View File
@@ -38,6 +38,7 @@
"desktop-description": "ファーストパーソン・フライング・コントローラー・モードでは、WASDとマウスを使ってゲーム内のメニューを操作できます。ヘッドセットを装着する必要がないので、テストがより簡単になります!",
"debug": "デバックモード",
"debug-description": "IPAの出力ログウィンドウを有効にします。これはMODのデバッグコンソールを表示します。",
"outdated-tippy": "このバージョンは古いため、一部のMODや機能が期待通りに動作しない可能性があります。最新の機能やバグ修正を楽しむには、推奨バージョン ({recommendedVersion}) のBeat Saberを使用することをお勧めします。",
"advanced-launch": {
"button": "高度な起動",
"placeholder": "追加引数 例:--revert; --nowait"
@@ -107,7 +108,8 @@
"latest": "最新",
"description": "說明",
"dropdown": {
"uninstall-all": "全てアンインストールする"
"uninstall-all": "全てアンインストールする",
"unselect-all": "すべて選択解除"
}
}
},
@@ -594,6 +596,14 @@
"error": {
"msg": "ショートカットの作成中にエラーが発生しました。"
}
},
"bs-version-oudated": {
"title": "バージョンが古い",
"msg": "このBeat Saberのバージョンは古いため、推奨バージョンを使用して最新の機能やバグ修正をお楽しみください。",
"actions": {
"do-not-remind": "再度通知しない",
"ok": "OK"
}
}
},
"modals": {
+11 -1
View File
@@ -38,6 +38,7 @@
"desktop-description": "FPFC 모드에서는 WASD와 마우스로 게임 내 메뉴를 조작할 수 있어 테스트가 더 쉬워집니다. 헤드셋을 착용할 필요가 없습니다!",
"debug": "디버그 모드",
"debug-description": "IPA 출력 로그 창을 활성화하여 MOD의 디버그 콘솔을 표시합니다.",
"outdated-tippy": "이 버전은 오래되어 일부 모드나 기능이 예상대로 작동하지 않을 수 있습니다. 최신 기능과 버그 수정을 사용하려면 권장 버전({recommendedVersion})의 Beat Saber를 사용하는 것이 좋습니다.",
"advanced-launch": {
"button": "고급 실행",
"placeholder": "추가 인수 예: --revert; --nowait"
@@ -107,7 +108,8 @@
"latest": "최신",
"description": "설명",
"dropdown": {
"uninstall-all": "모두 제거"
"uninstall-all": "모두 제거",
"unselect-all": "모두 선택 해제"
}
}
},
@@ -594,6 +596,14 @@
"error": {
"msg": "바로 가기 생성 중 오류가 발생했습니다."
}
},
"bs-version-oudated": {
"title": "버전이 오래됨",
"msg": "이 Beat Saber 버전은 오래되었습니다. 최신 기능과 버그 수정을 즐기려면 권장 버전을 사용하세요.",
"actions": {
"do-not-remind": "다시 알리지 않기",
"ok": "확인"
}
}
},
"modals": {
+11 -1
View File
@@ -38,6 +38,7 @@
"desktop-description": "Режим Летающих контроллеров от первого лица(FPFC) позволит вам использовать меню с помощью WASD и мышки. Это облегчает тестирование модов, потому что вам не нужно подключать шлем!",
"debug": "Режим отладки",
"debug-description": "Включает окно логов для IPA. В окне будут отображаться логи модов.",
"outdated-tippy": "Эта версия устарела, и некоторые моды или функции могут работать не так, как ожидалось. Рекомендуется использовать рекомендуемую версию ({recommendedVersion}) Beat Saber, чтобы воспользоваться последними функциями и исправлениями ошибок.",
"advanced-launch": {
"button": "Расширенный запуск",
"placeholder": "Параметры запуска, например: --revert; --nowait"
@@ -107,7 +108,8 @@
"latest": "Latest",
"description": "Описание",
"dropdown": {
"uninstall-all": "Удалить всё"
"uninstall-all": "Удалить всё",
"unselect-all": "Снять все выделения"
}
}
},
@@ -594,6 +596,14 @@
"error": {
"msg": "Ошибка создания ярлыка."
}
},
"bs-version-oudated": {
"title": "Устаревшая версия",
"msg": "Эта версия Beat Saber устарела. Используйте рекомендуемую версию, чтобы воспользоваться последними функциями и исправлениями ошибок.",
"actions": {
"do-not-remind": "Больше не напоминать",
"ok": "Ок"
}
}
},
"modals": {
+11 -1
View File
@@ -38,6 +38,7 @@
"desktop-description": "第一人稱飛控模式允許你使用鍵盤 WASD 和滑鼠在遊戲中進行導航。你無需帶上頭顯即可進行測試!",
"debug": "Debug 模式",
"debug-description": "為 IPA 啟用輸出日誌窗口。 會顯示所用 Mod 的 debug 輸出",
"outdated-tippy": "此版本已過時,某些模組或功能可能無法按預期運作。建議使用推薦版本的 Beat Saber ({recommendedVersion}),以享受最新功能和修復。",
"advanced-launch": {
"button": "高級啟動",
"placeholder": "額外啟動參數,例如: --revert; --nowait"
@@ -107,7 +108,8 @@
"latest": "最新",
"description": "描述",
"dropdown": {
"uninstall-all": "全部移除"
"uninstall-all": "全部移除",
"unselect-all": "取消全選"
}
}
},
@@ -594,6 +596,14 @@
"error": {
"msg": "創建捷徑時發生錯誤"
}
},
"bs-version-oudated": {
"title": "版本過時",
"msg": "此 Beat Saber 版本已過時,請使用推薦版本以享受最新功能和修復。",
"actions": {
"do-not-remind": "不要再提醒我",
"ok": "確定"
}
}
},
"modals": {
+11 -1
View File
@@ -38,6 +38,7 @@
"desktop-description": "第一人称飞控模式允许你使用键盘 WASD 和鼠标在游戏中进行导航。你无需带上头显即可进行测试!",
"debug": "Debug 模式",
"debug-description": "为 IPA 启用输出日志窗口。 会显示所用 Mod 的 debug 输出",
"outdated-tippy": "此版本已过时,某些模组或功能可能无法按预期运行。建议使用推荐版本的 Beat Saber ({recommendedVersion}),以享受最新功能和修复。",
"advanced-launch": {
"button": "高级启动",
"placeholder": "额外启动参数,例如: --revert; --nowait"
@@ -107,7 +108,8 @@
"latest": "最新",
"description": "描述",
"dropdown": {
"uninstall-all": "全部卸载"
"uninstall-all": "全部卸载",
"unselect-all": "取消全选"
}
}
},
@@ -594,6 +596,14 @@
"error": {
"msg": "创建快捷方式时发生错误"
}
},
"bs-version-oudated": {
"title": "版本过时",
"msg": "此 Beat Saber 版本已过时,请使用推荐版本以享受最新功能和修复。",
"actions": {
"do-not-remind": "不再提醒",
"ok": "确定"
}
}
},
"modals": {
+19
View File
@@ -0,0 +1,19 @@
import type { Config } from "jest";
const config: Config = {
// testURL: "http://localhost/",
// testEnvironment: "jsdom",
transform: {
"\\.(ts|tsx|js|jsx)$": "ts-jest",
},
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/.erb/mocks/fileMock.js",
"\\.(css|less|sass|scss)$": "identity-obj-proxy",
},
moduleFileExtensions: ["js", "jsx", "ts", "tsx", "json"],
moduleDirectories: ["node_modules", "src"],
testPathIgnorePatterns: ["release/app/dist"],
setupFiles: ["./.erb/scripts/check-build-exists.ts"],
};
export default config;
+30 -19
View File
@@ -32,11 +32,9 @@
"got": "^14.4.4",
"history": "^5.3.0",
"is-elevated": "^4.0.0",
"jszip": "^3.10.1",
"md5-file": "^5.0.0",
"node-abi": "^3.65.0",
"node-fetch": "^3.3.2",
"node-stream-zip": "^1.15.0",
"pako": "^2.1.0",
"protobufjs": "^7.4.0",
"qrcode.react": "^4.0.1",
@@ -61,7 +59,8 @@
"tippy.js": "^6.3.7",
"to-ico": "^1.1.5",
"use-double-click": "^1.0.5",
"use-fit-text": "^2.4.0"
"use-fit-text": "^2.4.0",
"yauzl": "^3.2.0"
},
"devDependencies": {
"@electron/fuses": "^1.7.0",
@@ -8555,7 +8554,6 @@
},
"node_modules/buffer-crc32": {
"version": "0.2.13",
"dev": true,
"license": "MIT",
"engines": {
"node": "*"
@@ -12585,6 +12583,17 @@
"@types/yauzl": "^2.9.1"
}
},
"node_modules/extract-zip/node_modules/yauzl": {
"version": "2.10.0",
"resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",
"integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",
"dev": true,
"license": "MIT",
"dependencies": {
"buffer-crc32": "~0.2.3",
"fd-slicer": "~1.1.0"
}
},
"node_modules/fast-deep-equal": {
"version": "3.1.3",
"license": "MIT"
@@ -12662,6 +12671,8 @@
},
"node_modules/fd-slicer": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",
"integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -13884,6 +13895,7 @@
},
"node_modules/immediate": {
"version": "3.0.6",
"dev": true,
"license": "MIT"
},
"node_modules/immutable": {
@@ -15800,6 +15812,7 @@
},
"node_modules/jszip": {
"version": "3.10.1",
"dev": true,
"license": "(MIT OR GPL-3.0-or-later)",
"dependencies": {
"lie": "~3.3.0",
@@ -15810,10 +15823,12 @@
},
"node_modules/jszip/node_modules/pako": {
"version": "1.0.11",
"dev": true,
"license": "(MIT AND Zlib)"
},
"node_modules/jszip/node_modules/readable-stream": {
"version": "2.3.7",
"dev": true,
"license": "MIT",
"dependencies": {
"core-util-is": "~1.0.0",
@@ -15931,6 +15946,7 @@
},
"node_modules/lie": {
"version": "3.3.0",
"dev": true,
"license": "MIT",
"dependencies": {
"immediate": "~3.0.5"
@@ -17217,17 +17233,6 @@
"dev": true,
"license": "MIT"
},
"node_modules/node-stream-zip": {
"version": "1.15.0",
"license": "MIT",
"engines": {
"node": ">=0.12.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/antelle"
}
},
"node_modules/nopt": {
"version": "6.0.0",
"dev": true,
@@ -17801,7 +17806,8 @@
},
"node_modules/pend": {
"version": "1.2.0",
"dev": true,
"resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
"integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",
"license": "MIT"
},
"node_modules/performance-now": {
@@ -20033,6 +20039,7 @@
},
"node_modules/setimmediate": {
"version": "1.0.5",
"dev": true,
"license": "MIT"
},
"node_modules/setprototypeof": {
@@ -22655,12 +22662,16 @@
}
},
"node_modules/yauzl": {
"version": "2.10.0",
"dev": true,
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/yauzl/-/yauzl-3.2.0.tgz",
"integrity": "sha512-Ow9nuGZE+qp1u4JIPvg+uCiUr7xGQWdff7JQSk5VGYTAZMDe2q8lxJ10ygv10qmSj031Ty/6FNJpLO4o1Sgc+w==",
"license": "MIT",
"dependencies": {
"buffer-crc32": "~0.2.3",
"fd-slicer": "~1.1.0"
"pend": "~1.2.0"
},
"engines": {
"node": ">=12"
}
},
"node_modules/yn": {
+3 -31
View File
@@ -19,6 +19,7 @@
"start:preload": "cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true webpack --config ./.erb/configs/webpack.config.preload.dev.ts",
"start:renderer": "cross-env NODE_ENV=development TS_NODE_TRANSPILE_ONLY=true webpack serve --config ./.erb/configs/webpack.config.renderer.dev.ts",
"test": "jest",
"test:unit": "jest ./src/__tests__/unit",
"publish": "npm run build && electron-builder -c.win.certificateSha1=2164d6a7d641ecf6ad57852f665a518ca2bf960f --publish always --win --x64",
"publish:linux": "npm run build && electron-builder --publish always --linux --x64"
},
@@ -116,34 +117,6 @@
"beat-saber"
],
"homepage": "https://github.com/Zagrios/bs-manager#readme",
"jest": {
"testURL": "http://localhost/",
"testEnvironment": "jsdom",
"transform": {
"\\.(ts|tsx|js|jsx)$": "ts-jest"
},
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/.erb/mocks/fileMock.js",
"\\.(css|less|sass|scss)$": "identity-obj-proxy"
},
"moduleFileExtensions": [
"js",
"jsx",
"ts",
"tsx",
"json"
],
"moduleDirectories": [
"node_modules",
"src"
],
"testPathIgnorePatterns": [
"release/app/dist"
],
"setupFiles": [
"./.erb/scripts/check-build-exists.ts"
]
},
"devDependencies": {
"@electron/fuses": "^1.7.0",
"@electron/notarize": "^2.3.0",
@@ -252,11 +225,9 @@
"got": "^14.4.4",
"history": "^5.3.0",
"is-elevated": "^4.0.0",
"jszip": "^3.10.1",
"md5-file": "^5.0.0",
"node-abi": "^3.65.0",
"node-fetch": "^3.3.2",
"node-stream-zip": "^1.15.0",
"pako": "^2.1.0",
"protobufjs": "^7.4.0",
"qrcode.react": "^4.0.1",
@@ -281,7 +252,8 @@
"tippy.js": "^6.3.7",
"to-ico": "^1.1.5",
"use-double-click": "^1.0.5",
"use-fit-text": "^2.4.0"
"use-fit-text": "^2.4.0",
"yauzl": "^3.2.0"
},
"engines": {
"node": ">=20.0.0"
-9
View File
@@ -1,9 +0,0 @@
import "@testing-library/jest-dom";
import { render } from "@testing-library/react";
import App from "../renderer/windows/App";
describe("App", () => {
it("should render", () => {
expect(render(<App />)).toBeTruthy();
});
});
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+329
View File
@@ -0,0 +1,329 @@
import path from "path";
import { mkdir, pathExistsSync, readFile, rm } from "fs-extra";
import { BsmZipExtractor } from "main/models/bsm-zip-extractor.class";
const TEST_FOLDER = path.resolve(__dirname, "..", "assets", "zip");
const STANDARD_ZIP = path.join(TEST_FOLDER, "standard.zip");
const WINDOWS_LEGACY_MAP_ZIP = path.join(TEST_FOLDER, "windows_legacy.zip");
const SUBFOLDERS_ZIP = path.join(TEST_FOLDER, "subfolders.zip");
const MANIFEST_ZIP = path.join(TEST_FOLDER, "manifest.zip");
const EMPTY_ZIP = path.join(TEST_FOLDER, "empty.zip");
const UNICODE_ZIP = path.join(TEST_FOLDER, "unicode.zip");
const DESTINATION_FOLDER = path.join(TEST_FOLDER, "out");
describe("Test BsmZipExtractor class", () => {
let zip: BsmZipExtractor;
beforeAll(async () => {
if (pathExistsSync(DESTINATION_FOLDER)) {
await rm(DESTINATION_FOLDER, { recursive: true, force: true });
}
await mkdir(DESTINATION_FOLDER);
});
afterEach(async () => {
if (zip) {
zip.close();
}
if (pathExistsSync(DESTINATION_FOLDER)) {
await rm(DESTINATION_FOLDER, { recursive: true, force: true });
}
await mkdir(DESTINATION_FOLDER);
});
afterAll(async () => {
if (pathExistsSync(DESTINATION_FOLDER)) {
await rm(DESTINATION_FOLDER, { recursive: true, force: true });
}
});
it("Extract standard zip", async () => {
zip = await BsmZipExtractor.fromPath(STANDARD_ZIP);
const res = await zip.extract(DESTINATION_FOLDER);
expect(res.sort()).toEqual([
"file_1.2.txt",
"file_1.3.txt",
"folder_1.1/",
"folder_1.1/file_2.1.txt",
"folder_1.1/file_2.2.txt",
].sort())
for (const file of [
"file_1.2.txt",
"file_1.3.txt",
]) {
expect(pathExistsSync(path.join(DESTINATION_FOLDER, file)))
.toBe(true);
}
const SUBFOLDER_PATH = path.join(DESTINATION_FOLDER, "folder_1.1");
for (const file of [
"file_2.1.txt",
"file_2.2.txt",
]) {
expect(pathExistsSync(path.join(SUBFOLDER_PATH, file)))
.toBe(true);
}
});
it("Extract map zips using back slashes", async () => {
zip = await BsmZipExtractor.fromPath(WINDOWS_LEGACY_MAP_ZIP);
const res = await zip.extract(DESTINATION_FOLDER);
expect(res.sort()).toEqual([
"BPMInfo.dat",
"cover.jpg",
"ExpertLegacy.dat",
"ExpertPlusLawless.dat",
"ExpertPlusLegacy.dat",
"ExpertPlusStandard.dat",
"ExpertStandard.dat",
"Info.dat",
"song.egg",
"pfp/",
"pfp/galaxyCompressed.jpg",
"pfp/gojiCompressed.jpg",
].sort());
// Expect all the files to exists
for (const file of [
"BPMInfo.dat",
"cover.jpg",
"ExpertLegacy.dat",
"ExpertPlusLawless.dat",
"ExpertPlusLegacy.dat",
"ExpertPlusStandard.dat",
"ExpertStandard.dat",
"Info.dat",
"song.egg",
]) {
expect(pathExistsSync(path.join(DESTINATION_FOLDER, file)))
.toBe(true);
}
const SUBFOLDER_PATH = path.join(DESTINATION_FOLDER, "pfp");
for (const file of [
"galaxyCompressed.jpg",
"gojiCompressed.jpg",
]) {
expect(pathExistsSync(path.join(SUBFOLDER_PATH, file)))
.toBe(true);
}
});
it("Read Zip with multiple subfolders", async () => {
const zip = await BsmZipExtractor.fromPath(SUBFOLDERS_ZIP);
const res = await zip.extract(DESTINATION_FOLDER);
expect(res.sort()).toEqual([
"1/",
"1/2/",
"1/2/3/",
"1/2/3/4/",
"1/2/3/4/5.txt",
].sort());
for (const folder of [
"1/",
"1/2/",
"1/2/3/",
"1/2/3/4/",
]) {
expect(pathExistsSync(path.join(DESTINATION_FOLDER, folder)))
.toBe(true);
}
const file = "1/2/3/4/5.txt";
expect(pathExistsSync(path.join(DESTINATION_FOLDER, file)))
.toBe(true);
});
it("Read manifest.json from zip file", async () => {
const zipBuffer = await readFile(MANIFEST_ZIP);
zip = await BsmZipExtractor.fromBuffer(zipBuffer);
const buffer = await (await zip.findEntry(entry => entry.fileName === "manifest.json")).read();
const manifest = JSON.parse(buffer.toString());
expect(manifest).toBeTruthy();
// Check some of the fields if they are correct
expect(manifest.appId).toBe("some-app-id");
expect(manifest.canonicalName).toBe("some-canonical-name");
expect(manifest.isCore).toBe(true);
});
it("Should find an entry using findEntry", async () => {
zip = await BsmZipExtractor.fromPath(STANDARD_ZIP);
const entry = await zip.findEntry(entry => entry.fileName === "file_1.2.txt");
expect(entry).toBeTruthy();
expect(entry.fileName).toBe("file_1.2.txt");
const contentBuffer = await entry.read();
const content = contentBuffer.toString();
expect(content).toContain("This is file 1.2"); // Assurez-vous que le contenu correspond
});
it("Should filter entries using filterEntries", async () => {
zip = await BsmZipExtractor.fromPath(STANDARD_ZIP);
const entries = await zip.filterEntries(entry => !entry.isDirectory && entry.fileName.startsWith("folder_1.1/"));
expect(entries.length).toBe(2);
const fileNames = entries.map(entry => entry.fileName).sort();
expect(fileNames).toEqual([
"folder_1.1/file_2.1.txt",
"folder_1.1/file_2.2.txt",
]);
});
it("Should get an entry by file name using getEntry", async () => {
zip = await BsmZipExtractor.fromPath(STANDARD_ZIP);
const entry = await zip.getEntry("file_1.3.txt");
expect(entry).toBeTruthy();
expect(entry.fileName).toBe("file_1.3.txt");
const contentBuffer = await entry.read();
const content = contentBuffer.toString();
expect(content).toContain("This is file 1.3"); // Assurez-vous que le contenu correspond
});
it("Should extract only specified entries using entriesNames option", async () => {
zip = await BsmZipExtractor.fromPath(STANDARD_ZIP);
const res = await zip.extract(DESTINATION_FOLDER, { entriesNames: ["file_1.2.txt", "folder_1.1/file_2.1.txt"] });
expect(res.sort()).toEqual([
"file_1.2.txt",
"folder_1.1/",
"folder_1.1/file_2.1.txt",
].sort());
for (const file of [
"file_1.2.txt",
"folder_1.1/file_2.1.txt",
]) {
expect(pathExistsSync(path.join(DESTINATION_FOLDER, file)))
.toBe(true);
}
// Vérifiez que les autres fichiers ne sont pas extraits
expect(pathExistsSync(path.join(DESTINATION_FOLDER, "file_1.3.txt")))
.toBe(false);
expect(pathExistsSync(path.join(DESTINATION_FOLDER, "folder_1.1/file_2.2.txt")))
.toBe(false);
});
it("Should not extract any files if abortToken is already aborted", async () => {
zip = await BsmZipExtractor.fromPath(STANDARD_ZIP);
const abortController = new AbortController();
// Abortez avant d'appeler extract
abortController.abort();
const res = await zip.extract(DESTINATION_FOLDER, { abortToken: abortController });
expect(res.length).toBe(0);
// Vérifiez qu'aucun fichier n'a été extrait
expect(pathExistsSync(path.join(DESTINATION_FOLDER, "file_1.2.txt")))
.toBe(false);
});
it("Should throw an error when opening a non-existent zip file", async () => {
await expect(BsmZipExtractor.fromPath("non_existent.zip"))
.rejects
.toThrow();
});
it("Should handle empty zip file correctly", async () => {
zip = await BsmZipExtractor.fromPath(EMPTY_ZIP);
const entries = [];
for await (const entry of zip.entries()) {
entries.push(entry);
}
expect(entries.length).toBe(0);
const res = await zip.extract(DESTINATION_FOLDER);
expect(res.length).toBe(0);
});
it("Should return the same entries on multiple calls to entries()", async () => {
zip = await BsmZipExtractor.fromPath(STANDARD_ZIP);
const entries1 = [];
for await (const entry of zip.entries()) {
entries1.push(entry);
}
expect(entries1.length).toBe(5); // Basé sur le contenu de STANDARD_ZIP
const entries2 = [];
for await (const entry of zip.entries()) {
entries2.push(entry);
}
expect(entries2.length).toBe(5);
expect(entries2.map(e => e.fileName).sort()).toEqual(entries1.map(e => e.fileName).sort());
});
it("Should not be able to read entries after zip is closed", async () => {
zip = await BsmZipExtractor.fromPath(STANDARD_ZIP);
zip.close();
await expect(zip.entries().next()).rejects.toThrow();
});
it("Should handle zip file from buffer", async () => {
const zipBuffer = await readFile(STANDARD_ZIP);
zip = await BsmZipExtractor.fromBuffer(zipBuffer);
const entries = [];
for await (const entry of zip.entries()) {
entries.push(entry.fileName);
}
expect(entries.sort()).toEqual([
"file_1.2.txt",
"file_1.3.txt",
"folder_1.1/",
"folder_1.1/file_2.1.txt",
"folder_1.1/file_2.2.txt",
].sort());
});
it("Should read and extract files with Unicode filenames", async () => {
zip = await BsmZipExtractor.fromPath(UNICODE_ZIP);
const entries = [];
for await (const entry of zip.entries()) {
entries.push(entry);
}
expect(entries.map(e => e.fileName)).toContain("こんにちは.txt"); // "Bonjour" en japonais
const res = await zip.extract(DESTINATION_FOLDER);
expect(res).toContain("こんにちは.txt");
expect(pathExistsSync(path.join(DESTINATION_FOLDER, "こんにちは.txt")))
.toBe(true);
});
it("Should throw an error when reading a corrupted zip file", async () => {
const CORRUPTED_ZIP = path.join(TEST_FOLDER, "corrupted.zip");
await expect(BsmZipExtractor.fromPath(CORRUPTED_ZIP)).rejects.toThrow(/.*[Error: Invalid comment length].*/)
});
});
-28
View File
@@ -1,28 +0,0 @@
import JSZip from "jszip";
import { pathExist } from "./fs.helpers";
import path from "path";
import { mkdir, writeFile } from "fs/promises";
export async function extractZip(zip: JSZip, dest: string): Promise<string[]> {
if (!(await pathExist(dest))) {
throw new Error(`Path ${dest} does not exist`);
}
const files: string[] = [];
for (const [relativePath, entry] of Object.entries(zip.files)) {
if (entry.dir) {
continue;
}
const content = await entry.async("nodebuffer");
const outPath = path.join(dest, relativePath);
const outDir = path.dirname(outPath);
await mkdir(outDir, { recursive: true });
await writeFile(outPath, content);
files.push(outPath);
}
return files;
}
+218
View File
@@ -0,0 +1,218 @@
import { createWriteStream, ensureDir } from "fs-extra";
import path from "path";
import { Readable } from "stream";
import yauzl, { ZipFile, Options, Entry } from "yauzl"
export class BsmZipExtractor {
private static readonly YAUZL_OPEN_OPTIONS: Options = {
lazyEntries: true,
decodeStrings: true,
autoClose: false,
};
public static fromPath(path: string): Promise<BsmZipExtractor> {
return new Promise((resolve, reject) => {
yauzl.open(path, BsmZipExtractor.YAUZL_OPEN_OPTIONS, (error: Error, zip: yauzl.ZipFile) => {
if (error) return reject(error);
resolve(new BsmZipExtractor(zip));
});
});
}
public static fromBuffer(buffer: Buffer): Promise<BsmZipExtractor> {
return new Promise((resolve, reject) => {
yauzl.fromBuffer(buffer, BsmZipExtractor.YAUZL_OPEN_OPTIONS, (error: Error, zip: yauzl.ZipFile) => {
if (error) return reject(error);
resolve(new BsmZipExtractor(zip));
});
});
}
private readonly zip: ZipFile;
private readonly entriesMap = new Map<string, BsmZipExtractorEntry>();
private constructor(zip: ZipFile) {
this.zip = zip;
}
private async readEntry(): Promise<BsmZipExtractorEntry> {
return new Promise((resolve, reject) => {
const onEntry = (entry: Entry) => {
cleanup();
resolve(new BsmZipExtractorEntry({ entry, zip: this.zip }));
};
const onEnd = () => {
cleanup();
resolve(null);
};
const onError = (err: Error) => {
cleanup();
reject(err);
};
const cleanup = () => {
this.zip.removeListener("entry", onEntry);
this.zip.removeListener("end", onEnd);
this.zip.removeListener("error", onError);
};
this.zip.once("entry", onEntry);
this.zip.once("end", onEnd);
this.zip.once("error", onError);
this.zip.readEntry();
});
}
// The first time this method is called, it will read all the entries and store them in a map
// The next times it will return the entries from the map to avoid reopening the zip file again
public async *entries(): AsyncGenerator<BsmZipExtractorEntry> {
for (const entry of Array.from(this.entriesMap.values())) {
yield entry;
}
let entry: BsmZipExtractorEntry = await this.readEntry();
while (entry) {
this.entriesMap.set(entry.fileName, entry);
yield entry;
entry = await this.readEntry();
}
}
public async findEntry(func: (entry: BsmZipExtractorEntry) => boolean): Promise<BsmZipExtractorEntry|null> {
for await (const entry of this.entries()) {
if (func(entry)) {
return entry;
}
}
return null;
}
public async filterEntries(func: (entry: BsmZipExtractorEntry) => boolean): Promise<BsmZipExtractorEntry[]> {
const filtered: BsmZipExtractorEntry[] = [];
for await (const entry of this.entries()) {
if (func(entry)) {
filtered.push(entry);
}
}
return filtered;
}
public async getEntry(fileName: string): Promise<BsmZipExtractorEntry> {
return this.entriesMap.get(fileName) ?? this.findEntry(entry => entry.fileName === fileName);
}
/**
* Extracts all entries from the zip file to the destination folder
* @param destination
* @param opt - { entriesNames?: string[], abortToken: AbortController }
* @returns {Promise<string[]>} The list of extracted files (relative paths in the destination folder)
*
* `opt` object:
* - `entriesNames` - The list of entries to extract (can be regexs or glob pattern). If not provided, all entries will be extracted
* - `abortToken` - The AbortController instance to abort the extraction
*
*/
public async extract(destination: string, opt?: { entriesNames?: (string|RegExp)[], abortToken?: AbortController }): Promise<string[]> {
const entriesNames = opt?.entriesNames;
const abortToken = opt?.abortToken;
if (abortToken?.signal?.aborted) {
return [];
}
await ensureDir(destination);
const extracted = new Set<string>()
for await (const entry of this.entries()) {
if (abortToken?.signal?.aborted) {
break;
}
if (entriesNames && !entriesNames.some(name => typeof name === "string" ? entry.fileName === name : name.test(entry.fileName))){
continue;
}
const extractedFile = await entry.extract(destination);
const dirname = path.dirname(extractedFile);
// Make zip that use backslash as separator have the same behavior as zip that use forward slash
if(dirname !== "."){
const split = dirname.split(path.posix.sep);
for (let i = 1; i <= split.length; i++) {
const folder = split.slice(0, i).join(path.posix.sep);
extracted.add(folder + path.posix.sep);
}
}
extracted.add(extractedFile);
}
return Array.from(extracted);
}
public close(): void {
this.zip.close();
}
}
class BsmZipExtractorEntry {
private readonly entry: Entry;
private readonly zip: ZipFile;
constructor(opt: { entry: Entry, zip: ZipFile }) {
this.entry = opt.entry;
this.zip = opt.zip;
}
public async read(): Promise<Buffer> {
return new Promise((resolve, reject) => {
this.zip.openReadStream(this.entry, (error: Error, stream: Readable) => {
if (error) return reject(error);
const buffers: Buffer[] = [];
stream.on("data", (data) => buffers.push(data as Buffer));
stream.on("end", () => resolve(Buffer.concat(buffers)));
stream.on("error", reject);
});
});
}
public async extract(destination: string): Promise<string> {
const destPath = path.join(destination, this.entry.fileName);
if (this.isDirectory) {
return ensureDir(destPath).then(() => this.entry.fileName);
}
return new Promise((resolve, reject) => {
this.zip.openReadStream(this.entry, async (error: Error, stream: Readable) => {
if (error) return reject(error);
await ensureDir(path.dirname(destPath));
const writeStream = createWriteStream(destPath);
stream.pipe(writeStream);
writeStream.on("finish", () => resolve(this.entry.fileName));
writeStream.on("error", reject);
});
});
}
public get isDirectory(): boolean {
return this.entry.fileName.endsWith("/");
}
public get fileName(): string {
return this.entry.fileName;
}
}
+27 -14
View File
@@ -1,4 +1,3 @@
import JSZip from "jszip";
import fetch from "node-fetch";
import { CustomError } from "../../shared/models/exceptions/custom-error.class";
import { mkdirs, createWriteStream, pathExists, WriteStream } from "fs-extra";
@@ -7,6 +6,8 @@ import { inflate } from "pako"
import { EMPTY, Observable, ReplaySubject, Subscriber, catchError, filter, from, lastValueFrom, mergeMap, scan, share, tap } from "rxjs";
import { Progression, hashFile } from "../helpers/fs.helpers";
import { OculusDownloaderErrorCodes } from "../../shared/models/bs-version-download/oculus-download.model";
import { BsmZipExtractor } from "./bsm-zip-extractor.class";
import { tryit } from "shared/helpers/error.helpers";
export class OculusDownloader {
@@ -23,26 +24,38 @@ export class OculusDownloader {
return `https://securecdn.oculus.com/binaries/segment/?access_token=${token}&binary_id=${binaryId}&segment_sha256=${segmentSha256}`;
}
private async downloadManifestZip(manifestUrl: string): Promise<JSZip> {
private async downloadManifestZip(manifestUrl: string): Promise<Buffer> {
const response = await fetch(manifestUrl);
const arrBuffer = await response.arrayBuffer();
return JSZip.loadAsync(arrBuffer);
return Buffer.from(arrBuffer);
}
private async getManifest(): Promise<OculusManifest> {
const downloadUrl = this.getDownloadManifestUrl(this.options.accessToken, this.options.binaryId);
const manifestZip = await this.downloadManifestZip(downloadUrl).catch(err => CustomError.throw(err, "DOWNLOAD_MANIFEST_FAILED"));
const manifestFile = manifestZip.file("manifest.json");
const buffer = await this.downloadManifestZip(downloadUrl)
.catch(err => CustomError.throw(err, "DOWNLOAD_MANIFEST_FAILED"));
if(!manifestFile){
const zip = await BsmZipExtractor.fromBuffer(buffer);
const entry = await zip.getEntry("manifest.json");
if(!entry) {
throw new CustomError("Manifest file not found", "MANIFEST_FILE_NOT_FOUND");
}
return manifestFile.async("text").then(JSON.parse).catch(err => CustomError.throw(err, "PARSE_MANIFEST_FILE_FAILED"));
const manifest = await entry.read();
zip.close();
const { result, error } = tryit(() => JSON.parse(manifest.toString()) as OculusManifest);
if(error){
throw CustomError.throw(error, "PARSE_MANIFEST_FILE_FAILED")
}
return result;
}
private downloadManifestFile(file: OculusManifestFile, destination: string): Observable<Progression<OculusManifestFile>> {
const downloadSegment = async (segment: OculusManifestFileSegment): Promise<ArrayBuffer> => {
const segmentUrl = this.getDownloadSegmentUrl(this.options.accessToken, this.options.binaryId, segment[1]);
const response = await fetch(segmentUrl);
@@ -66,11 +79,11 @@ export class OculusDownloader {
const arrBuffer = await downloadSegment(segment);
const inflated = inflate(arrBuffer);
await writeStream.write(inflated);
writeStream.write(inflated);
progress.current += inflated.byteLength;
progress.diff = inflated.byteLength;
sub.next(progress);
}
@@ -86,7 +99,7 @@ export class OculusDownloader {
});
}
private isFileIntegrityValid(file: OculusFileWithName, folder: string): Promise<boolean> {
private async isFileIntegrityValid(file: OculusFileWithName, folder: string): Promise<boolean> {
const [fileName, fileData] = file;
const destination = path.join(folder, fileName);
@@ -138,7 +151,7 @@ export class OculusDownloader {
if(this.isDownloading){
throw new CustomError("Already downloading", "ALREADY_DOWNLOADING");
}
this.options = options;
this.isDownloading = true;
@@ -182,7 +195,7 @@ export class OculusDownloader {
})));
const integrity = await lastValueFrom(this.verifyIntegrity(manifest, options.destination)).catch(err => CustomError.throw(err, "VERIFY_INTEGRITY_FAILED"));
if(integrity.data.length > 0){
throw new CustomError("Some files failed to download", "SOME_FILES_FAILED_TO_DOWNLOAD", integrity.data);
}
@@ -242,4 +255,4 @@ interface Logger {
info: (...args: unknown[]) => void;
warn: (...args: unknown[]) => void;
error: (...args: unknown[]) => void;
}
}
@@ -8,7 +8,6 @@ import { UtilsService } from "../../utils.service";
import crypto, { BinaryLike } from "crypto";
import { lstatSync } from "fs";
import { copy, createReadStream, ensureDir, pathExists, pathExistsSync, realpath, unlink } from "fs-extra";
import StreamZip from "node-stream-zip";
import { RequestService } from "../../request.service";
import sanitize from "sanitize-filename";
import { DeepLinkService } from "../../deep-link.service";
@@ -30,6 +29,8 @@ import { MapInfo } from "shared/models/maps/info/map-info.model";
import { parseMapInfoDat } from "shared/parsers/maps/map-info.parser";
import { CustomError } from "shared/models/exceptions/custom-error.class";
import { tryit } from "shared/helpers/error.helpers";
import { BsmZipExtractor } from "main/models/bsm-zip-extractor.class";
import { escapeRegExp } from "../../../../shared/helpers/string.helpers";
export class LocalMapsManagerService {
private static instance: LocalMapsManagerService;
@@ -169,17 +170,13 @@ export class LocalMapsManagerService {
return getUrlsAndReturn(mapInfo, hash, mapPath);
}
private async downloadMapZip(zipUrl: string): Promise<{ zip: StreamZip.StreamZipAsync; zipPath: string }> {
private async downloadMapZip(zipUrl: string): Promise<string> {
const fileName = `${path.basename(zipUrl, ".zip")}-${crypto.randomUUID()}.zip`;
const tempPath = this.utils.getTempPath();
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 });
return { zip, zipPath };
return (await lastValueFrom(this.reqService.downloadFile(zipUrl, dest))).data;
}
public getMaps(version?: BSVersion): Observable<BsmLocalMapsProgress> {
@@ -328,16 +325,16 @@ export class LocalMapsManagerService {
public importMaps(zipPaths: string[], version?: BSVersion): Observable<Progression<BsmLocalMap>> {
return new Observable<Progression<BsmLocalMap>>(obs => {
let unsubscribed = false;
let progress: Progression<BsmLocalMap> = { total: 0, current: 0 };
let nbImportedMaps = 0;
const abortController = new AbortController();
let zip: BsmZipExtractor;
(async () => {
const mapsPath = await this.getMapsFolderPath(version);
for(const zipPath of zipPaths) {
if(unsubscribed) {
log.info("Maps importation from zip has been cancelled");
if(abortController.signal?.aborted) {
log.info("Maps import from zip has been cancelled");
return;
}
@@ -346,75 +343,62 @@ export class LocalMapsManagerService {
if(!pathExistsSync(zipPath)) { continue; }
const zip = new StreamZip.async({ file: zipPath });
const { result: zipEntries, error } = await tryit(() => zip.entries());
zip = await BsmZipExtractor.fromPath(zipPath);
const mapsFolders = (await zip.filterEntries(entry => /(^|\/)[Ii]nfo\.dat$/.test(entry.fileName)))
.map(entry => path.dirname(entry.fileName));
if(error) {
const res = await tryit(() => zip.close());
log.error("Could not read zip entries", zipPath, error, res?.error);
continue;
}
const zipEntriesValues = Object.values(zipEntries);
const mapsFolders = zipEntriesValues.reduce((acc, entry) => {
if(!/(^|\/)[Ii]nfo\.dat$/.test(entry.name)){ return acc; }
acc.push(path.dirname(entry.name));
return acc;
}, []);
if(mapsFolders.length === 0) {
if (mapsFolders.length === 0) {
log.warn("No maps \"info.dat\" found in zip", zipPath);
progress.total = 1;
progress.current = 1;
obs.next(progress);
continue;
}
progress.total = mapsFolders.length;
obs.next(progress);
for(const folder of mapsFolders) {
const isRoot = mapsFolders.length === 1 && mapsFolders[0] === ".";
const destination = isRoot
? path.join(mapsPath, path.basename(zipPath, ".zip"))
: mapsPath;
if(unsubscribed) {
log.info("Maps importation from zip has been cancelled");
await zip.close();
return;
}
log.info("Extracting", `"${zipPath}"`, "into", `"${mapsPath}"`);
for (const folder of mapsFolders) {
log.info(">", folder);
const isRoot = folder === ".";
const dest = isRoot ? path.join(mapsPath, path.basename(zipPath, ".zip")) : path.join(mapsPath, folder);
const regex = new RegExp(`^${escapeRegExp(folder)}\\/`);
let extract: () => Promise<BsmLocalMap>;
const exported = await zip.extract(destination, {
entriesNames: [regex],
abortToken: abortController
});
if(isRoot){
const entries = zipEntriesValues.filter(entry => entry.isFile && path.dirname(entry.name) === ".");
extract = async () => {
await Promise.all(entries.map(entry => {
log.info("Extracting", `"${entry.name}"`, "from", `"${zipPath}"`, "into", `"${path.join(dest, path.basename(entry.name))}"`);
return zip.extract(entry.name, path.join(dest, path.basename(entry.name)));
}));
return this.loadMapInfoFromPath(dest);
};
} else {
extract = async () => {
log.info("Extracting", `"${folder}"`, "from", `"${zipPath}"`, "into", `"${mapsPath}"`);
await zip.extract(folder, dest);
return this.loadMapInfoFromPath(dest);
}
}
await ensureDir(dest);
const { result: bsmMap, error } = await tryit(extract);
if(error) {
log.error("Could not extract map", zipPath, folder, mapsPath, error);
if(exported.length === 0) {
log.warn("No files extracted from", folder);
continue;
}
nbImportedMaps++;
progress.current++;
progress.data = bsmMap;
if (abortController.signal?.aborted) {
break;
}
++nbImportedMaps;
++progress.current;
progress.data = await this.loadMapInfoFromPath(path.join(destination, folder));
obs.next(progress);
if (abortController.signal?.aborted) {
break;
}
}
await zip.close();
zip.close();
if (abortController.signal?.aborted) {
log.info("Maps import from zip has been cancelled");
return;
}
}
})()
.then(() => {
@@ -424,10 +408,15 @@ export class LocalMapsManagerService {
return log.info("Successfully imported", nbImportedMaps, "maps from", zipPaths.length, "zips");
})
.catch(e => obs.error(e))
.finally(() => obs.complete());
.finally(() => {
if (zip) {
zip.close();
}
obs.complete()
});
return () => {
unsubscribed = true;
abortController.abort();
};
});
}
@@ -454,16 +443,10 @@ export class LocalMapsManagerService {
return installedMap;
}
const { zip, zipPath } = await this.downloadMapZip(zipUrl);
if (!zip) {
throw new Error(`Cannot download ${zipUrl}`);
}
await ensureFolderExist(mapPath);
await zip.extract(null, mapPath);
await zip.close();
const zipPath = await this.downloadMapZip(zipUrl);
const zip = await BsmZipExtractor.fromPath(zipPath);
await zip.extract(mapPath);
zip.close();
await unlink(zipPath);
const localMap = await this.loadMapInfoFromPath(mapPath);
@@ -14,8 +14,11 @@ export abstract class AbstractLauncherService {
}
protected buildBsLaunchArgs(launchOptions: LaunchOption): string[]{
const launchArgs = ["--no-yeet"];
const launchArgs = [];
if(!launchOptions.version.steam && !launchOptions.version.oculus){
launchArgs.push("--no-yeet")
}
if (launchOptions.oculus) {
launchArgs.push("-vrmode");
launchArgs.push("oculus");
@@ -10,15 +10,16 @@ import { BS_EXECUTABLE } from "../../constants";
import log from "electron-log";
import { deleteFolder, pathExist, Progression, unlinkPath } from "../../helpers/fs.helpers";
import { lastValueFrom, Observable } from "rxjs";
import JSZip from "jszip";
import { extractZip } from "../../helpers/zip.helpers";
import recursiveReadDir from "recursive-readdir";
import { sToMs } from "../../../shared/helpers/time.helpers";
import { ensureDir, pathExistsSync } from "fs-extra";
import { pathExistsSync } from "fs-extra";
import { CustomError } from "shared/models/exceptions/custom-error.class";
import { popElement } from "shared/helpers/array.helpers";
import { LinuxService } from "../linux.service";
import { tryit } from "shared/helpers/error.helpers";
import { UtilsService } from "../utils.service";
import crypto from "crypto";
import { BsmZipExtractor } from "main/models/bsm-zip-extractor.class";
export class BsModsManagerService {
private static instance: BsModsManagerService;
@@ -27,6 +28,7 @@ export class BsModsManagerService {
private readonly bsLocalService: BSLocalVersionService;
private readonly linuxService: LinuxService;
private readonly requestService: RequestService;
private readonly utilsService: UtilsService;
private manifestMatches: Mod[];
@@ -42,6 +44,7 @@ export class BsModsManagerService {
this.bsLocalService = BSLocalVersionService.getInstance();
this.linuxService = LinuxService.getInstance();
this.requestService = RequestService.getInstance();
this.utilsService = UtilsService.getInstance();
}
private async getModFromHash(hash: string): Promise<Mod> {
@@ -110,7 +113,7 @@ export class BsModsManagerService {
return this.beatModsApi.getModByHash(injectorMd5);
}
private async downloadZip(zipUrl: string): Promise<JSZip> {
private async downloadZip(zipUrl: string): Promise<BsmZipExtractor> {
zipUrl = path.join(this.beatModsApi.BEAT_MODS_URL, zipUrl);
log.info("Download mod zip", zipUrl);
@@ -126,10 +129,7 @@ export class BsModsManagerService {
return null;
}
return JSZip.loadAsync(buffer).catch(e => {
log.error("ZIP", "Error while loading zip", e);
return null;
});
return BsmZipExtractor.fromBuffer(buffer);
}
private async executeBSIPA(version: BSVersion, args: string[]): Promise<boolean> {
@@ -201,43 +201,38 @@ export class BsModsManagerService {
log.info("Start download mod zip", mod.name, download.url);
const zip = await this.downloadZip(download.url);
log.info("Mod zip download end", mod.name, download.url, !!zip);
log.info("Mod zip download end", mod.name, download.url);
if (!zip) {
return false;
}
const crypto = require("crypto");
const { files } = zip;
let hashCount = 0;
for await (const entry of zip.entries()) {
const buffer = await entry.read();
const md5Hash = crypto.createHash("md5")
.update(buffer)
.digest("hex");
hashCount += +download.hashMd5.some(md5 => md5.hash === md5Hash);
}
const checkedEntries = (
await Promise.all(
Object.values(files).map(async entry => {
const data = await entry.async("nodebuffer");
const entryMd5 = crypto.createHash("md5").update(data).digest("hex");
return download.hashMd5.some(md5 => md5.hash === entryMd5) ? entry : undefined;
})
).catch(e => {
log.error("Error while checking mod zip entries", mod.name, e);
throw e;
})
).filter(entry => !!entry);
if (checkedEntries.length !== download.hashMd5.length) {
if (hashCount !== download.hashMd5.length) {
return false;
}
const verionPath = await this.bsLocalService.getVersionPath(version);
const versionPath = await this.bsLocalService.getVersionPath(version);
const isBSIPA = mod.name.toLowerCase() === "bsipa";
const destDir = isBSIPA ? verionPath : path.join(verionPath, ModsInstallFolder.PENDING);
const destDir = isBSIPA ? versionPath : path.join(versionPath, ModsInstallFolder.PENDING);
await ensureDir(destDir);
log.info("Start extracting mod zip", mod.name, "to", destDir);
const extracted = await extractZip(zip, destDir)
const extracted = await zip.extract(destDir)
.then(() => true)
.catch(e => {
log.error("Error while extracting mod zip", e);
return false;
})
.finally(() => {
zip.close();
});
log.info("Mod zip extraction end", mod.name, "to", destDir, "success:", extracted);
@@ -15,7 +15,7 @@ export class BeatSaverApiService {
private readonly request: RequestService;
private readonly bsaverApiUrl = "https://beatsaver.com/api";
private readonly bsaverApiUrl = "https://api.beatsaver.com";
private constructor() {
this.request = RequestService.getInstance();
@@ -18,7 +18,7 @@ export const BSVersionOutdatedModal: ModalComponent<void, { outdated: BSVersion,
const handleContinue = () => {
if (remember) {
config.set("not-show-bs-version-outdated", true);
config.set("not-show-bs-version-outdated-modal", true);
}
resolver({ exitCode: ModalExitCode.COMPLETED });
@@ -35,7 +35,7 @@ export function SupportersView({ isVisible, setVisible }: Props) {
(
{isVisible && (
<motion.div className="fixed top-0 left-0 w-full h-full bg-black bg-opacity-90 z-40 text-gray-200" transition={{ duration: 0.3 }} initial={{ opacity: 0, y: "-100%" }} animate={{ opacity: 1, y: "0%" }} exit={{ opacity: 0, y: "-100%" }}>
<BsmButton className="absolute right-10 top-10 !bg-transparent w-7 h-7" icon="cross" withBar={false} onClick={() => setVisible(false)} />
<BsmButton className="absolute right-10 top-10 !bg-transparent w-7 h-7" iconClassName="text-white size-full" icon="cross" withBar={false} onClick={() => setVisible(false)} />
{(!!sponsors.length || !!supporters.length) && <img className="absolute bottom-5 right-5 rotate-45 w-32 h-32" src={ManheraChanGif} />}
<div className="w-full h-full overflow-y-scroll">
{!!sponsors.length && <SupportersBlock className="mt-12" title="pages.settings.patreon.view.sponsors" supporters={sponsors} />}
@@ -65,11 +65,15 @@ import { SongDetailDiffCharactertistic } from "shared/models/maps/song-details-c
import { CleanIcon } from "./icons/clean-icon.component";
import { BrowseIcon } from "./icons/browse-icon.component";
import { AddFileIcon } from "./icons/add-file-icon.component";
import { CancelIcon } from "./icons/cancel-icon.component";
import { WarningIcon } from "./icons/warning-icon.component";
export type BsmIconType = SongDetailDiffCharactertistic | ("settings" | "trash" | "favorite" | "folder" | "bsNote" | "check" | "three-dots" | "twitch" | "eye" | "play" | "checkCircleIcon" | "discord" | "info" | "eye-cross" | "terminal" | "desktop" | "oculus" | "add" | "cross" | "task" | "github" | "close" | "thumbUpFill" | "timerFill" | "pause" | "twitter" | "sync" | "chevron-top" | "copy" | "steam" | "edit" | "export" | "patreon" | "search" | "bsMapDifficulty" | "link" | "unlink" | "download" | "filter" | "mee6" | "volume-up" | "volume-off" | "volume-down" | "shortcut" | "backup-restore" | "web-site" | "clean" | "browse" | "add-file" | "fr-FR-flag" | "es-ES-flag" | "en-US-flag" | "en-EN-flag" | "de-DE-flag" | "ru-RU-flag" | "zh-CN-flag" | "zh-TW-flag" | "ja-JP-flag" | "ko-KR-flag" | "null" );
export const BsmIcon = memo(({ className, icon, style }: { className?: string; icon: BsmIconType; style?: CSSProperties }) => {
export type BsmIconType = SongDetailDiffCharactertistic | ("settings" | "trash" | "favorite" | "folder" | "bsNote" | "check" | "three-dots" | "twitch" | "eye" | "play" | "checkCircleIcon" | "discord" | "info" | "eye-cross" | "terminal" | "desktop" | "oculus" | "add" | "cross" | "task" | "github" | "close" | "thumbUpFill" | "timerFill" | "pause" | "twitter" | "sync" | "chevron-top" | "copy" | "steam" | "edit" | "export" | "patreon" | "search" | "bsMapDifficulty" | "link" | "unlink" | "download" | "filter" | "mee6" | "volume-up" | "volume-off" | "volume-down" | "shortcut" | "backup-restore" | "web-site" | "clean" | "browse" | "add-file" | "cancel" | "warning" | "fr-FR-flag" | "es-ES-flag" | "en-US-flag" | "en-EN-flag" | "de-DE-flag" | "ru-RU-flag" | "zh-CN-flag" | "zh-TW-flag" | "ja-JP-flag" | "ko-KR-flag" | "null" );
export const BsmIcon = memo(({ className, icon, style }: { className?: string; icon: BsmIconType; style?: CSSProperties }) => {
// TODO : Very ugly very messy, need to find a better way to do this
// the rework have started, see `svg-icon.type.ts`
@@ -251,33 +255,34 @@ export const BsmIcon = memo(({ className, icon, style }: { className?: string; i
if (icon === "eye-cross") {
return <EyeCrossIcon className={className} style={style} />;
}
if (icon === "shortcut") {
return <ShortcutIcon className={className} style={style} />;
}
if (icon === "backup-restore") {
return <BackupRestoreIcon className={className} style={style} />;
}
if(icon === "web-site") {
return <WebSiteIcon className={className} style={style} />;
}
if(icon === "clean") {
return <CleanIcon className={className} style={style} />;
}
if (icon === "browse") {
return <BrowseIcon className={className} style={style} />;
}
if(icon === "add-file") {
return <AddFileIcon className={className} style={style} />;
}
if(icon === "cancel") {
return <CancelIcon className={className} style={style} />;
}
if(icon === "warning") {
return <WarningIcon className={className} style={style} />;
}
if(icon === "null") {
return null;
}
}
return <TrashIcon className={className} style={style} />;
@@ -0,0 +1,9 @@
import { createSvgIcon } from "../svg-icon.type";
export const CancelIcon = createSvgIcon((props, ref) => {
return (
<svg ref={ref} {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" fill="currentColor">
<path d="M480-421.37 592.17-309.2q11.72 11.72 29.32 11.6 17.6-.12 29.31-11.83 11.72-11.72 11.72-29.32t-11.72-29.32L538.63-480 650.8-592.17q11.72-11.72 11.72-29.32T650.8-650.8q-11.71-11.72-29.31-11.72-17.6 0-29.32 11.72L480-538.63 367.83-650.8q-11.72-11.72-29.2-11.72-17.48 0-29.2 11.72-11.71 11.71-11.71 29.31 0 17.6 11.71 29.32L421.37-480 309.2-367.83q-11.72 11.72-11.6 29.2.12 17.48 11.83 29.2 11.72 11.71 29.32 11.71t29.32-11.71L480-421.37Zm0 349.5q-84.91 0-159.35-32.1-74.43-32.1-129.51-87.17-55.07-55.08-87.17-129.51-32.1-74.44-32.1-159.35t32.1-159.35q32.1-74.43 87.17-129.51 55.08-55.07 129.51-87.17 74.44-32.1 159.35-32.1t159.35 32.1q74.43 32.1 129.51 87.17 55.07 55.08 87.17 129.51 32.1 74.44 32.1 159.35t-32.1 159.35q-32.1 74.43-87.17 129.51-55.08 55.07-129.51 87.17-74.44 32.1-159.35 32.1Zm0-91q133.04 0 225.09-92.04 92.04-92.05 92.04-225.09 0-133.04-92.04-225.09-92.05-92.04-225.09-92.04-133.04 0-225.09 92.04-92.04 92.05-92.04 225.09 0 133.04 92.04 225.09 92.05 92.04 225.09 92.04ZM480-480Z"/>
</svg>
)
})
@@ -0,0 +1,9 @@
import { createSvgIcon } from "../svg-icon.type";
export const WarningIcon = createSvgIcon((props, ref) => {
return (
<svg ref={ref} {...props} xmlns="http://www.w3.org/2000/svg" viewBox="0 -960 960 960" fill="currentColor">
<path d="M80-78q-15 0-27-8t-19-19q-7-11-7.5-25t7.5-28l400-689q8-14 20-20t26-6q14 0 26 6t20 20l400 689q8 14 7.5 28t-7.5 25q-7 11-19 19t-27 8H80Zm401-135q22 0 37.5-15.5T534-266q0-22-15.5-37.5T481-319q-22 0-37.5 15.5T428-266q0 22 15.5 37.5T481-213Zm0-143q22 0 37.5-15.5T534-409v-98q0-22-15.5-37.5T481-560q-22 0-37.5 15.5T428-507v98q0 22 15.5 37.5T481-356Z"/>
</svg>
);
})
@@ -1,7 +1,7 @@
import { ChangeEvent, useEffect, useState } from "react";
import { ChangeEvent, useEffect, useMemo, useState } from "react";
import { BsmButton } from "renderer/components/shared/bsm-button.component";
import { useObservable } from "renderer/hooks/use-observable.hook";
import { useTranslation } from "renderer/hooks/use-translation.hook";
import { useTranslationV2 } from "renderer/hooks/use-translation.hook";
import { BSLauncherService, LaunchMods } from "renderer/services/bs-launcher.service";
import { ConfigurationService } from "renderer/services/configuration.service";
import { BSVersion } from "shared/bs-version.interface";
@@ -15,15 +15,20 @@ import { BsDownloaderService } from "renderer/services/bs-version-download/bs-do
import equal from "fast-deep-equal";
import { GlowEffect } from "renderer/components/shared/glow-effect.component";
import { cn } from "renderer/helpers/css-class.helpers";
import { BSVersionManagerService } from "renderer/services/bs-version-manager.service";
import { safeLt } from "shared/helpers/semver.helpers";
import { WarningIcon } from "renderer/components/svgs/icons/warning-icon.component";
import Tippy from "@tippyjs/react";
type Props = { version: BSVersion };
export function LaunchSlide({ version }: Props) {
const t = useTranslation();
const { text: t, element: te } = useTranslationV2();
const configService = useService(ConfigurationService);
const bsLauncherService = useService(BSLauncherService);
const bsDownloader = useService(BsDownloaderService);
const versions = useService(BSVersionManagerService);
const [oculusMode, setOculusMode] = useState(!!configService.get<boolean>(LaunchMods.OCULUS_MOD));
const [desktopMode, setDesktopMode] = useState(!!configService.get<boolean>(LaunchMods.DESKTOP_MOD));
@@ -75,11 +80,24 @@ export function LaunchSlide({ version }: Props) {
return lastValueFrom(launch$).catch(() => {});
};
const isOutdated = useMemo(() => {
return safeLt(version?.BSVersion, versions.getRecommendedVersion()?.BSVersion);
}, [version]);
return (
<div className="w-full shrink-0 items-center relative flex flex-col justify-start">
<div className="flex flex-col gap-3 justify-center items-center mb-5">
<BsmImage className="relative object-cover h-28" image={BSLogo} />
<h1 className="relative text-4xl font-bold italic -top-3">{version.name ? `${version.BSVersion} - ${version.name}` : version.BSVersion}</h1>
<h1 className="relative text-4xl font-bold italic -top-3">
{version.name ? `${version.BSVersion} - ${version.name}` : version.BSVersion}
{isOutdated && (
<Tippy theme="default" content={te("pages.version-viewer.launch-mods.outdated-tippy", { recommendedVersion: <b>{versions.getRecommendedVersion().BSVersion}</b> })}>
<span className="absolute bg-theme-1 size-7 rounded-full p-1.5 flex justify-center items-center -right-2 top-2 translate-x-full translate-y-px cursor-help">
<WarningIcon className="text-warning-400 animate-pulse"/>
</span>
</Tippy>
)}
</h1>
</div>
<div className="grid grid-flow-col gap-6">
{!(version.oculus || version.metadata?.store === BsStore.OCULUS) && <LaunchModToogle infoText="pages.version-viewer.launch-mods.oculus-description" icon="oculus" onClick={() => setMode(LaunchMods.OCULUS_MOD, !oculusMode)} active={oculusMode} text="pages.version-viewer.launch-mods.oculus" />}
@@ -118,3 +136,5 @@ export function LaunchSlide({ version }: Props) {
</div>
);
}
@@ -16,9 +16,10 @@ type Props = {
disabled?: boolean;
uninstallMod?: (mods: Mod) => void;
uninstallAllMods?: () => void;
unselectAllMods?: () => void;
};
export function ModsGrid({ modsMap, installed, modsSelected, onModChange, moreInfoMod, onWantInfos, disabled, uninstallMod, uninstallAllMods }: Props) {
export function ModsGrid({ modsMap, installed, modsSelected, onModChange, moreInfoMod, onWantInfos, disabled, uninstallMod, uninstallAllMods, unselectAllMods }: Props) {
const [filter, setFilter] = useState("");
const [filterEnabled, setFilterEnabled] = useState(false);
@@ -66,7 +67,10 @@ export function ModsGrid({ modsMap, installed, modsSelected, onModChange, moreIn
<span className="z-10 sticky flex items-center justify-center top-0 bg-inherit border-b-2 border-main-color-1 h-8 px-2 whitespace-nowrap">{t("pages.version-viewer.mods.mods-grid.header-bar.latest")}</span>
<span className="z-10 sticky flex items-center justify-center top-0 bg-inherit border-b-2 border-main-color-1 h-8 whitespace-nowrap">{t("pages.version-viewer.mods.mods-grid.header-bar.description")}</span>
<span className="z-10 sticky top-0 bg-inherit border-b-2 border-main-color-1 h-8 flex justify-start items-center py-1 pl-[3px] min-w-[50px]">
<BsmDropdownButton className="h-full aspect-square relative rounded-full bg-light-main-color-1 dark:bg-main-color-3" withBar={false} icon="three-dots" buttonClassName="!rounded-full !p-[2px] !bg-light-main-color-2 dark:!bg-main-color-2 hover:!bg-light-main-color-1 dark:hover:!bg-main-color-3" menuTranslationY="5px" items={[{ text: "pages.version-viewer.mods.mods-grid.header-bar.dropdown.uninstall-all", icon: "trash", onClick: () => uninstallAllMods?.() }]} />
<BsmDropdownButton className="h-full aspect-square relative rounded-full bg-light-main-color-1 dark:bg-main-color-3" withBar={false} icon="three-dots" buttonClassName="!rounded-full !p-[2px] !bg-light-main-color-2 dark:!bg-main-color-2 hover:!bg-light-main-color-1 dark:hover:!bg-main-color-3" menuTranslationY="5px" items={[
{ text: "pages.version-viewer.mods.mods-grid.header-bar.dropdown.unselect-all", icon: "cancel", onClick: () => unselectAllMods?.() },
{ text: "pages.version-viewer.mods.mods-grid.header-bar.dropdown.uninstall-all", icon: "trash", onClick: () => uninstallAllMods?.() }
]} />
</span>
{Array.from(modsMap.keys()).map(
@@ -133,6 +133,10 @@ export function ModsSlide({ version, onDisclamerDecline }: { version: BSVersion;
})
};
const unselectAllMods = () => {
setModsSelected(() => []);
}
const loadMods = (): Promise<void> => {
if (os.isOffline) {
return Promise.resolve();
@@ -209,7 +213,18 @@ export function ModsSlide({ version, onDisclamerDecline }: { version: BSVersion;
return (
<>
<div className="grow overflow-y-scroll w-full min-h-0 scrollbar-default p-0 m-0">
<ModsGrid modsMap={modsAvailable} installed={modsInstalled} modsSelected={modsSelected} onModChange={handleModChange} moreInfoMod={moreInfoMod} onWantInfos={handleMoreInfo} disabled={uninstalling || installing} uninstallMod={uninstallMod} uninstallAllMods={uninstallAllMods}/>
<ModsGrid
modsMap={modsAvailable}
installed={modsInstalled}
modsSelected={modsSelected}
onModChange={handleModChange}
moreInfoMod={moreInfoMod}
onWantInfos={handleMoreInfo}
disabled={uninstalling || installing}
uninstallMod={uninstallMod}
uninstallAllMods={uninstallAllMods}
unselectAllMods={unselectAllMods}
/>
</div>
<div className="shrink-0 flex items-center justify-between px-3 py-2">
<BsmButton className="flex items-center justify-center rounded-md px-1 h-8" text="pages.version-viewer.mods.buttons.more-infos" typeColor="cancel" withBar={false} disabled={!moreInfoMod} onClick={handleOpenMoreInfo} style={{ width: downloadWith }}/>
@@ -30,7 +30,7 @@ export const defaultConfiguration: {
window.electron.path.join("Beat Saber_Data", "CustomWIPLevels"),
],
"playlist-sort-order": BsvSearchOrder.Relevance,
"map-sort-order": BsvSearchOrder.Latest,
"map-sort-order": BsvSearchOrder.Relevance,
};
export type ThemeConfig = "dark" | "light" | "os";
@@ -15,8 +15,7 @@ import { logRenderError } from "renderer";
import { ModalExitCode, ModalService } from "renderer/services/modale.service";
import { BSVersionOutdatedModal } from "renderer/components/modal/modal-types/bs-version-outdated-modal.component";
import { ConfigurationService } from "renderer/services/configuration.service";
import { coerce, lt, valid } from "semver";
import { tryit } from "shared/helpers/error.helpers";
import { safeLt } from "shared/helpers/semver.helpers";
export const AvailableVersionsContext = createContext<{ selectedVersion: BSVersion; setSelectedVersion: (version: BSVersion) => void }>(null);
@@ -34,12 +33,10 @@ export function AvailableVersionsList() {
const t = useTranslation();
const startDownload = async (version: BSVersion) => {
const showOutdated = !config.get("not-show-bs-version-outdated");
const recommendedVersion = showOutdated ? versionManager.availableVersions$.value.find(v => v.recommended) : undefined;
const showOutdated = !config.get("not-show-bs-version-outdated-modal");
const recommendedVersion = versionManager.getRecommendedVersion();
const isVersionOutdated = recommendedVersion?.BSVersion ? (
tryit(() => lt(valid(coerce(version.BSVersion)), valid(coerce(recommendedVersion.BSVersion)))).result ?? false
) : false;
const isVersionOutdated = safeLt(version.BSVersion, recommendedVersion?.BSVersion);
if (showOutdated && isVersionOutdated) {
@@ -21,6 +21,9 @@ import { CreateLaunchShortcutModal } from "renderer/components/modal/modal-types
import { lastValueFrom } from "rxjs";
import { NotificationService } from "renderer/services/notification.service";
import { BsDownloaderService } from "renderer/services/bs-version-download/bs-downloader.service";
import { useOnUpdate } from "renderer/hooks/use-on-update.hook";
import { safeLt } from "shared/helpers/semver.helpers";
import { ConfigurationService } from "renderer/services/configuration.service";
export function VersionViewer() {
@@ -31,11 +34,41 @@ export function VersionViewer() {
const ipcService = useService(IpcService);
const bsLauncher = useService(BSLauncherService);
const notification = useService(NotificationService);
const config = useService(ConfigurationService);
const { state } = useLocation() as { state: BSVersion };
const navigate = useNavigate();
const [currentTabIndex, setCurrentTabIndex] = useState(0);
useOnUpdate(() => {
checkIsVersionOutaded();
}, [state]);
const checkIsVersionOutaded = async () => {
if(config.get("not-show-bs-version-outdated-notification")){
return;
}
const recommended = bsVersionManagerService.getRecommendedVersion();
const isOutdated = safeLt(state.BSVersion, recommended?.BSVersion);
if(!isOutdated){
return;
}
const res = await notification.notifyWarning({ title: "notifications.bs-version-oudated.title", desc: "notifications.bs-version-oudated.msg", duration: 9000, actions: [
{ id: "0", title: "notifications.bs-version-oudated.actions.do-not-remind" },
{ id: "1", title: "notifications.bs-version-oudated.actions.ok", cancel: true }
] });
if(res === "0"){
config.set("not-show-bs-version-outdated-notification", true);
}
}
const navigateToVersion = (version?: BSVersion) => {
if (!version) {
return navigate("/available-versions");
@@ -211,4 +211,8 @@ export class BSVersionManagerService {
version
]))).values());
}
public getRecommendedVersion(): BSVersion | undefined {
return (this.availableVersions$.value ?? []).find(v => v.recommended);
}
}
+8
View File
@@ -0,0 +1,8 @@
import { coerce, lt, valid } from "semver";
import { tryit } from "./error.helpers";
export function safeLt(a: string, b: string): boolean {
const { result } = tryit(() => lt(valid(coerce(a)), valid(coerce(b))));
return result ?? false;
}
+5
View File
@@ -11,3 +11,8 @@ export function findHashInString(str: string, algorithm: keyof typeof HashAlgori
const match = regex.exec(str);
return match ? match[0] : undefined;
}
export function escapeRegExp(str: string): string {
// Regex taken from lodash escapeRegExp function
return str.replace(/[\\^$.*+?()[\]{}|]/g, '\\$&');
}