├── .gitattributes ├── .github └── workflows │ ├── build.yml │ └── release.yml ├── .gitignore ├── LICENSE.txt ├── README.md ├── ResoniteModUpdater.sln └── ResoniteModUpdater ├── Commands ├── Default.cs ├── Search.cs └── Update.cs ├── Manifest.cs ├── Program.cs ├── ResoniteModUpdater.csproj ├── Strings.cs └── Utils.cs /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | workflow_dispatch: 5 | 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | permissions: 10 | contents: write 11 | env: 12 | PROJECT: ResoniteModUpdater 13 | DOTNET_VERSION: '9.0.x' 14 | VPK_VERSION: '0.0.1298' 15 | DOTNET_NOLOGO: true 16 | 17 | strategy: 18 | fail-fast: true 19 | max-parallel: 1 20 | matrix: 21 | include: 22 | - platform: linux-x64 23 | self-contained: true 24 | extra-args: '' 25 | - platform: win-x64 26 | self-contained: false 27 | extra-args: '--noPortable --framework net9.0-x64-runtime' 28 | - platform: win-x64 29 | self-contained: true 30 | extra-args: '--noInst --packTitle win-x64-portable' 31 | is-portable: true 32 | 33 | steps: 34 | - name: Checkout Repository 35 | uses: actions/checkout@v4 36 | 37 | - name: Setup .NET 38 | uses: actions/setup-dotnet@v4 39 | with: 40 | dotnet-version: ${{ env.DOTNET_VERSION }} 41 | 42 | - name: Get Version from Project File 43 | id: get-version 44 | shell: bash 45 | run: echo "version=$(grep -oE '[^<]+' ${{ env.PROJECT }}/${{ env.PROJECT }}.csproj | sed 's///')" >> $GITHUB_OUTPUT 46 | 47 | - name: Install Velopack CLI 48 | run: dotnet tool install -g vpk --version ${{ env.VPK_VERSION }} 49 | 50 | - name: Build Project 51 | run: dotnet publish ${{ env.PROJECT }}/${{ env.PROJECT }}.csproj -c Release -o publish/${{ matrix.platform }}${{ matrix.is-portable && '-portable' || '' }} -r ${{ matrix.platform }} ${{ matrix.self-contained && '--self-contained' || '--no-self-contained' }} 52 | 53 | - name: Download Previous Releases 54 | run: vpk download github --repoUrl ${{ github.server_url }}/${{ github.repository }} --channel ${{ matrix.platform }}${{ matrix.is-portable && '-portable' || '' }} -o releases 55 | 56 | - name: Pack New Release 57 | run: vpk ${{ startsWith(matrix.platform, 'win') && '[win] ' || '' }}pack -u ${{ env.PROJECT }} -v ${{ steps.get-version.outputs.version }} -r ${{ matrix.platform }} --channel ${{ matrix.platform }}${{ matrix.is-portable && '-portable' || '' }} ${{ matrix.extra-args }} -p publish/${{ matrix.platform }}${{ matrix.is-portable && '-portable' || '' }} -o releases 58 | 59 | - name: Rename and Update Portable Package 60 | if: matrix.is-portable 61 | run: | 62 | mv releases/${{ env.PROJECT }}-${{ matrix.platform }}-portable-Portable.zip releases/${{ env.PROJECT }}-${{ matrix.platform }}-portable.zip 63 | JSON_FILE="./releases/assets.${{ matrix.platform }}-portable.json" 64 | sed -i 's/ResoniteModUpdater-win-x64-portable-Portable.zip/ResoniteModUpdater-win-x64-portable.zip/g' "$JSON_FILE" 65 | 66 | - name: Upload artifacts 67 | uses: actions/upload-artifact@v4 68 | with: 69 | name: ${{ env.PROJECT }}-${{ matrix.platform }}${{ matrix.is-portable && '-portable' || '' }}-${{ steps.get-version.outputs.version }} 70 | path: | 71 | releases/**/releases.*.json 72 | releases/**/*.nupkg 73 | releases/**/*.zip 74 | releases/**/*.exe 75 | releases/**/*.AppImage 76 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Build and Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | workflow_dispatch: 8 | 9 | jobs: 10 | build-and-release: 11 | runs-on: ubuntu-latest 12 | permissions: 13 | contents: write 14 | env: 15 | PROJECT: ResoniteModUpdater 16 | DOTNET_VERSION: '9.0.x' 17 | VPK_VERSION: '0.0.1298' 18 | DOTNET_NOLOGO: true 19 | 20 | strategy: 21 | fail-fast: true 22 | max-parallel: 1 23 | matrix: 24 | include: 25 | - platform: linux-x64 26 | self-contained: true 27 | extra-args: '' 28 | - platform: win-x64 29 | self-contained: false 30 | extra-args: '--noPortable --framework net9.0-x64-runtime' 31 | - platform: win-x64 32 | self-contained: true 33 | extra-args: '--noInst --packTitle win-x64-portable' 34 | is-portable: true 35 | 36 | steps: 37 | - name: Checkout Repository 38 | uses: actions/checkout@v4 39 | 40 | - name: Setup .NET 41 | uses: actions/setup-dotnet@v4 42 | with: 43 | dotnet-version: ${{ env.DOTNET_VERSION }} 44 | 45 | - name: Get Version from Project File 46 | id: get-version 47 | shell: bash 48 | run: echo "version=$(grep -oE '[^<]+' ${{ env.PROJECT }}/${{ env.PROJECT }}.csproj | sed 's///')" >> $GITHUB_OUTPUT 49 | 50 | - name: Install Velopack CLI 51 | run: dotnet tool install -g vpk --version ${{ env.VPK_VERSION }} 52 | 53 | - name: Build Project 54 | run: dotnet publish ${{ env.PROJECT }}/${{ env.PROJECT }}.csproj -c Release -o publish/${{ matrix.platform }}${{ matrix.is-portable && '-portable' || '' }} -r ${{ matrix.platform }} ${{ matrix.self-contained && '--self-contained' || '--no-self-contained' }} 55 | 56 | - name: Download Previous Releases 57 | run: vpk download github --repoUrl ${{ github.server_url }}/${{ github.repository }} --channel ${{ matrix.platform }}${{ matrix.is-portable && '-portable' || '' }} -o releases 58 | 59 | - name: Pack New Release 60 | run: vpk ${{ startsWith(matrix.platform, 'win') && '[win] ' || '' }}pack -u ${{ env.PROJECT }} -v ${{ steps.get-version.outputs.version }} -r ${{ matrix.platform }} --channel ${{ matrix.platform }}${{ matrix.is-portable && '-portable' || '' }} ${{ matrix.extra-args }} -p publish/${{ matrix.platform }}${{ matrix.is-portable && '-portable' || '' }} -o releases 61 | 62 | - name: Rename and Update Portable Package 63 | if: matrix.is-portable 64 | run: | 65 | mv releases/${{ env.PROJECT }}-${{ matrix.platform }}-portable-Portable.zip releases/${{ env.PROJECT }}-${{ matrix.platform }}-portable.zip 66 | JSON_FILE="./releases/assets.${{ matrix.platform }}-portable.json" 67 | sed -i 's/ResoniteModUpdater-win-x64-portable-Portable.zip/ResoniteModUpdater-win-x64-portable.zip/g' "$JSON_FILE" 68 | 69 | - name: Create Release 70 | uses: softprops/action-gh-release@v2 71 | with: 72 | draft: true 73 | prerelease: false 74 | generate_release_notes: false 75 | name: v${{ steps.get-version.outputs.version }} 76 | tag_name: v${{ steps.get-version.outputs.version }} 77 | target_commitish: ${{ github.sha }} 78 | files: | 79 | releases/**/releases.*.json 80 | releases/**/*.nupkg 81 | releases/**/*.zip 82 | releases/**/*.exe 83 | releases/**/*.AppImage 84 | env: 85 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 86 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | [Aa][Rr][Mm]/ 24 | [Aa][Rr][Mm]64/ 25 | bld/ 26 | [Bb]in/ 27 | [Oo]bj/ 28 | [Ll]og/ 29 | 30 | # Visual Studio 2015/2017 cache/options directory 31 | .vs/ 32 | # Uncomment if you have tasks that create the project's static files in wwwroot 33 | #wwwroot/ 34 | 35 | # Visual Studio 2017 auto generated files 36 | Generated\ Files/ 37 | 38 | # MSTest test Results 39 | [Tt]est[Rr]esult*/ 40 | [Bb]uild[Ll]og.* 41 | 42 | # NUNIT 43 | *.VisualState.xml 44 | TestResult.xml 45 | 46 | # Build Results of an ATL Project 47 | [Dd]ebugPS/ 48 | [Rr]eleasePS/ 49 | dlldata.c 50 | 51 | # Benchmark Results 52 | BenchmarkDotNet.Artifacts/ 53 | 54 | # .NET Core 55 | project.lock.json 56 | project.fragment.lock.json 57 | artifacts/ 58 | 59 | # StyleCop 60 | StyleCopReport.xml 61 | 62 | # Files built by Visual Studio 63 | *_i.c 64 | *_p.c 65 | *_h.h 66 | *.ilk 67 | *.meta 68 | *.obj 69 | *.iobj 70 | *.pch 71 | *.pdb 72 | *.ipdb 73 | *.pgc 74 | *.pgd 75 | *.rsp 76 | *.sbr 77 | *.tlb 78 | *.tli 79 | *.tlh 80 | *.tmp 81 | *.tmp_proj 82 | *_wpftmp.csproj 83 | *.log 84 | *.vspscc 85 | *.vssscc 86 | .builds 87 | *.pidb 88 | *.svclog 89 | *.scc 90 | 91 | # Chutzpah Test files 92 | _Chutzpah* 93 | 94 | # Visual C++ cache files 95 | ipch/ 96 | *.aps 97 | *.ncb 98 | *.opendb 99 | *.opensdf 100 | *.sdf 101 | *.cachefile 102 | *.VC.db 103 | *.VC.VC.opendb 104 | 105 | # Visual Studio profiler 106 | *.psess 107 | *.vsp 108 | *.vspx 109 | *.sap 110 | 111 | # Visual Studio Trace Files 112 | *.e2e 113 | 114 | # TFS 2012 Local Workspace 115 | $tf/ 116 | 117 | # Guidance Automation Toolkit 118 | *.gpState 119 | 120 | # ReSharper is a .NET coding add-in 121 | _ReSharper*/ 122 | *.[Rr]e[Ss]harper 123 | *.DotSettings.user 124 | 125 | # JustCode is a .NET coding add-in 126 | .JustCode 127 | 128 | # TeamCity is a build add-in 129 | _TeamCity* 130 | 131 | # DotCover is a Code Coverage Tool 132 | *.dotCover 133 | 134 | # AxoCover is a Code Coverage Tool 135 | .axoCover/* 136 | !.axoCover/settings.json 137 | 138 | # Visual Studio code coverage results 139 | *.coverage 140 | *.coveragexml 141 | 142 | # NCrunch 143 | _NCrunch_* 144 | .*crunch*.local.xml 145 | nCrunchTemp_* 146 | 147 | # MightyMoose 148 | *.mm.* 149 | AutoTest.Net/ 150 | 151 | # Web workbench (sass) 152 | .sass-cache/ 153 | 154 | # Installshield output folder 155 | [Ee]xpress/ 156 | 157 | # DocProject is a documentation generator add-in 158 | DocProject/buildhelp/ 159 | DocProject/Help/*.HxT 160 | DocProject/Help/*.HxC 161 | DocProject/Help/*.hhc 162 | DocProject/Help/*.hhk 163 | DocProject/Help/*.hhp 164 | DocProject/Help/Html2 165 | DocProject/Help/html 166 | 167 | # Click-Once directory 168 | publish/ 169 | 170 | # Publish Web Output 171 | *.[Pp]ublish.xml 172 | *.azurePubxml 173 | # Note: Comment the next line if you want to checkin your web deploy settings, 174 | # but database connection strings (with potential passwords) will be unencrypted 175 | *.pubxml 176 | *.publishproj 177 | 178 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 179 | # checkin your Azure Web App publish settings, but sensitive information contained 180 | # in these scripts will be unencrypted 181 | PublishScripts/ 182 | 183 | # NuGet Packages 184 | *.nupkg 185 | # The packages folder can be ignored because of Package Restore 186 | **/[Pp]ackages/* 187 | # except build/, which is used as an MSBuild target. 188 | !**/[Pp]ackages/build/ 189 | # Uncomment if necessary however generally it will be regenerated when needed 190 | #!**/[Pp]ackages/repositories.config 191 | # NuGet v3's project.json files produces more ignorable files 192 | *.nuget.props 193 | *.nuget.targets 194 | 195 | # Microsoft Azure Build Output 196 | csx/ 197 | *.build.csdef 198 | 199 | # Microsoft Azure Emulator 200 | ecf/ 201 | rcf/ 202 | 203 | # Windows Store app package directories and files 204 | AppPackages/ 205 | BundleArtifacts/ 206 | Package.StoreAssociation.xml 207 | _pkginfo.txt 208 | *.appx 209 | 210 | # Visual Studio cache files 211 | # files ending in .cache can be ignored 212 | *.[Cc]ache 213 | # but keep track of directories ending in .cache 214 | !?*.[Cc]ache/ 215 | 216 | # Others 217 | ClientBin/ 218 | ~$* 219 | *~ 220 | *.dbmdl 221 | *.dbproj.schemaview 222 | *.jfm 223 | *.pfx 224 | *.publishsettings 225 | orleans.codegen.cs 226 | 227 | # Including strong name files can present a security risk 228 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 229 | #*.snk 230 | 231 | # Since there are multiple workflows, uncomment next line to ignore bower_components 232 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 233 | #bower_components/ 234 | 235 | # RIA/Silverlight projects 236 | Generated_Code/ 237 | 238 | # Backup & report files from converting an old project file 239 | # to a newer Visual Studio version. Backup files are not needed, 240 | # because we have git ;-) 241 | _UpgradeReport_Files/ 242 | Backup*/ 243 | UpgradeLog*.XML 244 | UpgradeLog*.htm 245 | ServiceFabricBackup/ 246 | *.rptproj.bak 247 | 248 | # SQL Server files 249 | *.mdf 250 | *.ldf 251 | *.ndf 252 | 253 | # Business Intelligence projects 254 | *.rdl.data 255 | *.bim.layout 256 | *.bim_*.settings 257 | *.rptproj.rsuser 258 | *- Backup*.rdl 259 | 260 | # Microsoft Fakes 261 | FakesAssemblies/ 262 | 263 | # GhostDoc plugin setting file 264 | *.GhostDoc.xml 265 | 266 | # Node.js Tools for Visual Studio 267 | .ntvs_analysis.dat 268 | node_modules/ 269 | 270 | # Visual Studio 6 build log 271 | *.plg 272 | 273 | # Visual Studio 6 workspace options file 274 | *.opt 275 | 276 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 277 | *.vbw 278 | 279 | # Visual Studio LightSwitch build output 280 | **/*.HTMLClient/GeneratedArtifacts 281 | **/*.DesktopClient/GeneratedArtifacts 282 | **/*.DesktopClient/ModelManifest.xml 283 | **/*.Server/GeneratedArtifacts 284 | **/*.Server/ModelManifest.xml 285 | _Pvt_Extensions 286 | 287 | # Paket dependency manager 288 | .paket/paket.exe 289 | paket-files/ 290 | 291 | # FAKE - F# Make 292 | .fake/ 293 | 294 | # JetBrains Rider 295 | .idea/ 296 | *.sln.iml 297 | 298 | # CodeRush personal settings 299 | .cr/personal 300 | 301 | # Python Tools for Visual Studio (PTVS) 302 | __pycache__/ 303 | *.pyc 304 | 305 | # Cake - Uncomment if you are using it 306 | # tools/** 307 | # !tools/packages.config 308 | 309 | # Tabs Studio 310 | *.tss 311 | 312 | # Telerik's JustMock configuration file 313 | *.jmconfig 314 | 315 | # BizTalk build output 316 | *.btp.cs 317 | *.btm.cs 318 | *.odx.cs 319 | *.xsd.cs 320 | 321 | # OpenCover UI analysis results 322 | OpenCover/ 323 | 324 | # Azure Stream Analytics local run output 325 | ASALocalRun/ 326 | 327 | # MSBuild Binary and Structured Log 328 | *.binlog 329 | 330 | # NVidia Nsight GPU debugger configuration file 331 | *.nvuser 332 | 333 | # MFractors (Xamarin productivity tool) working folder 334 | .mfractor/ 335 | 336 | # Local History for Visual Studio 337 | .localhistory/ 338 | 339 | # BeatPulse healthcheck temp database 340 | healthchecksdb 341 | 342 | .env 343 | .env.* -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 hazre 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Resonite Mod Updater CLI 2 | 3 | **ResoniteModUpdater** is a command-line tool that helps you update mods for Resonite. Updates only mods that have a GitHub Link variable. 4 | > [!WARNING] 5 | > Does not work with monorepos with multiple mods nor with non GitHub repositories. 6 | 7 | ## Prerequisites 8 | - .NET 8.0 or higher is required 9 | - The Windows installer will automatically install .NET 9.0 if you don't have it 10 | 11 | ## Installation 12 | 13 | ### Windows 14 | 1. Download the Windows installer from the [latest release](https://github.com/hazre/ResoniteModUpdater/releases/latest) 15 | 2. Run the installer 16 | - The installer will create desktop and start menu shortcuts for ease of use 17 | - ResoniteModUpdater will be installed under `C:\Users\%UserProfile%\AppData\Local\ResoniteModUpdater` 18 | 19 | ### Linux 20 | 1. Download the AppImage from the [latest release](https://github.com/hazre/ResoniteModUpdater/releases/latest) 21 | 2. Make the AppImage executable and run it 22 | 23 | ## Usage 24 | 25 | > [!NOTE] 26 | > If you have private mods or mods that you don't want to update, you can ignore mods by adding a `_` prefix to the mod's filename. 27 | 28 | ResoniteModUpdater offers both an interactive mode and a CLI mode. 29 | 30 | To start interactive mode, simply run: 31 | 32 | ```sh 33 | ResoniteModUpdater 34 | ``` 35 | 36 | For CLI usage: 37 | 38 | ```sh 39 | ResoniteModUpdater [OPTIONS] [COMMAND] 40 | ``` 41 | 42 | ### Commands 43 | 44 | - `update`: Updates resonite mods 45 | - `search`: Searches for mods in the mod manifest 46 | 47 | ### Options 48 | 49 | - `-h, --help`: Prints help information 50 | - `-v, --version`: Display version in use 51 | 52 | ### Examples 53 | 54 | 1. Update Resonite mods: 55 | 56 | ```sh 57 | ResoniteModUpdater update 58 | ``` 59 | 60 | 2. Update Resonite mods with a specific mods folder: 61 | 62 | ```sh 63 | ResoniteModUpdater update ~/.steam/steam/steamapps/common/Resonite/rml_mods 64 | ``` 65 | 66 | 3. Update Resonite mods with a GitHub authentication token: 67 | 68 | ```sh 69 | ResoniteModUpdater update ~/.steam/steam/steamapps/common/Resonite/rml_mods -token xxxxxxxxxxxxxx 70 | ``` 71 | 72 | 4. Search for mods: 73 | 74 | ```sh 75 | ResoniteModUpdater search example 76 | ``` 77 | 78 | ### Update Command 79 | 80 | ```sh 81 | ResoniteModUpdater update [ModsFolder] [OPTIONS] 82 | ``` 83 | 84 | #### Arguments 85 | 86 | - `[ModsFolder]`: Path to resonite mods folder 87 | 88 | #### Options 89 | 90 | - `-h, --help`: Prints help information 91 | - `-t, --token`: GitHub authentication token for using GitHub's official API. Optional, alternative to RSS feed method 92 | - `-d, --dry`: Enables dry run mode. Checks for mod updates without installing them 93 | 94 | ### Search Command 95 | 96 | ```sh 97 | ResoniteModUpdater search [QUERY] [OPTIONS] 98 | ``` 99 | 100 | #### Arguments 101 | 102 | - `[QUERY]`: Query to search for in the mod manifest 103 | 104 | #### Options 105 | 106 | - `-h, --help`: Prints help information 107 | - `-m, --manifest`: Set alternative manifest json url. It must match the RML manifest schema (Advanced) 108 | 109 | ## Settings File 110 | 111 | The `settings.json` file is used to store the settings for the Resonite Mod Updater. This file is automatically created in the root of the ResoniteModUpdater installation directory when you choose to save your settings. 112 | 113 | On Linux, the `settings.json` file is located either in `$XDG_CONFIG_HOME/ResoniteModUpdater` or `$HOME/.config/ResoniteModUpdater`. 114 | 115 | Here is an example of what the `settings.json` file might look like: 116 | 117 | ```json 118 | { 119 | "ModsFolder": "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Resonite\\rml_mods", 120 | "Token": null, 121 | "DryMode": false, 122 | "ResoniteModLoaderSource": "https://github.com/resonite-modding-group/ResoniteModLoader", 123 | "manifest": "https://raw.githubusercontent.com/resonite-modding-group/resonite-mod-manifest/main/manifest.json" 124 | } 125 | ``` 126 | 127 | ### Fields 128 | 129 | - `ModsFolder`: The path to the Resonite mods folder. 130 | - `Token`: GitHub authentication token to allow downloading from GitHub's official API as an alternative to using GitHub's RSS feed. This option is optional and can be used if preferred over the RSS feed method. 131 | - `DryMode`: A boolean value that enables or disables dry run mode. When enabled, the tool checks for mod updates without installing them. 132 | - `ResoniteModLoaderSource`: Allows you to change where `ResoniteModLoader.dll` and `0Harmony.dll` are updated from. 133 | - `manifest`: It lets you set alternative manifest json url. It must match the ResoniteModLoader manifest schema. 134 | 135 | ### Usage 136 | 137 | If a `settings.json` file is present in the ResoniteModUpdater installation directory, the tool will automatically load the settings from this file. If you want to override these settings, you can do so by providing command line arguments. 138 | 139 | For example, if you have a `settings.json` file that specifies a `ModsFolder` and `Token`, but you want to run the tool in dry run mode, you can do so with the following command: 140 | 141 | ```sh 142 | ResoniteModUpdater update -d 143 | ``` 144 | 145 | This will load the `ModsFolder` and `Token` from the `settings.json` file and enable dry run mode. 146 | -------------------------------------------------------------------------------- /ResoniteModUpdater.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.7.34202.233 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ResoniteModUpdater", "ResoniteModUpdater\ResoniteModUpdater.csproj", "{FFFAB8F2-F1FB-4B01-89FE-B60F45693BFF}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {FFFAB8F2-F1FB-4B01-89FE-B60F45693BFF}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {FFFAB8F2-F1FB-4B01-89FE-B60F45693BFF}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {FFFAB8F2-F1FB-4B01-89FE-B60F45693BFF}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {FFFAB8F2-F1FB-4B01-89FE-B60F45693BFF}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {A8AC6AEA-DA85-4FE1-BD9E-BD4BB36FE1C6} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /ResoniteModUpdater/Commands/Default.cs: -------------------------------------------------------------------------------- 1 | using ResoniteModUpdater.Commands.Search; 2 | using ResoniteModUpdater.Commands.Update; 3 | using Spectre.Console; 4 | using Spectre.Console.Cli; 5 | using System.ComponentModel; 6 | using System.Diagnostics.CodeAnalysis; 7 | using System.Reflection; 8 | using Velopack; 9 | 10 | namespace ResoniteModUpdater.Commands.Default 11 | { 12 | public class DefaultCommand : AsyncCommand 13 | { 14 | public class Settings : CommandSettings 15 | { 16 | [Description(Strings.Descriptions.Version)] 17 | [CommandOption("-v|--version")] 18 | public bool Version { get; set; } 19 | } 20 | 21 | public override async Task ExecuteAsync([NotNull] CommandContext context, [NotNull] Settings settings) 22 | { 23 | if (!AnsiConsole.Profile.Capabilities.Interactive) 24 | { 25 | AnsiConsole.MarkupLine($"[red]{Strings.Errors.NotInteractiveConsole}[/]"); 26 | return 1; 27 | } 28 | 29 | if (settings.Version) 30 | { 31 | AnsiConsole.MarkupLine($"[yellow]{Strings.Application.AppName}[/] [b]v{Utils.GetVersion()}[/] ({VelopackRuntimeInfo.GetOsShortName(VelopackRuntimeInfo.SystemOs)}-{VelopackRuntimeInfo.SystemArch})"); 32 | return 0; 33 | } 34 | 35 | 36 | while (true) 37 | { 38 | AnsiConsole.Clear(); 39 | DisplayMainMenuHeader(); 40 | var choice = ShowMainMenu(); 41 | 42 | var loadedSettings = Utils.LoadSettings(); 43 | 44 | try 45 | { 46 | switch (choice) 47 | { 48 | case Strings.MenuOptions.UpdateMods: 49 | AnsiConsole.Clear(); 50 | var updateSettings = PromptForUpdateSettings(loadedSettings); 51 | AnsiConsole.WriteLine(); 52 | await new UpdateCommand().ExecuteAsync(context, updateSettings); 53 | break; 54 | case Strings.MenuOptions.UpdateLibraries: 55 | AnsiConsole.Clear(); 56 | var updateLibrariesSettings = PromptForUpdateLibrariesSettings(loadedSettings); 57 | AnsiConsole.WriteLine(); 58 | await Utils.UpdateAdditionalLibraries(updateLibrariesSettings, true); 59 | break; 60 | case Strings.MenuOptions.SearchModManifest: 61 | AnsiConsole.Clear(); 62 | var searchSettings = PromptForSearchSettings(loadedSettings); 63 | AnsiConsole.WriteLine(); 64 | await new SearchCommand().ExecuteAsync(context, searchSettings); 65 | break; 66 | case Strings.MenuOptions.ExitApplication: 67 | AnsiConsole.Clear(); 68 | return 0; 69 | } 70 | } 71 | catch (Exception ex) 72 | { 73 | AnsiConsole.WriteException(ex, ExceptionFormats.ShortenEverything); 74 | } 75 | 76 | if (!AnsiConsole.Confirm(Strings.Prompts.ReturnToMainMenu)) 77 | { 78 | return 0; 79 | } 80 | } 81 | } 82 | 83 | private void DisplayMainMenuHeader() 84 | { 85 | var versionString = Utils.GetVersion(); 86 | 87 | var table = new Table().HideHeaders().NoBorder(); 88 | table.Title($"[yellow]{Strings.Application.AppName}[/] [b]v{versionString}[/]"); 89 | table.AddColumn("col1", c => c.NoWrap().RightAligned().PadRight(3)); 90 | table.AddColumn("col2", c => c.PadRight(0)); 91 | table.AddEmptyRow(); 92 | 93 | table.AddEmptyRow(); 94 | table.AddRow( 95 | new Markup($"[yellow]{Strings.MenuOptions.UpdateMods}[/]"), 96 | new Markup(Strings.Descriptions.UpdateMods)); 97 | 98 | table.AddRow( 99 | new Markup($"[yellow]{Strings.MenuOptions.UpdateLibraries}[/]"), 100 | new Markup(Strings.Descriptions.UpdateLibraries)); 101 | 102 | table.AddRow( 103 | new Markup($"[yellow]{Strings.MenuOptions.SearchModManifest}[/]"), 104 | new Markup(Strings.Descriptions.SearchModManifest)); 105 | 106 | 107 | 108 | AnsiConsole.WriteLine(); 109 | AnsiConsole.Write(table); 110 | AnsiConsole.WriteLine(); 111 | } 112 | 113 | private string ShowMainMenu() 114 | { 115 | return AnsiConsole.Prompt( 116 | new SelectionPrompt() 117 | .Title(Strings.Prompts.InteractivePrompt) 118 | .HighlightStyle(new Style(foreground: Color.Orange1, decoration: Decoration.Bold)) 119 | .EnableSearch() 120 | .AddChoices(new[] { 121 | Strings.MenuOptions.UpdateMods, 122 | Strings.MenuOptions.UpdateLibraries, 123 | Strings.MenuOptions.SearchModManifest, 124 | Strings.MenuOptions.ExitApplication 125 | })); 126 | } 127 | 128 | private UpdateCommand.Settings PromptForUpdateSettings(Utils.SettingsConfig? loadedSettings) 129 | { 130 | var settings = new UpdateCommand.Settings 131 | { 132 | ModsFolder = loadedSettings?.ModsFolder ?? AnsiConsole.Ask(Strings.Prompts.EnterModsFolderPath, Utils.GetDefaultPath()), 133 | DryMode = AnsiConsole.Confirm(Strings.Prompts.EnableDryRunMode, false), 134 | Token = loadedSettings?.Token, 135 | ReadKeyExit = false 136 | }; 137 | 138 | return settings; 139 | } 140 | 141 | private Utils.SettingsConfig PromptForUpdateLibrariesSettings(Utils.SettingsConfig? loadedSettings) 142 | { 143 | var settings = new Utils.SettingsConfig 144 | { 145 | ModsFolder = loadedSettings?.ModsFolder ?? AnsiConsole.Ask(Strings.Prompts.EnterModsFolderPath, Utils.GetDefaultPath()), 146 | ResoniteModLoaderSource = loadedSettings?.ResoniteModLoaderSource 147 | }; 148 | 149 | return settings; 150 | } 151 | 152 | private SearchCommand.Settings PromptForSearchSettings(Utils.SettingsConfig? loadedSettings) 153 | { 154 | var settings = new SearchCommand.Settings 155 | { 156 | Query = AnsiConsole.Ask(Strings.Prompts.EnterSearchQuery), 157 | Manifest = loadedSettings?.Manifest, 158 | ReadKeyExit = false 159 | }; 160 | 161 | 162 | return settings; 163 | } 164 | } 165 | } -------------------------------------------------------------------------------- /ResoniteModUpdater/Commands/Search.cs: -------------------------------------------------------------------------------- 1 | using Spectre.Console; 2 | using Spectre.Console.Cli; 3 | using System.ComponentModel; 4 | using System.Diagnostics.CodeAnalysis; 5 | 6 | 7 | namespace ResoniteModUpdater.Commands.Search 8 | { 9 | public class SearchCommand : AsyncCommand 10 | { 11 | public class Settings : CommandSettings 12 | { 13 | [Description(Strings.Descriptions.Query)] 14 | [CommandArgument(0, "[QUERY]")] 15 | public required string Query { get; set; } 16 | 17 | [Description(Strings.Descriptions.Manifest)] 18 | [CommandOption("-m|--manifest")] 19 | public string? Manifest { get; set; } 20 | 21 | [CommandOption("--readkeyexit", IsHidden = true)] 22 | [DefaultValue(true)] 23 | public bool ReadKeyExit { get; set; } 24 | } 25 | 26 | public override async Task ExecuteAsync([NotNull] CommandContext context, [NotNull] Settings settings) 27 | { 28 | if (!AnsiConsole.Profile.Capabilities.Interactive) 29 | { 30 | AnsiConsole.MarkupLine($"[red]{Strings.Errors.NotInteractiveConsole}[/]"); 31 | return 1; 32 | } 33 | 34 | (var settingsConfig, var loadedSettings, var overriddenSettings) = await Utils.LoadAndOverrideSettingsAsync(settings); 35 | 36 | if (string.IsNullOrEmpty(settings.Query)) 37 | { 38 | AnsiConsole.MarkupLine($"[red]{Strings.Errors.NoSearchTerm}[/]"); 39 | return 0; 40 | } 41 | 42 | var results = await SearchAndDisplayResults(settings.Query, settingsConfig.Manifest ?? Utils.Manifest); 43 | 44 | if (results.Count == 0) 45 | { 46 | AnsiConsole.MarkupLine($"[red]{string.Format(Strings.Errors.NoResultsQuery, settings.Query)}.[/]"); 47 | if (settings.ReadKeyExit) 48 | { 49 | AnsiConsole.MarkupLine($"[slateblue3]{Strings.Messages.PressKeyExit}[/]"); 50 | Console.ReadKey(); 51 | } 52 | return 0; 53 | } 54 | 55 | Utils.CheckAndSaveOverriddenSettings(settingsConfig, loadedSettings, overriddenSettings); 56 | 57 | AnsiConsole.MarkupLine($"[slateblue3]{Strings.Messages.FinishedSearchingMods}[/]"); 58 | if (settings.ReadKeyExit) 59 | { 60 | AnsiConsole.MarkupLine($"[slateblue3]{Strings.Messages.PressKeyExit}[/]"); 61 | Console.ReadKey(); 62 | } 63 | 64 | return 0; 65 | } 66 | 67 | private async Task> SearchAndDisplayResults(string query, string manifest) 68 | { 69 | var results = await AnsiConsole.Status() 70 | .StartAsync(string.Format(Strings.Status.Searching, query), _ => Utils.SearchManifest(query, manifest)); 71 | 72 | if (results.Count > 0) 73 | { 74 | DisplayResultsTable(results); 75 | } 76 | 77 | return results; 78 | } 79 | 80 | private void DisplayResultsTable(List results) 81 | { 82 | var table = new Table() 83 | .AddColumn(new TableColumn($"[cyan]{Strings.SearchTableHeaders.Name}[/]")) 84 | .AddColumn(new TableColumn($"[cyan]{Strings.SearchTableHeaders.Author}[/]")) 85 | .AddColumn(new TableColumn($"[cyan]{Strings.SearchTableHeaders.ID}[/]")) 86 | .AddColumn(new TableColumn($"[cyan]{Strings.SearchTableHeaders.Version}[/]")) 87 | .AddColumn(new TableColumn($"[cyan]{Strings.SearchTableHeaders.Description}[/]")) 88 | .ShowRowSeparators(); 89 | 90 | foreach (var result in results) 91 | { 92 | Uri? releaseUrl = GetReleaseUrl(result); 93 | string versionDisplay = AnsiConsole.Profile.Capabilities.Links 94 | ? $"[link={releaseUrl}]{result.LatestVersion}[/]" 95 | : result.LatestVersion; 96 | 97 | table.AddRow(result.Entry.Name, result.AuthorName, result.ID, versionDisplay, result.Entry.Description); 98 | } 99 | 100 | AnsiConsole.Write(table); 101 | } 102 | 103 | private Uri? GetReleaseUrl(SearchResult result) 104 | { 105 | if (result.Entry.Versions.TryGetValue(result.LatestVersion, out var versionEntry)) 106 | { 107 | if (versionEntry.ReleaseUrl != null) 108 | { 109 | return versionEntry.ReleaseUrl; 110 | } 111 | 112 | var lastArtifact = versionEntry.Artifacts?.LastOrDefault(); 113 | if (lastArtifact?.Url != null && lastArtifact.Url.Host.EndsWith("github.com")) 114 | { 115 | Uri artifactUri = lastArtifact.Url; 116 | string[] pathParts = artifactUri.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); 117 | // Expected structure: {owner}/{repo}/releases/download/{tag}/{filename} 118 | if (pathParts.Length >= 5 && pathParts[2].Equals("releases", StringComparison.OrdinalIgnoreCase) && pathParts[3].Equals("download", StringComparison.OrdinalIgnoreCase)) 119 | { 120 | string repoOwner = pathParts[0]; 121 | string repoName = pathParts[1]; 122 | string tagOrVersion = pathParts[4]; 123 | if (Uri.TryCreate($"https://github.com/{repoOwner}/{repoName}/releases/tag/{tagOrVersion}", UriKind.Absolute, out var releasePageUrl)) 124 | { 125 | return releasePageUrl; 126 | } 127 | } 128 | } 129 | } 130 | 131 | if (result.Entry.SourceLocation != null) 132 | { 133 | return result.Entry.SourceLocation; 134 | } 135 | 136 | return null; 137 | } 138 | } 139 | } -------------------------------------------------------------------------------- /ResoniteModUpdater/Commands/Update.cs: -------------------------------------------------------------------------------- 1 | using Spectre.Console; 2 | using Spectre.Console.Cli; 3 | using System.ComponentModel; 4 | using System.Diagnostics.CodeAnalysis; 5 | 6 | namespace ResoniteModUpdater.Commands.Update 7 | { 8 | public enum ModUpdateResultStatus 9 | { 10 | Updated = 0, 11 | UpToDate = 1, 12 | NoLinkFound = 2, 13 | InvalidLink = 3, 14 | Ignored = 4, 15 | Error = -1 16 | } 17 | 18 | internal sealed class UpdateCommand : AsyncCommand 19 | { 20 | private readonly List<(string ModName, string? UrlAttempted, Exception Error)> _updateErrors = new(); 21 | 22 | public sealed class Settings : CommandSettings 23 | { 24 | [Description(Strings.Descriptions.ModsFolder)] 25 | [CommandArgument(0, "[ModsFolder]")] 26 | public string? ModsFolder { get; set; } 27 | 28 | [Description(Strings.Descriptions.Token)] 29 | [CommandOption("-t|--token")] 30 | public string? Token { get; set; } 31 | 32 | [Description(Strings.Descriptions.DryMode)] 33 | [CommandOption("-d|--dry")] 34 | [DefaultValue(false)] 35 | public bool DryMode { get; set; } 36 | 37 | [CommandOption("--readkeyexit", IsHidden = true)] 38 | [DefaultValue(true)] 39 | public bool ReadKeyExit { get; set; } 40 | } 41 | 42 | public override async Task ExecuteAsync([NotNull] CommandContext context, [NotNull] Settings settings) 43 | { 44 | if (!AnsiConsole.Profile.Capabilities.Interactive) 45 | { 46 | AnsiConsole.MarkupLine($"[red]{Strings.Errors.NotInteractiveConsole}[/]"); 47 | return 1; 48 | } 49 | 50 | (var settingsConfig, var loadedSettings, var overriddenSettings) = await Utils.LoadAndOverrideSettingsAsync(settings); 51 | 52 | Dictionary urls; 53 | try 54 | { 55 | if (string.IsNullOrEmpty(settingsConfig.ModsFolder)) 56 | { 57 | AnsiConsole.MarkupLine($"[red]Mods folder path is not configured. Please set it via settings or command line.[/]"); 58 | if (settings.ReadKeyExit) 59 | { 60 | AnsiConsole.MarkupLine($"[slateblue3]{Strings.Messages.PressKeyExit}[/]"); 61 | Console.ReadKey(); 62 | } 63 | return 1; 64 | } 65 | urls = Utils.GetFiles(settingsConfig.ModsFolder); 66 | } 67 | catch (Exception ex) 68 | { 69 | AnsiConsole.MarkupLine($"[red]Error accessing mods folder '{settingsConfig.ModsFolder}':[/]"); 70 | AnsiConsole.WriteException(ex, ExceptionFormats.ShortenEverything); 71 | if (settings.ReadKeyExit) 72 | { 73 | AnsiConsole.MarkupLine($"[slateblue3]{Strings.Messages.PressKeyExit}[/]"); 74 | Console.ReadKey(); 75 | } 76 | return 1; 77 | } 78 | 79 | if (!urls.Any()) 80 | { 81 | AnsiConsole.MarkupLine($"[red]{Strings.Errors.NoModsToUpdate}[/]"); 82 | if (settings.ReadKeyExit) 83 | { 84 | AnsiConsole.MarkupLine($"[slateblue3]{Strings.Messages.PressKeyExit}[/]"); 85 | Console.ReadKey(); 86 | } 87 | return 1; 88 | } 89 | 90 | await DisplayModUpdateStatus(urls, settingsConfig); 91 | await Utils.UpdateAdditionalLibraries(settingsConfig); 92 | 93 | Utils.CheckAndSaveOverriddenSettings(settingsConfig, loadedSettings, overriddenSettings); 94 | 95 | 96 | AnsiConsole.MarkupLine($"[slateblue3]{(settingsConfig.DryMode ? Strings.Messages.FinishedCheckingMods : Strings.Messages.FinishedUpdatingMods)}.[/]"); 97 | if (settings.ReadKeyExit) 98 | { 99 | AnsiConsole.MarkupLine($"[slateblue3]{Strings.Messages.PressKeyExit}[/]"); 100 | Console.ReadKey(); 101 | } 102 | return 0; 103 | } 104 | 105 | private async Task DisplayModUpdateStatus(Dictionary urls, Utils.SettingsConfig settingsConfig) 106 | { 107 | AnsiConsole.Write(new Padder(new Markup($"[orange1]Mods ({urls.Count})[/]")).Padding(0, 0)); 108 | AnsiConsole.WriteLine(); 109 | var table = new Table().Border(TableBorder.None).LeftAligned().Collapse().HideHeaders(); 110 | table.AddColumns("", "", "", ""); 111 | table.Columns[0].Width(1); 112 | 113 | await AnsiConsole.Live(new Padder(table).Padding(1, 0)) 114 | .StartAsync(async ctx => 115 | { 116 | foreach (var (dllFile, urlValue) in urls) 117 | { 118 | ModUpdateResultStatus status; 119 | string? releaseUrl = null; 120 | Exception? error = null; 121 | 122 | if (urlValue == null) 123 | { 124 | status = ModUpdateResultStatus.NoLinkFound; 125 | } 126 | else if (urlValue == "_") 127 | { 128 | status = ModUpdateResultStatus.Ignored; 129 | } 130 | else 131 | { 132 | (status, releaseUrl, error) = await UpdateMod(dllFile, urlValue, settingsConfig); 133 | if (error != null) 134 | { 135 | _updateErrors.Add((Path.GetFileName(dllFile), releaseUrl, error)); 136 | } 137 | } 138 | AddStatusToTable(table, status, dllFile, releaseUrl, settingsConfig.DryMode, error?.Message); 139 | ctx.Refresh(); 140 | } 141 | }); 142 | 143 | if (_updateErrors.Any()) 144 | { 145 | AnsiConsole.MarkupLine("\n[bold red]Errors Occurred During Update:[/]"); 146 | foreach (var (modName, urlAttempted, ex) in _updateErrors) 147 | { 148 | AnsiConsole.MarkupLine($"\n[bold yellow]Error updating {modName}:[/]"); 149 | if (!string.IsNullOrEmpty(urlAttempted)) 150 | { 151 | AnsiConsole.MarkupLine($"[grey]Attempted URL: {Markup.Escape(urlAttempted)}[/]"); 152 | } 153 | AnsiConsole.WriteException(ex, ExceptionFormats.ShortenEverything); 154 | } 155 | _updateErrors.Clear(); 156 | } 157 | } 158 | 159 | private async Task<(ModUpdateResultStatus Status, string? Url, Exception? Error)> UpdateMod(string dllFile, string urlValue, Utils.SettingsConfig settingsConfig) 160 | { 161 | if (!string.IsNullOrEmpty(settingsConfig.Token)) 162 | { 163 | return await Utils.Download(dllFile, urlValue, settingsConfig.DryMode, settingsConfig.Token); 164 | } 165 | else 166 | { 167 | return await Utils.DownloadFromRSS(dllFile, urlValue, settingsConfig.DryMode); 168 | } 169 | } 170 | 171 | private void AddStatusToTable(Table table, ModUpdateResultStatus status, string dllFile, string? releaseUrl, bool dryMode, string? errorMessage = null) 172 | { 173 | var (symbol, statusText) = status switch 174 | { 175 | ModUpdateResultStatus.Updated => (Strings.ModStatus.Symbols.Update, dryMode ? $"[green]{Strings.ModStatus.UpdateAvailable}[/]" : $"[green]{Strings.ModStatus.Updated}[/]"), 176 | ModUpdateResultStatus.UpToDate => (Strings.ModStatus.Symbols.NoChange, $"[dim]{Strings.ModStatus.UpToDate}[/]"), 177 | ModUpdateResultStatus.NoLinkFound => (Strings.ModStatus.Symbols.Issue, $"[red]{Strings.ModStatus.NoLinkFound}[/]"), 178 | ModUpdateResultStatus.InvalidLink => (Strings.ModStatus.Symbols.Issue, $"[red]{Strings.ModStatus.InvalidLink}[/]"), 179 | ModUpdateResultStatus.Ignored => (Strings.ModStatus.Symbols.NoChange, $"[dim]{Strings.ModStatus.Ignored}[/]"), 180 | ModUpdateResultStatus.Error => (Strings.ModStatus.Symbols.Issue, $"[red]{Strings.ModStatus.Error}{(string.IsNullOrEmpty(errorMessage) ? "" : $": {Markup.Escape(errorMessage.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? "")}")}[/]"), 181 | _ => (Strings.ModStatus.Symbols.Issue, $"[red]Unknown Status[/]") 182 | }; 183 | 184 | string linkMarkup = string.IsNullOrEmpty(releaseUrl) ? string.Empty : $"[link={releaseUrl}]{Markup.Escape(releaseUrl)}[/]"; 185 | table.AddRow($"[orange1]{symbol}[/]", Path.GetFileName(dllFile), statusText, linkMarkup); 186 | } 187 | } 188 | } -------------------------------------------------------------------------------- /ResoniteModUpdater/Manifest.cs: -------------------------------------------------------------------------------- 1 | using System.Text.Json.Serialization; 2 | 3 | 4 | namespace ResoniteModUpdater 5 | { 6 | 7 | public class ManifestData 8 | { 9 | public required Dictionary Objects { get; init; } 10 | 11 | [JsonPropertyName("schemaVersion")] 12 | public required string SchemaVersion { get; init; } 13 | } 14 | 15 | public class ManifestObject 16 | { 17 | [JsonPropertyName("author")] 18 | public required Dictionary Author { get; init; } 19 | 20 | public required Dictionary Entries { get; init; } 21 | } 22 | 23 | public class ManifestAuthor 24 | { 25 | public required Uri Url { get; init; } 26 | public Uri? Icon { get; init; } 27 | public Uri? Support { get; init; } 28 | } 29 | 30 | public class ManifestEntry 31 | { 32 | public required string Name { get; init; } 33 | public required string Description { get; init; } 34 | public required string Category { get; init; } 35 | 36 | [JsonPropertyName("sourceLocation")] 37 | public Uri? SourceLocation { get; init; } 38 | 39 | public Uri? Website { get; init; } 40 | public List? Tags { get; init; } = new(); 41 | public List? Flags { get; init; } = new(); 42 | public List? Platforms { get; init; } = new(); 43 | 44 | [JsonPropertyName("additionalAuthors")] 45 | public Dictionary? AdditionalAuthors { get; init; } = new(); 46 | 47 | public required Dictionary Versions { get; init; } 48 | } 49 | 50 | public class ManifestEntryVersion 51 | { 52 | public required List Artifacts { get; init; } 53 | public Dictionary? Dependencies { get; init; } = new(); 54 | public Dictionary? Conflicts { get; init; } = new(); 55 | 56 | [JsonPropertyName("releaseUrl")] 57 | public Uri? ReleaseUrl { get; init; } 58 | } 59 | 60 | public class ManifestEntryArtifact 61 | { 62 | public required Uri Url { get; init; } 63 | public required string Sha256 { get; init; } 64 | public string? Filename { get; init; } 65 | 66 | [JsonPropertyName("installLocation")] 67 | public string? InstallLocation { get; init; } 68 | } 69 | 70 | public class ManifestEntryDependency 71 | { 72 | public required string Version { get; init; } 73 | } 74 | public class SearchResult 75 | { 76 | public required ManifestEntry Entry { get; init; } 77 | public required string ID { get; init; } 78 | public required string AuthorName { get; init; } 79 | public required string LatestVersion { get; init; } 80 | public required Uri AuthorUrl { get; init; } 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /ResoniteModUpdater/Program.cs: -------------------------------------------------------------------------------- 1 | using ResoniteModUpdater.Commands.Default; 2 | using ResoniteModUpdater.Commands.Search; 3 | using ResoniteModUpdater.Commands.Update; 4 | using Spectre.Console; 5 | using Spectre.Console.Cli; 6 | using Velopack; 7 | using Velopack.Sources; 8 | 9 | namespace ResoniteModUpdater 10 | { 11 | public static class Program 12 | { 13 | private static readonly string AppUpdateRepoUrl = "https://github.com/hazre/ResoniteModUpdater"; 14 | public static async Task Main(string[] args) 15 | { 16 | VelopackApp.Build().Run(); 17 | #if !DEBUG 18 | await UpdateMyApp(); 19 | #endif 20 | var app = new CommandApp(); 21 | app.Configure(config => 22 | { 23 | config.SetApplicationName(Strings.Application.AppName); 24 | config.AddExample(Strings.Examples.Empty); 25 | config.AddExample(Strings.Examples.Update); 26 | config.AddExample(Strings.Examples.SearchExample); 27 | 28 | config.AddCommand(Strings.Commands.Update) 29 | .WithAlias(Strings.Commands.UpdateAlias1) 30 | .WithAlias(Strings.Commands.UpdateAlias2) 31 | .WithDescription(Strings.Descriptions.UpdateMods) 32 | .WithExample(Strings.Examples.Update) 33 | .WithExample(string.Format(Strings.Examples.UpdateWithPath, Utils.GetDefaultPath())) 34 | .WithExample(string.Format(Strings.Examples.UpdateWithPathAndToken, Utils.GetDefaultPath())); 35 | 36 | config.AddCommand(Strings.Commands.Search) 37 | .WithExample(Strings.Commands.Search, Strings.Examples.SearchExample) 38 | .WithAlias(Strings.Commands.SearchAlias) 39 | .WithDescription(Strings.Descriptions.UpdateMods); 40 | }); 41 | 42 | return await app.RunAsync(args); 43 | } 44 | public static async Task UpdateMyApp() 45 | { 46 | try 47 | { 48 | var mgr = new UpdateManager(new GithubSource(AppUpdateRepoUrl, null, false)); 49 | 50 | AnsiConsole.MarkupLine(Strings.Messages.CheckingForUpdate); 51 | var newVersion = await mgr.CheckForUpdatesAsync(); 52 | if (newVersion == null) 53 | { 54 | AnsiConsole.MarkupLine(Strings.Messages.NoUpdateAvailable); 55 | return; 56 | } 57 | 58 | if (!AnsiConsole.Confirm($"{Strings.Prompts.Update} ({Utils.GetVersion()} -> {newVersion.TargetFullRelease.Version})")) return; 59 | 60 | AnsiConsole.MarkupLine(Strings.Messages.DownloadingUpdate); 61 | await mgr.DownloadUpdatesAsync(newVersion); 62 | 63 | AnsiConsole.MarkupLine(Strings.Messages.InstallingUpdate); 64 | mgr.ApplyUpdatesAndRestart(newVersion); 65 | } 66 | catch (Exception ex) 67 | { 68 | AnsiConsole.WriteException(ex, ExceptionFormats.ShortenEverything); 69 | } 70 | } 71 | } 72 | } -------------------------------------------------------------------------------- /ResoniteModUpdater/ResoniteModUpdater.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Exe 5 | net9.0 6 | enable 7 | enable 8 | Resonite Mod Updater 9 | hazre 10 | https://github.com/hazre/ResoniteModUpdater 11 | README.md 12 | 2.4.1 13 | LatestMajor 14 | 15 | 16 | 17 | 18 | True 19 | \ 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | -------------------------------------------------------------------------------- /ResoniteModUpdater/Strings.cs: -------------------------------------------------------------------------------- 1 | namespace ResoniteModUpdater 2 | { 3 | public static class Strings 4 | { 5 | public static class Application 6 | { 7 | public const string AppName = "ResoniteModUpdater"; 8 | } 9 | public static class Commands 10 | { 11 | public const string Update = "update"; 12 | public const string UpdateAlias1 = "up"; 13 | public const string UpdateAlias2 = "upgrade"; 14 | public const string Search = "search"; 15 | public const string SearchAlias = "find"; 16 | } 17 | 18 | public static class Descriptions 19 | { 20 | public const string UpdateMods = "Updates resonite mods"; 21 | public const string UpdateLibraries = "Updates libraries such as ResoniteModLoader and Harmony"; 22 | public const string SearchModManifest = "Searches the manifest for mods"; 23 | public const string Query = "Query to search for in the mod manifest."; 24 | public const string ModsFolder = "Path to resonite mods folder"; 25 | public const string Token = "GitHub authentication token for using GitHub's official API. Optional, alternative to RSS feed method"; 26 | public const string DryMode = "Enables dry run mode. Checks for mod updates without installing them"; 27 | public const string Version = "Display version in use"; 28 | public const string Manifest = "Set alternative manifest json url. It must match the RML manifest schema (Advanced)"; 29 | } 30 | 31 | public static class Examples 32 | { 33 | public const string Empty = ""; 34 | public const string Update = "update"; 35 | public const string UpdateWithPath = "update {0}"; 36 | public const string UpdateWithPathAndToken = "update {0} -token xxxxxxxxxxxxxx"; 37 | public const string SearchExample = "search example"; 38 | } 39 | 40 | public static class MenuOptions 41 | { 42 | public const string UpdateMods = "Update Mods"; 43 | public const string UpdateLibraries = "Update Libraries"; 44 | public const string SearchModManifest = "Search Mod Manifest"; 45 | public const string ExitApplication = "Exit Application"; 46 | } 47 | 48 | public static class Prompts 49 | { 50 | public const string InteractivePrompt = "What would you like to do?"; 51 | public const string EnterModsFolderPath = "Enter the path to the mods folder:"; 52 | public const string EnableDryRunMode = "Enable dry run mode?"; 53 | public const string EnterSearchQuery = "Enter your search query:"; 54 | public const string ReturnToMainMenu = "Return to main menu?"; 55 | public const string SaveOverriddenSettings = "Do you want to update your saved settings with the overridden values?"; 56 | public const string SaveSettings = "No settings file found. Do you want to save the current settings?"; 57 | public const string Update = "There is a update available, would you like to update?"; 58 | public const string UpdateLibraries = "There is an update available for {0}. Would you like to update it?"; 59 | } 60 | 61 | public static class Messages 62 | { 63 | public const string PressKeyExit = "Press any key to Exit."; 64 | public const string FinishedUpdatingMods = "Finished Checking Mod Updates."; 65 | public const string FinishedCheckingMods = "Finished Updating mods."; 66 | public const string FinishedSearchingMods = "Finished searching for mods."; 67 | public const string Arguments = "Arguments"; 68 | public const string OverriddenSettings = "The following settings were overridden by command-line arguments:"; 69 | public const string SettingsUpdated = "Settings updated and saved successfully."; 70 | public const string SettingsSaved = "Settings saved successfully."; 71 | public const string DownloadingUpdate = "Downloading new version.."; 72 | public const string InstallingUpdate = "Installing new version and restarting.."; 73 | public const string NoUpdateLibraries = "No update available for {0}"; 74 | 75 | public const string CheckingForUpdate = "Checking for application updates..."; 76 | public const string NoUpdateAvailable = "No application updates available."; 77 | } 78 | public static class Errors 79 | { 80 | public const string NotInteractiveConsole = "Environment does not support interaction."; 81 | public const string NotValidDirectory = "That's not a valid directory."; 82 | public const string NoModsToUpdate = "No Mods found to update."; 83 | public const string DLLNotFoundSkipping = "{0} not found. Skipping.."; 84 | public const string Exception = "An error occurred: {0}"; 85 | public const string DetailedException = "An error occurred: {0}\nStack Trace:\n{1}"; 86 | public const string NoSearchTerm = "No search term provided"; 87 | public const string NoResultsQuery = "No results found for query: {0}"; 88 | public const string ForbiddenRetry = "Attempt {0}: Access to the resource is forbidden. Retrying in 1 minute..."; 89 | public const string ForbiddenRetryWithDelay = "Attempt {0}: Access to the resource is forbidden. Retrying in {1} seconds..."; 90 | public const string Forbidden = "Access to the resource is forbidden after multiple attempts."; 91 | public const string InvalidToken = "Invalid token provided"; 92 | public const string UpdateFailed = "Something went wrong trying to update {0}"; 93 | } 94 | public static class ModStatus 95 | { 96 | public const string UpdateAvailable = "Update Available"; 97 | public const string Updated = "Updated"; 98 | public const string UpToDate = "Up To Date"; 99 | public const string NoLinkFound = "No Link variable found"; 100 | public const string InvalidLink = "Invalid Link variable, no releases found"; 101 | public const string Ignored = "Ignored"; 102 | public const string Error = "Something went Wrong"; 103 | 104 | public static class Symbols 105 | { 106 | public const string Update = "+"; 107 | public const string NoChange = "-"; 108 | public const string Issue = "/"; 109 | } 110 | } 111 | public static class Status 112 | { 113 | public const string Searching = "Searching for {0}..."; 114 | public const string LoadingSettings = "Loading settings..."; 115 | public const string Starting = "Starting..."; 116 | public const string CheckingArguments = "Checking Arguments..."; 117 | } 118 | public static class SearchTableHeaders 119 | { 120 | public const string Name = "Name"; 121 | public const string Author = "Author"; 122 | public const string ID = "ID"; 123 | public const string Version = "Version"; 124 | public const string Description = "Description"; 125 | } 126 | } 127 | } -------------------------------------------------------------------------------- /ResoniteModUpdater/Utils.cs: -------------------------------------------------------------------------------- 1 | using System.Net; 2 | using System.Net.Http.Headers; 3 | using System.Reflection; 4 | using System.Security.Cryptography; 5 | using System.ServiceModel.Syndication; 6 | using System.Xml; 7 | using Mono.Cecil; 8 | using Mono.Cecil.Cil; 9 | using Newtonsoft.Json; 10 | using ResoniteModUpdater.Commands.Search; 11 | using ResoniteModUpdater.Commands.Update; 12 | using Spectre.Console; 13 | 14 | namespace ResoniteModUpdater 15 | { 16 | public static class Utils 17 | { 18 | private static readonly HttpClient _httpClient = new() 19 | { 20 | DefaultRequestHeaders = 21 | { 22 | UserAgent = { new ProductInfoHeaderValue(Strings.Application.AppName, GetVersion()) }, 23 | Accept = { new MediaTypeWithQualityHeaderValue("application/vnd.github+json") } 24 | } 25 | }; 26 | 27 | public class SettingsConfig 28 | { 29 | public string? ModsFolder { get; set; } 30 | public string? Token { get; set; } 31 | public bool DryMode { get; set; } 32 | public string? ResoniteModLoaderSource { get; set; } 33 | public string? Manifest { get; set; } 34 | } 35 | private const string SettingsFileName = "settings.json"; 36 | public const string ResoniteModLoaderSource = "https://github.com/resonite-modding-group/ResoniteModLoader"; 37 | public const string Manifest = "https://raw.githubusercontent.com/resonite-modding-group/resonite-mod-manifest/main/manifest.json"; 38 | public static string GetDefaultPath() 39 | { 40 | string defaultPath = ""; 41 | if (Environment.OSVersion.Platform == PlatformID.Win32NT) 42 | { 43 | defaultPath = Environment.ExpandEnvironmentVariables(@"%PROGRAMFILES(X86)%\Steam\steamapps\common\Resonite\rml_mods"); 44 | } 45 | else if (Environment.OSVersion.Platform == PlatformID.Unix) 46 | { 47 | defaultPath = Environment.ExpandEnvironmentVariables(@"~/.steam/steam/steamapps/common/Resonite/rml_mods"); 48 | } 49 | return defaultPath; 50 | } 51 | 52 | public static string GetSettingsPath() 53 | { 54 | if (Environment.OSVersion.Platform == PlatformID.Unix) 55 | { 56 | string? configDir = Environment.GetEnvironmentVariable("XDG_CONFIG_HOME"); 57 | if (string.IsNullOrEmpty(configDir)) 58 | { 59 | string? homeDir = Environment.GetEnvironmentVariable("HOME"); 60 | if (string.IsNullOrEmpty(homeDir)) 61 | { 62 | AnsiConsole.MarkupLine($"[red]Error: HOME environment variable not found. Cannot determine settings path.[/]"); 63 | return Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SettingsFileName); 64 | } 65 | configDir = Path.Combine(homeDir, ".config"); 66 | } 67 | string appConfigDir = Path.Combine(configDir, Strings.Application.AppName); 68 | Directory.CreateDirectory(appConfigDir); 69 | return Path.Combine(appConfigDir, SettingsFileName); 70 | } 71 | else 72 | { 73 | string executablePath = AppDomain.CurrentDomain.BaseDirectory; 74 | string parentDir = Directory.GetParent(executablePath.TrimEnd(Path.DirectorySeparatorChar))?.FullName ?? executablePath; 75 | return Path.Combine(parentDir, SettingsFileName); 76 | } 77 | } 78 | 79 | public static void SaveSettings(SettingsConfig settings) 80 | { 81 | var settingsJson = JsonConvert.SerializeObject(settings, Newtonsoft.Json.Formatting.Indented); 82 | 83 | string settingsFilePath = GetSettingsPath(); 84 | try 85 | { 86 | File.WriteAllText(settingsFilePath, settingsJson); 87 | } 88 | catch (Exception ex) 89 | { 90 | AnsiConsole.MarkupLine($"[red]Error saving settings to {settingsFilePath}:[/]"); 91 | AnsiConsole.WriteException(ex, ExceptionFormats.ShortenEverything); 92 | } 93 | } 94 | public static SettingsConfig? LoadSettings() 95 | { 96 | string settingsFilePath = GetSettingsPath(); 97 | 98 | if (File.Exists(settingsFilePath)) 99 | { 100 | try 101 | { 102 | var settingsJson = File.ReadAllText(settingsFilePath); 103 | return JsonConvert.DeserializeObject(settingsJson); 104 | } 105 | catch (Exception ex) 106 | { 107 | AnsiConsole.MarkupLine($"[red]Error loading or parsing settings from {settingsFilePath}:[/]"); 108 | AnsiConsole.WriteException(ex, ExceptionFormats.ShortenEverything); 109 | } 110 | } 111 | return null; 112 | } 113 | public static string? GetLibraryPath(string folderPath, string libraryFolderName, string dllFileName) 114 | { 115 | var parentFolderPath = Path.GetDirectoryName(folderPath); 116 | if (string.IsNullOrEmpty(parentFolderPath)) return null; 117 | 118 | var librariesFolderPath = Path.Combine(parentFolderPath, libraryFolderName); 119 | if (!Directory.Exists(librariesFolderPath)) return null; 120 | 121 | var dllFilePath = Path.Combine(librariesFolderPath, dllFileName); 122 | return File.Exists(dllFilePath) ? dllFilePath : null; 123 | } 124 | 125 | public static Dictionary GetFiles(string folderPath) 126 | { 127 | string[] dllFiles = Directory.GetFiles(folderPath, "*.dll"); 128 | var urlDictionary = new Dictionary(); 129 | 130 | foreach (string dllFile in dllFiles) 131 | { 132 | try 133 | { 134 | using var assembly = AssemblyDefinition.ReadAssembly(dllFile); 135 | string? foundUrl = null; 136 | 137 | foreach (var typeDef in assembly.MainModule.Types) 138 | { 139 | if (typeDef.BaseType?.Name == "ResoniteMod") 140 | { 141 | foreach (var propDef in typeDef.Properties) 142 | { 143 | if (propDef.Name == "Link" && propDef.GetMethod?.HasBody == true) 144 | { 145 | foreach (var instruction in propDef.GetMethod.Body.Instructions) 146 | { 147 | if (instruction.OpCode == OpCodes.Ldstr && instruction.Operand is string potentialUrl) 148 | { 149 | if (Uri.TryCreate(potentialUrl, UriKind.Absolute, out Uri? uri) && 150 | (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps) && 151 | uri.Host.EndsWith("github.com") && 152 | uri.ToString().TrimEnd('/').Split('/').Length > 4) 153 | { 154 | foundUrl = potentialUrl; 155 | break; 156 | } 157 | } 158 | } 159 | } 160 | if (foundUrl != null) break; 161 | } 162 | } 163 | if (foundUrl != null) break; 164 | } 165 | 166 | if (Path.GetFileName(dllFile).StartsWith("_")) foundUrl = "_"; 167 | urlDictionary[dllFile] = foundUrl; 168 | } 169 | catch (BadImageFormatException) 170 | { 171 | AnsiConsole.MarkupLine($"[yellow]Warning: Could not read assembly information from '{Path.GetFileName(dllFile)}'. It might not be a valid .NET assembly or may be obfuscated.[/]"); 172 | urlDictionary[dllFile] = null; 173 | } 174 | catch (Exception ex) 175 | { 176 | AnsiConsole.MarkupLine($"[red]Error processing {Path.GetFileName(dllFile)}:[/]"); 177 | AnsiConsole.WriteException(ex, ExceptionFormats.ShortenEverything); 178 | urlDictionary[dllFile] = null; 179 | } 180 | } 181 | 182 | return urlDictionary.OrderBy(pair => pair.Key).ToDictionary(pair => pair.Key, pair => pair.Value); 183 | } 184 | 185 | private record GitHubAsset(string name, string browser_download_url); 186 | private record GitHubReleaseInfo(List assets); 187 | public static async Task<(ModUpdateResultStatus Status, string? Url, Exception? Error)> Download(string dllFile, string url, bool dryMode, string? token) 188 | { 189 | string[] urlSegments = url.Split('/'); 190 | if (urlSegments.Length < 5) 191 | { 192 | string errMsg = $"Invalid GitHub URL format: {url}"; 193 | return (ModUpdateResultStatus.Error, null, new ArgumentException(errMsg, nameof(url))); 194 | } 195 | string owner = urlSegments[3]; 196 | string repo = urlSegments[4]; 197 | 198 | var requestMessage = new HttpRequestMessage(HttpMethod.Get, $"https://api.github.com/repos/{owner}/{repo}/releases/latest"); 199 | if (token != null) 200 | { 201 | requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); 202 | } 203 | 204 | int retryCount = 0; 205 | while (true) 206 | { 207 | HttpResponseMessage response; 208 | try 209 | { 210 | response = await _httpClient.SendAsync(requestMessage); 211 | } 212 | catch (HttpRequestException ex) 213 | { 214 | return (ModUpdateResultStatus.Error, null, ex); 215 | } 216 | 217 | if (response.IsSuccessStatusCode) 218 | { 219 | var responseBody = await response.Content.ReadAsStringAsync(); 220 | GitHubReleaseInfo? releaseInfo; 221 | try 222 | { 223 | releaseInfo = JsonConvert.DeserializeObject(responseBody); 224 | } 225 | catch (JsonException jsonEx) 226 | { 227 | return (ModUpdateResultStatus.Error, null, jsonEx); 228 | } 229 | 230 | if (releaseInfo?.assets == null) 231 | { 232 | string errMsg = $"Unexpected JSON structure from GitHub API for {owner}/{repo}. 'assets' field is missing or null."; 233 | return (ModUpdateResultStatus.Error, null, new JsonException(errMsg)); 234 | } 235 | 236 | foreach (var asset in releaseInfo.assets) 237 | { 238 | if (asset.name == Path.GetFileName(dllFile)) 239 | { 240 | var (valStatus, valUrl, valException) = await DownloadAndValidateDLL(dllFile, asset.browser_download_url, dryMode); 241 | return (valStatus, valUrl, valException); 242 | } 243 | } 244 | string notFoundMsg = $"Warning: DLL '{Path.GetFileName(dllFile)}' not found in the latest release assets for {owner}/{repo}."; 245 | return (ModUpdateResultStatus.NoLinkFound, null, new FileNotFoundException(notFoundMsg, dllFile)); 246 | } 247 | else if (response.StatusCode == HttpStatusCode.Forbidden && response.Headers.RetryAfter?.Delta.HasValue == true) 248 | { 249 | var delay = response.Headers.RetryAfter.Delta.Value; 250 | AnsiConsole.MarkupLine(string.Format(Strings.Errors.ForbiddenRetryWithDelay, retryCount + 1, delay.TotalSeconds)); 251 | if (retryCount >= 3) throw new Exception(Strings.Errors.Forbidden); 252 | await Task.Delay(delay); 253 | retryCount++; 254 | requestMessage = new HttpRequestMessage(HttpMethod.Get, $"https://api.github.com/repos/{owner}/{repo}/releases/latest"); 255 | if (token != null) requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); 256 | continue; 257 | } 258 | else if (response.StatusCode == HttpStatusCode.Forbidden) 259 | { 260 | AnsiConsole.MarkupLine(string.Format(Strings.Errors.ForbiddenRetry, retryCount + 1)); 261 | if (retryCount >= 3) throw new Exception(Strings.Errors.Forbidden); 262 | await Task.Delay(TimeSpan.FromSeconds(60 * (retryCount + 1))); 263 | retryCount++; 264 | requestMessage = new HttpRequestMessage(HttpMethod.Get, $"https://api.github.com/repos/{owner}/{repo}/releases/latest"); 265 | if (token != null) requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); 266 | continue; 267 | } 268 | else if (response.StatusCode == HttpStatusCode.Unauthorized) 269 | { 270 | throw new Exception(Strings.Errors.InvalidToken); 271 | } 272 | else 273 | { 274 | AnsiConsole.MarkupLine($"[red]Failed to fetch release information from GitHub API for {owner}/{repo}. Status code: {response.StatusCode}[/]"); 275 | var errorBody = await response.Content.ReadAsStringAsync(); 276 | if (!string.IsNullOrWhiteSpace(errorBody)) 277 | { 278 | AnsiConsole.MarkupLine($"[red]Response: {errorBody.Substring(0, Math.Min(errorBody.Length, 500))}[/]"); 279 | } 280 | return (ModUpdateResultStatus.InvalidLink, null, new HttpRequestException($"Failed to fetch release information. Status: {response.StatusCode}, Body: {errorBody}")); 281 | } 282 | } 283 | } 284 | 285 | public static async Task<(ModUpdateResultStatus Status, string? Url, Exception? Error)> DownloadFromRSS(string dllFile, string url, bool dryMode) 286 | { 287 | try 288 | { 289 | string[] urlParts = url.Split('/'); 290 | if (urlParts.Length < 5) 291 | { 292 | string errMsg = $"Invalid GitHub URL format for RSS: {url}"; 293 | return (ModUpdateResultStatus.Error, null, new ArgumentException(errMsg, nameof(url))); 294 | } 295 | string owner = urlParts[3]; 296 | string repo = urlParts[4]; 297 | 298 | using var xmlClient = new HttpClient(); 299 | xmlClient.DefaultRequestHeaders.UserAgent.ParseAdd(Strings.Application.AppName + "/" + GetVersion()); 300 | 301 | 302 | using var stream = await xmlClient.GetStreamAsync($"https://github.com/{owner}/{repo}/tags.atom"); 303 | using var reader = XmlReader.Create(stream); 304 | var tags = SyndicationFeed.Load(reader); 305 | 306 | if (!tags.Items.Any()) return (ModUpdateResultStatus.InvalidLink, null, new InvalidOperationException("No RSS/Atom feed items found.")); 307 | 308 | var latest = tags.Items.First(); 309 | if (latest?.Title?.Text == null || !latest.Links.Any()) return (ModUpdateResultStatus.InvalidLink, null, new InvalidOperationException("Latest RSS/Atom item is invalid or has no links.")); 310 | 311 | string? tag = latest.Links.FirstOrDefault(l => l.RelationshipType == "alternate")?.Uri.Segments.LastOrDefault()?.TrimEnd('/'); 312 | if (string.IsNullOrEmpty(tag)) 313 | { 314 | tag = latest.Id?.Split('/').LastOrDefault()?.TrimEnd('/'); 315 | } 316 | if (string.IsNullOrEmpty(tag)) return (ModUpdateResultStatus.InvalidLink, null, new InvalidOperationException("Could not determine tag from RSS/Atom feed item.")); 317 | 318 | string constructedDownloadUrl = $"https://github.com/{owner}/{repo}/releases/download/{tag}/{Path.GetFileName(dllFile)}"; 319 | 320 | var (valStatus, valUrl, valException) = await DownloadAndValidateDLL(dllFile, constructedDownloadUrl, dryMode); 321 | return (valStatus, valUrl, valException); 322 | } 323 | catch (Exception ex) 324 | { 325 | return (ModUpdateResultStatus.Error, null, ex); 326 | } 327 | } 328 | 329 | private static async Task<(ModUpdateResultStatus Status, string? Url, Exception? Error)> DownloadAndValidateDLL(string dllFile, string downloadUrl, bool dryMode) 330 | { 331 | var requestMessage = new HttpRequestMessage(HttpMethod.Get, downloadUrl); 332 | requestMessage.Headers.Accept.Clear(); 333 | requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream")); 334 | 335 | try 336 | { 337 | var response = await _httpClient.SendAsync(requestMessage); 338 | response.EnsureSuccessStatusCode(); 339 | 340 | byte[] downloadedDllBytes = await response.Content.ReadAsByteArrayAsync(); 341 | byte[] existingDllBytes = await File.ReadAllBytesAsync(dllFile); 342 | 343 | string downloadedHashString = ComputeHash(downloadedDllBytes); 344 | string existingHashString = ComputeHash(existingDllBytes); 345 | 346 | if (downloadedHashString != existingHashString) 347 | { 348 | if (!dryMode) await File.WriteAllBytesAsync(dllFile, downloadedDllBytes); 349 | return (ModUpdateResultStatus.Updated, downloadUrl, null); 350 | } 351 | else 352 | { 353 | return (ModUpdateResultStatus.UpToDate, null, null); 354 | } 355 | } 356 | catch (HttpRequestException httpEx) 357 | { 358 | return (ModUpdateResultStatus.Error, downloadUrl, httpEx); 359 | } 360 | catch (IOException ioEx) 361 | { 362 | return (ModUpdateResultStatus.Error, downloadUrl, ioEx); 363 | } 364 | catch (Exception ex) 365 | { 366 | return (ModUpdateResultStatus.Error, downloadUrl, ex); 367 | } 368 | } 369 | private static string ComputeHash(byte[] data) 370 | { 371 | using var sha256 = SHA256.Create(); 372 | byte[] hashBytes = sha256.ComputeHash(data); 373 | return Convert.ToHexString(hashBytes); 374 | } 375 | 376 | public static async Task> SearchManifest(string searchTerm, string manifestUrl) 377 | { 378 | var results = new List(); 379 | string manifestContent = await DownloadManifest(manifestUrl); 380 | if (string.IsNullOrEmpty(manifestContent)) return results; 381 | ManifestData? manifest = null; 382 | try 383 | { 384 | manifest = JsonConvert.DeserializeObject(manifestContent); 385 | } 386 | catch (JsonException jsonEx) 387 | { 388 | AnsiConsole.MarkupLine($"[red]Error parsing manifest JSON from {manifestUrl}:[/]"); 389 | AnsiConsole.WriteException(jsonEx, ExceptionFormats.ShortenEverything); 390 | return results; 391 | } 392 | 393 | if (manifest?.Objects == null) return results; 394 | foreach (var authorKey in manifest.Objects.Values) 395 | { 396 | foreach (var entryKey in authorKey.Entries) 397 | { 398 | if (entryKey.Value.Name.Contains(searchTerm, StringComparison.OrdinalIgnoreCase) || 399 | entryKey.Value.Description.Contains(searchTerm, StringComparison.OrdinalIgnoreCase)) 400 | { 401 | string authorName = authorKey.Author.Keys.First(); 402 | var latestVersionKey = entryKey.Value.Versions.Keys.Max(); 403 | string id = entryKey.Key; 404 | results.Add(new SearchResult 405 | { 406 | Entry = entryKey.Value, 407 | ID = id, 408 | AuthorName = authorName, 409 | LatestVersion = latestVersionKey!, 410 | AuthorUrl = authorKey.Author.First().Value.Url, 411 | }); 412 | } 413 | } 414 | } 415 | return results; 416 | } 417 | private static async Task DownloadManifest(string url) 418 | { 419 | try 420 | { 421 | return await _httpClient.GetStringAsync(url); 422 | } 423 | catch (HttpRequestException httpEx) 424 | { 425 | AnsiConsole.MarkupLine($"[red]Error downloading manifest from {url}:[/]"); 426 | AnsiConsole.WriteException(httpEx, ExceptionFormats.ShortenEverything); 427 | return string.Empty; 428 | } 429 | catch (Exception ex) 430 | { 431 | AnsiConsole.MarkupLine($"[red]An unexpected error occurred while downloading manifest from {url}:[/]"); 432 | AnsiConsole.WriteException(ex, ExceptionFormats.ShortenEverything); 433 | return string.Empty; 434 | } 435 | } 436 | 437 | public static void NotifyOverriddenSettings(List overriddenSettings) 438 | { 439 | if (overriddenSettings.Any()) 440 | { 441 | AnsiConsole.MarkupLine($"[yellow]{Strings.Messages.OverriddenSettings}[/]"); 442 | foreach (var setting in overriddenSettings) 443 | { 444 | AnsiConsole.Write(new Padder(new Markup($"[yellow]+[/] {setting}")).Padding(1, 0)); 445 | } 446 | } 447 | } 448 | public static void CheckAndSaveOverriddenSettings(SettingsConfig settingsConfig, bool loadedSettings, bool overriddenSettings) 449 | { 450 | if (overriddenSettings && loadedSettings) 451 | { 452 | bool updateSettings = AnsiConsole.Confirm(Strings.Prompts.SaveOverriddenSettings); 453 | if (updateSettings) 454 | { 455 | SaveSettings(settingsConfig); 456 | AnsiConsole.MarkupLine($"[green]{Strings.Messages.SettingsUpdated}[/]"); 457 | } 458 | } 459 | else if (!loadedSettings) 460 | { 461 | bool saveSettings = AnsiConsole.Confirm(Strings.Prompts.SaveSettings); 462 | if (saveSettings) 463 | { 464 | SaveSettings(settingsConfig); 465 | AnsiConsole.MarkupLine($"[green]{Strings.Messages.SettingsSaved}[/]"); 466 | } 467 | } 468 | } 469 | public static (SettingsConfig, List) OverrideSettings(SettingsConfig config, TCliSettings cliSettings) 470 | { 471 | var overriddenSettings = new List(); 472 | var configProperties = typeof(SettingsConfig).GetProperties(); 473 | var cliProperties = typeof(TCliSettings).GetProperties(); 474 | foreach (var cliProp in cliProperties) 475 | { 476 | var configProp = configProperties.FirstOrDefault(p => p.Name == cliProp.Name); 477 | if (configProp != null) 478 | { 479 | var newValue = cliProp.GetValue(cliSettings); 480 | if (IsValueProvided(newValue)) 481 | { 482 | var oldValue = configProp.GetValue(config); 483 | if (!Equals(oldValue, newValue)) 484 | { 485 | configProp.SetValue(config, newValue); 486 | if (cliProp.Name == nameof(SettingsConfig.Token)) 487 | { 488 | newValue = "********"; 489 | } 490 | string str1 = $"{cliProp.Name} [red]{oldValue}[/] -> [green]{newValue}[/]"; 491 | string str2 = $"{cliProp.Name} [green]{newValue}[/]"; 492 | overriddenSettings.Add(oldValue != null ? str1 : str2); 493 | } 494 | } 495 | } 496 | } 497 | return (config, overriddenSettings); 498 | } 499 | private static bool IsValueProvided(object? value) 500 | { 501 | return value switch 502 | { 503 | null => false, 504 | string s => !string.IsNullOrEmpty(s), 505 | _ => true 506 | }; 507 | } 508 | public static async Task<(SettingsConfig, bool, bool)> LoadAndOverrideSettingsAsync(TSettings settings) 509 | { 510 | var settingsConfig = new SettingsConfig(); 511 | var loadedSettings = LoadSettings(); 512 | if (loadedSettings != null) 513 | { 514 | await AnsiConsole.Status().StartAsync(Strings.Status.LoadingSettings, async _ => 515 | { 516 | settingsConfig = loadedSettings; 517 | await Task.Delay(1000); 518 | }); 519 | } 520 | (settingsConfig, var overriddenSettings) = OverrideSettings(settingsConfig, settings); 521 | if (overriddenSettings.Any() && loadedSettings != null) 522 | { 523 | NotifyOverriddenSettings(overriddenSettings); 524 | } 525 | await AnsiConsole.Status() 526 | .StartAsync(Strings.Status.Starting, async ctx => 527 | { 528 | await Task.Delay(1000); 529 | ctx.Status(Strings.Status.CheckingArguments); 530 | List propertiesList = new List(); 531 | foreach (PropertyInfo property in typeof(SettingsConfig).GetProperties()) 532 | { 533 | if (property.GetValue(settingsConfig) != null) 534 | { 535 | string propertyName = property.Name; 536 | if (typeof(TSettings) == typeof(SearchCommand.Settings)) 537 | { 538 | if (propertyName != "Manifest") continue; 539 | } 540 | if (propertyName == "DryMode" && property.GetValue(settingsConfig) is bool && (bool)property.GetValue(settingsConfig)! == false) continue; 541 | var propertyValue = property.GetValue(settingsConfig); 542 | if (propertyName == "Token") propertyValue = "********"; 543 | string message = $"[yellow]+[/] {propertyName} [gray]{propertyValue}[/]"; 544 | propertiesList.Add(message); 545 | } 546 | } 547 | if (propertiesList.Any()) 548 | { 549 | AnsiConsole.Write(new Padder(new Markup($"[yellow]{Strings.Messages.Arguments}[/]")).Padding(0, 0)); 550 | foreach (string property in propertiesList) 551 | { 552 | AnsiConsole.Write(new Padder(new Markup(property)).Padding(1, 0)); 553 | } 554 | } 555 | }); 556 | if (typeof(TSettings) == typeof(UpdateCommand.Settings)) 557 | { 558 | settingsConfig.ModsFolder ??= AskPath(); 559 | } 560 | return (settingsConfig, loadedSettings != null ? true : false, overriddenSettings.Any() ? true : false); 561 | } 562 | public static string AskPath() 563 | { 564 | return AnsiConsole.Prompt( 565 | new TextPrompt(Strings.Prompts.EnterModsFolderPath) 566 | .DefaultValue(GetDefaultPath()) 567 | .DefaultValueStyle("gray") 568 | .PromptStyle("green") 569 | .AllowEmpty() 570 | .ValidationErrorMessage($"[red]{Strings.Errors.NotValidDirectory}[/]") 571 | .Validate(path => 572 | { 573 | return path switch 574 | { 575 | _ when string.IsNullOrWhiteSpace(path) => ValidationResult.Success(), 576 | _ when !Directory.Exists(path) => ValidationResult.Error(Strings.Errors.NotValidDirectory), 577 | _ => ValidationResult.Success(), 578 | }; 579 | })); 580 | } 581 | public static string GetVersion() 582 | { 583 | var assembly = Assembly.GetEntryAssembly(); 584 | if (assembly == null) return "Unknown"; 585 | 586 | var version = assembly.GetName().Version; 587 | return version != null ? $"{version.Major}.{version.Minor}.{version.Build}" : "Unknown Version"; 588 | } 589 | 590 | public static async Task UpdateAdditionalLibraries(Utils.SettingsConfig settingsConfig, bool UpdateStatus = false) 591 | { 592 | if (string.IsNullOrEmpty(settingsConfig.ModsFolder) || !Directory.Exists(settingsConfig.ModsFolder)) 593 | { 594 | AnsiConsole.MarkupLine($"[red]Mods folder path is not valid or not set. Skipping library updates.[/]"); 595 | return; 596 | } 597 | await UpdateLibraryAsync("ResoniteModLoader.dll", "Libraries", settingsConfig, UpdateStatus); 598 | await UpdateLibraryAsync("0Harmony.dll", "rml_libs", settingsConfig, UpdateStatus); 599 | } 600 | 601 | public static async Task UpdateLibraryAsync(string dllName, string subFolder, Utils.SettingsConfig settingsConfig, bool UpdateStatus = false) 602 | { 603 | string? libraryPath = GetLibraryPath(settingsConfig.ModsFolder!, subFolder, dllName); 604 | if (string.IsNullOrEmpty(libraryPath)) 605 | { 606 | AnsiConsole.MarkupLine($"[red]{string.Format(Strings.Errors.DLLNotFoundSkipping, dllName)}[/]"); 607 | return; 608 | } 609 | 610 | var librarySourceUrl = settingsConfig.ResoniteModLoaderSource ?? ResoniteModLoaderSource; 611 | 612 | var (status, _, initialCheckException) = await DownloadFromRSS(libraryPath, librarySourceUrl, dryMode: true); 613 | 614 | if (status == ModUpdateResultStatus.Updated) 615 | { 616 | if (AnsiConsole.Confirm(string.Format(Strings.Prompts.UpdateLibraries, dllName))) 617 | { 618 | var (applyStatus, _, applyException) = await DownloadFromRSS(libraryPath, librarySourceUrl, dryMode: false); 619 | if (UpdateStatus) 620 | { 621 | if (applyStatus == ModUpdateResultStatus.Updated) AnsiConsole.MarkupLine($"[green]{dllName} updated successfully.[/]"); 622 | else if (applyStatus == ModUpdateResultStatus.Error) 623 | { 624 | AnsiConsole.MarkupLine($"[red]{string.Format(Strings.Errors.UpdateFailed, dllName)}: {Markup.Escape(applyException?.Message ?? "Unknown error")}[/]"); 625 | } 626 | } 627 | } 628 | } 629 | 630 | if (UpdateStatus) 631 | { 632 | if (status == ModUpdateResultStatus.UpToDate) 633 | { 634 | AnsiConsole.MarkupLine($"[slateblue3]{string.Format(Strings.Messages.NoUpdateLibraries, dllName)}[/]"); 635 | } 636 | else if (status == ModUpdateResultStatus.Error) 637 | { 638 | AnsiConsole.MarkupLine($"[red]{string.Format(Strings.Errors.UpdateFailed, dllName)}: {Markup.Escape(initialCheckException?.Message ?? "Unknown error during check")}[/]"); 639 | } 640 | } 641 | } 642 | } 643 | } 644 | --------------------------------------------------------------------------------