├── .editorconfig ├── .gitattributes ├── .github ├── ISSUE_TEMPLATE │ ├── bug.yaml │ ├── config.yml │ ├── feature-request.yaml │ ├── plugin-bug.yaml │ └── plugin-feature-request.yaml └── workflows │ └── msbuild.yml ├── .gitignore ├── .gitmodules ├── BetterNCMII.sln ├── BetterNCMII.vcxproj ├── BetterNCMII.vcxproj.filters ├── BetterNCMII.x86.vcxproj ├── BetterNCMII.x86.vcxproj.filters ├── InstallDependencies.bat ├── LICENSE ├── README.md ├── resource └── PluginMarket.plugin ├── src ├── App.cpp ├── App.h ├── BetterNCMNativePlugin.h ├── EasyCEFHooks.cpp ├── EasyCEFHooks.h ├── ErrorHandler.cpp ├── ErrorHandler.h ├── PluginManager.cpp ├── PluginManager.h ├── dllmain.cpp ├── framework.h ├── hijack.cpp ├── hijack_jump.asm ├── hijack_x86.cpp ├── pch.cpp ├── pch.h ├── resource.aps ├── resource.h ├── resource.rc ├── timercpp.h ├── utils │ ├── BNString.hpp │ ├── Interprocess.hpp │ ├── NamedPipe.cpp │ ├── utils.cpp │ └── utils.h └── v8NativeCalls.cpp └── vcpkg.json /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | [*] 3 | 4 | # ReSharper properties 5 | resharper_cpp_anonymous_method_declaration_braces = end_of_line 6 | resharper_cpp_case_block_braces = end_of_line 7 | resharper_cpp_invocable_declaration_braces = end_of_line 8 | resharper_cpp_other_braces = end_of_line 9 | resharper_cpp_type_declaration_braces = end_of_line 10 | resharper_expression_braces = outside_and_inside 11 | resharper_namespace_declaration_braces = end_of_line 12 | resharper_requires_expression_braces = end_of_line 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.h linguist-vendored 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug.yaml: -------------------------------------------------------------------------------- 1 | name: 本体 Bug 报告 2 | description: 提交一个与 BetterNCM 本体相关的 Bug 3 | title: "[ Bug ] 在此输入标题" 4 | labels: [bug] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | 在提交该 Issue 之前,请确保: 10 | + 先前不存在相同的 Issue 11 | + 该 Bug 是由 BetterNCM 本体,而不是插件导致的 12 | - type: textarea 13 | id: description 14 | attributes: 15 | label: Bug 描述 16 | description: 简明扼要地描述该错误是什么。 17 | validations: 18 | required: true 19 | - type: textarea 20 | id: reproduce-steps 21 | attributes: 22 | label: 复现步骤 23 | description: 重现这一行为的步骤。 24 | value: | 25 | **例**: 26 | 1. 转到"... 27 | 2. 点击'....' 28 | 3. 向下滚动到'....' 29 | 4. 看到错误 30 | validations: 31 | required: true 32 | - type: textarea 33 | id: expected-behavior 34 | attributes: 35 | label: 期望行为 36 | description: 清晰而简明地描述你所期望发生的事情。 37 | validations: 38 | required: true 39 | - type: textarea 40 | id: screenshot 41 | attributes: 42 | label: 屏幕截图 43 | description: 如果适用,请添加屏幕截图以帮助解释你的问题。 44 | value: 45 | - type: input 46 | id: betterncm-version 47 | attributes: 48 | label: BetterNCM 版本 49 | placeholder: "例: 1.0.0" 50 | validations: 51 | required: true 52 | - type: input 53 | id: ncm-version 54 | attributes: 55 | label: 网易云音乐版本 56 | placeholder: "例: 2.10.6" 57 | validations: 58 | required: true 59 | - type: input 60 | id: ncm-patch-version 61 | attributes: 62 | label: 网易云音乐 Patch 版本 63 | description: 在关于网易云音乐页可以看到。 64 | placeholder: "例: 5ad43a6" 65 | validations: 66 | required: true 67 | - type: textarea 68 | id: extra-info 69 | attributes: 70 | label: 补充 71 | description: 在此添加关于该问题的任何其他背景信息。 72 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: BetterNCM 文档 4 | url: https://github.com/MicroCBer/BetterNCM/wiki 5 | about: 包含使用说明和常见问题 -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature-request.yaml: -------------------------------------------------------------------------------- 1 | name: 功能请求 2 | description: 提交一个与 BetterNCM 本体相关的 功能请求 3 | title: "[ FR ] 在此输入标题" 4 | labels: [enhancement] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | 在提交该 Issue 之前,请确保: 10 | + 先前不存在相同的 Issue 11 | + 最新版本的 BetterNCM 不存在该功能 12 | - type: textarea 13 | id: description 14 | attributes: 15 | label: 描述你想要的功能 16 | description: 简明扼要地描述你希望发生什么。 17 | validations: 18 | required: true 19 | - type: textarea 20 | id: alternative-solution 21 | attributes: 22 | label: 描述你考虑过的替代方案 23 | description: 简明扼要地描述你考虑过的任何替代解决方案或功能。 24 | - type: textarea 25 | id: extra-info 26 | attributes: 27 | label: 额外的背景 28 | description: 在此添加关于该功能请求的任何其他背景、屏幕截图或设计草图。 29 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/plugin-bug.yaml: -------------------------------------------------------------------------------- 1 | name: 插件 Bug 报告 2 | description: 提交一个与 某个插件 相关的 Bug 3 | title: "[ Plugin Bug ] 在此输入标题" 4 | labels: [bug, plugin-related] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | 在提交该 Issue 之前,请确保: 10 | + 先前不存在相同的 Issue 11 | + 该 Bug 是由插件, 而不是 BetterNCM 本体导致的 12 | 13 | ## 注意: 14 | ### 我们建议您尽可能地在插件 repo 下提交与插件相关的问题报告。 15 | ### 但是,如果一个插件没有自己的插件 repo,或您不清楚是哪个插件出了问题,您可以在此提交。 16 | - type: textarea 17 | id: description 18 | attributes: 19 | label: Bug 描述 20 | description: 简明扼要地描述该错误是什么。 21 | validations: 22 | required: true 23 | - type: textarea 24 | id: reproduce-steps 25 | attributes: 26 | label: 复现步骤 27 | description: 重现这一行为的步骤。 28 | value: | 29 | **例**: 30 | 1. 转到"... 31 | 2. 点击'....' 32 | 3. 向下滚动到'....' 33 | 4. 看到错误 34 | validations: 35 | required: true 36 | - type: textarea 37 | id: expected-behavior 38 | attributes: 39 | label: 期望行为 40 | description: 清晰而简明地描述你所期望发生的事情。 41 | validations: 42 | required: true 43 | - type: textarea 44 | id: screenshot 45 | attributes: 46 | label: 屏幕截图 47 | description: 如果适用,请添加屏幕截图以帮助解释你的问题。 48 | value: 49 | - type: input 50 | id: betterncm-version 51 | attributes: 52 | label: BetterNCM 版本 53 | placeholder: "例: 1.0.0" 54 | validations: 55 | required: true 56 | - type: input 57 | id: ncm-version 58 | attributes: 59 | label: 网易云音乐版本 60 | placeholder: "例: 2.10.6" 61 | validations: 62 | required: true 63 | - type: input 64 | id: ncm-patch-version 65 | attributes: 66 | label: 网易云音乐 Patch 版本 67 | description: 在关于网易云音乐页可以看到。 68 | placeholder: "例: 5ad43a6" 69 | validations: 70 | required: true 71 | - type: textarea 72 | id: plugin-list 73 | attributes: 74 | label: 已安装插件 75 | description: 你所装的所有插件列表 76 | value: | 77 | **例**: 78 | - StylesheetLoader 79 | - ActionEnhancement 80 | validations: 81 | required: true 82 | - type: textarea 83 | id: extra-info 84 | attributes: 85 | label: 补充 86 | description: 在此添加关于该问题的任何其他背景信息。 87 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/plugin-feature-request.yaml: -------------------------------------------------------------------------------- 1 | name: 插件功能请求 2 | description: 请求制作 提供某个功能的插件 3 | title: "[ Plugin FR ] 在此输入标题" 4 | labels: [enhancement, plugin-related] 5 | body: 6 | - type: markdown 7 | attributes: 8 | value: | 9 | 在提交该 Issue 之前,请确保: 10 | + 先前不存在相同的 Issue 11 | + 现有插件的最新版本不存在该功能 12 | - type: textarea 13 | id: problem 14 | attributes: 15 | label: 你的功能请求是否与某个问题/需求有关?请描述 16 | description: 清晰简洁地描述问题/需求是什么。 17 | validations: 18 | required: true 19 | - type: textarea 20 | id: description 21 | attributes: 22 | label: 描述你想要的解决方案 23 | description: 简明扼要地描述你希望发生什么。 24 | validations: 25 | required: true 26 | - type: textarea 27 | id: alternative-solution 28 | attributes: 29 | label: 描述你考虑过的替代方案 30 | description: 简明扼要地描述你考虑过的任何替代解决方案或功能。 31 | - type: textarea 32 | id: extra-info 33 | attributes: 34 | label: 额外的背景 35 | description: 在此添加关于该功能请求的任何其他背景、屏幕截图或设计草图。 36 | -------------------------------------------------------------------------------- /.github/workflows/msbuild.yml: -------------------------------------------------------------------------------- 1 | name: MSBuild 2 | 3 | on: 4 | push: 5 | branches: [ "v2" ] 6 | pull_request: 7 | branches: [ "v2" ] 8 | 9 | 10 | env: 11 | SOLUTION_FILE_PATH: . 12 | BUILD_CONFIGURATION: Release 13 | VCPKG_DEFAULT_TRIPLET: x86-windows 14 | VCPKG_INSTALLED_DIR: ./vcpkg_installed/ 15 | 16 | permissions: 17 | contents: read 18 | 19 | jobs: 20 | build: 21 | runs-on: windows-latest 22 | permissions: write-all 23 | steps: 24 | - uses: actions/checkout@v3 25 | with: 26 | submodules: recursive 27 | 28 | - name: Add MSBuild to PATH 29 | uses: microsoft/setup-msbuild@v1.0.2 30 | 31 | - name: Setup vcpkg 32 | uses: lukka/run-vcpkg@v10 33 | with: 34 | vcpkgGitCommitId: 69efe9cc2df0015f0bb2d37d55acde4a75c9a25b 35 | - name: Install vcpkg dependencies 36 | working-directory: ${{env.GITHUB_WORKSPACE}} 37 | run: ./InstallDependencies.bat 38 | - name: Install NPM packages 39 | working-directory: ${{env.GITHUB_WORKSPACE}} 40 | run: cd ./src/js-framework ; npm i 41 | 42 | - name: Build 43 | working-directory: ${{env.GITHUB_WORKSPACE}} 44 | run: msbuild .\BetterNCMII.sln -p:Platform="All" -p:Configuration=Release 45 | 46 | - uses: "marvinpinto/action-automatic-releases@latest" 47 | name: Upload to Github Release 48 | if: github.event_name != 'pull_request' 49 | with: 50 | repo_token: "${{ secrets.GITHUB_TOKEN }}" 51 | automatic_release_tag: "dev-nightly" 52 | prerelease: true 53 | title: "Latest Test Release" 54 | files: | 55 | ${{ github.workspace }}/x64/Release/BetterNCMII.dll 56 | ${{ github.workspace }}/Release_86/BetterNCMII86.dll 57 | 58 | - name: Upload Artifact 59 | uses: actions/upload-artifact@v3.1.1 60 | with: 61 | name: BetterNCMII 62 | path: | 63 | ${{ github.workspace }}/x64/Release/BetterNCMII.dll 64 | ${{ github.workspace }}/Release_86/BetterNCMII86.dll 65 | 66 | 67 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | 28 | # Executables 29 | *.exe 30 | *.out 31 | *.app 32 | .vs/ 33 | Debug/ 34 | Release/ 35 | Debug_86/ 36 | Release_86/ 37 | 38 | # https://github.com/microsoft/vcpkg/blob/master/.gitignore 39 | *.user 40 | *.aps 41 | 42 | # JS Framework 43 | .vscode/ 44 | src/framework.js 45 | src/framework.js.map 46 | src/framework.css 47 | src/framework.css.map 48 | src/js-framework/node_modules/ 49 | src/js-framework/package-lock.json 50 | 51 | # VS 52 | *.vcxproj.user 53 | enc_temp_folder 54 | 55 | # VCPKG packages 56 | vcpkg_installed/ 57 | vcpkg_installed_86/ -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/js-framework"] 2 | path = src/js-framework 3 | url = https://github.com/BetterNCM/js-framework 4 | [submodule "src/3rd/libcef"] 5 | path = src/3rd/libcef 6 | url = https://github.com/BetterNCM/libcef 7 | -------------------------------------------------------------------------------- /BetterNCMII.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33205.214 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BetterNCMII", "BetterNCMII.vcxproj", "{BCD79D10-988E-4A2C-BF59-D6225F3836AA}" 7 | EndProject 8 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "BetterNCMII86", "BetterNCMII.x86.vcxproj", "{7786D731-2A43-45A1-B17B-313043E31F0A}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|All = Debug|All 13 | Release|All = Release|All 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {BCD79D10-988E-4A2C-BF59-D6225F3836AA}.Debug|All.ActiveCfg = Debug|x64 17 | {BCD79D10-988E-4A2C-BF59-D6225F3836AA}.Debug|All.Build.0 = Debug|x64 18 | {BCD79D10-988E-4A2C-BF59-D6225F3836AA}.Release|All.ActiveCfg = Release|x64 19 | {BCD79D10-988E-4A2C-BF59-D6225F3836AA}.Release|All.Build.0 = Release|x64 20 | {7786D731-2A43-45A1-B17B-313043E31F0A}.Debug|All.ActiveCfg = Debug|Win32 21 | {7786D731-2A43-45A1-B17B-313043E31F0A}.Debug|All.Build.0 = Debug|Win32 22 | {7786D731-2A43-45A1-B17B-313043E31F0A}.Release|All.ActiveCfg = Release|Win32 23 | {7786D731-2A43-45A1-B17B-313043E31F0A}.Release|All.Build.0 = Release|Win32 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {C885971D-39AF-4F89-82C1-D015D4DFD2D0} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /BetterNCMII.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | x64 7 | 8 | 9 | Release 10 | x64 11 | 12 | 13 | 14 | 16.0 15 | x64Proj 16 | {bcd79d10-988e-4a2c-bf59-d6225f3836aa} 17 | BetterNCMII 18 | 10.0 19 | BetterNCMII 20 | 21 | 22 | 23 | DynamicLibrary 24 | true 25 | v143 26 | Unicode 27 | 28 | 29 | DynamicLibrary 30 | false 31 | v143 32 | true 33 | Unicode 34 | 35 | 36 | DynamicLibrary 37 | true 38 | v143 39 | Unicode 40 | 41 | 42 | DynamicLibrary 43 | false 44 | v143 45 | true 46 | Unicode 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | true 69 | $(PublicIncludeDirectories) 70 | true 71 | true 72 | $(ProjectDir)vcpkg_installed\x64-windows\include;$(VC_IncludePath);$(WindowsSDK_IncludePath); 73 | $(VC_LibraryPath_x64);$(WindowsSDK_LibraryPath_x64);$(ProjectDir)vcpkg_installed\x64-windows\lib 74 | 75 | 76 | false 77 | $(ProjectDir)vcpkg_installed\x64-windows\include;$(VC_IncludePath);$(WindowsSDK_IncludePath); 78 | false 79 | $(PublicIncludeDirectories) 80 | true 81 | true 82 | $(VC_LibraryPath_x64);$(WindowsSDK_LibraryPath_x64);$(ProjectDir)vcpkg_installed\x64-windows\lib 83 | 84 | 85 | true 86 | 87 | 88 | false 89 | 90 | 91 | 92 | Level3 93 | true 94 | x64;_DEBUG;EASYCEFINJECT_EXPORTS;_WINDOWS;_USRDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) 95 | true 96 | Create 97 | pch.h 98 | stdcpp20 99 | false 100 | src;src\3rd\libcef;%(AdditionalIncludeDirectories) 101 | 102 | 103 | Windows 104 | true 105 | false 106 | src/3rd/libcef/libcef_x64.lib;dwmapi.lib;vcpkg_installed\x64-windows\debug\lib\*.lib;%(AdditionalDependencies) 107 | Default 108 | 109 | 110 | taskkill /f /im cloudmusic.exe > nul 111 | ping localhost -n 2 > nul 112 | copy "$(TargetDir)BetterNCMII.dll" "J:\Program Files\Netease\CloudMusic\msimg32.dll" /y 113 | 114 | 115 | cd /D $(SolutionDir)/src/js-framework 116 | npm run build:dev 117 | 118 | 119 | 120 | 121 | Level3 122 | true 123 | false 124 | true 125 | x64;_CRT_NONSTDC_NO_DEPRECATE;_HAS_STD_BYTE=0;NDEBUG;EASYCEFINJECT_EXPORTS;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) 126 | true 127 | Create 128 | pch.h 129 | stdcpp20 130 | src;src\3rd\libcef;%(AdditionalIncludeDirectories) 131 | MultiThreadedDLL 132 | true 133 | MinSpace 134 | Size 135 | Default 136 | 137 | 138 | Windows 139 | true 140 | true 141 | true 142 | false 143 | dwmapi.lib;src/3rd/libcef/libcef_x64.lib;vcpkg_installed\x64-windows\lib\*.lib;%(AdditionalDependencies) 144 | 145 | 146 | 147 | 148 | 149 | 150 | cd src/js-framework 151 | npm run build 152 | 153 | 154 | %(Inputs) 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | true 186 | 187 | 188 | true 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | -------------------------------------------------------------------------------- /BetterNCMII.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Hook 6 | 7 | 8 | Utils 9 | 10 | 11 | Service\Main 12 | 13 | 14 | Service\Plugin 15 | 16 | 17 | Service\Plugin 18 | 19 | 20 | Service\Main 21 | 22 | 23 | Service\Error 24 | 25 | 26 | Chore 27 | 28 | 29 | Hook 30 | 31 | 32 | 33 | 34 | Hook 35 | 36 | 37 | Utils 38 | 39 | 40 | JS Framework 41 | 42 | 43 | Utils 44 | 45 | 46 | Service\Main 47 | 48 | 49 | Service\Plugin 50 | 51 | 52 | Service\Plugin 53 | 54 | 55 | Service\Error 56 | 57 | 58 | Chore 59 | 60 | 61 | Chore 62 | 63 | 64 | Chore 65 | 66 | 67 | 68 | 69 | JS Framework 70 | 71 | 72 | JS Framework 73 | 74 | 75 | 76 | 77 | JS Framework 78 | 79 | 80 | JS Framework 81 | 82 | 83 | 84 | 85 | {313eb4b6-e87f-43e6-9e73-0ac42f8c4ec8} 86 | 87 | 88 | {4494f3d0-0b12-4281-b660-8ece04b1727f} 89 | 90 | 91 | {44dccf43-ec1c-431a-ac9a-782b39e5ea7a} 92 | 93 | 94 | {4b90cf1c-a219-4b87-b534-ef3b54de7a25} 95 | 96 | 97 | {32dd3c44-8399-4a2b-9e74-b7fb37f920c2} 98 | 99 | 100 | {b5588d2f-0a97-443e-8464-f13504275e2b} 101 | 102 | 103 | {32153dac-a10c-41cb-b1ae-d8c2484ec90f} 104 | 105 | 106 | {67ed3ef2-b4ad-4373-bd18-9709646dc93b} 107 | 108 | 109 | 110 | 111 | JS Framework 112 | 113 | 114 | 115 | 116 | Hook 117 | 118 | 119 | -------------------------------------------------------------------------------- /BetterNCMII.x86.vcxproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Debug 6 | Win32 7 | 8 | 9 | Release 10 | Win32 11 | 12 | 13 | 14 | 16.0 15 | Win32Proj 16 | {7786D731-2A43-45A1-B17B-313043E31F0A} 17 | BetterNCMII86 18 | 10.0 19 | BetterNCMII86 20 | 21 | 22 | 23 | DynamicLibrary 24 | true 25 | v143 26 | Unicode 27 | 28 | 29 | DynamicLibrary 30 | false 31 | v143 32 | true 33 | Unicode 34 | 35 | 36 | DynamicLibrary 37 | true 38 | v143 39 | Unicode 40 | 41 | 42 | DynamicLibrary 43 | false 44 | v143 45 | true 46 | Unicode 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | true 68 | $(PublicIncludeDirectories) 69 | true 70 | true 71 | $(ProjectDir)vcpkg_installed_86\x86-windows\include;$(VC_IncludePath);$(WindowsSDK_IncludePath); 72 | $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(ProjectDir)vcpkg_installed_86\x86-windows\lib 73 | $(SolutionDir)$(Configuration)_86\ 74 | 75 | 76 | false 77 | $(ProjectDir)vcpkg_installed_86\x86-windows\include;$(VC_IncludePath);$(WindowsSDK_IncludePath); 78 | false 79 | $(PublicIncludeDirectories) 80 | true 81 | true 82 | $(VC_LibraryPath_x86);$(WindowsSDK_LibraryPath_x86);$(ProjectDir)vcpkg_installed_86\x86-windows\lib 83 | $(SolutionDir)$(Configuration)_86\ 84 | 85 | 86 | true 87 | 88 | 89 | false 90 | 91 | 92 | 93 | Level3 94 | true 95 | WIN32;_DEBUG;EASYCEFINJECT_EXPORTS;_WINDOWS;_USRDLL;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) 96 | true 97 | Create 98 | pch.h 99 | stdcpp20 100 | false 101 | src;src\3rd\libcef;%(AdditionalIncludeDirectories) 102 | 103 | 104 | Windows 105 | true 106 | false 107 | src/3rd/libcef/libcef.lib;dwmapi.lib;vcpkg_installed_86\x86-windows\debug\lib\*.lib;%(AdditionalDependencies) 108 | Default 109 | 110 | 111 | taskkill /f /im cloudmusic.exe > nul 112 | ping localhost -n 2 > nul 113 | copy "$(TargetDir)BetterNCMII.dll" "C:\Program Files (x86)\Netease\CloudMusic\msimg32.dll" /y 114 | 115 | 116 | cd /D $(SolutionDir)/src/js-framework 117 | npm run build:dev 118 | 119 | 120 | 121 | 122 | Level3 123 | true 124 | false 125 | true 126 | WIN32;_CRT_NONSTDC_NO_DEPRECATE;_HAS_STD_BYTE=0;NDEBUG;EASYCEFINJECT_EXPORTS;_WINDOWS;_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) 127 | true 128 | Create 129 | pch.h 130 | stdcpp20 131 | src;src\3rd\libcef;%(AdditionalIncludeDirectories) 132 | MultiThreadedDLL 133 | true 134 | MinSpace 135 | Size 136 | Default 137 | 138 | 139 | Windows 140 | true 141 | true 142 | true 143 | false 144 | dwmapi.lib;src/3rd/libcef/libcef.lib;vcpkg_installed_86\x86-windows\lib\*.lib;%(AdditionalDependencies) 145 | 146 | 147 | 148 | 149 | 150 | 151 | cd src/js-framework 152 | npm run build 153 | 154 | 155 | %(Inputs) 156 | 157 | 158 | 159 | 160 | Level3 161 | true 162 | _DEBUG;EASYCEFINJECT_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 163 | true 164 | Use 165 | pch.h 166 | 167 | 168 | Windows 169 | true 170 | false 171 | 172 | 173 | 174 | 175 | Level3 176 | true 177 | true 178 | true 179 | NDEBUG;EASYCEFINJECT_EXPORTS;_WINDOWS;_USRDLL;%(PreprocessorDefinitions) 180 | true 181 | Use 182 | pch.h 183 | 184 | 185 | Windows 186 | true 187 | true 188 | true 189 | false 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | true 221 | 222 | 223 | true 224 | 225 | 226 | 227 | 228 | 229 | 230 | 231 | 232 | -------------------------------------------------------------------------------- /BetterNCMII.x86.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Hook 6 | 7 | 8 | Utils 9 | 10 | 11 | Service\Main 12 | 13 | 14 | Service\Plugin 15 | 16 | 17 | Service\Plugin 18 | 19 | 20 | Service\Main 21 | 22 | 23 | Service\Error 24 | 25 | 26 | Chore 27 | 28 | 29 | Service\Main 30 | 31 | 32 | 33 | 34 | Hook 35 | 36 | 37 | Utils 38 | 39 | 40 | JS Framework 41 | 42 | 43 | Utils 44 | 45 | 46 | Service\Main 47 | 48 | 49 | Service\Plugin 50 | 51 | 52 | Service\Plugin 53 | 54 | 55 | Service\Error 56 | 57 | 58 | Chore 59 | 60 | 61 | Chore 62 | 63 | 64 | Chore 65 | 66 | 67 | 68 | 69 | JS Framework 70 | 71 | 72 | JS Framework 73 | 74 | 75 | 76 | 77 | JS Framework 78 | 79 | 80 | JS Framework 81 | 82 | 83 | 84 | 85 | {313eb4b6-e87f-43e6-9e73-0ac42f8c4ec8} 86 | 87 | 88 | {4494f3d0-0b12-4281-b660-8ece04b1727f} 89 | 90 | 91 | {44dccf43-ec1c-431a-ac9a-782b39e5ea7a} 92 | 93 | 94 | {4b90cf1c-a219-4b87-b534-ef3b54de7a25} 95 | 96 | 97 | {32dd3c44-8399-4a2b-9e74-b7fb37f920c2} 98 | 99 | 100 | {b5588d2f-0a97-443e-8464-f13504275e2b} 101 | 102 | 103 | {32153dac-a10c-41cb-b1ae-d8c2484ec90f} 104 | 105 | 106 | {67ed3ef2-b4ad-4373-bd18-9709646dc93b} 107 | 108 | 109 | 110 | 111 | JS Framework 112 | 113 | 114 | -------------------------------------------------------------------------------- /InstallDependencies.bat: -------------------------------------------------------------------------------- 1 | vcpkg install --triplet=x86-windows --x-install-root=./vcpkg_installed_86/ 2 | vcpkg install --triplet=x64-windows --x-install-root=./vcpkg_installed/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 |
3 | 4 |
5 |

BetterNCM

6 | 7 |

PC版 NCM 客户端插件管理器

8 | 9 | 10 |

11 | 开发文档 · 12 | 介绍视频 · 13 | 用户文档(社区) · 14 | 项目页面 15 | 16 |

17 | 18 |
19 | 20 |
21 | 22 | ![image](https://github.com/MicroCBer/BetterNCM/assets/66859419/9765fc45-a22b-4469-a015-e6b33b14418c) 23 | 24 | 25 | --- 26 | 27 | 兼容版本:`2.10.* ~ 3.0.*` 28 | 29 | 30 | 31 | # 安装 32 | 33 | 使用 [BetterNCM Installer](https://github.com/MicroCBer/BetterNCM-Installer) 一键安装~ 34 | 35 | # 其他 36 | ## 相关 37 | - [BetterNCM 生态组织](https://github.com/BetterNCM) 38 | - [插件商店 下载量统计 仓库](https://github.com/BetterNCM/BetterNCM-PluginMarket-Analyze) 39 | - [插件商店 插件源 仓库](https://github.com/BetterNCM/BetterNCM-Plugins) 40 | - [Star History](https://api.star-history.com/svg?repos=MicroCBer/BetterNCM&type=Date) 41 | -------------------------------------------------------------------------------- /resource/PluginMarket.plugin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/std-microblock/BetterNCM/b9d32df79ab0eafe060da8ae605f458acb346c77/resource/PluginMarket.plugin -------------------------------------------------------------------------------- /src/App.cpp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/std-microblock/BetterNCM/b9d32df79ab0eafe060da8ae605f458acb346c77/src/App.cpp -------------------------------------------------------------------------------- /src/App.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include "EasyCEFHooks.h" 4 | #include "shellapi.h" 5 | #include 6 | #include 7 | #include "PluginManager.h" 8 | #include "utils/Interprocess.hpp" 9 | extern const std::string version; 10 | 11 | class App { 12 | httplib::Server* httpServer = nullptr; 13 | std::thread* server_thread; 14 | int server_port; 15 | std::thread* create_server(const std::string& apiKey); 16 | std::string readConfig(const std::string& key, const std::string& def); 17 | void writeConfig(const std::string& key, const std::string& val); 18 | std::shared_timed_mutex succeeded_hijacks_lock; 19 | std::vector succeeded_hijacks; 20 | void parseConfig(); 21 | nlohmann::json config{}; 22 | std::mutex configMutex{}; 23 | public: 24 | void Init(); 25 | App() = default; 26 | ~App(); 27 | }; 28 | -------------------------------------------------------------------------------- /src/BetterNCMNativePlugin.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #ifdef NATIVE_PLUGIN_CPP_EXTENSIONS 3 | #include "pch.h" 4 | #include 5 | #include 6 | #include "3rd/libcef/include/capi/cef_v8_capi.h" 7 | #include 8 | #include 9 | using cef_task_post_exec_t = struct _cef_task_post_exec; 10 | 11 | void CEF_CALLBACK exec(struct _cef_task_t* self); 12 | #endif 13 | 14 | enum NativeAPIType { 15 | Int, 16 | // *int 17 | Boolean, 18 | // *bool 19 | Double, 20 | // *double 21 | String, 22 | // *char 23 | V8Value, 24 | // *cef_v8value_t 25 | }; 26 | 27 | typedef enum NativeAPIType NativeAPIType; 28 | 29 | enum NCMProcessType { 30 | Undetected = 0x0, 31 | Main = 0x0001, 32 | Renderer = 0x10, 33 | GpuProcess = 0x100, 34 | Utility = 0x1000, 35 | }; 36 | 37 | typedef enum NCMProcessType NCMProcessType; 38 | 39 | #ifdef NATIVE_PLUGIN_CPP_EXTENSIONS 40 | namespace BetterNCMNativePlugin { 41 | #endif 42 | struct PluginAPI { 43 | int (*addNativeAPI)(NativeAPIType args[], int argsNum, const char* identifier, char* function(void**)); 44 | const char* betterncmVersion; 45 | NCMProcessType processType; 46 | const unsigned short(*ncmVersion)[3]; 47 | }; 48 | 49 | #ifdef NATIVE_PLUGIN_CPP_EXTENSIONS 50 | 51 | #define CEF_V8_ADDREF(expr) expr->base.add_ref(&expr->base) 52 | #define CEF_V8_RELEASE(expr) expr->base.release(&expr->base) 53 | 54 | namespace extensions { 55 | class JSFunction { 56 | static cef_v8value_t* create_v8value(const std::string& val) { 57 | CefString s; 58 | s.FromString(val); 59 | return cef_v8value_create_string(s.GetStruct()); 60 | } 61 | 62 | static cef_v8value_t* create_v8value(const std::wstring& val) { 63 | CefString s; 64 | s.FromWString(val); 65 | return cef_v8value_create_string(s.GetStruct()); 66 | } 67 | 68 | static cef_v8value_t* create_v8value(int val) { 69 | return cef_v8value_create_int(val); 70 | } 71 | 72 | 73 | static cef_v8value_t* create_v8value(unsigned int val) { 74 | return cef_v8value_create_uint(val); 75 | } 76 | 77 | static cef_v8value_t* create_v8value(double val) { 78 | return cef_v8value_create_double(val); 79 | } 80 | 81 | static cef_v8value_t* create_v8value(bool val) { 82 | return cef_v8value_create_bool(val); 83 | } 84 | 85 | static cef_v8value_t* create_v8value() { 86 | return cef_v8value_create_undefined(); 87 | } 88 | 89 | static cef_v8value_t* create_v8value(cef_v8value_t* val) { 90 | return val; 91 | } 92 | 93 | template 94 | static cef_v8value_t* create_v8value(std::vector val) { 95 | cef_v8value_t* arr = cef_v8value_create_array(val.size()); 96 | for (const auto& item : val) 97 | arr->set_value_byindex(arr, &item - &val[0], create_v8value(item)); 98 | return arr; 99 | } 100 | 101 | 102 | using cef_task_post_exec = struct _cef_task_post_exec { 103 | cef_task_t task; 104 | JSFunction* func; 105 | std::function()> args; 106 | }; 107 | 108 | static void CEF_CALLBACK exec(struct _cef_task_t* self) { 109 | JSFunction* func = ((_cef_task_post_exec*)self)->func; 110 | auto args = (((_cef_task_post_exec*)self)->args)(); 111 | int nArg = 0; 112 | 113 | auto ctx = func->context.load(); 114 | 115 | func->valid = ctx->is_valid(ctx); 116 | 117 | if (!func->valid) { 118 | func->busy = false; 119 | return; 120 | } 121 | 122 | func->updateContext(); 123 | 124 | ctx->enter(ctx); 125 | auto ret = func->func->execute_function(func->func, nullptr, args.size(), args.data()); 126 | ctx->exit(ctx); 127 | 128 | func->busy = false; 129 | } 130 | 131 | cef_v8value_t* func; 132 | std::atomic context; 133 | std::atomic busy = false; 134 | std::atomic valid = true; 135 | cef_task_runner_t* runner; 136 | 137 | public: 138 | ~JSFunction() { 139 | CEF_V8_RELEASE(this->func); 140 | CEF_V8_RELEASE(this->context.load()); 141 | CEF_V8_RELEASE(this->runner); 142 | } 143 | 144 | void updateContext(cef_v8context_t* baseContext = nullptr) { 145 | if (!this->valid)return; 146 | 147 | if (!baseContext)baseContext = this->context; 148 | auto browser = baseContext->get_browser(baseContext); 149 | if (!browser)return; 150 | auto mainFrame = browser->get_main_frame(browser); 151 | this->context = mainFrame->get_v8context(mainFrame); 152 | } 153 | 154 | JSFunction(cef_v8value_t* func, cef_v8context_t* context = nullptr) { 155 | CEF_V8_ADDREF(func); 156 | this->func = func; 157 | 158 | if (context) { 159 | CEF_V8_ADDREF(context); 160 | this->context.store(context); 161 | } 162 | else { 163 | updateContext(cef_v8context_get_entered_context()); 164 | } 165 | 166 | if (context) 167 | this->runner = this->context.load()->get_task_runner(cef_v8context_get_entered_context()); 168 | else { 169 | auto ctx = cef_v8context_get_current_context(); 170 | this->runner = ctx->get_task_runner(ctx); 171 | } 172 | CEF_V8_ADDREF(this->runner); 173 | } 174 | 175 | bool isValid() { 176 | return this->valid; 177 | } 178 | 179 | template 180 | int operator()(Args... args) { 181 | if (!this->valid) return -1; 182 | bool expected = false; 183 | while (!busy.compare_exchange_strong(expected, true)) 184 | expected = false; 185 | 186 | auto task = static_cast(calloc(1, sizeof(cef_task_post_exec))); 187 | task->func = this; 188 | 189 | task->task.base.size = sizeof(cef_task_t); 190 | 191 | task->args = [=]() { 192 | auto v8Args = std::vector(); 193 | (v8Args.push_back(create_v8value(args)), ...); 194 | return v8Args; 195 | }; 196 | 197 | ((cef_task_t*)task)->execute = exec; 198 | this->runner->post_task(runner, (cef_task_t*)task); 199 | return 1; 200 | } 201 | }; 202 | } 203 | #endif 204 | #ifdef NATIVE_PLUGIN_CPP_EXTENSIONS 205 | } 206 | #endif 207 | -------------------------------------------------------------------------------- /src/EasyCEFHooks.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | #include "EasyCEFHooks.h" 4 | #include "3rd/libcef/include/capi/cef_base_capi.h" 5 | #include "utils/Interprocess.hpp" 6 | 7 | class LambdaTask { 8 | using cef_task_post_exec = struct _cef_task_post_exec { 9 | cef_task_t task; 10 | std::function lambda; 11 | }; 12 | 13 | static void CEF_CALLBACK exec(struct _cef_task_t* self) { 14 | auto task = (cef_task_post_exec*)self; 15 | task->lambda(); 16 | } 17 | 18 | cef_task_runner_t* runner; 19 | 20 | public: 21 | LambdaTask(cef_task_runner_t* runner) { 22 | this->runner = runner; 23 | this->runner->base.add_ref(&this->runner->base); 24 | } 25 | 26 | ~LambdaTask() { 27 | } 28 | 29 | template 30 | void post(F&& f) const { 31 | auto task = static_cast(calloc(1, sizeof(cef_task_post_exec))); 32 | task->lambda = f; 33 | task->task.base.size = sizeof(cef_task_t); 34 | task->task.execute = exec; 35 | this->runner->post_task(runner, (cef_task_t*)task); 36 | } 37 | }; 38 | 39 | _cef_frame_t* frame = nullptr; 40 | cef_v8context_t* contextl = nullptr; 41 | 42 | struct _cef_client_t* cef_client = nullptr; 43 | PVOID origin_cef_browser_host_create_browser = nullptr; 44 | PVOID origin_cef_initialize = nullptr; 45 | PVOID origin_cef_execute_process = nullptr; 46 | PVOID origin_cef_get_keyboard_handler = nullptr; 47 | PVOID origin_cef_client_get_display_handler = nullptr; 48 | PVOID origin_cef_on_key_event = nullptr; 49 | PVOID origin_cef_v8context_get_current_context = nullptr; 50 | PVOID origin_cef_load_handler = nullptr; 51 | PVOID origin_cef_on_load_start = nullptr; 52 | PVOID origin_cef_app_on_context_created = nullptr; 53 | PVOID origin_cef_app_on_context_released = nullptr; 54 | PVOID origin_on_before_command_line_processing = nullptr; 55 | PVOID origin_get_render_process_handler = nullptr; 56 | PVOID origin_command_line_append_switch = nullptr; 57 | PVOID origin_cef_register_scheme_handler_factory = nullptr; 58 | PVOID origin_cef_scheme_handler_create = nullptr; 59 | PVOID origin_scheme_handler_read = nullptr; 60 | PVOID origin_get_headers = nullptr; 61 | 62 | std::function EasyCEFHooks::onLoadStart = [ 63 | ](auto browser, auto frame) { 64 | }; 65 | std::function EasyCEFHooks::onKeyEvent = [ 66 | ](auto client, auto browser, auto key) { 67 | }; 68 | std::function EasyCEFHooks::onAddCommandLine = [](std::string arg) { return true; }; 69 | std::function(std::string)> EasyCEFHooks::onHijackRequest = 70 | [](std::string url) { return nullptr; }; 71 | std::function EasyCEFHooks::onCommandLine = [ 72 | ](struct _cef_command_line_t* command_line) { 73 | }; 74 | 75 | 76 | int CEF_CALLBACK hook_cef_on_key_event(struct _cef_keyboard_handler_t* self, 77 | struct _cef_browser_t* browser, 78 | const struct _cef_key_event_t* event, 79 | cef_event_handle_t os_event) { 80 | EasyCEFHooks::onKeyEvent(cef_client, browser, event); 81 | 82 | return CAST_TO(origin_cef_on_key_event, hook_cef_on_key_event)(self, browser, event, os_event); 83 | } 84 | 85 | 86 | void process_context(cef_v8context_t* context); 87 | 88 | // Deprecated 89 | cef_v8context_t* hook_cef_v8context_get_current_context() { 90 | cef_v8context_t* context = CAST_TO(origin_cef_v8context_get_current_context, 91 | hook_cef_v8context_get_current_context)(); 92 | return context; 93 | } 94 | 95 | struct _cef_keyboard_handler_t* CEF_CALLBACK hook_cef_get_keyboard_handler(struct _cef_client_t* self) { 96 | auto keyboard_handler = CAST_TO(origin_cef_get_keyboard_handler, hook_cef_get_keyboard_handler)(self); 97 | if (keyboard_handler) { 98 | cef_client = self; 99 | origin_cef_on_key_event = keyboard_handler->on_key_event; 100 | keyboard_handler->on_key_event = hook_cef_on_key_event; 101 | } 102 | return keyboard_handler; 103 | } 104 | 105 | 106 | void CEF_CALLBACK hook_cef_on_load_start(struct _cef_load_handler_t* self, 107 | struct _cef_browser_t* browser, 108 | struct _cef_frame_t* frame, 109 | cef_transition_type_t transition_type) { 110 | EasyCEFHooks::onLoadStart(browser, frame); 111 | CAST_TO(origin_cef_on_load_start, hook_cef_on_load_start)(self, browser, frame, transition_type); 112 | } 113 | 114 | void CEF_CALLBACK hook_cef_on_load_error(struct _cef_load_handler_t* self, 115 | struct _cef_browser_t* browser, 116 | struct _cef_frame_t* frame, 117 | cef_errorcode_t errorCode, 118 | const cef_string_t* errorText, 119 | const cef_string_t* failedUrl) { 120 | EasyCEFHooks::executeJavaScript( 121 | frame, 122 | R"(if (location.href === "chrome-error://chromewebdata/") location.href = "orpheus://orpheus/pub/app.html")", 123 | "libeasycef/fix_white_screen.js"); 124 | } 125 | 126 | struct _cef_load_handler_t* CEF_CALLBACK hook_cef_load_handler(struct _cef_client_t* self) { 127 | auto load_handler = CAST_TO(origin_cef_load_handler, hook_cef_load_handler)(self); 128 | if (load_handler) { 129 | cef_client = self; 130 | load_handler->on_load_error = hook_cef_on_load_error; 131 | origin_cef_on_load_start = load_handler->on_load_start; 132 | load_handler->on_load_start = hook_cef_on_load_start; 133 | } 134 | return load_handler; 135 | } 136 | 137 | 138 | _cef_display_handler_t* CEF_CALLBACK hook_cef_client_get_display_handler(_cef_client_t* self) { 139 | _cef_display_handler_t* display_handler = CAST_TO(origin_cef_client_get_display_handler, 140 | hook_cef_client_get_display_handler)(self); 141 | display_handler->on_title_change = [](struct _cef_display_handler_t* self, 142 | struct _cef_browser_t* browser, 143 | const cef_string_t* title) -> void { 144 | auto frame = browser->get_main_frame(browser); 145 | if (frame && !BNString(util::cefFromCEFUserFreeTakeOwnership(frame->get_url(frame)).ToWString()).startsWith( 146 | L"devtools://")) { 147 | auto host = browser->get_host(browser); 148 | auto hwnd = host->get_window_handle(host); 149 | SetWindowText(hwnd, std::wstring(util::cefFromCEFUserFree(title)).c_str()); 150 | } 151 | }; 152 | 153 | return display_handler; 154 | } 155 | 156 | cef_browser_t* hook_cef_browser_host_create_browser( 157 | const cef_window_info_t* windowInfo, 158 | struct _cef_client_t* client, 159 | const cef_string_t* url, 160 | const struct _cef_browser_settings_t* settings, 161 | struct _cef_dictionary_value_t* extra_info, 162 | struct _cef_request_context_t* request_context) { 163 | origin_cef_get_keyboard_handler = client->get_keyboard_handler; 164 | client->get_keyboard_handler = hook_cef_get_keyboard_handler; 165 | 166 | 167 | origin_cef_load_handler = client->get_load_handler; 168 | client->get_load_handler = hook_cef_load_handler; 169 | 170 | origin_cef_client_get_display_handler = client->get_display_handler; 171 | client->get_display_handler = hook_cef_client_get_display_handler; 172 | 173 | cef_browser_t* origin = CAST_TO(origin_cef_browser_host_create_browser, hook_cef_browser_host_create_browser) 174 | (windowInfo, client, url, settings, extra_info, request_context); 175 | return origin; 176 | } 177 | 178 | void CEF_CALLBACK hook_command_line_append_switch(_cef_command_line_t* self, const cef_string_t* name) { 179 | if (EasyCEFHooks::onAddCommandLine(util::cefFromCEFUserFree(name).ToString())) { 180 | CAST_TO(origin_command_line_append_switch, hook_command_line_append_switch)(self, name); 181 | } 182 | } 183 | 184 | void CEF_CALLBACK hook_on_before_command_line_processing( 185 | struct _cef_app_t* self, 186 | const cef_string_t* process_type, 187 | struct _cef_command_line_t* command_line) { 188 | EasyCEFHooks::onCommandLine(command_line); 189 | origin_command_line_append_switch = command_line->append_switch; 190 | command_line->append_switch = hook_command_line_append_switch; 191 | CAST_TO(origin_on_before_command_line_processing, hook_on_before_command_line_processing)( 192 | self, process_type, command_line); 193 | } 194 | 195 | 196 | void CEF_CALLBACK hook_on_context_created( 197 | struct _cef_render_process_handler_t* self, 198 | struct _cef_browser_t* browser, 199 | struct _cef_frame_t* frame, 200 | struct _cef_v8context_t* context) { 201 | auto url = BNString(util::cefFromCEFUserFreeTakeOwnership(frame->get_url(frame)).ToWString()); 202 | if (url.startsWith(L"orpheus://")) { 203 | process_context(context); 204 | 205 | CAST_TO(origin_cef_app_on_context_created, hook_on_context_created)(self, browser, frame, context); 206 | } 207 | } 208 | 209 | void CEF_CALLBACK hook_on_context_released( 210 | struct _cef_render_process_handler_t* self, 211 | struct _cef_browser_t* browser, 212 | struct _cef_frame_t* frame, 213 | struct _cef_v8context_t* context) { 214 | if (BNString(util::cefFromCEFUserFreeTakeOwnership(frame->get_url(frame)).ToWString()).startsWith(L"orpheus://")) 215 | CAST_TO(origin_cef_app_on_context_released, hook_on_context_released)(self, browser, frame, context); 216 | } 217 | 218 | struct _cef_render_process_handler_t* CEF_CALLBACK hook_get_render_process_handler(struct _cef_app_t* self) { 219 | auto handler = CAST_TO(origin_get_render_process_handler, hook_get_render_process_handler)(self); 220 | 221 | origin_cef_app_on_context_created = handler->on_context_created; 222 | handler->on_context_created = hook_on_context_created; 223 | origin_cef_app_on_context_released = handler->on_context_released; 224 | handler->on_context_released = hook_on_context_released; 225 | handler->on_browser_destroyed = nullptr; 226 | return handler; 227 | } 228 | 229 | int hook_cef_execute_process(const struct _cef_main_args_t* args, 230 | cef_app_t* application, 231 | void* windows_sandbox_info) { 232 | origin_get_render_process_handler = application->get_render_process_handler; 233 | application->get_render_process_handler = hook_get_render_process_handler; 234 | 235 | return CAST_TO(origin_cef_execute_process, hook_cef_execute_process)(args, application, windows_sandbox_info); 236 | } 237 | 238 | int hook_cef_initialize(const struct _cef_main_args_t* args, 239 | const struct _cef_settings_t* settings, 240 | cef_app_t* application, 241 | void* windows_sandbox_info) { 242 | _cef_settings_t s = *settings; 243 | s.background_color = 0x000000ff; 244 | 245 | origin_on_before_command_line_processing = application->on_before_command_line_processing; 246 | application->on_before_command_line_processing = hook_on_before_command_line_processing; 247 | 248 | origin_get_render_process_handler = application->get_render_process_handler; 249 | application->get_render_process_handler = hook_get_render_process_handler; 250 | 251 | return CAST_TO(origin_cef_initialize, hook_cef_initialize)(args, &s, application, windows_sandbox_info); 252 | } 253 | 254 | 255 | class CefRequestMITMProcess { 256 | const static int bytesPerTime = 65535; 257 | 258 | public: 259 | std::string url; 260 | std::vector data; 261 | int datasize = 0; 262 | int dataPointer = 0; 263 | 264 | void fillData(const std::wstring& s) { 265 | fillData(util::wstring_to_utf8(s)); 266 | }; 267 | 268 | void fillData(const std::string& s) { 269 | data = std::vector(s.begin(), s.end()); 270 | }; 271 | void fillData(_cef_resource_handler_t* self, _cef_callback_t* callback); 272 | 273 | std::wstring getDataStr() { 274 | try { 275 | return util::utf8_to_wstring(std::string(data.begin(), data.end())); 276 | } 277 | catch (std::exception& e) { 278 | util::alert(e.what()); 279 | return L""; 280 | } 281 | } 282 | 283 | bool dataFilled() { 284 | return data.size(); 285 | } 286 | 287 | int sendData(void* data_out, 288 | int bytes_to_read, 289 | int* bytes_read) { 290 | int dataSize = min(bytes_to_read, data.size() - dataPointer); 291 | 292 | #ifdef DEBUG 293 | cout << dataSize << " bytes copied\n"; 294 | #endif 295 | 296 | if (dataSize == 0) { 297 | *bytes_read = 0; 298 | return 0; 299 | } 300 | 301 | std::copy(std::next(data.begin(), dataPointer), 302 | std::next(data.begin(), dataPointer + dataSize), 303 | static_cast(data_out)); 304 | 305 | dataPointer += dataSize; 306 | *bytes_read = dataSize; 307 | 308 | return 1; 309 | } 310 | }; 311 | 312 | std::map<_cef_resource_handler_t*, CefRequestMITMProcess> urlMap; 313 | 314 | int CEF_CALLBACK hook_scheme_handler_read(struct _cef_resource_handler_t* self, 315 | void* data_out, 316 | int bytes_to_read, 317 | int* bytes_read, 318 | struct _cef_callback_t* callback) { 319 | if (urlMap[self].dataFilled()) { 320 | return urlMap[self].sendData(data_out, bytes_to_read, bytes_read); 321 | } 322 | 323 | auto tick = GetTickCount64(); 324 | auto processor = EasyCEFHooks::onHijackRequest(urlMap[self].url); 325 | 326 | if (processor) { 327 | urlMap[self].fillData(self, callback); 328 | urlMap[self].fillData(util::wstring_to_utf8(processor(urlMap[self].getDataStr()))); 329 | 330 | std::cout << "[ BetterNCM Hijack ]" << urlMap[self].url << " hijacked, time used: " << GetTickCount64() - tick 331 | << "ms\n"; 332 | if (urlMap[self].sendData(data_out, bytes_to_read, bytes_read))return 1; 333 | urlMap.erase(self); 334 | return 0; 335 | } 336 | return CAST_TO(origin_scheme_handler_read, hook_scheme_handler_read)( 337 | self, data_out, bytes_to_read, bytes_read, callback); 338 | } 339 | 340 | 341 | _cef_resource_handler_t* CEF_CALLBACK hook_cef_scheme_handler_create( 342 | struct _cef_scheme_handler_factory_t* self, 343 | struct _cef_browser_t* browser, 344 | struct _cef_frame_t* frame, 345 | const cef_string_t* scheme_name, 346 | struct _cef_request_t* request) { 347 | _cef_resource_handler_t* ret = CAST_TO(origin_cef_scheme_handler_create, hook_cef_scheme_handler_create)( 348 | self, browser, frame, scheme_name, request); 349 | CefString url = util::cefFromCEFUserFreeTakeOwnership(request->get_url(request)); 350 | urlMap[ret] = CefRequestMITMProcess{ 351 | url.ToString() 352 | }; 353 | 354 | origin_scheme_handler_read = ret->read_response; 355 | ret->read_response = hook_scheme_handler_read; 356 | return ret; 357 | } 358 | 359 | 360 | void CefRequestMITMProcess::fillData(_cef_resource_handler_t* self, _cef_callback_t* callback) { 361 | if (data.size())return; 362 | auto bytes_read = new int(0); 363 | auto outdata = new char[bytesPerTime]; 364 | _cef_callback_t a{}; 365 | while (CAST_TO(origin_scheme_handler_read, hook_scheme_handler_read) 366 | (self, outdata, bytesPerTime - 1, bytes_read, &a)) { 367 | data.insert(data.end(), outdata, outdata + (*bytes_read)); 368 | datasize += *bytes_read; 369 | 370 | *bytes_read = 0; 371 | } 372 | } 373 | 374 | 375 | int hook_cef_register_scheme_handler_factory( 376 | const cef_string_t* scheme_name, 377 | const cef_string_t* domain_name, 378 | cef_scheme_handler_factory_t* factory) { 379 | origin_cef_scheme_handler_create = factory->create; 380 | factory->create = hook_cef_scheme_handler_create; 381 | 382 | int ret = CAST_TO(origin_cef_register_scheme_handler_factory, hook_cef_register_scheme_handler_factory)( 383 | scheme_name, domain_name, factory); 384 | return ret; 385 | } 386 | 387 | 388 | bool EasyCEFHooks::InstallHooks() { 389 | DetourTransactionBegin(); 390 | DetourUpdateThread(GetCurrentThread()); 391 | 392 | 393 | origin_cef_v8context_get_current_context = DetourFindFunction("libcef.dll", "cef_v8context_get_current_context"); 394 | origin_cef_browser_host_create_browser = DetourFindFunction("libcef.dll", "cef_browser_host_create_browser_sync"); 395 | origin_cef_initialize = DetourFindFunction("libcef.dll", "cef_initialize"); 396 | origin_cef_execute_process = DetourFindFunction("libcef.dll", "cef_execute_process"); 397 | origin_cef_register_scheme_handler_factory = 398 | DetourFindFunction("libcef.dll", "cef_register_scheme_handler_factory"); 399 | 400 | 401 | 402 | if (origin_cef_v8context_get_current_context) 403 | DetourAttach(&origin_cef_v8context_get_current_context, hook_cef_v8context_get_current_context); 404 | 405 | if (origin_cef_browser_host_create_browser) 406 | DetourAttach(&origin_cef_browser_host_create_browser, hook_cef_browser_host_create_browser); 407 | 408 | if (origin_cef_register_scheme_handler_factory) 409 | DetourAttach(&origin_cef_register_scheme_handler_factory, hook_cef_register_scheme_handler_factory); 410 | 411 | if (origin_cef_initialize) 412 | DetourAttach(&origin_cef_initialize, hook_cef_initialize); 413 | 414 | if (origin_cef_execute_process) 415 | DetourAttach(&origin_cef_execute_process, hook_cef_execute_process); 416 | 417 | LONG ret = DetourTransactionCommit(); 418 | 419 | cef_v8context_get_current_context(); 420 | return ret == NO_ERROR; 421 | } 422 | 423 | bool EasyCEFHooks::UninstallHook() { 424 | //DetourTransactionBegin(); 425 | //DetourUpdateThread(GetCurrentThread()); 426 | //DetourDetach(&origin_cef_browser_host_create_browser, hook_cef_browser_host_create_browser); 427 | //DetourDetach(&origin_cef_register_scheme_handler_factory, hook_cef_register_scheme_handler_factory); 428 | //DetourDetach(&origin_cef_initialize, hook_cef_initialize); 429 | //DetourDetach(&origin_cef_v8context_get_current_context, hook_cef_v8context_get_current_context); 430 | 431 | //LONG ret = DetourTransactionCommit(); 432 | return true; 433 | } 434 | 435 | void EasyCEFHooks::executeJavaScript(_cef_frame_t* frame, const std::string& script, const std::string& url) { 436 | CefString exec_script = script; 437 | CefString purl = url; 438 | frame->execute_java_script(frame, exec_script.GetStruct(), purl.GetStruct(), 0); 439 | } 440 | -------------------------------------------------------------------------------- /src/EasyCEFHooks.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include "3rd/libcef/include/cef_v8.h" 4 | #include "3rd/libcef/include/cef_app.h" 5 | #include "3rd/libcef/include/cef_browser.h" 6 | 7 | #include "pystring/pystring.h" 8 | 9 | #include "3rd/libcef/include/capi/cef_client_capi.h" 10 | #include "3rd/libcef/include/capi/cef_app_capi.h" 11 | #include "3rd/libcef/include/internal/cef_export.h" 12 | #include "3rd/libcef/include/capi/cef_v8_capi.h" 13 | #include "utils/utils.h" 14 | #include "shellapi.h" 15 | #include 16 | #define CAST_TO(target,to) reinterpret_cast(target) 17 | 18 | namespace EasyCEFHooks { 19 | bool InstallHooks(); 20 | bool UninstallHook(); 21 | void executeJavaScript(_cef_frame_t* frame, const std::string& script, 22 | const std::string& url = "libeasycef/injext.js"); 23 | extern std::function onKeyEvent; 24 | extern std::function onLoadStart; 25 | extern std::function onAddCommandLine; 26 | extern std::function(std::string)> onHijackRequest; 27 | extern std::function onCommandLine; 28 | }; 29 | 30 | void process_context(cef_v8context_t* context); 31 | -------------------------------------------------------------------------------- /src/ErrorHandler.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "ErrorHandler.h" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include 14 | #include 15 | 16 | #include 17 | 18 | #include "PluginManager.h" 19 | #include "BetterNCMNativePlugin.h" 20 | 21 | #include "utils/BNString.hpp" 22 | #include "utils/utils.h" 23 | 24 | extern NCMProcessType process_type; 25 | 26 | inline const char* u8(const char8_t* s) { 27 | return reinterpret_cast(s); 28 | } 29 | 30 | void show_error_dialog(ErrorDialogParams params) { 31 | // Init window 32 | Fl_Window* window = new Fl_Window(500, 650, "BetterNCM Crashed!"); 33 | 34 | // Display error message 35 | Fl_Box* error_title = new Fl_Box(0, 5, window->w(), 40, u8(u8"抱歉, 网易云音乐崩溃了!")); 36 | error_title->labelsize(20); 37 | error_title->align(FL_ALIGN_CENTER); 38 | 39 | Fl_Box* error_desc = new Fl_Box(0, 35, window->w(), 40, u8(u8"这有可能是因为 BetterNCM 的原因")); 40 | error_desc->labelsize(13); 41 | error_desc->align(FL_ALIGN_CENTER); 42 | 43 | // Display error type and process id 44 | Fl_Box* error_detail = new Fl_Box(20, 70, window->w() - 40, 20, 45 | (new std::string(params.error_type + ", Proc:" + std::to_string(params.error_process_id)))->c_str() 46 | ); 47 | 48 | // Display stack trace 49 | Fl_Group* text_group = new Fl_Group(20, 120, window->w() - 40, 100); 50 | Fl_Text_Buffer* text_buffer = new Fl_Text_Buffer(); 51 | Fl_Text_Display* text_display = new Fl_Text_Display(20, 100, window->w() - 40, 400); 52 | text_display->buffer(text_buffer); 53 | text_group->end(); 54 | text_display->textsize(8); 55 | text_buffer->text(params.stack_trace.c_str()); 56 | 57 | // Display plugin name if available 58 | if (!params.plugin_name.empty()) { 59 | Fl_Box* probable_plugin = new Fl_Box(20, 520, window->w() - 40, 20, 60 | u8(u8"可能的出现问题的插件:") 61 | ); 62 | 63 | Fl_Input* plugin_name_input = new Fl_Input(20, 540, window->w() - 40, 25); 64 | plugin_name_input->value(params.plugin_name.c_str()); 65 | } 66 | 67 | // Display action buttons 68 | Fl_Button* restart_button = new Fl_Button(20, window->h() - 50, (window->w() - 40) / 2 - 5, 25, 69 | u8(u8"重启")); 70 | restart_button->callback([](Fl_Widget* w, void* data) { 71 | auto callback = reinterpret_cast*>(data); 72 | (*callback)(); 73 | }, ¶ms.restart_callback); 74 | 75 | Fl_Button* disable_restart_button = new Fl_Button(restart_button->x() + restart_button->w() + 10, 76 | restart_button->y(), 77 | (window->w() - 40) / 2 - 5, 25, 78 | u8(u8"禁用本体并重启")); 79 | disable_restart_button->callback([](Fl_Widget* w, void* data) { 80 | auto callback = reinterpret_cast*>(data); 81 | (*callback)(); 82 | }, ¶ms.disable_restart_callback); 83 | 84 | Fl_Button* close_button = new Fl_Button(20, restart_button->y() - restart_button->h() - 5, 85 | (window->w() - 40) / 2 - 5, 25, u8(u8"关闭")); 86 | close_button->callback([](Fl_Widget* w, void* data) { 87 | auto callback = reinterpret_cast*>(data); 88 | (*callback)(); 89 | }, ¶ms.close_callback); 90 | 91 | Fl_Button* fix_button = 92 | new Fl_Button(restart_button->x() + disable_restart_button->w() + 10, close_button->y(), 93 | (window->w() - 40) / 2 - 5, 25, u8(u8"尝试自动修复")); 94 | fix_button->callback([](Fl_Widget* w, void* data) { 95 | auto callback = reinterpret_cast*>(data); 96 | (*callback)(); 97 | }, ¶ms.fix_callback); 98 | fix_button->deactivate(); // Disable fix button by default 99 | 100 | if (params.show_fix_button) { 101 | fix_button->activate(); // Enable fix button if requested 102 | } 103 | 104 | 105 | window->resizable(0); 106 | window->color(fl_rgb_color(255, 255, 255)); 107 | window->end(); 108 | window->show(); 109 | window->set_tooltip_window(); 110 | Fl::run(); 111 | } 112 | 113 | 114 | 115 | #include 116 | #include 117 | #include 118 | 119 | #pragma comment(lib, "dbghelp.lib") 120 | 121 | std::wstring GetBacktrace(const EXCEPTION_POINTERS* ExceptionInfo) { 122 | std::wstring info; 123 | wchar_t symbol_mem[sizeof(IMAGEHLP_SYMBOL64) + 256]; 124 | auto symbol = (IMAGEHLP_SYMBOL64*)symbol_mem; 125 | 126 | // Get the context record from the exception information 127 | CONTEXT* contextRecord = ExceptionInfo->ContextRecord; 128 | 129 | // Initialize the symbol handler 130 | SymInitialize(GetCurrentProcess(), nullptr, TRUE); 131 | 132 | // Initialize the stack frame 133 | STACKFRAME64 stackFrame = { 0 }; 134 | 135 | #ifdef _WIN64 136 | stackFrame.AddrPC.Offset = contextRecord->Rip; 137 | stackFrame.AddrPC.Mode = AddrModeFlat; 138 | stackFrame.AddrFrame.Offset = contextRecord->Rbp; 139 | stackFrame.AddrFrame.Mode = AddrModeFlat; 140 | stackFrame.AddrStack.Offset = contextRecord->Rsp; 141 | stackFrame.AddrStack.Mode = AddrModeFlat; 142 | #else 143 | stackFrame.AddrPC.Offset = contextRecord->Eip; 144 | stackFrame.AddrPC.Mode = AddrModeFlat; 145 | stackFrame.AddrFrame.Offset = contextRecord->Ebp; 146 | stackFrame.AddrFrame.Mode = AddrModeFlat; 147 | stackFrame.AddrStack.Offset = contextRecord->Esp; 148 | stackFrame.AddrStack.Mode = AddrModeFlat; 149 | #endif 150 | 151 | DWORD64 displacement = 0; 152 | // Walk the call stack and append each frame to the string 153 | while (StackWalk64( 154 | #ifdef _WIN64 155 | IMAGE_FILE_MACHINE_AMD64 156 | #else 157 | IMAGE_FILE_MACHINE_I386 158 | #endif 159 | 160 | , GetCurrentProcess(), GetCurrentThread(), &stackFrame, contextRecord, 161 | nullptr, SymFunctionTableAccess64, SymGetModuleBase64, nullptr)) { 162 | // Get the module name and offset for this frame 163 | DWORD64 moduleBase = SymGetModuleBase64(GetCurrentProcess(), stackFrame.AddrPC.Offset); 164 | wchar_t moduleName[MAX_PATH]; 165 | GetModuleFileNameW((HMODULE)moduleBase, moduleName, MAX_PATH); 166 | DWORD64 offset = stackFrame.AddrPC.Offset - moduleBase; 167 | 168 | symbol->SizeOfStruct = sizeof(IMAGEHLP_SYMBOL64); 169 | symbol->MaxNameLength = 255; 170 | 171 | wchar_t name[256] = {}; 172 | SymGetSymFromAddr64(GetCurrentProcess(), stackFrame.AddrPC.Offset, &displacement, symbol); 173 | UnDecorateSymbolNameW(BNString(symbol->Name).c_str(), name, 256, UNDNAME_COMPLETE); 174 | 175 | // Append the frame to the string 176 | wchar_t frameInfo[1024]; 177 | swprintf_s(frameInfo, L"%s + %I64X", moduleName, offset); 178 | info += std::wstring(frameInfo) + std::wstring(L"(") + std::wstring(name) + std::wstring(L")\n"); 179 | } 180 | 181 | // Cleanup the symbol handler 182 | SymCleanup(GetCurrentProcess()); 183 | 184 | // Return the backtrace string 185 | return info; 186 | } 187 | 188 | std::string GetExceptionName(EXCEPTION_POINTERS* ExceptionInfo) { 189 | std::string exceptionName; 190 | switch (ExceptionInfo->ExceptionRecord->ExceptionCode) { 191 | case EXCEPTION_ACCESS_VIOLATION: 192 | exceptionName = "ACCESS_VIOLATION"; 193 | break; 194 | case EXCEPTION_ARRAY_BOUNDS_EXCEEDED: 195 | exceptionName = "ARRAY_BOUNDS_EXCEEDED"; 196 | break; 197 | case EXCEPTION_BREAKPOINT: 198 | exceptionName = "BREAKPOINT"; 199 | break; 200 | case EXCEPTION_DATATYPE_MISALIGNMENT: 201 | exceptionName = "DATATYPE_MISALIGNMENT"; 202 | break; 203 | case EXCEPTION_FLT_DENORMAL_OPERAND: 204 | exceptionName = "FLT_DENORMAL_OPERAND"; 205 | break; 206 | case EXCEPTION_FLT_DIVIDE_BY_ZERO: 207 | exceptionName = "FLT_DIVIDE_BY_ZERO"; 208 | break; 209 | case EXCEPTION_FLT_INEXACT_RESULT: 210 | exceptionName = "FLT_INEXACT_RESULT"; 211 | break; 212 | case EXCEPTION_FLT_INVALID_OPERATION: 213 | exceptionName = "FLT_INVALID_OPERATION"; 214 | break; 215 | case EXCEPTION_FLT_OVERFLOW: 216 | exceptionName = "FLT_OVERFLOW"; 217 | break; 218 | case EXCEPTION_FLT_STACK_CHECK: 219 | exceptionName = "FLT_STACK_CHECK"; 220 | break; 221 | case EXCEPTION_FLT_UNDERFLOW: 222 | exceptionName = "FLT_UNDERFLOW"; 223 | break; 224 | case EXCEPTION_ILLEGAL_INSTRUCTION: 225 | exceptionName = "ILLEGAL_INSTRUCTION"; 226 | break; 227 | case EXCEPTION_IN_PAGE_ERROR: 228 | exceptionName = "IN_PAGE_ERROR"; 229 | break; 230 | case EXCEPTION_INT_DIVIDE_BY_ZERO: 231 | exceptionName = "INT_DIVIDE_BY_ZERO"; 232 | break; 233 | case EXCEPTION_INT_OVERFLOW: 234 | exceptionName = "INT_OVERFLOW"; 235 | break; 236 | case EXCEPTION_INVALID_DISPOSITION: 237 | exceptionName = "INVALID_DISPOSITION"; 238 | break; 239 | case EXCEPTION_NONCONTINUABLE_EXCEPTION: 240 | exceptionName = "NONCONTINUABLE_EXCEPTION"; 241 | break; 242 | case EXCEPTION_PRIV_INSTRUCTION: 243 | exceptionName = "PRIV_INSTRUCTION"; 244 | break; 245 | case EXCEPTION_SINGLE_STEP: 246 | exceptionName = "SINGLE_STEP"; 247 | break; 248 | case EXCEPTION_STACK_OVERFLOW: 249 | exceptionName = "STACK_OVERFLOW"; 250 | break; 251 | default: 252 | exceptionName = "UNKNOWN"; 253 | break; 254 | } 255 | return exceptionName; 256 | } 257 | 258 | std::wstring PrintExceptionInfo(EXCEPTION_POINTERS* ExceptionInfo) { 259 | std::wostringstream Stream; 260 | 261 | EXCEPTION_RECORD* ExceptionRecord = ExceptionInfo->ExceptionRecord; 262 | CONTEXT* ContextRecord = ExceptionInfo->ContextRecord; 263 | 264 | Stream << L"Exception flags: 0x" << std::hex << ExceptionRecord->ExceptionFlags << std::endl; 265 | Stream << L"Exception address: 0x" << std::hex << ExceptionRecord->ExceptionAddress << std::endl; 266 | 267 | #ifdef _WIN64 268 | Stream << L" RIP: 0x" << std::hex << ContextRecord->Rip << std::endl; 269 | Stream << L" RSP: 0x" << std::hex << ContextRecord->Rsp << std::endl; 270 | Stream << L" RBP: 0x" << std::hex << ContextRecord->Rbp << std::endl; 271 | #else 272 | Stream << L" EIP: 0x" << std::hex << ContextRecord->Eip << std::endl; 273 | Stream << L" ESP: 0x" << std::hex << ContextRecord->Esp << std::endl; 274 | Stream << L" EBP: 0x" << std::hex << ContextRecord->Ebp << std::endl; 275 | #endif 276 | 277 | 278 | Stream << L"Backtrace:\n See console for detail" << std::endl; 279 | 280 | return Stream.str(); 281 | } 282 | 283 | extern BNString datapath; 284 | 285 | LONG WINAPI BNUnhandledExceptionFilter(EXCEPTION_POINTERS* ExceptionInfo) { 286 | HWND ncmWin = FindWindow(L"OrpheusBrowserHost", nullptr); 287 | 288 | #define IGNORE_ERROR_EXIT(code) if(ExceptionInfo->ExceptionRecord->ExceptionCode==code){ util::killNCM(); return EXCEPTION_EXECUTE_HANDLER;} 289 | #define IGNORE_ERROR_RESTART(code) if(ExceptionInfo->ExceptionRecord->ExceptionCode==code){ util::restartNCM(); return EXCEPTION_EXECUTE_HANDLER; } 290 | #define IGNORE_ERROR_PASS_TO_NCM(code) if(ExceptionInfo->ExceptionRecord->ExceptionCode==code){ return EXCEPTION_CONTINUE_SEARCH; } 291 | #define IGNORE_ERROR_AUTO(code) if(ExceptionInfo->ExceptionRecord->ExceptionCode==code){ if(ncmWin) util::restartNCM(); else util::killNCM(); return EXCEPTION_EXECUTE_HANDLER;}; 292 | #define IGNORE_ERROR_IGNORE(code) if(ExceptionInfo->ExceptionRecord->ExceptionCode==code){ return EXCEPTION_CONTINUE_EXECUTION;}; 293 | 294 | IGNORE_ERROR_AUTO(0xe0000008); // Restart UNKNOWN 295 | IGNORE_ERROR_EXIT(0x80000003); // Ignore BREAKPOINT 296 | 297 | std::stringstream ss; 298 | ss << "-------- BetterNCM CrashReport -------\nBackTrace: \n\n" << BNString(GetBacktrace(ExceptionInfo)).utf8(); 299 | 300 | std::string backtrace(ss.str()); 301 | 302 | const auto plugins = PluginManager::getAllPlugins(); 303 | 304 | const auto probable_crashed_plugin = std::ranges::find_if(plugins, [&](const std::shared_ptr& val) { 305 | return backtrace.find(val->manifest.slug) != std::string::npos; 306 | }); 307 | 308 | const auto pluginName = probable_crashed_plugin == plugins.end() ? std::string("Unknown") : (*probable_crashed_plugin)->manifest.name; 309 | 310 | 311 | show_error_dialog({ 312 | .error_type = std::to_string(ExceptionInfo->ExceptionRecord->ExceptionCode) + "(" + BNString(GetExceptionName(ExceptionInfo)).utf8() + ")", 313 | .error_process_id = process_type, 314 | .stack_trace = ss.str(), 315 | .plugin_name = pluginName, 316 | 317 | .restart_callback = []() { 318 | util::restartNCM(); 319 | }, 320 | .disable_restart_callback = []() { 321 | SetEnvironmentVariable(L"BETTERNCM_DISABLED_FLAG", L"1"); 322 | util::restartNCM(); 323 | }, 324 | .close_callback = []() { 325 | util::killNCM(); 326 | }, 327 | .fix_callback = [=]() { 328 | auto list = PluginManager::getDisableList(); 329 | const auto slug = (*probable_crashed_plugin)->manifest.slug; 330 | if (std::ranges::find(list, slug) == list.end()) { 331 | list.push_back(slug); 332 | std::ofstream ofs(datapath + L"/disable_list.txt"); 333 | for (const auto&v : list) { 334 | ofs << v << std::endl; 335 | } 336 | ofs.close(); 337 | util::restartNCM(); 338 | } else { 339 | util::alert("自动修复失败,程序即将重启"); 340 | util::restartNCM(); 341 | } 342 | }, 343 | .show_fix_button = probable_crashed_plugin != plugins.end(), 344 | }); 345 | 346 | return EXCEPTION_EXECUTE_HANDLER; 347 | } 348 | -------------------------------------------------------------------------------- /src/ErrorHandler.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | 4 | struct ErrorDialogParams { 5 | std::string error_type; 6 | int error_process_id; 7 | std::string stack_trace; 8 | std::string plugin_name; 9 | std::function restart_callback; 10 | std::function disable_restart_callback; 11 | std::function close_callback; 12 | std::function fix_callback; 13 | bool show_fix_button = true; // default show fix button 14 | }; 15 | 16 | void show_error_dialog(ErrorDialogParams params); -------------------------------------------------------------------------------- /src/PluginManager.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "PluginManager.h" 3 | 4 | #include 5 | 6 | #include "resource.h" 7 | 8 | 9 | extern const std::string version; 10 | std::map> plugin_native_apis; 11 | 12 | std::vector> PluginManager::packedPlugins; 13 | 14 | auto ncmVer = util::getNCMExecutableVersion(); 15 | const unsigned short ncmVersion[3] = { ncmVer.major, ncmVer.minor, ncmVer.patch }; 16 | namespace fs = std::filesystem; 17 | 18 | int addNativeAPI(NativeAPIType args[], int argsNum, const char* identifier, char* function(void**)) { 19 | plugin_native_apis[std::string(identifier)] = 20 | std::make_shared(PluginNativeAPI{ args, argsNum, std::string(identifier), function }); 21 | return true; 22 | } 23 | 24 | int addNativeAPIEmpty(NativeAPIType args[], int argsNum, const char* identifier, char* function(void**)) { 25 | return false; 26 | } 27 | 28 | extern BNString datapath; 29 | 30 | void from_json(const nlohmann::json& j, RemotePlugin& plugin) { 31 | plugin.name = j.value("name", "unknown"); 32 | plugin.author = j.value("author", "unknown"); 33 | plugin.version = j.value("version", "unknown"); 34 | plugin.description = j.value("description", "unknown"); 35 | plugin.betterncm_version = j.value("betterncm_version", "unknown"); 36 | plugin.preview = j.value("preview", "unknown"); 37 | plugin.slug = j.value("slug", "unknown"); 38 | plugin.update_time = j.value("update_time", 0); 39 | plugin.publish_time = j.value("publish_time", 0); 40 | plugin.repo = j.value("repo", "unknown"); 41 | plugin.file = j.value("file", "unknown"); 42 | plugin.file_url = j.value("file-url", "unknown"); 43 | plugin.force_install = j.value("force-install", false); 44 | plugin.force_uninstall = j.value("force-uninstall", false); 45 | plugin.force_update = j.value("force-update", "< 0.0.0"); 46 | } 47 | 48 | 49 | void from_json(const nlohmann::json& j, PluginManifest& p) { 50 | p.manifest_version = j.value("manifest_version", 0); 51 | p.name = j.value("name", "unknown"); 52 | 53 | auto getSlugName = [](std::string name) { 54 | if (name.empty()) return name; 55 | std::replace(name.begin(), name.end(), ' ', '-'); 56 | try { 57 | std::erase_if(name, [](char c) { return c > 0 && c < 255 && !isalnum(c) && c != '-'; }); 58 | } 59 | catch (std::exception& e) { 60 | } 61 | return name; 62 | }; 63 | 64 | p.slug = j.value("slug", getSlugName(p.name)); 65 | p.version = j.value("version", "unknown"); 66 | p.author = j.value("author", "unknown"); 67 | p.description = j.value("description", "unknown"); 68 | p.betterncm_version = j.value("betterncm_version", ">=1.0.0"); 69 | p.preview = j.value("preview", "unknown"); 70 | p.injects = j.value("injects", std::map>>()); 71 | p.startup_script = j.value("startup_script", "startup_script.js"); 72 | p.ncm3Compatible = j.value("ncm3-compatible", false); 73 | p.ncm_version_req = j.value("ncm-version-req", "> 2.10.2"); 74 | 75 | p.hijacks.clear(); 76 | if (j.count("hijacks")) { 77 | const auto& hijack_version_map = j.at("hijacks"); 78 | for (auto version_it = hijack_version_map.begin(); version_it != hijack_version_map.end(); ++version_it) { 79 | const auto& hijack_version = version_it.key(); 80 | HijackURLMap hijack_url_map; 81 | const auto& hijack_url_map_json = version_it.value(); 82 | for (auto url_it = hijack_url_map_json.begin(); url_it != hijack_url_map_json.end(); ++url_it) { 83 | const auto& hijack_url = url_it.key(); 84 | std::vector hijack_actions; 85 | auto& hijack_actions_json = url_it.value(); 86 | 87 | auto process_hijack_entry = [](nlohmann::json hijack_action_json) -> HijackAction { 88 | const std::string type = hijack_action_json.at("type").get(); 89 | const std::string id = hijack_action_json.value("id", ""); 90 | 91 | if (type == "regex") { 92 | return HijackActionRegex{ 93 | id , 94 | hijack_action_json.at("from").get(), 95 | hijack_action_json.at("to").get() 96 | }; 97 | } 98 | 99 | if (type == "replace") { 100 | return HijackActionReplace{ 101 | id , 102 | hijack_action_json.at("from").get(), 103 | hijack_action_json.at("to").get() 104 | }; 105 | } 106 | 107 | if (type == "append") { 108 | return HijackActionAppend{ 109 | id , 110 | hijack_action_json.at("code").get() 111 | }; 112 | } 113 | 114 | if (type == "prepend") { 115 | return HijackActionPrepend{ 116 | id , 117 | hijack_action_json.at("code").get() 118 | }; 119 | } 120 | }; 121 | 122 | if (url_it->is_object()) { 123 | hijack_actions.push_back(process_hijack_entry(url_it.value())); 124 | } 125 | else { 126 | for (auto action_it = hijack_actions_json.begin(); action_it != hijack_actions_json.end(); ++action_it) 127 | hijack_actions.push_back(process_hijack_entry(*action_it)); 128 | } 129 | 130 | hijack_url_map[hijack_url] = hijack_actions; 131 | } 132 | p.hijacks[hijack_version] = hijack_url_map; 133 | } 134 | } 135 | 136 | p.native_plugin = j.value("native_plugin", "\0"); 137 | } 138 | 139 | Plugin::Plugin(PluginManifest manifest, 140 | std::filesystem::path runtime_path, 141 | std::optional packed_file_path) 142 | : manifest(std::move(manifest)), runtime_path(std::move(runtime_path)) 143 | , packed_file_path(std::move(packed_file_path)) { 144 | } 145 | 146 | Plugin::~Plugin() { 147 | /*if (this->hNativeDll) { 148 | this->hNativeDll = nullptr; 149 | FreeLibrary(this->hNativeDll); 150 | }*/ 151 | } 152 | 153 | void Plugin::loadNativePluginDll(NCMProcessType processType) { 154 | 155 | if (manifest.native_plugin[0] != '\0') { 156 | try { 157 | HMODULE hDll = LoadLibrary((runtime_path / manifest.native_plugin).wstring().c_str()); 158 | if (!hDll) { 159 | const fs::path x64path = runtime_path / fs::path(manifest.native_plugin).parent_path() / (fs::path(manifest.native_plugin).filename().string() + ".x64.dll"); 160 | std::cout << "NativePlugin x64path: " << (x64path.string()); 161 | hDll = LoadLibrary(x64path.wstring().c_str()); 162 | } 163 | 164 | if (!hDll) { 165 | throw std::exception("dll doesn't exists or is not adapted to this arch."); 166 | } 167 | 168 | auto BetterNCMPluginMain = (BetterNCMPluginMainFunc)GetProcAddress(hDll, "BetterNCMPluginMain"); 169 | if (!BetterNCMPluginMain) { 170 | throw std::exception("dll is not a betterncm plugin dll"); 171 | } 172 | 173 | 174 | auto pluginAPI = new BetterNCMNativePlugin::PluginAPI{ 175 | processType & Renderer ? addNativeAPI : addNativeAPIEmpty, 176 | version.c_str(), 177 | processType, 178 | &ncmVersion 179 | }; // leaked but not a big problem 180 | 181 | BetterNCMPluginMain(pluginAPI); 182 | this->hNativeDll = hDll; 183 | } 184 | catch (std::exception& e) { 185 | util::write_file_text(datapath.utf8() + "/log.log", 186 | std::string("\n[" + manifest.slug + "] Plugin Native Plugin load Error: ") + (e. 187 | what()), true); 188 | } 189 | } 190 | } 191 | 192 | std::optional Plugin::getStartupScript() 193 | { 194 | if(fs::exists(runtime_path / manifest.startup_script)) 195 | return util::read_to_string_utf8(runtime_path / manifest.startup_script).utf8(); 196 | return std::nullopt; 197 | } 198 | 199 | void PluginManager::performForceInstallAndUpdateAsync(const std::string& source) 200 | { 201 | std::thread([source]() { 202 | performForceInstallAndUpdateSync(source); 203 | }).detach(); 204 | } 205 | 206 | void PluginManager::loadAll() { 207 | unloadAll(); 208 | loadRuntime(); 209 | } 210 | 211 | void PluginManager::unloadAll() { 212 | plugin_native_apis.clear(); 213 | packedPlugins.clear(); 214 | } 215 | 216 | void PluginManager::loadRuntime() { 217 | packedPlugins = loadInPath(datapath + L"/plugins_runtime"); 218 | } 219 | 220 | void PluginManager::extractPackedPlugins() { 221 | util::write_file_text(datapath + L"/PLUGIN_EXTRACTING_LOCK.lock", ""); 222 | 223 | const auto disable_list = PluginManager::getDisableList(); 224 | 225 | if (fs::exists(datapath + L"/plugins_runtime")) { 226 | for (auto file : fs::directory_iterator(datapath + L"/plugins_runtime")) { 227 | try { 228 | PluginManifest manifest; 229 | auto modManifest = nlohmann::json::parse(util::read_to_string(file.path() / "manifest.json")); 230 | modManifest.get_to(manifest); 231 | 232 | if (manifest.native_plugin[0] == '\0') 233 | remove_all(file.path()); 234 | else { 235 | std::error_code ec; 236 | fs::remove(file.path() / manifest.native_plugin, ec); 237 | if (ec.value() == 0)remove_all(file.path()); 238 | } 239 | } 240 | catch (std::exception& e) { 241 | remove_all(file.path()); 242 | } 243 | } 244 | } 245 | 246 | fs::create_directories(datapath + L"/plugins_runtime"); 247 | static const bool isNCM3 = util::getNCMExecutableVersion().major == 3; 248 | 249 | for (auto file : fs::directory_iterator(datapath + L"/plugins")) { 250 | BNString path = file.path().wstring(); 251 | if (path.endsWith(L".plugin")) { 252 | try { 253 | 254 | PluginManifest manifest; 255 | 256 | const auto extractPlugin = [&]() { 257 | if(fs::exists(datapath.utf8() + "/plugins_runtime/tmp")) 258 | fs::remove_all(datapath.utf8() + "/plugins_runtime/tmp"); 259 | 260 | const auto zip = zip_open(path.utf8().c_str(), 0, 'r'); 261 | 262 | auto code = zip_entry_open(zip, "manifest.json"); 263 | if (code < 0) throw std::exception("manifest.json not found in plugin"); 264 | 265 | char* buf = nullptr; 266 | size_t size = 0; 267 | code = zip_entry_read(zip, (void**) & buf, &size); 268 | if (code < 0) throw std::exception("manifest.json read error"); 269 | zip_entry_close(zip); 270 | zip_close(zip); 271 | 272 | const auto modManifest = nlohmann::json::parse(std::string(buf, size)); 273 | modManifest.get_to(manifest); 274 | }; 275 | 276 | extractPlugin(); 277 | if (manifest.name == "PluginMarket") { 278 | if (semver::version(manifest.version) < semver::version("0.7.2")) { 279 | util::extractPluginMarket(); 280 | extractPlugin(); 281 | } 282 | } 283 | 284 | if (std::ranges::find(disable_list, manifest.slug) != disable_list.end() || 285 | ( 286 | isNCM3 && 287 | !manifest.ncm3Compatible // duplicated / ncm3 but not ncm3-compatible / do not meet version req 288 | ) || 289 | ( 290 | !semver::range::satisfies( 291 | util::getNCMExecutableVersion(), manifest.ncm_version_req 292 | ) 293 | ) 294 | ) { 295 | continue; 296 | } 297 | 298 | if (manifest.manifest_version == 1) { 299 | BNString realPath = datapath + L"/plugins_runtime/" + BNString(manifest.slug); 300 | 301 | std::error_code ec; 302 | if (fs::exists(realPath.utf8()) && manifest.native_plugin[0] == '\0') 303 | fs::remove_all(realPath.utf8(), ec); 304 | 305 | const auto code = zip_extract(path.utf8().c_str(), realPath.utf8().c_str(), nullptr, nullptr); 306 | if (code != 0) throw std::exception(("unzip err code:" + std::to_string(code)).c_str()); 307 | 308 | util::write_file_text(realPath + L"/.plugin.path.meta", 309 | pystring::slice(path, datapath.length())); 310 | } 311 | else { 312 | throw std::exception("Unsupported manifest version."); 313 | } 314 | } 315 | catch (std::exception& e) { 316 | std::cout << BNString::fromGBK(std::string("\n[BetterNCM] Plugin Loading Error: ") + (e.what())).utf8() 317 | + "\n"; 318 | fs::remove_all(datapath.utf8() + "/plugins_runtime/tmp"); 319 | } 320 | } 321 | } 322 | 323 | fs::remove(datapath + L"/PLUGIN_EXTRACTING_LOCK.lock"); 324 | } 325 | 326 | std::vector> PluginManager::getDevPlugins() 327 | { 328 | return loadInPath(datapath + L"/plugins_dev"); 329 | } 330 | 331 | 332 | std::vector> PluginManager::getAllPlugins() 333 | { 334 | std::vector> tmp = getPackedPlugins(); 335 | auto devPlugins = getDevPlugins(); 336 | tmp.insert(tmp.end(), devPlugins.begin(), devPlugins.end()); 337 | 338 | std::sort(tmp.begin(), tmp.end(), [](const auto& a, const auto& b) { 339 | return a->manifest.slug < b->manifest.slug; 340 | }); 341 | 342 | auto last = std::unique(tmp.begin(), tmp.end(), [](const auto& a, const auto& b) { 343 | return a->manifest.slug == b->manifest.slug; 344 | }); 345 | 346 | tmp.erase(last, tmp.end()); 347 | 348 | return tmp; 349 | } 350 | 351 | std::vector> PluginManager::getPackedPlugins() 352 | { 353 | return PluginManager::packedPlugins; 354 | } 355 | 356 | std::vector PluginManager::getDisableList() 357 | { 358 | std::vector disable_list; 359 | std::ifstream file(datapath + L"/disable_list.txt"); 360 | if (!file.is_open()) { 361 | return disable_list; 362 | } 363 | 364 | std::string line; 365 | while (std::getline(file, line)) { 366 | // Trim leading and trailing white space characters 367 | auto isspace = [](char c) { return std::isspace(static_cast(c)); }; 368 | line.erase(line.begin(), std::find_if_not(line.begin(), line.end(), isspace)); 369 | line.erase(std::find_if_not(line.rbegin(), line.rend(), isspace).base(), line.end()); 370 | 371 | disable_list.push_back(line); 372 | } 373 | file.close(); 374 | return disable_list; 375 | } 376 | 377 | std::vector> PluginManager::loadInPath(const std::wstring& path) { 378 | std::vector> plugins; 379 | if (fs::exists(path)) 380 | for (const auto& file : fs::directory_iterator(path)) { 381 | try { 382 | if (fs::exists(file.path() / "manifest.json")) { 383 | auto json = nlohmann::json::parse(util::read_to_string(file.path() / "manifest.json")); 384 | PluginManifest manifest; 385 | json.get_to(manifest); 386 | 387 | std::optional packed_file_path = std::nullopt; 388 | auto plugin_meta_path = file.path() / ".plugin.path.meta"; 389 | if (fs::exists(plugin_meta_path)) packed_file_path = util::read_to_string(plugin_meta_path); 390 | plugins.push_back(std::make_shared(manifest, file.path(), packed_file_path)); 391 | } 392 | } 393 | catch (std::exception& e) { 394 | util::write_file_text(datapath.utf8() + "log.log", 395 | std::string("\n[" + file.path().string() + "] Plugin Native load Error: ") + (e. 396 | what()), true); 397 | } 398 | } 399 | 400 | return plugins; 401 | } 402 | 403 | void PluginManager::performForceInstallAndUpdateSync(const std::string& source, bool isRetried) 404 | { 405 | try { 406 | const auto body = util::FetchWebContent(source + "plugins.json"); 407 | nlohmann::json plugins_json = nlohmann::json::parse(body); 408 | std::vector remote_plugins; 409 | plugins_json.get_to(remote_plugins); 410 | const auto local_plugins = getPackedPlugins(); 411 | 412 | for (const auto& remote_plugin : remote_plugins) { 413 | const auto local = std::find_if(local_plugins.begin(), local_plugins.end(), [&remote_plugin](const auto& local) { 414 | return remote_plugin.slug == local->manifest.slug; 415 | }); 416 | 417 | // output log 418 | std::cout << "\n[ BetterNCM ] [Plugin Remote Tasks] Plugin " << remote_plugin.slug 419 | << " FUni: " << (remote_plugin.force_uninstall ? "true" : "false") 420 | << " FUpd: " << remote_plugin.force_update << "\n"; 421 | 422 | if (local != local_plugins.end()) { 423 | auto localVer = (*local)->manifest.version; 424 | std::cout << "\t\tlocal: " << localVer << "\n\t\t - at " << (*local)->runtime_path << std::endl; 425 | 426 | auto packed_file_path_relative = (*local)->packed_file_path; 427 | if (packed_file_path_relative.has_value()) { 428 | std::cout << "\t\t - at " << packed_file_path_relative.value() << std::endl; 429 | auto origin_packed_plugin_path = datapath.utf8() / packed_file_path_relative.value(); 430 | if (remote_plugin.force_uninstall) { 431 | fs::remove(origin_packed_plugin_path); 432 | std::cout << "\t\t - Force uninstall performed.\n"; 433 | std::cout << std::endl; 434 | } 435 | 436 | try { 437 | if ((remote_plugin.force_update == "*" || semver::range::satisfies(semver::from_string(localVer), remote_plugin.force_update)) && 438 | localVer != remote_plugin.version) { 439 | std::cout << "\t\t - Force update: Downloading...\n"; 440 | 441 | const auto dest = datapath + L"/plugins/" + BNString(remote_plugin.file); 442 | if (fs::exists(dest)) fs::remove(dest); 443 | if (fs::exists(origin_packed_plugin_path)) fs::remove(origin_packed_plugin_path); 444 | util::DownloadFile(source + remote_plugin.file_url, dest); 445 | std::cout << "\t\t - Force update performed.\n"; 446 | std::cout << std::endl; 447 | } 448 | } 449 | catch (std::exception& e) { 450 | std::cout << "[ BetterNCM ] [Plugin Remote Tasks] Failed to check update for remote plugin " << remote_plugin.slug << ": " << e.what() << std::endl; 451 | } 452 | } 453 | } 454 | } 455 | } 456 | catch (std::exception& e) { 457 | if(isRetried) { 458 | std::cout << "[ BetterNCM ] [Plugin Remote Tasks] Failed to check update on " << source << ": " << e.what() << "." << std::endl; 459 | }else { 460 | const auto onlineConfig = util::FetchWebContent("https://microblock.cc/bncm-config.txt"); 461 | const auto marketConf = onlineConfig.split(L"\n")[0]; 462 | std::cout << "[ BetterNCM ] [Plugin Remote Tasks] Failed to check update on " << source << ": " << e.what() << " , fallbacking to default..." << std::endl; 463 | performForceInstallAndUpdateSync(BNString(marketConf).utf8(), true); 464 | } 465 | 466 | } 467 | 468 | } 469 | -------------------------------------------------------------------------------- /src/PluginManager.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | 6 | #define NATIVE_PLUGIN_CPP_EXTENSIONS 7 | #include 8 | #include 9 | #include 10 | 11 | 12 | 13 | struct PluginNativeAPI { 14 | NativeAPIType* args; 15 | int argsNum; 16 | const std::string identifier; 17 | char* (*function)(void**); 18 | }; 19 | 20 | extern std::map> plugin_native_apis; 21 | 22 | struct HijackActionBase { 23 | std::string id; 24 | }; 25 | 26 | struct HijackActionReplace: HijackActionBase { 27 | std::string from; 28 | std::string to; 29 | }; 30 | 31 | struct HijackActionRegex: HijackActionBase { 32 | std::string from; 33 | std::string to; 34 | }; 35 | 36 | struct HijackActionPrepend: HijackActionBase { 37 | std::string code; 38 | }; 39 | 40 | struct HijackActionAppend: HijackActionBase { 41 | std::string code; 42 | }; 43 | 44 | typedef std::variant HijackAction; 45 | 46 | struct PluginHijackAction { 47 | HijackAction action; 48 | std::string plugin_slug; 49 | std::string url; 50 | }; 51 | 52 | typedef std::map> HijackURLMap; 53 | typedef std::map HijackVersionMap; 54 | 55 | struct PluginManifest { 56 | int manifest_version; 57 | std::string name; 58 | std::string slug; 59 | std::string version; 60 | std::string author; 61 | std::string description; 62 | std::string betterncm_version; 63 | std::string preview; 64 | std::string startup_script; 65 | bool ncm3Compatible; 66 | std::string ncm_version_req; 67 | 68 | std::map>> injects; 69 | HijackVersionMap hijacks; 70 | std::string native_plugin; 71 | }; 72 | 73 | 74 | void from_json(const nlohmann::json& j, PluginManifest& p); 75 | 76 | class Plugin { 77 | HMODULE hNativeDll=nullptr; 78 | 79 | public: 80 | Plugin(PluginManifest manifest, 81 | std::filesystem::path runtime_path, 82 | std::optional packed_file_path); 83 | ~Plugin(); 84 | PluginManifest manifest; 85 | std::filesystem::path runtime_path; 86 | std::optional packed_file_path; 87 | void loadNativePluginDll(NCMProcessType processType); 88 | std::optional getStartupScript(); 89 | }; 90 | 91 | struct RemotePlugin { 92 | std::string name; 93 | std::string author; 94 | std::string version; 95 | std::string description; 96 | std::string betterncm_version; 97 | std::string preview; 98 | std::string slug; 99 | uint64_t update_time; 100 | uint64_t publish_time; 101 | std::string repo; 102 | std::string file; 103 | std::string file_url; 104 | boolean force_install; 105 | boolean force_uninstall; 106 | std::string force_update; 107 | }; 108 | 109 | 110 | class PluginManager { 111 | static std::vector> loadInPath(const std::wstring& path); 112 | static std::vector> packedPlugins; 113 | static void performForceInstallAndUpdateSync(const std::string& source, bool isRetried = false); 114 | public: 115 | static void performForceInstallAndUpdateAsync(const std::string& source); 116 | static void loadAll(); 117 | static void unloadAll(); 118 | static void loadRuntime(); 119 | static void extractPackedPlugins(); 120 | static std::vector> getDevPlugins(); 121 | static std::vector> getAllPlugins(); 122 | static std::vector> getPackedPlugins(); 123 | static std::vector getDisableList(); 124 | }; 125 | 126 | using BetterNCMPluginMainFunc = int(*)(BetterNCMNativePlugin::PluginAPI*); 127 | -------------------------------------------------------------------------------- /src/dllmain.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "pystring/pystring.h" 3 | #include "EasyCEFHooks.h" 4 | #include 5 | #include "App.h" 6 | #include "resource.h" 7 | #include "utils/utils.h" 8 | #include 9 | #include 10 | #pragma comment(lib, "dbghelp.lib") 11 | #pragma comment(lib, "Wininet.lib") 12 | 13 | std::string script; 14 | 15 | void message(const std::string& title, const std::string& text) { 16 | MessageBox(nullptr, util::s2ws(text).c_str(), util::s2ws(title).c_str(), 0); 17 | } 18 | 19 | extern BNString datapath; 20 | 21 | NCMProcessType process_type = Undetected; 22 | LONG WINAPI BNUnhandledExceptionFilter(EXCEPTION_POINTERS* ExceptionInfo); 23 | extern HMODULE g_hModule; 24 | void bncmMain() { 25 | SetUnhandledExceptionFilter(BNUnhandledExceptionFilter); 26 | 27 | 28 | try { 29 | if (!getenv("BETTERNCM_DISABLED_FLAG")) { 30 | if (util::get_command_line().includes(L"--type=renderer"))process_type = Renderer; 31 | else if (util::get_command_line().includes(L"--type=gpu-process"))process_type = GpuProcess; 32 | else if (util::get_command_line().includes(L"--type=utility"))process_type = Utility; 33 | else process_type = Main; 34 | namespace fs = std::filesystem; 35 | 36 | // Pick data folder 37 | if (getenv("BETTERNCM_PROFILE")) { 38 | datapath = util::getEnvironment("BETTERNCM_PROFILE"); 39 | } 40 | else { 41 | datapath = "C:\\betterncm"; // 不再向前兼容 42 | } 43 | 44 | if (process_type == Main) { 45 | AllocConsole(); 46 | freopen("CONOUT$", "w", stdout); 47 | ShowWindow(GetConsoleWindow(), SW_HIDE); 48 | 49 | std::filesystem::path datapathPath((std::wstring)datapath); 50 | 51 | if (datapathPath.has_root_path() && !datapathPath.has_relative_path()) { 52 | util::alert(L"BetterNCM 数据目录不能在磁盘根目录!请将数据目录放在其他位置。\n修改数据目录后可能需要重启\n\nBetterNCM 将不会运行"); 53 | return; 54 | } 55 | 56 | std::wcout << L"Data folder picked: " << datapath << "\n"; 57 | 58 | if (static_cast(fs::status((std::wstring)datapath).permissions()) & static_cast( 59 | std::filesystem::perms::owner_write)) { 60 | // Create data folder 61 | fs::create_directories(datapath + L"/plugins"); 62 | 63 | // PluginMarket 64 | if (!fs::exists(datapath + L"/plugins/PluginMarket.plugin")) { 65 | util::extractPluginMarket(); 66 | } 67 | 68 | // Inject NCM 69 | auto app = new App(); 70 | app->Init(); 71 | } 72 | else { 73 | util::alert(L"BetterNCM访问数据目录失败!可能需要以管理员身份运行或更改数据目录。\n\nBetterNCM将不会运行"); 74 | } 75 | } 76 | else if (process_type == Renderer) { 77 | EasyCEFHooks::InstallHooks(); 78 | 79 | PluginManager::loadAll(); 80 | SetUnhandledExceptionFilter(BNUnhandledExceptionFilter); 81 | for (auto& plugin : PluginManager::getAllPlugins()) { 82 | plugin->loadNativePluginDll(process_type); 83 | } 84 | } 85 | else { 86 | PluginManager::loadAll(); 87 | SetUnhandledExceptionFilter(BNUnhandledExceptionFilter); 88 | for (auto& plugin : PluginManager::getAllPlugins()) { 89 | plugin->loadNativePluginDll(process_type); 90 | } 91 | } 92 | } 93 | 94 | } 95 | catch (std::exception& e) { 96 | std::optional probableReason; 97 | const auto systemReason = std::string(e.what()); 98 | 99 | if(systemReason.find("Unicode") != std::string::npos) { 100 | probableReason = "这很有可能是因为你修改了默认数据位置导致的,请在 BetterNCM Installer 内将其改回默认位置:C:\\betterncm\n\nThis is probably because you edited the default data location. Please change it back to the default location in BetterNCM Installer: C:\\betterncm"; 101 | } 102 | 103 | if (systemReason.find("remove_all") != std::string::npos) { 104 | probableReason = "这有可能是因为你运行了多个实例的网易云,请只点击一次,然后等待网易云打开。不要多次点击。\n\nThis is probably because you ran multiple instances of CloudMusic. Please only click once."; 105 | } 106 | 107 | util::alert("BetterNCM 崩溃了!\n\nBetterNCM 将不会运行\n网易云将有可能崩溃\n\n崩溃原因:" + systemReason + (probableReason.has_value() ? "\n\n" + probableReason.value() : "")); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/framework.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #define WIN32_LEAN_AND_MEAN // 从 Windows 头文件中排除极少使用的内容 4 | // Windows 头文件 5 | #include 6 | -------------------------------------------------------------------------------- /src/hijack.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include 3 | #include 4 | 5 | #pragma comment( lib, "Shlwapi.lib") 6 | 7 | #pragma comment(linker, "/EXPORT:vSetDdrawflag=AheadLib_vSetDdrawflag,@1") 8 | #pragma comment(linker, "/EXPORT:AlphaBlend=AheadLib_AlphaBlend,@2") 9 | #pragma comment(linker, "/EXPORT:DllInitialize=AheadLib_DllInitialize,@3") 10 | #pragma comment(linker, "/EXPORT:GradientFill=AheadLib_GradientFill,@4") 11 | #pragma comment(linker, "/EXPORT:TransparentBlt=AheadLib_TransparentBlt,@5") 12 | 13 | 14 | extern "C" 15 | { 16 | PVOID pfnAheadLib_vSetDdrawflag; 17 | PVOID pfnAheadLib_AlphaBlend; 18 | PVOID pfnAheadLib_DllInitialize; 19 | PVOID pfnAheadLib_GradientFill; 20 | PVOID pfnAheadLib_TransparentBlt; 21 | } 22 | 23 | 24 | static 25 | HMODULE g_OldModule = NULL; 26 | 27 | VOID WINAPI Free() 28 | { 29 | if (g_OldModule) 30 | { 31 | FreeLibrary(g_OldModule); 32 | } 33 | } 34 | 35 | void bncmMain(HMODULE hModule); 36 | BOOL WINAPI Load() 37 | { 38 | TCHAR tzPath[MAX_PATH]; 39 | TCHAR tzTemp[MAX_PATH * 2]; 40 | 41 | 42 | GetSystemDirectory(tzPath, MAX_PATH); 43 | 44 | lstrcat(tzPath, TEXT("\\msimg32.dll")); 45 | 46 | g_OldModule = LoadLibrary(tzPath); 47 | if (g_OldModule == NULL) 48 | { 49 | wsprintf(tzTemp, TEXT("无法找到模块 %s,程序无法正常运行"), tzPath); 50 | MessageBox(NULL, tzTemp, TEXT("AheadLib"), MB_ICONSTOP); 51 | } 52 | 53 | return (g_OldModule != NULL); 54 | 55 | } 56 | 57 | 58 | FARPROC WINAPI GetAddress(PCSTR pszProcName) 59 | { 60 | FARPROC fpAddress; 61 | CHAR szProcName[64]; 62 | TCHAR tzTemp[MAX_PATH]; 63 | 64 | fpAddress = GetProcAddress(g_OldModule, pszProcName); 65 | if (fpAddress == NULL) 66 | { 67 | if (HIWORD(pszProcName) == 0) 68 | { 69 | wsprintfA(szProcName, "#%d", pszProcName); 70 | pszProcName = szProcName; 71 | } 72 | 73 | wsprintf(tzTemp, TEXT("无法找到函数 %hs,程序无法正常运行"), pszProcName); 74 | MessageBox(NULL, tzTemp, TEXT("AheadLib"), MB_ICONSTOP); 75 | ExitProcess(-2); 76 | } 77 | return fpAddress; 78 | } 79 | 80 | BOOL WINAPI Init() 81 | { 82 | pfnAheadLib_vSetDdrawflag = GetAddress("vSetDdrawflag"); 83 | pfnAheadLib_AlphaBlend = GetAddress("AlphaBlend"); 84 | pfnAheadLib_DllInitialize = GetAddress("DllInitialize"); 85 | pfnAheadLib_GradientFill = GetAddress("GradientFill"); 86 | pfnAheadLib_TransparentBlt = GetAddress("TransparentBlt"); 87 | return TRUE; 88 | } 89 | 90 | 91 | HMODULE g_hModule = nullptr; 92 | void bncmMain(); 93 | 94 | BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, PVOID pvReserved) 95 | { 96 | if (dwReason == DLL_PROCESS_ATTACH) 97 | { 98 | DisableThreadLibraryCalls(hModule); 99 | g_hModule = hModule; 100 | 101 | if (Load() && Init()) 102 | { 103 | TCHAR szAppName[MAX_PATH] = TEXT("cloudmusic.exe"); 104 | TCHAR szCurName[MAX_PATH]; 105 | 106 | GetModuleFileName(NULL, szCurName, MAX_PATH); 107 | PathStripPath(szCurName); 108 | 109 | if (StrCmpI(szCurName, szAppName) == 0) 110 | { 111 | bncmMain(); 112 | } 113 | } 114 | } 115 | else if (dwReason == DLL_PROCESS_DETACH) 116 | { 117 | Free(); 118 | } 119 | 120 | return TRUE; 121 | } 122 | 123 | -------------------------------------------------------------------------------- /src/hijack_jump.asm: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/std-microblock/BetterNCM/b9d32df79ab0eafe060da8ae605f458acb346c77/src/hijack_jump.asm -------------------------------------------------------------------------------- /src/hijack_x86.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include 3 | #include 4 | 5 | #pragma comment( lib, "Shlwapi.lib") 6 | 7 | #pragma comment(linker, "/EXPORT:vSetDdrawflag=_AheadLib_vSetDdrawflag,@1") 8 | #pragma comment(linker, "/EXPORT:AlphaBlend=_AheadLib_AlphaBlend,@2") 9 | #pragma comment(linker, "/EXPORT:DllInitialize=_AheadLib_DllInitialize,@3") 10 | #pragma comment(linker, "/EXPORT:GradientFill=_AheadLib_GradientFill,@4") 11 | #pragma comment(linker, "/EXPORT:TransparentBlt=_AheadLib_TransparentBlt,@5") 12 | 13 | 14 | PVOID pfnAheadLib_vSetDdrawflag; 15 | PVOID pfnAheadLib_AlphaBlend; 16 | PVOID pfnAheadLib_DllInitialize; 17 | PVOID pfnAheadLib_GradientFill; 18 | PVOID pfnAheadLib_TransparentBlt; 19 | 20 | 21 | static 22 | HMODULE g_OldModule = NULL; 23 | 24 | VOID WINAPI Free() 25 | { 26 | if (g_OldModule) 27 | { 28 | FreeLibrary(g_OldModule); 29 | } 30 | } 31 | 32 | 33 | BOOL WINAPI Load() 34 | { 35 | TCHAR tzPath[MAX_PATH]; 36 | TCHAR tzTemp[MAX_PATH * 2]; 37 | 38 | GetSystemDirectory(tzPath, MAX_PATH); 39 | 40 | lstrcat(tzPath, TEXT("\\msimg32.dll")); 41 | 42 | g_OldModule = LoadLibrary(tzPath); 43 | if (g_OldModule == NULL) 44 | { 45 | wsprintf(tzTemp, TEXT("无法找到模块 %s,程序无法正常运行"), tzPath); 46 | MessageBox(NULL, tzTemp, TEXT("AheadLib"), MB_ICONSTOP); 47 | } 48 | 49 | return (g_OldModule != NULL); 50 | 51 | } 52 | 53 | 54 | FARPROC WINAPI GetAddress(PCSTR pszProcName) 55 | { 56 | FARPROC fpAddress; 57 | CHAR szProcName[64]; 58 | TCHAR tzTemp[MAX_PATH]; 59 | 60 | fpAddress = GetProcAddress(g_OldModule, pszProcName); 61 | if (fpAddress == NULL) 62 | { 63 | if (HIWORD(pszProcName) == 0) 64 | { 65 | wsprintfA(szProcName, "#%d", pszProcName); 66 | pszProcName = szProcName; 67 | } 68 | 69 | wsprintf(tzTemp, TEXT("无法找到函数 %hs,程序无法正常运行"), pszProcName); 70 | MessageBox(NULL, tzTemp, TEXT("AheadLib"), MB_ICONSTOP); 71 | ExitProcess(-2); 72 | } 73 | return fpAddress; 74 | } 75 | 76 | BOOL WINAPI Init() 77 | { 78 | pfnAheadLib_vSetDdrawflag = GetAddress("vSetDdrawflag"); 79 | pfnAheadLib_AlphaBlend = GetAddress("AlphaBlend"); 80 | pfnAheadLib_DllInitialize = GetAddress("DllInitialize"); 81 | pfnAheadLib_GradientFill = GetAddress("GradientFill"); 82 | pfnAheadLib_TransparentBlt = GetAddress("TransparentBlt"); 83 | return TRUE; 84 | } 85 | 86 | void bncmMain(); 87 | HMODULE g_hModule = nullptr; 88 | 89 | BOOL APIENTRY DllMain(HMODULE hModule, DWORD dwReason, PVOID pvReserved) 90 | { 91 | if (dwReason == DLL_PROCESS_ATTACH) 92 | { 93 | DisableThreadLibraryCalls(hModule); 94 | 95 | if (Load() && Init()) 96 | { 97 | TCHAR szAppName[MAX_PATH] = TEXT("cloudmusic.exe"); 98 | TCHAR szCurName[MAX_PATH]; 99 | 100 | GetModuleFileName(NULL, szCurName, MAX_PATH); 101 | PathStripPath(szCurName); 102 | 103 | if (StrCmpI(szCurName, szAppName) == 0) 104 | { 105 | g_hModule = hModule; 106 | bncmMain(); 107 | } 108 | } 109 | } 110 | else if (dwReason == DLL_PROCESS_DETACH) 111 | { 112 | Free(); 113 | } 114 | 115 | return TRUE; 116 | } 117 | 118 | EXTERN_C __declspec(naked) void __cdecl AheadLib_vSetDdrawflag(void) 119 | { 120 | __asm jmp pfnAheadLib_vSetDdrawflag; 121 | } 122 | 123 | EXTERN_C __declspec(naked) void __cdecl AheadLib_AlphaBlend(void) 124 | { 125 | __asm jmp pfnAheadLib_AlphaBlend; 126 | } 127 | 128 | EXTERN_C __declspec(naked) void __cdecl AheadLib_DllInitialize(void) 129 | { 130 | __asm jmp pfnAheadLib_DllInitialize; 131 | } 132 | 133 | EXTERN_C __declspec(naked) void __cdecl AheadLib_GradientFill(void) 134 | { 135 | __asm jmp pfnAheadLib_GradientFill; 136 | } 137 | 138 | EXTERN_C __declspec(naked) void __cdecl AheadLib_TransparentBlt(void) 139 | { 140 | __asm jmp pfnAheadLib_TransparentBlt; 141 | } 142 | 143 | -------------------------------------------------------------------------------- /src/pch.cpp: -------------------------------------------------------------------------------- 1 | // pch.cpp: 与预编译标头对应的源文件 2 | 3 | #include "pch.h" 4 | 5 | // 当使用预编译的头时,需要使用此源文件,编译才能成功。 6 | -------------------------------------------------------------------------------- /src/pch.h: -------------------------------------------------------------------------------- 1 | // pch.h: 这是预编译标头文件。 2 | // 下方列出的文件仅编译一次,提高了将来生成的生成性能。 3 | // 这还将影响 IntelliSense 性能,包括代码完成和许多代码浏览功能。 4 | // 但是,如果此处列出的文件中的任何一个在生成之间有更新,它们全部都将被重新编译。 5 | // 请勿在此处添加要频繁更新的文件,这将使得性能优势无效。 6 | 7 | #ifndef PCH_H 8 | #define PCH_H 9 | #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING 10 | 11 | // 添加要在此处预编译的标头 12 | #include "framework.h" 13 | #include 14 | 15 | #include 16 | #include 17 | #include 18 | #include 19 | #include 20 | #include 21 | #include "httplib.h" 22 | #include "nlohmann/json.hpp" 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | #include 29 | #include "neargye/semver.hpp" 30 | #include "kubazip/zip/zip.h" 31 | #include 32 | 33 | #endif //PCH_H 34 | -------------------------------------------------------------------------------- /src/resource.aps: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/std-microblock/BetterNCM/b9d32df79ab0eafe060da8ae605f458acb346c77/src/resource.aps -------------------------------------------------------------------------------- /src/resource.h: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/std-microblock/BetterNCM/b9d32df79ab0eafe060da8ae605f458acb346c77/src/resource.h -------------------------------------------------------------------------------- /src/resource.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/std-microblock/BetterNCM/b9d32df79ab0eafe060da8ae605f458acb346c77/src/resource.rc -------------------------------------------------------------------------------- /src/timercpp.h: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | class Timer { 7 | std::atomic active{ true }; 8 | 9 | public: 10 | void setTimeout(auto function, int delay); 11 | void setInterval(auto function, int interval); 12 | void stop(); 13 | 14 | }; 15 | 16 | void Timer::setTimeout(auto function, int delay) { 17 | active = true; 18 | std::thread t([=]() { 19 | if (!active.load()) return; 20 | std::this_thread::sleep_for(std::chrono::milliseconds(delay)); 21 | if (!active.load()) return; 22 | function(); 23 | }); 24 | t.detach(); 25 | } 26 | 27 | void Timer::setInterval(auto function, int interval) { 28 | active = true; 29 | std::thread t([=]() { 30 | while (active.load()) { 31 | std::this_thread::sleep_for(std::chrono::milliseconds(interval)); 32 | if (!active.load()) return; 33 | function(); 34 | } 35 | }); 36 | t.detach(); 37 | } 38 | 39 | void Timer::stop() { 40 | active = false; 41 | } -------------------------------------------------------------------------------- /src/utils/BNString.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | 10 | class BNString : public std::wstring { 11 | private: 12 | static std::string wstring_to_utf8(const BNString& str) { 13 | return std::filesystem::path((std::wstring)str).string(); 14 | } 15 | 16 | static BNString gbk_to_wstring(const std::string& str) { 17 | auto GBK_LOCALE_NAME = ".936"; 18 | std::wstring_convert> convert( 19 | new std::codecvt_byname(GBK_LOCALE_NAME)); 20 | return convert.from_bytes(str); 21 | } 22 | 23 | std::string gbk_to_utf8_string(const std::string& str) { 24 | auto GBK_LOCALE_NAME = ".936"; 25 | std::wstring_convert> convert( 26 | new std::codecvt_byname(GBK_LOCALE_NAME)); 27 | std::wstring tmp_wstr = convert.from_bytes(str); 28 | 29 | std::wstring_convert> cv2; 30 | return cv2.to_bytes(tmp_wstr); 31 | } 32 | 33 | // https://stackoverflow.com/questions/8298081/convert-utf-8-to-ansi-in-c/35272822#35272822 34 | static std::string utf8_string_to_asni_string(const std::string& s) { 35 | BSTR bstrWide; 36 | char* pszAnsi; 37 | int nLength; 38 | const char* pszCode = s.c_str(); 39 | 40 | nLength = MultiByteToWideChar(CP_UTF8, 0, pszCode, strlen(pszCode) + 1, nullptr, NULL); 41 | bstrWide = SysAllocStringLen(nullptr, nLength); 42 | 43 | MultiByteToWideChar(CP_UTF8, 0, pszCode, strlen(pszCode) + 1, bstrWide, nLength); 44 | 45 | nLength = WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, nullptr, 0, nullptr, nullptr); 46 | pszAnsi = new char[nLength]; 47 | 48 | WideCharToMultiByte(CP_ACP, 0, bstrWide, -1, pszAnsi, nLength, nullptr, nullptr); 49 | SysFreeString(bstrWide); 50 | 51 | std::string r(pszAnsi); 52 | delete[] pszAnsi; 53 | return r; 54 | } 55 | 56 | static std::string utf8_string_to_gbk_string(const std::string& str) { 57 | std::wstring_convert> conv; 58 | std::wstring tmp_wstr = conv.from_bytes(str); 59 | 60 | auto GBK_LOCALE_NAME = ".936"; 61 | std::wstring_convert> convert( 62 | new std::codecvt_byname(GBK_LOCALE_NAME)); 63 | return convert.to_bytes(tmp_wstr); 64 | } 65 | 66 | static BNString utf8_to_wstring(const std::string& utf8) { 67 | std::vector unicode; 68 | size_t i = 0; 69 | while (i < utf8.size()) { 70 | unsigned long uni; 71 | size_t todo; 72 | bool error = false; 73 | unsigned char ch = utf8[i++]; 74 | if (ch <= 0x7F) { 75 | uni = ch; 76 | todo = 0; 77 | } 78 | else if (ch <= 0xBF) { 79 | throw std::logic_error("not a UTF-8 string"); 80 | } 81 | else if (ch <= 0xDF) { 82 | uni = ch & 0x1F; 83 | todo = 1; 84 | } 85 | else if (ch <= 0xEF) { 86 | uni = ch & 0x0F; 87 | todo = 2; 88 | } 89 | else if (ch <= 0xF7) { 90 | uni = ch & 0x07; 91 | todo = 3; 92 | } 93 | else { 94 | throw std::logic_error("not a UTF-8 string"); 95 | } 96 | for (size_t j = 0; j < todo; ++j) { 97 | if (i == utf8.size()) 98 | throw std::logic_error("not a UTF-8 string"); 99 | unsigned char ch = utf8[i++]; 100 | if (ch < 0x80 || ch > 0xBF) 101 | throw std::logic_error("not a UTF-8 string"); 102 | uni <<= 6; 103 | uni += ch & 0x3F; 104 | } 105 | if (uni >= 0xD800 && uni <= 0xDFFF) 106 | throw std::logic_error("not a UTF-8 string"); 107 | if (uni > 0x10FFFF) 108 | throw std::logic_error("not a UTF-8 string"); 109 | unicode.push_back(uni); 110 | } 111 | std::wstring utf16; 112 | for (size_t i = 0; i < unicode.size(); ++i) { 113 | unsigned long uni = unicode[i]; 114 | if (uni <= 0xFFFF) { 115 | utf16 += static_cast(uni); 116 | } 117 | else { 118 | uni -= 0x10000; 119 | utf16 += static_cast((uni >> 10) + 0xD800); 120 | utf16 += static_cast((uni & 0x3FF) + 0xDC00); 121 | } 122 | } 123 | return utf16; 124 | } 125 | 126 | public: 127 | static BNString fromGBK(const std::string& s) { 128 | return BNString(gbk_to_wstring(s)); 129 | } 130 | 131 | BNString() : std::wstring() { 132 | } 133 | 134 | BNString(const std::string s) { 135 | *this = utf8_to_wstring(s); 136 | } 137 | 138 | BNString(const std::wstring_view s) { 139 | *this = BNString(std::wstring(s)); 140 | } 141 | 142 | BNString(const char* s) { 143 | *this = BNString(std::string(s)); 144 | } 145 | 146 | BNString(const std::wstring s) : std::wstring(s) { 147 | } 148 | 149 | 150 | // To UTF8 String 151 | operator const std::string() { 152 | return this->utf8(); 153 | } 154 | 155 | operator const std::wstring() { 156 | return *this; 157 | } 158 | 159 | [[nodiscard]] const std::string toUtf8String() const { 160 | return wstring_to_utf8(*this); 161 | } 162 | 163 | [[nodiscard]] const std::string utf8() const { 164 | return this->toUtf8String(); 165 | } 166 | 167 | [[nodiscard]] const std::string toANSIString() const { 168 | return utf8_string_to_asni_string(wstring_to_utf8(*this)); 169 | } 170 | 171 | [[nodiscard]] const std::string ansi() const { 172 | return this->toANSIString(); 173 | } 174 | 175 | [[nodiscard]] const std::string toGBKString() const { 176 | return utf8_string_to_gbk_string(this->toUtf8String()); 177 | } 178 | 179 | [[nodiscard]] const std::string gbk() const { 180 | return this->toGBKString(); 181 | } 182 | 183 | 184 | [[nodiscard]] bool startsWith(const std::wstring& prefix) const { 185 | if (prefix.length() > this->length()) return false; 186 | return this->substr(0, prefix.length()) == prefix; 187 | } 188 | 189 | [[nodiscard]] bool endsWith(const std::wstring& suffix) const { 190 | if (suffix.length() > this->length()) return false; 191 | return this->substr(this->length() - suffix.length()) == suffix; 192 | } 193 | 194 | [[nodiscard]] bool includes(const std::wstring& search) const { 195 | return this->find(search) != std::wstring::npos; 196 | } 197 | 198 | [[nodiscard]] int indexOf(const std::wstring& search) const { 199 | size_t index = this->find(search); 200 | if (index == std::wstring::npos) return -1; 201 | return static_cast(index); 202 | } 203 | 204 | [[nodiscard]] std::vector split(const std::wstring& delimiter) const { 205 | std::vector result; 206 | size_t start = 0; 207 | size_t end = 0; 208 | while ((end = this->find(delimiter, start)) != std::wstring::npos) { 209 | result.push_back(this->substr(start, end - start)); 210 | start = end + delimiter.length(); 211 | } 212 | result.push_back(this->substr(start)); 213 | return result; 214 | } 215 | 216 | BNString& replace(const std::wstring& search, const std::wstring& replacement) { 217 | size_t index = 0; 218 | while ((index = this->find(search, index)) != std::wstring::npos) { 219 | this->erase(index, search.length()); 220 | this->insert(index, replacement); 221 | index += replacement.length(); 222 | } 223 | return *this; 224 | } 225 | }; 226 | -------------------------------------------------------------------------------- /src/utils/Interprocess.hpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | 11 | #include 12 | 13 | #include 14 | 15 | class SharedMemory { 16 | private: 17 | HANDLE hMapFile; 18 | LPVOID buf; 19 | 20 | public: 21 | SharedMemory(const char* name, size_t size) { 22 | hMapFile = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, name); 23 | if (hMapFile == NULL) { 24 | throw std::runtime_error("Could not create file mapping object"); 25 | } 26 | 27 | buf = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, size); 28 | if (buf == NULL) { 29 | CloseHandle(hMapFile); 30 | throw std::runtime_error("Could not map file to memory"); 31 | } 32 | } 33 | 34 | ~SharedMemory() { 35 | UnmapViewOfFile(buf); 36 | CloseHandle(hMapFile); 37 | } 38 | 39 | LPVOID getBuf() const { 40 | return buf; 41 | } 42 | 43 | void write(const void* data, size_t size) { 44 | CopyMemory(buf, data, size); 45 | } 46 | 47 | void read(void* data, size_t size) { 48 | CopyMemory(data, buf, size); 49 | } 50 | }; 51 | 52 | 53 | template 54 | class SharedMemoryData { 55 | private: 56 | SharedMemory mem; 57 | T* data; 58 | 59 | public: 60 | SharedMemoryData(const char* name) : mem(name, sizeof(T)) { 61 | data = static_cast(mem.getBuf()); 62 | } 63 | 64 | void write(const T& value) { 65 | *data = value; 66 | } 67 | 68 | T read() { 69 | return *data; 70 | } 71 | 72 | void wait_for(const T& val, const int interval=10) const { 73 | while (*data != val) { 74 | Sleep(interval); 75 | } 76 | } 77 | }; 78 | 79 | template<> 80 | class SharedMemoryData { 81 | private: 82 | static const size_t MAX_LENGTH = 256; 83 | SharedMemory mem; 84 | char* data; 85 | 86 | public: 87 | SharedMemoryData(const char* name) : mem(name, MAX_LENGTH) { 88 | data = static_cast(mem.getBuf()); 89 | } 90 | 91 | void write(const std::string& value) { 92 | memset(data, '\0', MAX_LENGTH); 93 | strncpy(data, value.c_str(), MAX_LENGTH - 1); 94 | } 95 | 96 | std::string_view read() { 97 | return std::string_view(data); 98 | } 99 | 100 | }; -------------------------------------------------------------------------------- /src/utils/NamedPipe.cpp: -------------------------------------------------------------------------------- 1 | #include "pch.h" 2 | #include "NamedPipe.h" 3 | -------------------------------------------------------------------------------- /src/utils/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | #include "pch.h" 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #include "resource.h" 10 | #pragma comment(lib, "version.lib") 11 | using namespace util; 12 | 13 | 14 | extern HMODULE g_hModule; 15 | 16 | BNString util::read_to_string_utf8(const std::filesystem::path& path) { 17 | std::ifstream file(path); 18 | std::stringstream ss; 19 | ss << file.rdbuf(); 20 | return ss.str(); 21 | } 22 | 23 | BNString util::read_to_string(const std::filesystem::path& path) { 24 | std::wifstream file(path); 25 | std::wstring content((std::istreambuf_iterator(file)), 26 | std::istreambuf_iterator()); 27 | return content; 28 | } 29 | 30 | // https://stackoverflow.com/questions/4804298/how-to-convert-wstring-into-string (modified) 31 | std::string util::ws2s(const std::wstring& str) { 32 | std::string strTo; 33 | auto szTo = new char[str.length() + 1]; 34 | szTo[str.size()] = '\0'; 35 | WideCharToMultiByte(CP_ACP, 0, str.c_str(), -1, szTo, static_cast(str.length()), nullptr, nullptr); 36 | strTo = szTo; 37 | delete szTo; 38 | return strTo; 39 | } 40 | 41 | std::wstring util::s2ws(const std::string& s, bool isUtf8) { 42 | int len; 43 | int slength = static_cast(s.length()) + 1; 44 | len = MultiByteToWideChar(isUtf8 ? CP_UTF8 : CP_ACP, 0, s.c_str(), slength, nullptr, 0); 45 | std::wstring buf; 46 | buf.resize(len); 47 | MultiByteToWideChar(isUtf8 ? CP_UTF8 : CP_ACP, 0, s.c_str(), slength, 48 | const_cast(buf.c_str()), len); 49 | return buf; 50 | } 51 | 52 | void util::write_file_text_utf8(const std::string& path, const std::string& text, bool append) { 53 | std::ofstream file; 54 | if (append) 55 | file.open(path, std::ios_base::app); 56 | else 57 | file.open(path); 58 | 59 | file << text; 60 | file.close(); 61 | } 62 | 63 | void util::write_file_text(const BNString& path, const BNString& text, bool append) { 64 | std::wofstream file; 65 | if (append) 66 | file.open(path, std::ios_base::app); 67 | else 68 | file.open(path); 69 | 70 | file << text; 71 | file.close(); 72 | } 73 | 74 | // https://stackoverflow.com/questions/4130180/how-to-use-vs-c-getenvironmentvariable-as-cleanly-as-possible 75 | BNString util::getEnvironment(const BNString& key) { 76 | if (!_wgetenv(key.c_str()))return BNString(""); 77 | return std::wstring(_wgetenv(key.c_str())); 78 | } 79 | 80 | BNString datapath = "\\betterncm"; 81 | 82 | BNString util::getNCMPath() { 83 | wchar_t buffer[MAX_PATH]; 84 | GetModuleFileNameW(nullptr, buffer, MAX_PATH); 85 | std::wstring::size_type pos = std::wstring(buffer).find_last_of(L"\\/"); 86 | if (pos != std::wstring::npos) 87 | buffer[pos] = L'\0'; 88 | return std::wstring(buffer); 89 | } 90 | 91 | BNString util::get_command_line() { 92 | LPTSTR cmd = GetCommandLine(); 93 | 94 | return std::wstring(cmd); 95 | } 96 | 97 | 98 | ScreenCapturePart::ScreenCapturePart() { 99 | this->hdcSource = GetDC(nullptr); 100 | this->hdcMemory = CreateCompatibleDC(hdcSource); 101 | 102 | int capX = GetDeviceCaps(hdcSource, HORZRES); 103 | int capY = GetDeviceCaps(hdcSource, VERTRES); 104 | 105 | int x = GetSystemMetrics(SM_XVIRTUALSCREEN); 106 | int y = GetSystemMetrics(SM_YVIRTUALSCREEN); 107 | int w = GetSystemMetrics(SM_CXVIRTUALSCREEN); 108 | int h = GetSystemMetrics(SM_CYVIRTUALSCREEN); 109 | 110 | this->hBitmap = CreateCompatibleBitmap(hdcSource, w, h); 111 | this->hBitmapOld = static_cast(SelectObject(hdcMemory, this->hBitmap)); 112 | 113 | BitBlt(hdcMemory, 0, 0, w, h, hdcSource, x, y, SRCCOPY); 114 | this->hBitmap = static_cast(SelectObject(hdcMemory, this->hBitmapOld)); 115 | 116 | BITMAPINFOHEADER bmiHeader{}; 117 | bmiHeader.biSize = sizeof(BITMAPINFOHEADER); 118 | bmiHeader.biWidth = w; 119 | bmiHeader.biHeight = h; 120 | bmiHeader.biPlanes = 1; 121 | bmiHeader.biBitCount = 24; 122 | bmiHeader.biCompression = BI_RGB; 123 | bmiHeader.biSizeImage = 0; 124 | bmiHeader.biXPelsPerMeter = 0; 125 | bmiHeader.biYPelsPerMeter = 0; 126 | bmiHeader.biClrUsed = 0; 127 | bmiHeader.biClrImportant = 0; 128 | 129 | DWORD dwBmpSize = ((w * bmiHeader.biBitCount + 31) / 32) * 4 * h; 130 | this->dwSizeofDIB = dwBmpSize + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); 131 | 132 | BITMAPFILEHEADER bmfHeader{}; 133 | bmfHeader.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER); 134 | bmfHeader.bfSize = this->dwSizeofDIB; 135 | bmfHeader.bfType = 0x4D42; 136 | 137 | this->lpbitmap = new char[dwBmpSize]; 138 | ZeroMemory(lpbitmap, dwBmpSize); 139 | GetDIBits(hdcMemory, this->hBitmap, 0, h, lpbitmap, (BITMAPINFO*)&bmiHeader, DIB_RGB_COLORS); 140 | 141 | this->allData = new char[this->dwSizeofDIB]; 142 | ZeroMemory(allData, this->dwSizeofDIB); 143 | memcpy(allData, &bmfHeader, sizeof(BITMAPFILEHEADER)); 144 | memcpy(allData + sizeof(BITMAPFILEHEADER), &bmiHeader, sizeof(BITMAPINFOHEADER)); 145 | memcpy(allData + sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER), lpbitmap, dwBmpSize); 146 | } 147 | 148 | ScreenCapturePart::~ScreenCapturePart() { 149 | ReleaseDC(nullptr, this->hdcSource); 150 | DeleteDC(this->hdcMemory); 151 | DeleteObject(this->hBitmap); 152 | DeleteObject(this->hBitmapOld); 153 | delete[] this->allData; 154 | delete[] this->lpbitmap; 155 | this->allData = nullptr; 156 | this->lpbitmap = nullptr; 157 | } 158 | 159 | char* ScreenCapturePart::getData() { 160 | return this->allData; 161 | } 162 | 163 | // https://stackoverflow.com/questions/440133/how-do-i-create-a-random-alpha-numeric-string-in-c 164 | std::string util::random_string(std::string::size_type length) { 165 | static auto& chrs = "0123456789" 166 | "abcdefghijklmnopqrstuvwxyz" 167 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; 168 | 169 | thread_local static std::mt19937 rg{ std::random_device{}() }; 170 | thread_local static std::uniform_int_distribution pick(0, sizeof(chrs) - 2); 171 | 172 | std::string s; 173 | 174 | s.reserve(length); 175 | 176 | while (length--) 177 | s += chrs[pick(rg)]; 178 | 179 | return s; 180 | } 181 | 182 | DWORD ScreenCapturePart::getDataSize() { 183 | return this->dwSizeofDIB; 184 | } 185 | 186 | std::map mimeTypes = { 187 | {".html", "text/html"}, 188 | {".txt", "text/plain"}, 189 | {".jpg", "image/jpeg"}, 190 | {".jpeg", "image/jpeg"}, 191 | {".png", "image/png"}, 192 | {".gif", "image/gif"}, 193 | {".css", "text/css"}, 194 | {".js", "application/javascript"}, 195 | {".flac", "audio/mpeg"}, 196 | {".mp3", "audio/mpeg"} 197 | }; 198 | 199 | std::string util::guessMimeType(std::string fileExtension) { 200 | std::string mimeType = "application/octet-stream"; 201 | 202 | if (mimeTypes.contains(fileExtension)) { 203 | mimeType = mimeTypes[fileExtension]; 204 | } 205 | 206 | return mimeType; 207 | } 208 | 209 | std::string util::load_string_resource(LPCTSTR name) { 210 | HRSRC hRes = FindResource(g_hModule, name, RT_RCDATA); 211 | assert(hRes); 212 | DWORD size = SizeofResource(g_hModule, hRes); 213 | HGLOBAL hGlobal = LoadResource(g_hModule, hRes); 214 | assert(hGlobal); 215 | 216 | std::string ret; 217 | 218 | const uint8_t bom[3] = { 0xEF, 0xBB, 0xBF }; 219 | auto ptr = static_cast(LockResource(hGlobal)); 220 | 221 | if (size >= 3 && memcmp(bom, ptr, 3) == 0) { 222 | ret.assign((char*)ptr + 3, static_cast(size) - 3); 223 | } 224 | else { 225 | ret.assign((char*)ptr, static_cast(size)); 226 | } 227 | 228 | UnlockResource(ptr); 229 | return ret; 230 | } 231 | 232 | std::string util::wstring_to_utf8(const std::wstring& str) { 233 | std::string ret; 234 | int len = WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.length(), nullptr, 0, nullptr, nullptr); 235 | if (len > 0) { 236 | ret.resize(len); 237 | WideCharToMultiByte(CP_UTF8, 0, str.c_str(), str.length(), &ret[0], len, nullptr, nullptr); 238 | } 239 | return ret; 240 | } 241 | 242 | // https://stackoverflow.com/questions/7153935/how-to-convert-utf-8-stdstring-to-utf-16-stdwstring 243 | std::wstring util::utf8_to_wstring(const std::string& utf8) { 244 | std::vector unicode; 245 | size_t i = 0; 246 | while (i < utf8.size()) { 247 | unsigned long uni; 248 | size_t todo; 249 | bool error = false; 250 | unsigned char ch = utf8[i++]; 251 | if (ch <= 0x7F) { 252 | uni = ch; 253 | todo = 0; 254 | } 255 | else if (ch <= 0xBF) { 256 | throw std::logic_error("not a UTF-8 string"); 257 | } 258 | else if (ch <= 0xDF) { 259 | uni = ch & 0x1F; 260 | todo = 1; 261 | } 262 | else if (ch <= 0xEF) { 263 | uni = ch & 0x0F; 264 | todo = 2; 265 | } 266 | else if (ch <= 0xF7) { 267 | uni = ch & 0x07; 268 | todo = 3; 269 | } 270 | else { 271 | throw std::logic_error("not a UTF-8 string"); 272 | } 273 | for (size_t j = 0; j < todo; ++j) { 274 | if (i == utf8.size()) 275 | throw std::logic_error("not a UTF-8 string"); 276 | unsigned char ch = utf8[i++]; 277 | if (ch < 0x80 || ch > 0xBF) 278 | throw std::logic_error("not a UTF-8 string"); 279 | uni <<= 6; 280 | uni += ch & 0x3F; 281 | } 282 | if (uni >= 0xD800 && uni <= 0xDFFF) 283 | throw std::logic_error("not a UTF-8 string"); 284 | if (uni > 0x10FFFF) 285 | throw std::logic_error("not a UTF-8 string"); 286 | unicode.push_back(uni); 287 | } 288 | std::wstring utf16; 289 | for (size_t i = 0; i < unicode.size(); ++i) { 290 | unsigned long uni = unicode[i]; 291 | if (uni <= 0xFFFF) { 292 | utf16 += static_cast(uni); 293 | } 294 | else { 295 | uni -= 0x10000; 296 | utf16 += static_cast((uni >> 10) + 0xD800); 297 | utf16 += static_cast((uni & 0x3FF) + 0xDC00); 298 | } 299 | } 300 | return utf16; 301 | } 302 | 303 | semver::version util::getNCMExecutableVersion() { 304 | static std::optional cached; 305 | if (cached.has_value()) return cached.value(); 306 | 307 | DWORD verHandle = 0; 308 | UINT size = 0; 309 | LPBYTE lpBuffer = nullptr; 310 | DWORD verSize = GetFileVersionInfoSize((getNCMPath() + L"\\cloudmusic.exe").c_str(), &verHandle); 311 | 312 | if (verSize != NULL) { 313 | auto verData = new char[verSize]; 314 | 315 | if (GetFileVersionInfo((getNCMPath() + L"\\cloudmusic.exe").c_str(), verHandle, verSize, verData)) { 316 | if (VerQueryValue(verData, L"\\", (VOID FAR * FAR*) & lpBuffer, &size)) { 317 | if (size) { 318 | auto verInfo = (VS_FIXEDFILEINFO*)lpBuffer; 319 | if (verInfo->dwSignature == 0xfeef04bd) { 320 | cached = semver::version{ 321 | static_cast((verInfo->dwFileVersionMS >> 16) & 0xffff), 322 | static_cast((verInfo->dwFileVersionMS >> 0) & 0xffff), 323 | static_cast((verInfo->dwFileVersionLS >> 16) & 0xffff) 324 | }; 325 | return cached.value(); 326 | } 327 | } 328 | } 329 | } 330 | delete[] verData; 331 | } 332 | } 333 | 334 | std::wstring util::wreplaceAll(std::wstring str, const std::wstring& from, const std::wstring& to) { 335 | size_t start_pos = 0; 336 | while ((start_pos = str.find(from, start_pos)) != std::wstring::npos) { 337 | str.replace(start_pos, from.length(), to); 338 | start_pos += to.length(); // Handles case where 'to' is a substring of 'from' 339 | } 340 | return str; 341 | } 342 | 343 | void util::killNCM() { 344 | // Get the ID of the current process 345 | DWORD dwCurrentProcessId = GetCurrentProcessId(); 346 | 347 | // Get a snapshot of all the processes in the system 348 | HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); 349 | if (hSnapshot == INVALID_HANDLE_VALUE) { 350 | return; 351 | } 352 | std::vector pidlist; 353 | // Set up the process entry structure 354 | PROCESSENTRY32W processEntry; 355 | processEntry.dwSize = sizeof(PROCESSENTRY32W); 356 | 357 | // Iterate through the processes in the snapshot 358 | if (Process32FirstW(hSnapshot, &processEntry)) { 359 | do { 360 | if (wcscmp(processEntry.szExeFile, L"cloudmusic.exe") == 0) { 361 | pidlist.push_back(processEntry.th32ProcessID); 362 | } 363 | } while (Process32NextW(hSnapshot, &processEntry)); 364 | } 365 | 366 | // Close the snapshot handle 367 | CloseHandle(hSnapshot); 368 | 369 | std::string cmd = "cmd /c echo"; 370 | for (const auto& pid : pidlist) { 371 | cmd += " & taskkill /f /pid "; 372 | cmd += std::to_string(pid); 373 | } 374 | exec(s2ws(cmd), false); 375 | } 376 | 377 | void util::watchDir(const BNString& directory, std::function callback) { 378 | HANDLE hDirectory = CreateFileW(directory.c_str(), 379 | FILE_LIST_DIRECTORY, 380 | FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, 381 | nullptr, 382 | OPEN_EXISTING, 383 | FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, 384 | nullptr); 385 | 386 | if (hDirectory == INVALID_HANDLE_VALUE) { 387 | std::wcerr << L"Error opening directory: " << GetLastError() << std::endl; 388 | return; 389 | } 390 | 391 | OVERLAPPED overlapped = { 0 }; 392 | HANDLE hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr); 393 | overlapped.hEvent = hEvent; 394 | 395 | char buffer[4096]; 396 | 397 | while (true) { 398 | if (ReadDirectoryChangesW(hDirectory, 399 | buffer, 400 | sizeof(buffer), 401 | TRUE, 402 | FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | 403 | FILE_NOTIFY_CHANGE_ATTRIBUTES | 404 | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE, 405 | nullptr, 406 | &overlapped, 407 | nullptr)) { 408 | WaitForSingleObject(hEvent, INFINITE); 409 | 410 | DWORD dwBytes; 411 | if (!GetOverlappedResult(hDirectory, &overlapped, &dwBytes, FALSE)) { 412 | std::wcerr << L"Error getting overlapped result: " << GetLastError() << std::endl; 413 | break; 414 | } 415 | 416 | auto pNotify = (PFILE_NOTIFY_INFORMATION)buffer; 417 | while (pNotify != nullptr) { 418 | std::wstring fileName(pNotify->FileName, pNotify->FileNameLength / sizeof(WCHAR)); 419 | if (!callback(directory, fileName))goto close; 420 | if (pNotify->NextEntryOffset == 0) { 421 | pNotify = nullptr; 422 | } 423 | else { 424 | pNotify = (PFILE_NOTIFY_INFORMATION)(((LPBYTE)pNotify) + pNotify->NextEntryOffset); 425 | } 426 | } 427 | 428 | ResetEvent(hEvent); 429 | } 430 | else { 431 | std::wcerr << L"Error reading directory changes: " << GetLastError() << std::endl; 432 | break; 433 | } 434 | } 435 | close: 436 | CloseHandle(hDirectory); 437 | CloseHandle(hEvent); 438 | } 439 | 440 | bool util::DownloadFile(const BNString& url, const BNString& dest) 441 | { 442 | // Initialize WinInet library 443 | HINTERNET hInternet = InternetOpenW(L"Download", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); 444 | if (!hInternet) 445 | { 446 | return FALSE; 447 | } 448 | 449 | // Open the URL 450 | HINTERNET hUrl = InternetOpenUrlW(hInternet, url.c_str(), NULL, 0, INTERNET_FLAG_RELOAD, 0); 451 | if (!hUrl) 452 | { 453 | InternetCloseHandle(hInternet); 454 | return FALSE; 455 | } 456 | 457 | // Create a file at the destination path 458 | HANDLE hFile = CreateFileW( 459 | dest.c_str(), 460 | GENERIC_WRITE, 461 | 0, 462 | NULL, 463 | CREATE_ALWAYS, 464 | FILE_ATTRIBUTE_NORMAL, 465 | NULL 466 | ); 467 | if (hFile == INVALID_HANDLE_VALUE) 468 | { 469 | InternetCloseHandle(hUrl); 470 | InternetCloseHandle(hInternet); 471 | return FALSE; 472 | } 473 | 474 | // Download the file and write to the created file 475 | DWORD dwBytesRead = 0; 476 | BOOL bResult = FALSE; 477 | CHAR szBuffer[4096]; 478 | while (InternetReadFile(hUrl, szBuffer, 4096, &dwBytesRead) && dwBytesRead) 479 | { 480 | DWORD dwBytesWritten = 0; 481 | bResult = WriteFile(hFile, szBuffer, dwBytesRead, &dwBytesWritten, NULL); 482 | if (!bResult) 483 | { 484 | break; 485 | } 486 | } 487 | 488 | // Clean up 489 | CloseHandle(hFile); 490 | InternetCloseHandle(hUrl); 491 | InternetCloseHandle(hInternet); 492 | 493 | return bResult; 494 | } 495 | 496 | BNString util::FetchWebContent(const BNString& url) 497 | { 498 | HINTERNET hInternet = InternetOpenW(L"WinINetExample", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); 499 | if (hInternet == NULL) { 500 | return ""; 501 | } 502 | 503 | HINTERNET hUrl = InternetOpenUrlW(hInternet, url.c_str(), NULL, 0, INTERNET_FLAG_RELOAD, 0); 504 | if (hUrl == NULL) { 505 | InternetCloseHandle(hInternet); 506 | return ""; 507 | } 508 | 509 | std::string content; 510 | 511 | DWORD bytesRead = 0; 512 | char buffer[1024]; 513 | while (InternetReadFile(hUrl, buffer, sizeof(buffer), &bytesRead) && bytesRead != 0) { 514 | std::string temp(buffer, bytesRead); 515 | content += std::string(temp.begin(), temp.end()); 516 | } 517 | 518 | InternetCloseHandle(hUrl); 519 | InternetCloseHandle(hInternet); 520 | 521 | return content; 522 | } 523 | 524 | void util::restartNCM() { 525 | WCHAR szProcessName[MAX_PATH]; 526 | GetModuleFileNameW(nullptr, szProcessName, MAX_PATH); 527 | STARTUPINFOW si; 528 | PROCESS_INFORMATION pi; 529 | ZeroMemory(&si, sizeof(si)); 530 | si.cb = sizeof(si); 531 | ZeroMemory(&pi, sizeof(pi)); 532 | 533 | killNCM(); 534 | CreateProcessW(szProcessName, nullptr, nullptr, nullptr, FALSE, 0, nullptr, nullptr, &si, &pi); 535 | } 536 | 537 | 538 | void util::alert(const wchar_t* item) { 539 | MessageBoxW(nullptr, item, L"BetterNCM", MB_OK | MB_ICONINFORMATION); 540 | } 541 | 542 | void util::alert(const std::wstring* item) { 543 | MessageBoxW(nullptr, item->c_str(), L"BetterNCM", MB_OK | MB_ICONINFORMATION); 544 | } 545 | 546 | 547 | void util::exec(std::wstring cmd, bool ele, bool showWindow) { 548 | int nArg; 549 | LPWSTR* pArgs = CommandLineToArgvW(cmd.c_str(), &nArg); 550 | if (nArg > 0) { 551 | std::wstring param; 552 | SHELLEXECUTEINFOW info; 553 | ZeroMemory(&info, sizeof(info)); 554 | info.cbSize = sizeof(info); 555 | info.fMask = 0; 556 | info.hwnd = nullptr; 557 | info.lpVerb = ele ? L"runas" : L"open"; 558 | 559 | info.lpFile = pArgs[0]; 560 | 561 | if (nArg >= 2) { 562 | for (int i = 1; i < nArg; ++i) { 563 | if (i > 1) param += L' '; 564 | param += pArgs[i]; 565 | } 566 | info.lpParameters = param.c_str(); 567 | } 568 | else { 569 | info.lpParameters = nullptr; 570 | } 571 | info.lpDirectory = nullptr; 572 | info.nShow = showWindow ? SW_SHOW : SW_HIDE; 573 | 574 | ShellExecuteExW(&info); 575 | } 576 | 577 | LocalFree(pArgs); 578 | } 579 | 580 | void util::extractPluginMarket() { 581 | HRSRC myResource = ::FindResource(g_hModule, MAKEINTRESOURCE(IDR_RCDATA1), RT_RCDATA); 582 | unsigned int myResourceSize = SizeofResource(g_hModule, myResource); 583 | HGLOBAL myResourceData = LoadResource(g_hModule, myResource); 584 | void* pMyBinaryData = LockResource(myResourceData); 585 | std::ofstream f(datapath + L"/plugins/PluginMarket.plugin", std::ios::out | std::ios::binary); 586 | f.write(static_cast(pMyBinaryData), myResourceSize); 587 | f.close(); 588 | } -------------------------------------------------------------------------------- /src/utils/utils.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | #include 4 | #define BNSTRING_USE_CEFSTRING_FEATURES 5 | #include "../utils/BNString.hpp" 6 | #include "pystring/pystring.h" 7 | #include 8 | 9 | 10 | namespace util { 11 | // as wide char 12 | BNString read_to_string(const std::filesystem::path& path); 13 | BNString read_to_string_utf8(const std::filesystem::path& path); 14 | std::string ws2s(const std::wstring& str); 15 | std::wstring s2ws(const std::string& s, bool isUtf8 = true); 16 | void write_file_text_utf8(const std::string& path, const std::string& text, bool append = false); 17 | void write_file_text(const BNString& path, const BNString& text, bool append = false); 18 | BNString getEnvironment(const BNString& key); 19 | BNString getNCMPath(); 20 | 21 | BNString get_command_line(); 22 | 23 | template 24 | CefString cefFromCEFUserFreeTakeOwnership(S* s) { 25 | CefString st; 26 | st.AttachToUserFree(s); 27 | return st; 28 | } 29 | 30 | template 31 | CefString cefFromCEFUserFree(S* s) { 32 | return CefString(s); 33 | } 34 | 35 | class ScreenCapturePart { 36 | public: 37 | ScreenCapturePart(); 38 | ~ScreenCapturePart(); 39 | char* getData(); 40 | DWORD getDataSize(); 41 | 42 | private: 43 | HDC hdcSource; 44 | HDC hdcMemory; 45 | HBITMAP hBitmap; 46 | HBITMAP hBitmapOld; 47 | DWORD dwSizeofDIB; 48 | char* lpbitmap = nullptr; 49 | char* allData = nullptr; 50 | }; 51 | 52 | 53 | // https://stackoverflow.com/questions/1394053/how-to-write-a-generic-alert-message-using-win32 54 | void alert(const wchar_t* item); 55 | void alert(const std::wstring* item); 56 | 57 | template 58 | void alert(T item) { 59 | //this accepts all types that supports operator << 60 | std::ostringstream os; 61 | os << item; 62 | MessageBoxA(nullptr, os.str().c_str(), "BetterNCM", MB_OK | MB_ICONINFORMATION); 63 | } 64 | 65 | 66 | std::string random_string(std::string::size_type length); 67 | 68 | std::string guessMimeType(std::string fileExtension); 69 | 70 | std::string load_string_resource(LPCTSTR name); 71 | std::string wstring_to_utf8(const std::wstring& str); 72 | std::wstring utf8_to_wstring(const std::string& utf8); 73 | semver::version getNCMExecutableVersion(); 74 | std::wstring wreplaceAll(std::wstring str, const std::wstring& from, const std::wstring& to); 75 | void restartNCM(); 76 | void exec(std::wstring cmd, bool ele, bool showWindow = false); 77 | void killNCM(); 78 | void watchDir(const BNString& directory, std::function); 79 | 80 | bool DownloadFile(const BNString& url, const BNString& dest); 81 | BNString FetchWebContent(const BNString& url); 82 | 83 | void extractPluginMarket(); 84 | } 85 | -------------------------------------------------------------------------------- /src/v8NativeCalls.cpp: -------------------------------------------------------------------------------- 1 | #pragma once 2 | #include "pch.h" 3 | #include "3rd/libcef/include/capi/cef_base_capi.h" 4 | #include "3rd/libcef/include/capi/cef_v8_capi.h" 5 | #include "EasyCEFHooks.h" 6 | #include 7 | #include "App.h" 8 | #include 9 | #include 10 | using cef_str_arg = cef_string_userfree_t; 11 | extern BNString datapath; 12 | extern std::map> plugin_native_apis; 13 | #include 14 | 15 | CefString create_cefstring(const std::string& val) { 16 | CefString s; 17 | s.FromString(val); 18 | return s; 19 | } 20 | 21 | CefString create_cefstring(const std::wstring& val) { 22 | CefString s; 23 | s.FromWString(val); 24 | return s; 25 | } 26 | 27 | template 28 | CefString create_cefstring(const T& val) { 29 | static_assert(std::is_same::value || std::is_same::value, 30 | "create_cefstring() requires a specialization for this type"); 31 | return CefString(); 32 | } 33 | 34 | std::vector apis; 35 | _cef_v8value_t* native_value; 36 | 37 | cef_v8value_t* create_v8value(const std::string& val); 38 | cef_v8value_t* create_v8value(const std::wstring& val); 39 | cef_v8value_t* create_v8value(int val); 40 | cef_v8value_t* create_v8value(unsigned int val); 41 | cef_v8value_t* create_v8value(double val); 42 | cef_v8value_t* create_v8value(long val); 43 | cef_v8value_t* create_v8value(long long val); 44 | cef_v8value_t* create_v8value(bool val); 45 | template 46 | cef_v8value_t* create_v8value(std::vector val); 47 | template 48 | cef_v8value_t* create_v8value(const std::map& val); 49 | template 50 | cef_v8value_t* create_v8value(const std::variant& val); 51 | 52 | cef_v8value_t* create_v8value(const std::string& val) { 53 | CefString s; 54 | s.FromString(val); 55 | return cef_v8value_create_string(create_cefstring(val).GetStruct()); 56 | } 57 | 58 | cef_v8value_t* create_v8value(const std::wstring& val) { 59 | return cef_v8value_create_string(create_cefstring(val).GetStruct()); 60 | } 61 | 62 | cef_v8value_t* create_v8value(int val) { 63 | return cef_v8value_create_int(val); 64 | } 65 | 66 | cef_v8value_t* create_v8value(unsigned int val) { 67 | return cef_v8value_create_uint(val); 68 | } 69 | 70 | cef_v8value_t* create_v8value(double val) { 71 | return cef_v8value_create_double(val); 72 | } 73 | 74 | cef_v8value_t* create_v8value(long val) { 75 | return cef_v8value_create_double((double)val); 76 | } 77 | 78 | cef_v8value_t* create_v8value(long long val) { 79 | return cef_v8value_create_double((double)val); 80 | } 81 | 82 | cef_v8value_t* create_v8value(bool val) { 83 | return cef_v8value_create_bool(val); 84 | } 85 | 86 | cef_v8value_t* create_v8value() { 87 | return cef_v8value_create_undefined(); 88 | } 89 | 90 | cef_v8value_t* create_v8value(cef_v8value_t* val) { 91 | return val; 92 | } 93 | 94 | struct V8ValueCreatorVisitor { 95 | template 96 | cef_v8value_t* operator()(const T& val) { 97 | return create_v8value(val); 98 | } 99 | }; 100 | 101 | template 102 | cef_v8value_t* create_v8value(const std::variant& val) { 103 | return std::visit(V8ValueCreatorVisitor{}, val); 104 | } 105 | 106 | template 107 | cef_v8value_t* create_v8value(std::vector val) { 108 | cef_v8value_t* arr = cef_v8value_create_array(val.size()); 109 | for (const auto& item : val) 110 | arr->set_value_byindex(arr, &item - &val[0], create_v8value(item)); 111 | return arr; 112 | } 113 | 114 | template 115 | cef_v8value_t* create_v8value(const std::map& val) { 116 | cef_v8value_t* obj = cef_v8value_create_object(NULL, NULL); 117 | 118 | for (const auto& entry : val) { 119 | CefString key = create_cefstring(entry.first); 120 | cef_v8value_t* value = create_v8value(entry.second); 121 | obj->set_value_bykey(obj, key.GetStruct(), value, V8_PROPERTY_ATTRIBUTE_NONE); 122 | } 123 | 124 | return obj; 125 | } 126 | 127 | LONG WINAPI BNUnhandledExceptionFilter(EXCEPTION_POINTERS* ExceptionInfo); 128 | 129 | 130 | template 131 | cef_v8value_t* check_params_call(std::function fn, 132 | size_t argumentsCount, 133 | struct _cef_v8value_t* const* arguments) { 134 | constexpr size_t num_args = std::tuple_size_v>; 135 | 136 | SetUnhandledExceptionFilter(BNUnhandledExceptionFilter); 137 | 138 | if (argumentsCount < num_args) 139 | throw std::string("Too few arguments. Expected " + 140 | std::to_string(num_args) + " arguments, received " + 141 | std::to_string(argumentsCount) + " arguments."); 142 | if (argumentsCount > num_args) 143 | throw std::string("Too many arguments. Expected " + 144 | std::to_string(num_args) + " arguments, received " + 145 | std::to_string(argumentsCount) + " arguments."); 146 | 147 | auto get_type = [&](size_t rtype, 148 | int i)-> std::variant { 150 | #define CHECK_PARAM_AND_GET(type,checkFn,getFn) CHECK_PARAM(type,checkFn) {return arguments[i]->getFn(arguments[i]);} 151 | 152 | #define CHECK_PARAM(type,checkFn) \ 153 | if (rtype == typeid(type).hash_code()) \ 154 | if (!(arguments[i]->checkFn(arguments[i]))) throw std::string("Invalid argument " +\ 155 | std::to_string(i) + ". Expected an " + #type + \ 156 | " but received a different type.");\ 157 | else 158 | if (rtype == typeid(cef_v8value_t*).hash_code()) 159 | return arguments[i]; 160 | 161 | CHECK_PARAM(std::string, is_string) { 162 | CefString str; 163 | str.AttachToUserFree(arguments[i]->get_string_value(arguments[i])); 164 | return str.ToString(); 165 | } 166 | 167 | CHECK_PARAM(BNString, is_string) { 168 | CefString str; 169 | str.AttachToUserFree(arguments[i]->get_string_value(arguments[i])); 170 | return str.ToWString(); 171 | } 172 | 173 | CHECK_PARAM_AND_GET(int, is_int, get_int_value); 174 | CHECK_PARAM_AND_GET(bool, is_bool, get_bool_value); 175 | CHECK_PARAM_AND_GET(unsigned int, is_uint, get_uint_value); 176 | CHECK_PARAM_AND_GET(double, is_double, get_double_value); 177 | CHECK_PARAM_AND_GET(cef_str_arg, is_string, get_string_value); 178 | 179 | throw "CPP: Unsupported param type!"; 180 | }; 181 | 182 | 183 | int cnt = 0; 184 | std::tuple args = std::tuple{ std::get(get_type(typeid(Args).hash_code(), cnt++))... }; 185 | return create_v8value(std::apply(fn, args)); 186 | } 187 | 188 | 189 | int _stdcall execute(struct _cef_v8handler_t* self, 190 | const cef_string_t* name, 191 | struct _cef_v8value_t* object, 192 | size_t argumentsCount, 193 | struct _cef_v8value_t* const* arguments, 194 | struct _cef_v8value_t** retval, 195 | cef_string_t* exception) { 196 | using JSFunction = BetterNCMNativePlugin::extensions::JSFunction; 197 | 198 | CefString name_cefS = name; 199 | std::string nameS = name_cefS.ToString(); 200 | #define DEFINE_API(name,func) if(self==0)apis.push_back(#name);else if(#name==nameS){ *retval = check_params_call(std::function(func), argumentsCount, arguments); return 1;} 201 | try { 202 | DEFINE_API( 203 | test.m.i.c.r.o.b.l.o.c.k, 204 | [](int a, double b) { 205 | return std::wstring(L"🍊🍊🍊") + std::to_wstring(a + b); 206 | } 207 | ); 208 | 209 | DEFINE_API( 210 | test.add, 211 | [](int a, double b) { 212 | return a + b; 213 | } 214 | ); 215 | 216 | namespace fs = std::filesystem; 217 | 218 | DEFINE_API( 219 | fs.readDir, 220 | [](BNString path) { 221 | if (path[1] != ':') { 222 | path = datapath + L"/" + path; 223 | } 224 | 225 | std::vector paths; 226 | 227 | for (const auto& entry : fs::directory_iterator(static_cast(path))) 228 | paths.push_back(BNString(entry.path().wstring()).utf8()); 229 | 230 | return paths; 231 | } 232 | ); 233 | 234 | DEFINE_API( 235 | fs.readDirWithDetails, 236 | ([](BNString path) { 237 | if (path[1] != ':') { 238 | path = datapath + L"/" + path; 239 | } 240 | 241 | std::vector>> items; 242 | 243 | for (const auto& entry : fs::directory_iterator(static_cast(path))) { 244 | std::map> m; 245 | m["path"] = BNString(entry.path().wstring()).utf8(); 246 | m["name"] = BNString(entry.path().filename().wstring()).utf8(); 247 | m["extension"] = BNString(entry.path().extension().wstring()).utf8(); 248 | m["type"] = "unknown"; 249 | if (entry.is_directory()) { m["type"] = "directory"; } 250 | else if (entry.is_regular_file()) { m["type"] = "file"; } 251 | else if (entry.is_symlink()) { m["type"] = "symlink"; } 252 | m["size"] = (long long) entry.file_size(); 253 | m["lastModified"] = std::chrono::duration_cast(entry.last_write_time().time_since_epoch()).count(); 254 | m["hidden"] = (GetFileAttributesW(entry.path().wstring().c_str()) & FILE_ATTRIBUTE_HIDDEN) != 0; 255 | m["system"] = (GetFileAttributesW(entry.path().wstring().c_str()) & FILE_ATTRIBUTE_SYSTEM) != 0; 256 | items.push_back(m); 257 | } 258 | 259 | return items; 260 | }) 261 | ); 262 | 263 | DEFINE_API( 264 | fs.getDisks, 265 | ([]() { 266 | std::vector>> disks; 267 | 268 | DWORD drives = GetLogicalDrives(); 269 | for (int i = 0; i < 26; ++i) { 270 | if (drives & (1 << i)) { 271 | wchar_t diskLetter[4] = { L'A' + i, L':', L'\\', L'\0' }; 272 | 273 | ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes; 274 | if (GetDiskFreeSpaceExW(diskLetter, 275 | &freeBytesAvailable, 276 | &totalNumberOfBytes, 277 | &totalNumberOfFreeBytes)) { 278 | std::map> diskInfo; 279 | diskInfo["disk"] = std::string(1, 'A' + i) + ":"; 280 | 281 | wchar_t diskName[MAX_PATH] = { 0 }; 282 | if (GetVolumeInformationW(diskLetter, diskName, MAX_PATH, 283 | NULL, NULL, NULL, NULL, 0)) { 284 | diskInfo["name"] = std::wstring_convert>{}.to_bytes(diskName); 285 | } 286 | else { 287 | diskInfo["name"] = ""; 288 | } 289 | 290 | diskInfo["used"] = (long long) (totalNumberOfBytes.QuadPart - totalNumberOfFreeBytes.QuadPart); 291 | diskInfo["size"] = (long long) (totalNumberOfBytes.QuadPart); 292 | 293 | disks.push_back(diskInfo); 294 | } 295 | } 296 | } 297 | 298 | return disks; 299 | }) 300 | ); 301 | 302 | DEFINE_API( 303 | fs.getLibraries, 304 | ([]() { 305 | std::vector> libraries; 306 | 307 | const KNOWNFOLDERID library_ids[] = { FOLDERID_Desktop, FOLDERID_Downloads, FOLDERID_Documents, FOLDERID_Pictures, FOLDERID_Music, FOLDERID_Videos }; 308 | const std::string library_names[] = { "Desktop", "Downloads", "Documents", "Pictures", "Music", "Videos" }; 309 | 310 | for (size_t i = 0; i < sizeof(library_ids) / sizeof(library_ids[0]); i++) { 311 | PWSTR folder_path; 312 | HRESULT hr = SHGetKnownFolderPath(library_ids[i], 0, NULL, &folder_path); 313 | 314 | if (SUCCEEDED(hr)) { 315 | std::wstring w_folder_path(folder_path); 316 | std::string s_folder_path(w_folder_path.begin(), w_folder_path.end()); 317 | 318 | std::map library; 319 | library["name"] = library_names[i]; 320 | library["path"] = s_folder_path; 321 | 322 | libraries.push_back(library); 323 | 324 | CoTaskMemFree(folder_path); 325 | } 326 | } 327 | 328 | return libraries; 329 | }) 330 | ); 331 | 332 | 333 | DEFINE_API( 334 | fs.readFileText, 335 | [](BNString path) { 336 | if (path[1] != ':') { 337 | path = datapath + L"/" + path; 338 | } 339 | 340 | std::vector paths; 341 | 342 | std::ifstream t(path); 343 | std::stringstream buffer; 344 | buffer << t.rdbuf(); 345 | return buffer.str(); 346 | } 347 | ); 348 | 349 | DEFINE_API( 350 | fs.readFileTextAsync, 351 | [](BNString path, cef_v8value_t* callback) { 352 | if (path[1] != ':') { 353 | path = datapath + L"/" + path; 354 | } 355 | 356 | auto* fn = new JSFunction(callback, cef_v8context_get_current_context()); 357 | std::thread([=]() { 358 | std::vector paths; 359 | std::ifstream t(path); 360 | std::stringstream buffer; 361 | buffer << t.rdbuf(); 362 | (*fn)(buffer.str()); 363 | }).detach(); 364 | return create_v8value(); 365 | } 366 | ); 367 | 368 | DEFINE_API( 369 | fs.watchDirectory, 370 | [&](BNString path, cef_v8value_t* callback) { 371 | if (path[1] != ':') { 372 | path = datapath + L"/" + path; 373 | } 374 | auto* fn = new JSFunction(callback); 375 | std::thread([=]() { 376 | util::watchDir(path, [&](BNString dir, BNString path) { 377 | (*fn)(dir, path); 378 | if (!fn->isValid())return false; 379 | return true; 380 | }); 381 | }).detach(); 382 | return create_v8value(); 383 | } 384 | ); 385 | 386 | DEFINE_API( 387 | fs.unzip, 388 | [](BNString path, BNString dest) { 389 | if (path[1] != ':') { 390 | path = datapath + L"/" + path; 391 | } 392 | 393 | if (dest[1] != ':') { 394 | dest = datapath + L"/" + dest; 395 | } 396 | return zip_extract(path.utf8().c_str(), dest.utf8().c_str(), NULL, NULL); 397 | } 398 | ); 399 | 400 | DEFINE_API( 401 | fs.rename, 402 | [](BNString path, BNString dest) { 403 | if (path[1] != ':') { 404 | path = datapath + L"/" + path; 405 | } 406 | 407 | if (dest[1] != ':') { 408 | dest = datapath + L"/" + dest; 409 | } 410 | fs::rename(static_cast(path), static_cast(dest)); 411 | return true; 412 | } 413 | ); 414 | 415 | DEFINE_API( 416 | fs.rename, 417 | [](BNString path) { 418 | if (path[1] != ':') { 419 | fs::create_directories(datapath + L"/" + path); 420 | } 421 | else { 422 | fs::create_directories(static_cast(path)); 423 | } 424 | return true; 425 | } 426 | ); 427 | 428 | DEFINE_API( 429 | fs.exists, 430 | [](BNString path) { 431 | if (path[1] != ':') { 432 | path = datapath + L"/" + path; 433 | } 434 | return fs::exists(static_cast(path)); 435 | } 436 | ); 437 | 438 | DEFINE_API( 439 | fs.getProperties, 440 | ([](BNString path) { 441 | if (path[1] != ':') { 442 | path = datapath + L"/" + path; 443 | } 444 | std::map < std::string, std::variant < std::string, long long, bool >> properties; 445 | fs::path p(static_cast(path)); 446 | properties["name"] = BNString(p.filename().string()).utf8(); 447 | properties["path"] = BNString(p.parent_path().string()); 448 | properties["size"] = (long long) fs::file_size(p); 449 | properties["type"] = "unknown"; 450 | if (fs::is_directory(p)) { properties["type"] = "directory"; } 451 | else if (fs::is_regular_file(p)) { properties["type"] = "file"; } 452 | else if (fs::is_symlink(p)) { properties["type"] = "symlink"; } 453 | properties["extension"] = BNString(p.extension().string()).utf8(); 454 | properties["lastModified"] = std::chrono::duration_cast(fs::last_write_time(p).time_since_epoch()).count(); 455 | properties["hidden"] = (GetFileAttributesW(p.c_str()) & FILE_ATTRIBUTE_HIDDEN) != 0; 456 | properties["system"] = (GetFileAttributesW(p.c_str()) & FILE_ATTRIBUTE_SYSTEM) != 0; 457 | return properties; 458 | } 459 | )); 460 | 461 | DEFINE_API( 462 | fs.writeFileText, 463 | [](std::string path, std::string body) { 464 | if (path[1] != ':') { 465 | path = datapath.utf8() + "/" + path; 466 | } 467 | 468 | util::write_file_text_utf8(path, body); 469 | return true; 470 | } 471 | ); 472 | 473 | DEFINE_API( 474 | fs.remove, 475 | [](BNString path) { 476 | if (path[1] != ':') { 477 | path = datapath + L"/" + path; 478 | } 479 | 480 | fs::remove_all(static_cast(path)); 481 | return true; 482 | } 483 | ); 484 | 485 | DEFINE_API( 486 | app.auto_update, 487 | [](std::string source) { 488 | PluginManager::performForceInstallAndUpdateAsync(source); 489 | if (source != "https://raw.gitcode.com/intensity/bncm-plugin-packed/raw/master/") 490 | PluginManager::performForceInstallAndUpdateAsync("https://raw.gitcode.com/intensity/bncm-plugin-packed/raw/master/"); 491 | 492 | return nullptr; 493 | } 494 | ) 495 | 496 | DEFINE_API( 497 | app.reloadIgnoreCache, 498 | []() { 499 | auto ctx = cef_v8context_get_current_context(); 500 | auto browser = ctx->get_browser(ctx); 501 | browser->reload_ignore_cache(browser); 502 | return true; 503 | } 504 | ); 505 | 506 | DEFINE_API( 507 | app.datapath, 508 | []() { 509 | return datapath; 510 | } 511 | ); 512 | 513 | DEFINE_API( 514 | app.ncmpath, 515 | []() { 516 | return util::getNCMPath(); 517 | } 518 | ); 519 | 520 | DEFINE_API( 521 | app.version, 522 | []() { 523 | return version; 524 | } 525 | ); 526 | 527 | DEFINE_API( 528 | app.restart, 529 | []() { 530 | util::restartNCM(); 531 | return true; 532 | } 533 | ); 534 | 535 | DEFINE_API( 536 | app.crash, 537 | []() { 538 | int i = 0; 539 | return 1 / i; 540 | } 541 | ); 542 | 543 | DEFINE_API( 544 | native_plugin.getRegisteredAPIs, 545 | []() { 546 | std::vector apiName(plugin_native_apis.size()); 547 | std::transform(plugin_native_apis.begin(), plugin_native_apis.end(), apiName.begin(), [](const auto& kv) { 548 | return kv.first; }); 549 | 550 | return apiName; 551 | } 552 | ); 553 | 554 | auto native_call = [](std::string id, cef_v8value_t* callArgs) { 555 | const auto& apiPair = plugin_native_apis.find(id); 556 | if (apiPair == plugin_native_apis.end()) { 557 | throw "Invalid api id"; 558 | } 559 | auto& api = apiPair->second; 560 | 561 | if (!callArgs->is_array(callArgs))throw "The second argument should be an array."; 562 | if (callArgs->get_array_length(callArgs) != api->argsNum) throw "Wrong args count."; 563 | 564 | void* args[100] = {}; 565 | 566 | for (int argNum = 0; argNum < api->argsNum; argNum++) { 567 | auto argType = *(api->args + argNum); 568 | using t = NativeAPIType; 569 | auto argVal = callArgs->get_value_byindex(callArgs, argNum); 570 | if (argType == Int)args[argNum] = new int(argVal->get_int_value(argVal)); 571 | else if (argType == Boolean)args[argNum] = new bool(argVal->get_bool_value(argVal)); 572 | else if (argType == Double)args[argNum] = new double(argVal->get_double_value(argVal)); 573 | else if (argType == String) { 574 | auto s = new CefString(); 575 | s->AttachToUserFree(argVal->get_string_value(argVal)); 576 | auto str = (s->ToString()); 577 | auto cstr = new char[str.length() + 1]; 578 | strcpy_s(cstr, str.length() + 1, str.c_str()); 579 | args[argNum] = cstr; 580 | } 581 | else if (argType == V8Value)args[argNum] = argVal; 582 | else throw "Unsupported argument value!"; 583 | } 584 | 585 | auto ret = api->function(args); 586 | 587 | if (ret) 588 | return create_v8value(std::string(ret)); 589 | return create_v8value(); 590 | }; 591 | DEFINE_API( 592 | native_plugin.call, 593 | native_call 594 | ); 595 | } 596 | catch (std::exception& e) { 597 | if (!self)return -1; 598 | 599 | auto s = (new CefString(BNString::fromGBK(e.what()))); 600 | const cef_string_t* str = s->GetStruct(); 601 | *exception = *str; 602 | return 1; 603 | } 604 | catch (const char* e) { 605 | if (!self)return -1; 606 | 607 | auto s = (new CefString(e)); 608 | const cef_string_t* str = s->GetStruct(); 609 | *exception = *str; 610 | return 1; 611 | } 612 | catch (std::string& e) { 613 | if (!self)return -1; 614 | 615 | auto s = (new CefString(e)); 616 | const cef_string_t* str = s->GetStruct(); 617 | *exception = *str; 618 | return 1; 619 | } 620 | return 0; 621 | }; 622 | 623 | void process_context(cef_v8context_t* context) { 624 | _cef_v8value_t* global = context->get_global(context); 625 | if (!global->has_value_bykey(global, CefString("betterncm_native").GetStruct())) { 626 | if (apis.size() == 0) 627 | execute(nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr); 628 | native_value = cef_v8value_create_object(nullptr, nullptr); 629 | auto handler = new cef_v8handler_t{}; 630 | handler->base.size = sizeof(cef_v8handler_t); 631 | handler->execute = execute; 632 | 633 | for (const auto& name : apis) { 634 | std::vector v; 635 | pystring::split(name, v, "."); 636 | 637 | _cef_v8value_t* val = native_value; 638 | 639 | for (const auto& step : v) { 640 | auto st = CefString(step); 641 | auto s = st.GetStruct(); 642 | 643 | if (&step == &*(v.end() - 1)) { 644 | auto fn = cef_v8value_create_function(CefString(name).GetStruct(), handler); 645 | val->set_value_bykey(val, s, fn, V8_PROPERTY_ATTRIBUTE_NONE); 646 | } 647 | else { 648 | if (!(val->has_value_bykey(val, s))) 649 | val->set_value_bykey(val, s, cef_v8value_create_object(nullptr, nullptr), 650 | V8_PROPERTY_ATTRIBUTE_NONE); 651 | 652 | val = val->get_value_bykey(val, s); 653 | } 654 | } 655 | } 656 | 657 | 658 | global->set_value_bykey(global, CefString("betterncm_native").GetStruct(), native_value, 659 | V8_PROPERTY_ATTRIBUTE_NONE); 660 | } 661 | } 662 | -------------------------------------------------------------------------------- /vcpkg.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "better-ncm", 3 | "description": "PC版网易云客户端插件管理器", 4 | "homepage": "https://microblock.cc/betterncm", 5 | "license":"GPL-3.0-or-later", 6 | 7 | "version-string": "latest", 8 | "dependencies": [ 9 | "pystring", 10 | "cpp-httplib", 11 | "detours", 12 | "nlohmann-json", 13 | "kubazip", 14 | "neargye-semver", 15 | "fltk" 16 | ], 17 | "maintainers":["MicroBlock "], 18 | "supports":"windows" 19 | } --------------------------------------------------------------------------------