├── .documentation ├── .gitignore ├── docfx.json ├── index.md └── toc.yml ├── .github ├── icon.png ├── supabase-storage.png └── workflows │ ├── build-and-test.yml │ ├── build-documentation.yaml │ └── release.yml ├── .gitignore ├── .release-please-manifest.json ├── CHANGELOG.md ├── LICENSE ├── README.md ├── Storage ├── Bucket.cs ├── BucketUpsertOptions.cs ├── Client.cs ├── ClientOptions.cs ├── CreateSignedUrlResponse.cs ├── DestinationOptions.cs ├── DownloadOptions.cs ├── Exceptions │ ├── FailureHint.cs │ └── SupabaseStorageException.cs ├── Extensions │ ├── DownloadOptionsExtension.cs │ ├── HttpClientProgress.cs │ ├── ProgressableStreamContent.cs │ └── TransformOptionsExtension.cs ├── FileObject.cs ├── FileOptions.cs ├── Helpers.cs ├── Interfaces │ ├── IProgressableStreamContent.cs │ ├── IStorageBucketApi.cs │ ├── IStorageClient.cs │ └── IStorageFileApi.cs ├── Responses │ └── CreatedUploadSignedUrlResponse.cs ├── SearchOptions.cs ├── SortBy.cs ├── Storage.csproj ├── StorageBucketApi.cs ├── StorageFileApi.cs ├── TransformOptions.cs └── UploadSignedUrl.cs ├── StorageTests ├── Assets │ └── supabase-csharp.png ├── ClientTests.cs ├── ExceptionTests.cs ├── Helpers.cs ├── StorageBucketAnonTests.cs ├── StorageBucketTests.cs ├── StorageClientTests.cs ├── StorageFileAnonTests.cs ├── StorageFileTests.cs ├── StorageTests.csproj └── db │ ├── 00-schema.sql │ ├── 01-auth-schema.sql │ ├── 02-storage-schema.sql │ └── 03-dummy-data.sql ├── Supabase.Storage.sln ├── prepare-infra.sh ├── release-please-config.json └── supabase ├── .gitignore └── config.toml /.documentation/.gitignore: -------------------------------------------------------------------------------- 1 | ############### 2 | # folder # 3 | ############### 4 | /**/DROP/ 5 | /**/TEMP/ 6 | /**/packages/ 7 | /**/bin/ 8 | /**/obj/ 9 | /_site 10 | /api 11 | -------------------------------------------------------------------------------- /.documentation/docfx.json: -------------------------------------------------------------------------------- 1 | { 2 | "metadata": [ 3 | { 4 | "src": [ 5 | { 6 | "src": "../Storage", 7 | "files": [ 8 | "**/*.csproj" 9 | ] 10 | } 11 | ], 12 | "dest": "api" 13 | } 14 | ], 15 | "build": { 16 | "content": [ 17 | { 18 | "files": [ 19 | "**/*.{md,yml}" 20 | ], 21 | "exclude": [ 22 | "_site/**" 23 | ] 24 | } 25 | ], 26 | "resource": [ 27 | { 28 | "files": [ 29 | "images/**" 30 | ] 31 | } 32 | ], 33 | "output": "_site", 34 | "template": [ 35 | "default", 36 | "modern" 37 | ], 38 | "globalMetadata": { 39 | "_appName": "storage-csharp", 40 | "_appTitle": "storage-csharp", 41 | "_enableSearch": true 42 | } 43 | } 44 | } -------------------------------------------------------------------------------- /.documentation/index.md: -------------------------------------------------------------------------------- 1 | --- 2 | _layout: landing 3 | --- 4 | 5 | # storage-csharp 6 | -------------------------------------------------------------------------------- /.documentation/toc.yml: -------------------------------------------------------------------------------- 1 | - name: API 2 | href: api/ 3 | -------------------------------------------------------------------------------- /.github/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/supabase-community/storage-csharp/83dcdfe6c3f153b63b1c493cfaf1d53b3ae9f737/.github/icon.png -------------------------------------------------------------------------------- /.github/supabase-storage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/supabase-community/storage-csharp/83dcdfe6c3f153b63b1c493cfaf1d53b3ae9f737/.github/supabase-storage.png -------------------------------------------------------------------------------- /.github/workflows/build-and-test.yml: -------------------------------------------------------------------------------- 1 | name: Build and Test 2 | 3 | on: 4 | push: 5 | branches: [master] 6 | pull_request: 7 | branches: [master] 8 | 9 | jobs: 10 | build-and-test: 11 | runs-on: ubuntu-latest 12 | 13 | env: 14 | SUPABASE_URL: ${{ secrets.SUPABASE_URL }} 15 | SUPABASE_SERVICE_KEY: ${{ secrets.SUPABASE_SERVICE_KEY }} 16 | SUPABASE_PUBLIC_KEY: ${{ secrets.SUPABASE_PUBLIC_KEY }} 17 | 18 | steps: 19 | - uses: actions/checkout@v3 20 | 21 | - name: Setup .NET 22 | uses: actions/setup-dotnet@v3 23 | with: 24 | dotnet-version: 8.x 25 | 26 | - name: Restore dependencies 27 | run: dotnet restore 28 | 29 | - name: Build 30 | run: dotnet build --configuration Release --no-restore 31 | 32 | - uses: supabase/setup-cli@v1 33 | with: 34 | version: latest 35 | 36 | - name: Start supabase 37 | run: supabase start 38 | 39 | # - name: Initialize Testing Stack 40 | # run: chmod +x ./prepare-infra.sh && ./prepare-infra.sh && sleep 5 41 | 42 | - name: Test 43 | run: dotnet test --no-restore 44 | -------------------------------------------------------------------------------- /.github/workflows/build-documentation.yaml: -------------------------------------------------------------------------------- 1 | name: Build and Deploy Documentation 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | - release/* # Default release branch 8 | 9 | jobs: 10 | docs: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: actions/checkout@v3 14 | with: 15 | persist-credentials: false 16 | 17 | - name: Setup .NET 18 | uses: actions/setup-dotnet@v3 19 | with: 20 | dotnet-version: 8.x 21 | 22 | - name: Install docfx 23 | run: dotnet tool update -g docfx 24 | 25 | - name: Build documentation 26 | run: docfx .documentation/docfx.json 27 | 28 | - name: Deploy 🚀 29 | uses: JamesIves/github-pages-deploy-action@v4 30 | with: 31 | folder: .documentation/_site 32 | token: ${{ secrets.GITHUB_TOKEN }} 33 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release - Publish NuGet Package 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | release-please: 10 | runs-on: ubuntu-latest 11 | permissions: 12 | contents: write 13 | pull-requests: write 14 | issues: write 15 | steps: 16 | - uses: googleapis/release-please-action@v4 17 | with: 18 | target-branch: ${{ github.ref_name }} 19 | manifest-file: .release-please-manifest.json 20 | config-file: release-please-config.json 21 | 22 | publish: 23 | needs: release-please 24 | if: ${{ github.repository_owner == 'supabase-community' && startsWith(github.event.head_commit.message, 'chore(master)') && github.ref == 'refs/heads/master' && github.event_name == 'push' }} 25 | name: build, pack & publish 26 | runs-on: ubuntu-latest 27 | steps: 28 | - uses: actions/checkout@v3 29 | 30 | - name: Setup .NET 31 | uses: actions/setup-dotnet@v3 32 | with: 33 | dotnet-version: 8.x 34 | 35 | - name: Wait for tests to succeed 36 | uses: lewagon/wait-on-check-action@v1.3.1 37 | with: 38 | ref: ${{ github.ref }} 39 | check-name: build-and-test 40 | repo-token: ${{ secrets.GITHUB_TOKEN }} 41 | wait-interval: 10 42 | 43 | - name: Restore dependencies 44 | run: dotnet restore 45 | 46 | - name: Build 47 | run: dotnet build --configuration Release --no-restore 48 | 49 | - name: Generate package 50 | run: dotnet pack ./Storage/Storage.csproj --configuration Release 51 | 52 | - name: Publish on version change 53 | run: dotnet nuget push "**/*.nupkg" --source https://api.nuget.org/v3/index.json --api-key ${{ secrets.NUGET_API_KEY }} 54 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # globs 2 | Makefile.in 3 | *.userprefs 4 | *.usertasks 5 | config.make 6 | config.status 7 | aclocal.m4 8 | install-sh 9 | autom4te.cache/ 10 | *.tar.gz 11 | tarballs/ 12 | test-results/ 13 | 14 | .storage-server 15 | .env 16 | 17 | # Mac bundle stuff 18 | *.dmg 19 | *.app 20 | 21 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 22 | # General 23 | .DS_Store 24 | .AppleDouble 25 | .LSOverride 26 | 27 | # Icon must end with two \r 28 | Icon 29 | 30 | 31 | # Thumbnails 32 | ._* 33 | 34 | # Files that might appear in the root of a volume 35 | .DocumentRevisions-V100 36 | .fseventsd 37 | .Spotlight-V100 38 | .TemporaryItems 39 | .Trashes 40 | .VolumeIcon.icns 41 | .com.apple.timemachine.donotpresent 42 | 43 | # Directories potentially created on remote AFP share 44 | .AppleDB 45 | .AppleDesktop 46 | Network Trash Folder 47 | Temporary Items 48 | .apdisk 49 | 50 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 51 | # Windows thumbnail cache files 52 | Thumbs.db 53 | ehthumbs.db 54 | ehthumbs_vista.db 55 | 56 | # Dump file 57 | *.stackdump 58 | 59 | # Folder config file 60 | [Dd]esktop.ini 61 | 62 | # Recycle Bin used on file shares 63 | $RECYCLE.BIN/ 64 | 65 | # Windows Installer files 66 | *.cab 67 | *.msi 68 | *.msix 69 | *.msm 70 | *.msp 71 | 72 | # Windows shortcuts 73 | *.lnk 74 | 75 | # content below from: https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 76 | ## Ignore Visual Studio temporary files, build results, and 77 | ## files generated by popular Visual Studio add-ons. 78 | ## 79 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 80 | 81 | # User-specific files 82 | *.suo 83 | *.user 84 | *.userosscache 85 | *.sln.docstates 86 | 87 | # User-specific files (MonoDevelop/Xamarin Studio) 88 | *.userprefs 89 | 90 | # Build results 91 | [Dd]ebug/ 92 | [Dd]ebugPublic/ 93 | [Rr]elease/ 94 | [Rr]eleases/ 95 | x64/ 96 | x86/ 97 | bld/ 98 | [Bb]in/ 99 | [Oo]bj/ 100 | [Ll]og/ 101 | 102 | # Visual Studio 2015/2017 cache/options directory 103 | .vs/ 104 | # Uncomment if you have tasks that create the project's static files in wwwroot 105 | #wwwroot/ 106 | 107 | # Visual Studio 2017 auto generated files 108 | Generated\ Files/ 109 | 110 | # MSTest test Results 111 | [Tt]est[Rr]esult*/ 112 | [Bb]uild[Ll]og.* 113 | 114 | # NUNIT 115 | *.VisualState.xml 116 | TestResult.xml 117 | 118 | # Build Results of an ATL Project 119 | [Dd]ebugPS/ 120 | [Rr]eleasePS/ 121 | dlldata.c 122 | 123 | # Benchmark Results 124 | BenchmarkDotNet.Artifacts/ 125 | 126 | # .NET Core 127 | project.lock.json 128 | project.fragment.lock.json 129 | artifacts/ 130 | 131 | # StyleCop 132 | StyleCopReport.xml 133 | 134 | # Files built by Visual Studio 135 | *_i.c 136 | *_p.c 137 | *_h.h 138 | *.ilk 139 | *.meta 140 | *.obj 141 | *.iobj 142 | *.pch 143 | *.pdb 144 | *.ipdb 145 | *.pgc 146 | *.pgd 147 | *.rsp 148 | *.sbr 149 | *.tlb 150 | *.tli 151 | *.tlh 152 | *.tmp 153 | *.tmp_proj 154 | *_wpftmp.csproj 155 | *.log 156 | *.vspscc 157 | *.vssscc 158 | .builds 159 | *.pidb 160 | *.svclog 161 | *.scc 162 | 163 | # Chutzpah Test files 164 | _Chutzpah* 165 | 166 | # Visual C++ cache files 167 | ipch/ 168 | *.aps 169 | *.ncb 170 | *.opendb 171 | *.opensdf 172 | *.sdf 173 | *.cachefile 174 | *.VC.db 175 | *.VC.VC.opendb 176 | 177 | # Visual Studio profiler 178 | *.psess 179 | *.vsp 180 | *.vspx 181 | *.sap 182 | 183 | # Visual Studio Trace Files 184 | *.e2e 185 | 186 | # TFS 2012 Local Workspace 187 | $tf/ 188 | 189 | # Guidance Automation Toolkit 190 | *.gpState 191 | 192 | # ReSharper is a .NET coding add-in 193 | _ReSharper*/ 194 | *.[Rr]e[Ss]harper 195 | *.DotSettings.user 196 | 197 | # JustCode is a .NET coding add-in 198 | .JustCode 199 | 200 | # TeamCity is a build add-in 201 | _TeamCity* 202 | 203 | # DotCover is a Code Coverage Tool 204 | *.dotCover 205 | 206 | # AxoCover is a Code Coverage Tool 207 | .axoCover/* 208 | !.axoCover/settings.json 209 | 210 | # Visual Studio code coverage results 211 | *.coverage 212 | *.coveragexml 213 | 214 | # NCrunch 215 | _NCrunch_* 216 | .*crunch*.local.xml 217 | nCrunchTemp_* 218 | 219 | # MightyMoose 220 | *.mm.* 221 | AutoTest.Net/ 222 | 223 | # Web workbench (sass) 224 | .sass-cache/ 225 | 226 | # Installshield output folder 227 | [Ee]xpress/ 228 | 229 | # DocProject is a documentation generator add-in 230 | DocProject/buildhelp/ 231 | DocProject/Help/*.HxT 232 | DocProject/Help/*.HxC 233 | DocProject/Help/*.hhc 234 | DocProject/Help/*.hhk 235 | DocProject/Help/*.hhp 236 | DocProject/Help/Html2 237 | DocProject/Help/html 238 | 239 | # Click-Once directory 240 | publish/ 241 | 242 | # Publish Web Output 243 | *.[Pp]ublish.xml 244 | *.azurePubxml 245 | # Note: Comment the next line if you want to checkin your web deploy settings, 246 | # but database connection strings (with potential passwords) will be unencrypted 247 | *.pubxml 248 | *.publishproj 249 | 250 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 251 | # checkin your Azure Web App publish settings, but sensitive information contained 252 | # in these scripts will be unencrypted 253 | PublishScripts/ 254 | 255 | # NuGet Packages 256 | *.nupkg 257 | # The packages folder can be ignored because of Package Restore 258 | **/[Pp]ackages/* 259 | # except build/, which is used as an MSBuild target. 260 | !**/[Pp]ackages/build/ 261 | # Uncomment if necessary however generally it will be regenerated when needed 262 | #!**/[Pp]ackages/repositories.config 263 | # NuGet v3's project.json files produces more ignorable files 264 | *.nuget.props 265 | *.nuget.targets 266 | 267 | # Microsoft Azure Build Output 268 | csx/ 269 | *.build.csdef 270 | 271 | # Microsoft Azure Emulator 272 | ecf/ 273 | rcf/ 274 | 275 | # Windows Store app package directories and files 276 | AppPackages/ 277 | BundleArtifacts/ 278 | Package.StoreAssociation.xml 279 | _pkginfo.txt 280 | *.appx 281 | 282 | # Visual Studio cache files 283 | # files ending in .cache can be ignored 284 | *.[Cc]ache 285 | # but keep track of directories ending in .cache 286 | !*.[Cc]ache/ 287 | 288 | # Others 289 | ClientBin/ 290 | ~$* 291 | *~ 292 | *.dbmdl 293 | *.dbproj.schemaview 294 | *.jfm 295 | *.pfx 296 | *.publishsettings 297 | orleans.codegen.cs 298 | 299 | # Including strong name files can present a security risk 300 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 301 | #*.snk 302 | 303 | # Since there are multiple workflows, uncomment next line to ignore bower_components 304 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 305 | #bower_components/ 306 | 307 | # RIA/Silverlight projects 308 | Generated_Code/ 309 | 310 | # Backup & report files from converting an old project file 311 | # to a newer Visual Studio version. Backup files are not needed, 312 | # because we have git ;-) 313 | _UpgradeReport_Files/ 314 | Backup*/ 315 | UpgradeLog*.XML 316 | UpgradeLog*.htm 317 | ServiceFabricBackup/ 318 | *.rptproj.bak 319 | 320 | # SQL Server files 321 | *.mdf 322 | *.ldf 323 | *.ndf 324 | 325 | # Business Intelligence projects 326 | *.rdl.data 327 | *.bim.layout 328 | *.bim_*.settings 329 | *.rptproj.rsuser 330 | 331 | # Microsoft Fakes 332 | FakesAssemblies/ 333 | 334 | # GhostDoc plugin setting file 335 | *.GhostDoc.xml 336 | 337 | # Node.js Tools for Visual Studio 338 | .ntvs_analysis.dat 339 | node_modules/ 340 | 341 | # Visual Studio 6 build log 342 | *.plg 343 | 344 | # Visual Studio 6 workspace options file 345 | *.opt 346 | 347 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 348 | *.vbw 349 | 350 | # Visual Studio LightSwitch build output 351 | **/*.HTMLClient/GeneratedArtifacts 352 | **/*.DesktopClient/GeneratedArtifacts 353 | **/*.DesktopClient/ModelManifest.xml 354 | **/*.Server/GeneratedArtifacts 355 | **/*.Server/ModelManifest.xml 356 | _Pvt_Extensions 357 | 358 | # Paket dependency manager 359 | .paket/paket.exe 360 | paket-files/ 361 | 362 | # FAKE - F# Make 363 | .fake/ 364 | 365 | # JetBrains Rider 366 | .idea/ 367 | *.sln.iml 368 | 369 | # CodeRush personal settings 370 | .cr/personal 371 | 372 | # Python Tools for Visual Studio (PTVS) 373 | __pycache__/ 374 | *.pyc 375 | 376 | # Cake - Uncomment if you are using it 377 | # tools/** 378 | # !tools/packages.config 379 | 380 | # Tabs Studio 381 | *.tss 382 | 383 | # Telerik's JustMock configuration file 384 | *.jmconfig 385 | 386 | # BizTalk build output 387 | *.btp.cs 388 | *.btm.cs 389 | *.odx.cs 390 | *.xsd.cs 391 | 392 | # OpenCover UI analysis results 393 | OpenCover/ 394 | 395 | # Azure Stream Analytics local run output 396 | ASALocalRun/ 397 | 398 | # MSBuild Binary and Structured Log 399 | *.binlog 400 | 401 | # NVidia Nsight GPU debugger configuration file 402 | *.nvuser 403 | 404 | # MFractors (Xamarin productivity tool) working folder 405 | .mfractor/ 406 | 407 | # Local History for Visual Studio 408 | .localhistory/ 409 | StorageTests/.runsettings 410 | -------------------------------------------------------------------------------- /.release-please-manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | ".": "2.1.0" 3 | } -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [2.1.0](https://github.com/supabase-community/storage-csharp/compare/v2.0.2...v2.1.0) (2025-05-25) 4 | 5 | 6 | ### Miscellaneous Chores 7 | 8 | * release 2.1.0 ([d037a54](https://github.com/supabase-community/storage-csharp/commit/d037a54a55dae8f4d7f13d57bcfb0d6c166472a9)) 9 | 10 | ## 2.0.2 - 06-29-2024 11 | 12 | - Removes unused testing dependencies from `Storage.csproj` that may have caused build errors for projects. 13 | 14 | ## 2.0.1 - 05-16-2024 15 | 16 | - Re: [#15](https://github.com/supabase-community/storage-csharp/issues/15) 17 | and [#16](https://github.com/supabase-community/storage-csharp/pull/16) 18 | Fix CreateSignedUrl with TransformOptions. Thanks [@alustrement-bob](https://github.com/alustrement-bob)! 19 | 20 | ## 2.0.0 - 04-21-2024 21 | 22 | - Re: [#135](https://github.com/supabase-community/supabase-csharp/issues/135) Update nuget package 23 | name `storage-csharp` to `Supabase.Storage` 24 | 25 | ## 1.4.0 - 08-26-2023 26 | 27 | - Fixes [#11](https://github.com/supabase-community/storage-csharp/issues/11) - Which implements 28 | missing `SupabaseStorageException` on failure status codes for `Upload`, `Download`, `Move`, `CreateSignedUrl` 29 | and `CreateSignedUrls`. 30 | 31 | ## 1.3.2 - 06-10-2023 32 | 33 | - Uses new `Supabase.Core` assembly name. 34 | - Renames output assembly to `Supabase.Storage`. 35 | 36 | ## 1.3.0 - 05-06-2023 37 | 38 | - Re: [supabase-community/gotrue-csharp#57](https://github.com/supabase-community/gotrue-csharp/pull/57) - cleaner 39 | exception handling + expanded tests. 40 | - Re: [#9](https://github.com/supabase-community/storage-csharp/issues/9) - `FileObject` supports the return of 41 | folders (use `IsFolder`) property to distinguish 42 | - Re: [#8](https://github.com/supabase-community/storage-csharp/issues/8) - Fixes Socket Starvation issue by using 43 | static `HttpClient`s 44 | 45 | ## 1.2.10 - 04-17-2023 46 | 47 | - Re: [#7](https://github.com/supabase-community/storage-csharp/issues/7) Implements a `DownloadPublicFile` method. 48 | 49 | ## 1.2.9 - 04-12-2023 50 | 51 | Implements storage features from LW7: 52 | 53 | - feat: custom file size limit and mime types at bucket 54 | level [supabase/storage-js#151](https://github.com/supabase/storage-js/pull/151) file size and mime type limits per 55 | bucket 56 | - feat: quality option, image transformation [supabase/storage-js#145](https://github.com/supabase/storage-js/pull/152) 57 | quality option for image transformations 58 | - feat: format option for webp support [supabase/storage-js#142](https://github.com/supabase/storage-js/pull/142) format 59 | option for image transformation 60 | 61 | ## 1.2.8 - 03-14-2023 62 | 63 | - [Merge #5](https://github.com/supabase-community/storage-csharp/pull/5) Added search string as an optional search 64 | parameter. Thanks [@ElectroKnight22](https://github.com/ElectroKnight22)! 65 | 66 | ## 1.2.7 - 03-02-2023 67 | 68 | - Fix incorrect namespacing for Supabase.Storage.ClientOptions. 69 | 70 | ## 1.2.6 - 03-02-2023 71 | 72 | - Re: [#4](https://github.com/supabase-community/storage-csharp/issues/4) Implementation for `ClientOptions` which 73 | supports specifying Upload, Download, and Request timeouts. 74 | 75 | ## 1.2.5 - 02-28-2023 76 | 77 | - Provides fix 78 | for [supabase-community/supabase-csharp#54](https://github.com/supabase-community/supabase-csharp/issues/54) - Dynamic 79 | headers were always being overwritten by initialized headers, so the storage client would not receive user's access 80 | token as expected. 81 | - Provides fix for upload progress not reporting 82 | in [supabase-community/storage-csharp#3](https://github.com/supabase-community/storage-csharp/issues/3) 83 | 84 | ## 1.2.4 - 02-26-2023 85 | 86 | - `UploadOrUpdate` now appropriately throws request exception if server returns a bad status code. 87 | 88 | ## 1.2.3 - 11-12-2022 89 | 90 | - Use `supabase-core` and implement `IGettableHeaders` on `Client` 91 | - `Client` no longer has `headers` as a required parameter. 92 | 93 | ## 1.2.2 - 11-10-2022 94 | 95 | - Clarifies `IStorageClient` as implementing `IStorageBucket` 96 | 97 | ## 1.2.1 - 11-10-2022 98 | 99 | - Expose `StorageBucketApi.Headers` as a public property. 100 | 101 | ## 1.2.0 - 11-4-2022 102 | 103 | - [#2](https://github.com/supabase-community/storage-csharp/issues/2) Restructure Library to support Dependency 104 | Injection (DI) 105 | - Enable nullability in the project and make use of nullable reference types. 106 | 107 | ## 1.1.1 - 07-17-2022 108 | 109 | - Fix missing API change on `Update` method of `StorageFileApi` 110 | 111 | ## 1.1.0 - 07-17-2022 112 | 113 | - API Change [Breaking/Minor] Library no longer uses `WebClient` and instead leverages `HttpClient`. Progress events 114 | on `Upload` and `Download` are now handled with `EventHandler` instead of `WebClient` EventHandlers. 115 | 116 | ## 1.0.2 - 02-27-2022 117 | 118 | - Add `CreatedSignedUrls` method. 119 | 120 | ## 1.0.1 - 12-9-2021 121 | 122 | - Add missing support for `X-Client-Info` 123 | 124 | ## 1.0.0 - 12-9-2021 125 | 126 | - Initial release of separated storage client 127 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Joseph Schultz 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. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Supabase.Storage 2 | 3 | [![Build and Test](https://github.com/supabase-community/storage-csharp/actions/workflows/build-and-test.yml/badge.svg)](https://github.com/supabase-community/storage-csharp/acionts/workflows/build-and-test.yml) 4 | [![NuGet](https://img.shields.io/nuget/vpre/Supabase.Storage")](https://www.nuget.org/packages/Supabase.Storage/) 5 | 6 | --- 7 | 8 | Integrate your [Supabase](https://supabase.io) projects with C#. 9 | 10 | ## [Notice]: v2.0.0 renames this package from `storage-csharp` to `Supabase.Storage`. The depreciation notice has been set in NuGet. The API remains the same. 11 | 12 | ## Examples (using supabase-csharp) 13 | 14 | ```c# 15 | public async void Main() 16 | { 17 | // Make sure you set these (or similar) 18 | var url = Environment.GetEnvironmentVariable("SUPABASE_URL"); 19 | var key = Environment.GetEnvironmentVariable("SUPABASE_KEY"); 20 | 21 | await Supabase.Client.InitializeAsync(url, key); 22 | 23 | // The Supabase Instance can be accessed at any time using: 24 | // Supabase.Client.Instance {.Realtime|.Auth|etc.} 25 | // For ease of readability we'll use this: 26 | var instance = Supabase.Client.Instance; 27 | 28 | // Interact with Supabase Storage 29 | var storage = Supabase.Client.Instance.Storage 30 | await storage.CreateBucket("testing") 31 | 32 | var bucket = storage.From("testing"); 33 | 34 | var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Replace("file:", ""); 35 | var imagePath = Path.Combine(basePath, "Assets", "supabase-csharp.png"); 36 | 37 | await bucket.Upload(imagePath, "supabase-csharp.png"); 38 | 39 | // If bucket is public, get url 40 | bucket.GetPublicUrl("supabase-csharp.png"); 41 | 42 | // If bucket is private, generate url 43 | await bucket.CreateSignedUrl("supabase-csharp.png", 3600)); 44 | 45 | // Download it! 46 | await bucket.Download("supabase-csharp.png", Path.Combine(basePath, "testing-download.png")); 47 | } 48 | ``` 49 | 50 | ## Package made possible through the efforts of: 51 | 52 | Join the ranks! See a problem? Help fix it! 53 | 54 | 55 | 56 | 57 | 58 | Made with [contrib.rocks](https://contrib.rocks/preview?repo=supabase-community%storage-csharp). 59 | 60 | ## Contributing 61 | 62 | We are more than happy to have contributions! Please submit a PR. 63 | -------------------------------------------------------------------------------- /Storage/Bucket.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Newtonsoft.Json; 4 | 5 | namespace Supabase.Storage 6 | { 7 | public class Bucket 8 | { 9 | [JsonProperty("id")] 10 | public string? Id { get; set; } 11 | 12 | [JsonProperty("name")] 13 | public string? Name { get; set; } 14 | 15 | [JsonProperty("owner")] 16 | public string? Owner { get; set; } 17 | 18 | [JsonProperty("created_at")] 19 | public DateTime? CreatedAt { get; set; } 20 | 21 | [JsonProperty("updated_at")] 22 | public DateTime? UpdatedAt { get; set; } 23 | 24 | /// 25 | /// The visibility of the bucket. Public buckets don't require an authorization token to download objects, 26 | /// but still require a valid token for all other operations. By default, buckets are private. 27 | /// 28 | [JsonProperty("public")] 29 | public bool Public { get; set; } 30 | 31 | /// 32 | /// Specifies the file size limit that this bucket can accept during upload. 33 | /// 34 | /// Expects a string value following a format like: '1kb', '50mb', '150kb', etc. 35 | /// 36 | [JsonProperty("file_size_limit", NullValueHandling = NullValueHandling.Include)] 37 | public string? FileSizeLimit { get; set; } 38 | 39 | /// 40 | /// Specifies the allowed mime types that this bucket can accept during upload. 41 | /// 42 | /// Expects a List of values such as: ['image/jpeg', 'image/png', etc] 43 | /// 44 | [JsonProperty("allowed_mime_types", NullValueHandling = NullValueHandling.Ignore)] 45 | public List? AllowedMimes { get; set; } 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /Storage/BucketUpsertOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using Newtonsoft.Json; 3 | 4 | namespace Supabase.Storage 5 | { 6 | public class BucketUpsertOptions 7 | { 8 | /// 9 | /// The visibility of the bucket. Public buckets don't require an authorization token to download objects, 10 | /// but still require a valid token for all other operations. By default, buckets are private. 11 | /// 12 | [JsonProperty("public")] 13 | public bool Public { get; set; } = false; 14 | 15 | /// 16 | /// Specifies the file size limit that this bucket can accept during upload. 17 | /// 18 | /// Expects a string value following a format like: '1kb', '50mb', '150kb', etc. 19 | /// 20 | [JsonProperty("file_size_limit", NullValueHandling = NullValueHandling.Include)] 21 | public string? FileSizeLimit { get; set; } 22 | 23 | /// 24 | /// Specifies the allowed mime types that this bucket can accept during upload. 25 | /// 26 | /// Expects a List of values such as: ['image/jpeg', 'image/png', etc] 27 | /// 28 | [JsonProperty("allowed_mime_types", NullValueHandling = NullValueHandling.Ignore)] 29 | public List? AllowedMimes { get; set; } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Storage/Client.cs: -------------------------------------------------------------------------------- 1 | using Supabase.Storage.Interfaces; 2 | using System.Collections.Generic; 3 | 4 | namespace Supabase.Storage 5 | { 6 | public class Client : StorageBucketApi, IStorageClient 7 | { 8 | public Client(string url, Dictionary? headers = null) : base(url, headers) 9 | { } 10 | 11 | public Client(string url, ClientOptions? options, Dictionary? headers = null) : base(url, options, headers) 12 | {} 13 | 14 | /// 15 | /// Perform a file operation in a bucket 16 | /// 17 | /// Bucket Id 18 | /// 19 | public IStorageFileApi From(string id) => new StorageFileApi(Url, Headers, id); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /Storage/ClientOptions.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Threading; 3 | 4 | namespace Supabase.Storage 5 | { 6 | /// 7 | /// Options that can be passed into the Storage Client 8 | /// 9 | public class ClientOptions 10 | { 11 | /// 12 | /// The timespan to wait before an HTTP Upload Timesout 13 | /// See: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=net-7.0 14 | /// 15 | public TimeSpan HttpUploadTimeout = Timeout.InfiniteTimeSpan; 16 | 17 | /// 18 | /// The timespan to wait before an HTTP Upload Timesout 19 | /// See: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=net-7.0 20 | /// 21 | public TimeSpan HttpDownloadTimeout = Timeout.InfiniteTimeSpan; 22 | 23 | /// 24 | /// The timespan to wait before an HTTP Client request times out. 25 | /// See: https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclient.timeout?view=net-7.0 26 | /// 27 | public TimeSpan HttpRequestTimeout = TimeSpan.FromSeconds(100); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Storage/CreateSignedUrlResponse.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Supabase.Storage 4 | { 5 | public class CreateSignedUrlResponse 6 | { 7 | [JsonProperty("signedURL")] 8 | public string? SignedUrl { get; set; } 9 | } 10 | 11 | public class CreateSignedUrlsResponse: CreateSignedUrlResponse 12 | { 13 | [JsonProperty("path")] 14 | public string? Path { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Storage/DestinationOptions.cs: -------------------------------------------------------------------------------- 1 | namespace Supabase.Storage; 2 | 3 | /// 4 | /// Represents the options for a destination in the context of Supabase Storage. 5 | /// 6 | public class DestinationOptions 7 | { 8 | /// 9 | /// Gets or sets the name of the destination bucket in the context of Supabase Storage. 10 | /// 11 | public string? DestinationBucket { get; set; } 12 | } -------------------------------------------------------------------------------- /Storage/DownloadOptions.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Supabase.Storage 4 | { 5 | public class DownloadOptions 6 | { 7 | /// 8 | ///

Use the original file name when downloading

9 | ///
10 | public static readonly DownloadOptions UseOriginalFileName = new DownloadOptions { FileName = "" }; 11 | 12 | /// 13 | ///

The name of the file to be downloaded

14 | ///

When field is null, no download attribute will be added.

15 | ///

When field is empty, the original file name will be used. Use for quick initialized with original file names.

16 | ///
17 | public string? FileName { get; set; } 18 | } 19 | } -------------------------------------------------------------------------------- /Storage/Exceptions/FailureHint.cs: -------------------------------------------------------------------------------- 1 | using System.Linq; 2 | using static Supabase.Storage.Exceptions.FailureHint.Reason; 3 | 4 | namespace Supabase.Storage.Exceptions 5 | { 6 | public static class FailureHint 7 | { 8 | public enum Reason 9 | { 10 | Unknown, 11 | NotAuthorized, 12 | Internal, 13 | NotFound, 14 | AlreadyExists, 15 | InvalidInput 16 | } 17 | 18 | public static Reason DetectReason(SupabaseStorageException storageException) 19 | { 20 | if (storageException.Content == null) 21 | return Unknown; 22 | 23 | return storageException.StatusCode switch 24 | { 25 | 400 when storageException.Content.ToLower().Contains("authorization") => NotAuthorized, 26 | 400 when storageException.Content.ToLower().Contains("malformed") => NotAuthorized, 27 | 400 when storageException.Content.ToLower().Contains("invalid signature") => NotAuthorized, 28 | 400 when storageException.Content.ToLower().Contains("invalid") => InvalidInput, 29 | 401 => NotAuthorized, 30 | 403 when storageException.Content.ToLower().Contains("invalid compact jws") => NotAuthorized, 31 | 403 when storageException.Content.ToLower().Contains("signature verification failed") => NotAuthorized, 32 | 404 when storageException.Content.ToLower().Contains("not found") => NotFound, 33 | 409 when storageException.Content.ToLower().Contains("exists") => AlreadyExists, 34 | 500 => Internal, 35 | _ => Unknown 36 | }; 37 | } 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /Storage/Exceptions/SupabaseStorageException.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Net.Http; 3 | 4 | namespace Supabase.Storage.Exceptions 5 | { 6 | public class SupabaseStorageException : Exception 7 | { 8 | public SupabaseStorageException(string? message) : base(message) { } 9 | public SupabaseStorageException(string? message, Exception? innerException) : base(message, innerException) { } 10 | 11 | public HttpResponseMessage? Response { get; internal set; } 12 | 13 | public string? Content { get; internal set; } 14 | 15 | public int StatusCode { get; internal set; } 16 | 17 | public FailureHint.Reason Reason { get; private set; } 18 | 19 | public void AddReason() 20 | { 21 | Reason = FailureHint.DetectReason(this); 22 | } 23 | } 24 | } -------------------------------------------------------------------------------- /Storage/Extensions/DownloadOptionsExtension.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Specialized; 2 | using System.Web; 3 | 4 | namespace Supabase.Storage.Extensions 5 | { 6 | public static class DownloadOptionsExtension 7 | { 8 | /// 9 | /// Transforms options into a NameValueCollection to be used with a 10 | /// 11 | /// 12 | /// 13 | public static NameValueCollection ToQueryCollection(this DownloadOptions download) 14 | { 15 | var query = HttpUtility.ParseQueryString(string.Empty); 16 | 17 | if (download.FileName == null) 18 | { 19 | return query; 20 | } 21 | 22 | query.Add("download", string.IsNullOrEmpty(download.FileName) ? "true" : download.FileName); 23 | 24 | return query; 25 | } 26 | } 27 | } -------------------------------------------------------------------------------- /Storage/Extensions/HttpClientProgress.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Net.Http; 5 | using System.Threading; 6 | using System.Threading.Tasks; 7 | using Newtonsoft.Json; 8 | using Supabase.Storage.Exceptions; 9 | 10 | namespace Supabase.Storage.Extensions 11 | { 12 | /// 13 | /// Adapted from: https://gist.github.com/dalexsoto/9fd3c5bdbe9f61a717d47c5843384d11 14 | /// 15 | internal static class HttpClientProgress 16 | { 17 | public static async Task DownloadDataAsync(this HttpClient client, Uri uri, Dictionary? headers = null, IProgress? progress = null, CancellationToken cancellationToken = default(CancellationToken)) 18 | { 19 | var destination = new MemoryStream(); 20 | var message = new HttpRequestMessage(HttpMethod.Get, uri); 21 | 22 | if (headers != null) 23 | { 24 | foreach (var header in headers) 25 | { 26 | message.Headers.Add(header.Key, header.Value); 27 | } 28 | } 29 | 30 | using (var response = await client.SendAsync(message, HttpCompletionOption.ResponseHeadersRead)) 31 | { 32 | if (!response.IsSuccessStatusCode) 33 | { 34 | var content = await response.Content.ReadAsStringAsync(); 35 | var errorResponse = JsonConvert.DeserializeObject(content); 36 | var e = new SupabaseStorageException(errorResponse?.Message ?? content) 37 | { 38 | Content = content, 39 | Response = response, 40 | StatusCode = errorResponse?.StatusCode ?? (int)response.StatusCode 41 | }; 42 | 43 | e.AddReason(); 44 | throw e; 45 | } 46 | 47 | var contentLength = response.Content.Headers.ContentLength; 48 | using (var download = await response.Content.ReadAsStreamAsync()) 49 | { 50 | // no progress... no contentLength... very sad 51 | if (progress is null || !contentLength.HasValue) 52 | { 53 | await download.CopyToAsync(destination); 54 | return destination; 55 | } 56 | 57 | // Such progress and contentLength much reporting Wow! 58 | var progressWrapper = new Progress(totalBytes => progress.Report(GetProgressPercentage(totalBytes, contentLength.Value))); 59 | await download.CopyToAsync(destination, 81920, progressWrapper, cancellationToken); 60 | } 61 | } 62 | 63 | float GetProgressPercentage(float totalBytes, float currentBytes) => (totalBytes / currentBytes) * 100f; 64 | 65 | return destination; 66 | } 67 | 68 | static async Task CopyToAsync(this Stream source, Stream destination, int bufferSize, IProgress? progress = null, CancellationToken cancellationToken = default(CancellationToken)) 69 | { 70 | if (bufferSize < 0) 71 | throw new ArgumentOutOfRangeException(nameof(bufferSize)); 72 | if (source is null) 73 | throw new ArgumentNullException(nameof(source)); 74 | if (!source.CanRead) 75 | throw new InvalidOperationException($"'{nameof(source)}' is not readable."); 76 | if (destination == null) 77 | throw new ArgumentNullException(nameof(destination)); 78 | if (!destination.CanWrite) 79 | throw new InvalidOperationException($"'{nameof(destination)}' is not writable."); 80 | 81 | var buffer = new byte[bufferSize]; 82 | long totalBytesRead = 0; 83 | int bytesRead; 84 | 85 | while ((bytesRead = await source.ReadAsync(buffer, 0, buffer.Length, cancellationToken).ConfigureAwait(false)) != 0) 86 | { 87 | await destination.WriteAsync(buffer, 0, bytesRead, cancellationToken).ConfigureAwait(false); 88 | totalBytesRead += bytesRead; 89 | progress?.Report(totalBytesRead); 90 | } 91 | } 92 | 93 | public static Task UploadFileAsync(this HttpClient client, Uri uri, string filePath, Dictionary? headers = null, Progress? progress = null) 94 | { 95 | var fileStream = new FileStream(filePath, mode: FileMode.Open, FileAccess.Read); 96 | return UploadAsync(client, uri, fileStream, headers, progress); 97 | } 98 | 99 | public static Task UploadBytesAsync(this HttpClient client, Uri uri, byte[] data, Dictionary? headers = null, Progress? progress = null) 100 | { 101 | var stream = new MemoryStream(data); 102 | return UploadAsync(client, uri, stream, headers, progress); 103 | } 104 | 105 | public static async Task UploadAsync(this HttpClient client, Uri uri, Stream stream, Dictionary? headers = null, Progress? progress = null) 106 | { 107 | var content = new ProgressableStreamContent(stream, 4096, progress); 108 | 109 | if (headers != null) 110 | { 111 | client.DefaultRequestHeaders.Clear(); 112 | 113 | foreach (var header in headers) 114 | { 115 | if (header.Key.Contains("content")) 116 | content.Headers.Add(header.Key, header.Value); 117 | else 118 | client.DefaultRequestHeaders.Add(header.Key, header.Value); 119 | } 120 | } 121 | 122 | var response = await client.PostAsync(uri, content); 123 | 124 | if (!response.IsSuccessStatusCode) 125 | { 126 | var httpContent = await response.Content.ReadAsStringAsync(); 127 | var errorResponse = JsonConvert.DeserializeObject(httpContent); 128 | var e = new SupabaseStorageException(errorResponse?.Message ?? httpContent) 129 | { 130 | Content = httpContent, 131 | Response = response, 132 | StatusCode = errorResponse?.StatusCode ?? (int)response.StatusCode 133 | }; 134 | 135 | e.AddReason(); 136 | throw e; 137 | } 138 | 139 | return response; 140 | } 141 | } 142 | } 143 | -------------------------------------------------------------------------------- /Storage/Extensions/ProgressableStreamContent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Diagnostics.Contracts; 3 | using System.IO; 4 | using System.Net; 5 | using System.Net.Http; 6 | using System.Threading.Tasks; 7 | using Supabase.Storage.Interfaces; 8 | 9 | namespace Supabase.Storage.Extensions 10 | { 11 | internal class ProgressableStreamContent : HttpContent, IProgressableStreamContent 12 | { 13 | private const int defaultBufferSize = 4096; 14 | 15 | private Stream content; 16 | private int bufferSize; 17 | 18 | public EventHandler? StateChanged; 19 | public IProgress? Progress { get; private set; } 20 | 21 | public enum UploadState 22 | { 23 | PendingUpload, 24 | InProgress, 25 | PendingResponse, 26 | Complete 27 | } 28 | 29 | public ProgressableStreamContent(Stream content) : this(content, defaultBufferSize) { } 30 | 31 | public ProgressableStreamContent(Stream content, int bufferSize, Progress? progress = null) 32 | { 33 | if (content == null) 34 | { 35 | throw new ArgumentNullException("content"); 36 | } 37 | 38 | if (bufferSize <= 0) 39 | { 40 | throw new ArgumentOutOfRangeException("bufferSize"); 41 | } 42 | 43 | if (progress == null) 44 | { 45 | progress = new Progress(); 46 | } 47 | 48 | this.content = content; 49 | this.bufferSize = bufferSize; 50 | 51 | Progress = progress; 52 | } 53 | 54 | protected override Task SerializeToStreamAsync(Stream stream, TransportContext context) 55 | { 56 | Contract.Assert(stream != null); 57 | 58 | return Task.Run(() => 59 | { 60 | var buffer = new byte[bufferSize]; 61 | decimal size = content.Length; 62 | decimal uploaded = 0; 63 | 64 | StateChanged?.Invoke(this, UploadState.PendingUpload); 65 | 66 | using (content) 67 | { 68 | while (true) 69 | { 70 | var length = content.Read(buffer, 0, buffer.Length); 71 | if (length <= 0) break; 72 | 73 | uploaded += length; 74 | float currentProgress = (float)((uploaded / size) * 100); 75 | Progress?.Report(currentProgress); 76 | 77 | stream!.Write(buffer, 0, length); 78 | 79 | StateChanged?.Invoke(this, UploadState.InProgress); 80 | } 81 | } 82 | 83 | StateChanged?.Invoke(this, UploadState.PendingResponse); 84 | }); 85 | } 86 | 87 | protected override bool TryComputeLength(out long length) 88 | { 89 | length = content.Length; 90 | return length > 0; 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /Storage/Extensions/TransformOptionsExtension.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Specialized; 3 | using System.Web; 4 | 5 | namespace Supabase.Storage.Extensions 6 | { 7 | public static class TransformOptionsExtension 8 | { 9 | /// 10 | /// Transforms options into a NameValueCollecto to be used with a 11 | /// 12 | /// 13 | /// 14 | public static NameValueCollection ToQueryCollection(this TransformOptions transform) 15 | { 16 | var query = HttpUtility.ParseQueryString(string.Empty); 17 | 18 | if (transform.Width != null) 19 | query.Add("width", transform.Width.ToString()); 20 | 21 | if (transform.Height != null) 22 | query.Add("height", transform.Height.ToString()); 23 | 24 | if (transform.Format != null) 25 | query.Add("format", transform.Format); 26 | 27 | var mapResizeTo = Supabase.Core.Helpers.GetMappedToAttr(transform.Resize); 28 | query.Add("resize", mapResizeTo.Mapping); 29 | 30 | query.Add("quality", transform.Quality.ToString()); 31 | 32 | return query; 33 | } 34 | } 35 | } 36 | 37 | -------------------------------------------------------------------------------- /Storage/FileObject.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Newtonsoft.Json; 4 | 5 | namespace Supabase.Storage 6 | { 7 | public class FileObject 8 | { 9 | /// 10 | /// Flag representing if this object is a folder, all properties will be null but the name 11 | /// 12 | public bool IsFolder => !string.IsNullOrEmpty(Name) && Id == null && CreatedAt == null && UpdatedAt == null; 13 | 14 | [JsonProperty("name")] 15 | public string? Name { get; set; } 16 | 17 | [JsonProperty("bucket_id")] 18 | public string? BucketId { get; set; } 19 | 20 | [JsonProperty("owner")] 21 | public string? Owner { get; set; } 22 | 23 | [JsonProperty("id")] 24 | public string? Id { get; set; } 25 | 26 | [JsonProperty("updated_at")] 27 | public DateTime? UpdatedAt { get; set; } 28 | 29 | [JsonProperty("created_at")] 30 | public DateTime? CreatedAt { get; set; } 31 | 32 | [JsonProperty("last_accessed_at")] 33 | public DateTime? LastAccessedAt { get; set; } 34 | 35 | [JsonProperty("metadata")] 36 | public Dictionary MetaData = new Dictionary(); 37 | 38 | [JsonProperty("buckets")] 39 | public Bucket? Buckets { get; set; } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /Storage/FileOptions.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Supabase.Storage 4 | { 5 | public class FileOptions 6 | { 7 | [JsonProperty("cacheControl")] 8 | public string CacheControl { get; set; } = "3600"; 9 | 10 | [JsonProperty("contentType")] 11 | public string ContentType { get; set; } = "text/plain;charset=UTF-8"; 12 | 13 | [JsonProperty("upsert")] 14 | public bool Upsert { get; set; } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /Storage/Helpers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net.Http; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using System.Web; 7 | using Newtonsoft.Json; 8 | using System.Runtime.CompilerServices; 9 | using Supabase.Storage.Exceptions; 10 | using System.Threading; 11 | 12 | [assembly: InternalsVisibleTo("StorageTests")] 13 | namespace Supabase.Storage 14 | { 15 | internal static class Helpers 16 | { 17 | internal static HttpClient? HttpRequestClient; 18 | 19 | internal static HttpClient? HttpUploadClient; 20 | 21 | internal static HttpClient? HttpDownloadClient; 22 | 23 | /// 24 | /// Initializes HttpClients with their appropriate timeouts. Called at the initialization of StorageBucketApi. 25 | /// 26 | /// 27 | internal static void Initialize(ClientOptions options) 28 | { 29 | HttpRequestClient = new HttpClient { Timeout = options.HttpRequestTimeout }; 30 | HttpDownloadClient = new HttpClient { Timeout = options.HttpDownloadTimeout }; 31 | HttpUploadClient = new HttpClient { Timeout = options.HttpUploadTimeout }; 32 | } 33 | 34 | /// 35 | /// Helper to make a request using the defined parameters to an API Endpoint and coerce into a model. 36 | /// 37 | /// 38 | /// 39 | /// 40 | /// 41 | /// 42 | /// 43 | public static async Task MakeRequest(HttpMethod method, string url, object? data = null, 44 | Dictionary? headers = null) where T : class 45 | { 46 | var response = await MakeRequest(method, url, data, headers); 47 | var content = await response.Content.ReadAsStringAsync(); 48 | 49 | return JsonConvert.DeserializeObject(content); 50 | } 51 | 52 | /// 53 | /// Helper to make a request using the defined parameters to an API Endpoint. 54 | /// 55 | /// 56 | /// 57 | /// 58 | /// 59 | /// 60 | /// 61 | public static async Task MakeRequest(HttpMethod method, string url, object? data = null, Dictionary? headers = null, CancellationToken cancellationToken = default) 62 | { 63 | var builder = new UriBuilder(url); 64 | var query = HttpUtility.ParseQueryString(builder.Query); 65 | 66 | if (data != null && method != HttpMethod.Get) 67 | { 68 | // Case if it's a Get request the data object is a dictionary 69 | if (data is Dictionary reqParams) 70 | { 71 | foreach (var param in reqParams) 72 | query[param.Key] = param.Value; 73 | } 74 | } 75 | 76 | builder.Query = query.ToString(); 77 | 78 | using var requestMessage = new HttpRequestMessage(method, builder.Uri); 79 | 80 | if (data != null && method != HttpMethod.Get) 81 | requestMessage.Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"); 82 | 83 | if (headers != null) 84 | { 85 | foreach (var kvp in headers) 86 | requestMessage.Headers.TryAddWithoutValidation(kvp.Key, kvp.Value); 87 | } 88 | 89 | var response = await HttpRequestClient!.SendAsync(requestMessage, cancellationToken); 90 | 91 | var content = await response.Content.ReadAsStringAsync(); 92 | 93 | if (!response.IsSuccessStatusCode) 94 | { 95 | var errorResponse = JsonConvert.DeserializeObject(content); 96 | var e = new SupabaseStorageException(errorResponse?.Message ?? content) 97 | { 98 | Content = content, 99 | Response = response, 100 | StatusCode = errorResponse?.StatusCode ?? (int)response.StatusCode 101 | }; 102 | 103 | e.AddReason(); 104 | throw e; 105 | } 106 | 107 | return response; 108 | } 109 | } 110 | 111 | public class GenericResponse 112 | { 113 | [JsonProperty("message")] 114 | public string? Message { get; set; } 115 | } 116 | 117 | public class ErrorResponse 118 | { 119 | [JsonProperty("statusCode")] 120 | public int StatusCode { get; set; } 121 | 122 | [JsonProperty("message")] 123 | public string? Message { get; set; } 124 | } 125 | } -------------------------------------------------------------------------------- /Storage/Interfaces/IProgressableStreamContent.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace Supabase.Storage.Interfaces 4 | { 5 | internal interface IProgressableStreamContent 6 | { 7 | IProgress? Progress { get; } 8 | } 9 | } -------------------------------------------------------------------------------- /Storage/Interfaces/IStorageBucketApi.cs: -------------------------------------------------------------------------------- 1 | using Supabase.Core.Interfaces; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace Supabase.Storage.Interfaces 6 | { 7 | public interface IStorageBucketApi : IGettableHeaders 8 | where TBucket : Bucket 9 | { 10 | ClientOptions Options { get; } 11 | Dictionary Headers { get; set; } 12 | 13 | Task CreateBucket(string id, BucketUpsertOptions? options = null); 14 | Task DeleteBucket(string id); 15 | Task EmptyBucket(string id); 16 | Task GetBucket(string id); 17 | Task?> ListBuckets(); 18 | Task UpdateBucket(string id, BucketUpsertOptions? options = null); 19 | } 20 | } -------------------------------------------------------------------------------- /Storage/Interfaces/IStorageClient.cs: -------------------------------------------------------------------------------- 1 | using Supabase.Core.Interfaces; 2 | 3 | namespace Supabase.Storage.Interfaces 4 | { 5 | public interface IStorageClient : IStorageBucketApi, IGettableHeaders 6 | where TBucket : Bucket 7 | where TFileObject : FileObject 8 | { 9 | IStorageFileApi From(string id); 10 | } 11 | } -------------------------------------------------------------------------------- /Storage/Interfaces/IStorageFileApi.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Threading.Tasks; 4 | 5 | namespace Supabase.Storage.Interfaces 6 | { 7 | public interface IStorageFileApi 8 | where TFileObject : FileObject 9 | { 10 | ClientOptions Options { get; } 11 | Task CreateSignedUrl(string path, int expiresIn, TransformOptions? transformOptions = null, DownloadOptions? options = null); 12 | Task?> CreateSignedUrls(List paths, int expiresIn, DownloadOptions? options = null); 13 | Task Download(string supabasePath, EventHandler? onProgress = null); 14 | Task Download(string supabasePath, TransformOptions? transformOptions = null, EventHandler? onProgress = null); 15 | Task Download(string supabasePath, string localPath, EventHandler? onProgress = null); 16 | Task Download(string supabasePath, string localPath, TransformOptions? transformOptions = null, EventHandler? onProgress = null); 17 | Task DownloadPublicFile(string supabasePath, TransformOptions? transformOptions = null, EventHandler? onProgress = null); 18 | Task DownloadPublicFile(string supabasePath, string localPath, TransformOptions? transformOptions = null, EventHandler? onProgress = null); 19 | string GetPublicUrl(string path, TransformOptions? transformOptions = null, DownloadOptions? options = null); 20 | Task?> List(string path = "", SearchOptions? options = null); 21 | Task Move(string fromPath, string toPath, DestinationOptions? options = null); 22 | Task Copy(string fromPath, string toPath, DestinationOptions? options = null); 23 | Task Remove(string path); 24 | Task?> Remove(List paths); 25 | Task Update(byte[] data, string supabasePath, FileOptions? options = null, EventHandler? onProgress = null); 26 | Task Update(string localFilePath, string supabasePath, FileOptions? options = null, EventHandler? onProgress = null); 27 | Task Upload(byte[] data, string supabasePath, FileOptions? options = null, EventHandler? onProgress = null, bool inferContentType = true); 28 | Task Upload(string localFilePath, string supabasePath, FileOptions? options = null, EventHandler? onProgress = null, bool inferContentType = true); 29 | Task UploadToSignedUrl(byte[] data, UploadSignedUrl url, FileOptions? options = null, EventHandler? onProgress = null, bool inferContentType = true); 30 | Task UploadToSignedUrl(string localFilePath, UploadSignedUrl url, FileOptions? options = null, EventHandler? onProgress = null, bool inferContentType = true); 31 | Task CreateUploadSignedUrl(string supabasePath); 32 | } 33 | } -------------------------------------------------------------------------------- /Storage/Responses/CreatedUploadSignedUrlResponse.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Supabase.Storage.Responses 4 | { 5 | internal class CreatedUploadSignedUrlResponse 6 | { 7 | [JsonProperty("url")] 8 | public string? Url { get; set; } 9 | } 10 | } 11 | 12 | -------------------------------------------------------------------------------- /Storage/SearchOptions.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Supabase.Storage 4 | { 5 | public class SearchOptions 6 | { 7 | /// 8 | /// Number of files to be returned 9 | /// 10 | [JsonProperty("limit")] 11 | public int Limit { get; set; } = 100; 12 | 13 | /// 14 | /// Starting position of query 15 | /// 16 | [JsonProperty("offset")] 17 | public int Offset { get; set; } = 0; 18 | 19 | /// 20 | /// The search string to filter files by 21 | /// 22 | [JsonProperty("search")] 23 | public string Search { get; set; } = string.Empty; 24 | 25 | /// 26 | /// Column to sort by. Can be any colum inside of a 27 | /// 28 | [JsonProperty("sortBy")] 29 | public SortBy SortBy { get; set; } = new SortBy { Column = "name", Order = "asc" }; 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /Storage/SortBy.cs: -------------------------------------------------------------------------------- 1 | using Newtonsoft.Json; 2 | 3 | namespace Supabase.Storage 4 | { 5 | public class SortBy 6 | { 7 | [JsonProperty("column")] 8 | public string? Column { get; set; } 9 | 10 | [JsonProperty("order")] 11 | public string? Order { get; set; } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /Storage/Storage.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | netstandard2.0 4 | true 5 | Supabase.Storage 6 | Supabase.Storage 7 | Supabase.Storage 8 | Joseph Schultz <joseph@acupofjose.com> 9 | A C# implementation of the Supabase Storage client 10 | MIT 11 | en-US 12 | MIT 13 | Joseph Schultz <joseph@acupofjose.com> 14 | https://github.com/supabase-community/storage-csharp 15 | A C# implementation of the Supabase Storage client 16 | Supabase Storage 17 | https://avatars.githubusercontent.com/u/54469796?s=200&v=4 18 | supabase, storage 19 | 20 | 2.1.0 21 | 2.1.0 22 | 23 | https://github.com/supabase-community/storage-csharp 24 | git 25 | true 26 | icon.png 27 | README.md 28 | true 29 | true 30 | snupkg 31 | true 32 | enable 33 | latest 34 | CS8600;CS8602;CS8603 35 | 36 | 37 | 38 | 2.1.0 39 | $(VersionPrefix) 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | -------------------------------------------------------------------------------- /Storage/StorageBucketApi.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Net.Http; 4 | using System.Threading.Tasks; 5 | using Supabase.Core; 6 | using Supabase.Core.Extensions; 7 | using Supabase.Storage.Exceptions; 8 | using Supabase.Storage.Interfaces; 9 | 10 | namespace Supabase.Storage 11 | { 12 | public class StorageBucketApi : IStorageBucketApi 13 | { 14 | public ClientOptions Options { get; protected set; } 15 | protected string Url { get; set; } 16 | 17 | private readonly Dictionary _initializedHeaders; 18 | private Dictionary _headers; 19 | public Dictionary Headers 20 | { 21 | get 22 | { 23 | if (GetHeaders != null) 24 | _headers = GetHeaders(); 25 | 26 | return _headers.MergeLeft(_initializedHeaders); 27 | } 28 | set 29 | { 30 | _headers = value; 31 | 32 | if (!_headers.ContainsKey("X-Client-Info")) 33 | _headers.Add("X-Client-Info", Util.GetAssemblyVersion(typeof(Client))); 34 | } 35 | } 36 | 37 | /// 38 | /// Function that can be set to return dynamic headers. 39 | /// 40 | /// Headers specified in the constructor will ALWAYS take precendece over headers returned by this function. 41 | /// 42 | public Func>? GetHeaders { get; set; } 43 | 44 | protected StorageBucketApi(string url, ClientOptions? options, Dictionary? headers = null) : this(url, headers) 45 | { 46 | Options = options ?? new ClientOptions(); 47 | } 48 | 49 | protected StorageBucketApi(string url, Dictionary? headers = null) 50 | { 51 | Url = url; 52 | Options ??= new ClientOptions(); 53 | 54 | // Initializes HttpClients with Timeouts to be Reused [Re: #8](https://github.com/supabase-community/storage-csharp/issues/8) 55 | Helpers.Initialize(Options); 56 | 57 | headers ??= new Dictionary(); 58 | _headers = headers; 59 | _initializedHeaders = headers; 60 | } 61 | 62 | /// 63 | /// Retrieves the details of all Storage buckets within an existing product. 64 | /// 65 | /// 66 | public Task?> ListBuckets() => 67 | Helpers.MakeRequest>(HttpMethod.Get, $"{Url}/bucket", null, Headers); 68 | 69 | /// 70 | /// Retrieves the details of an existing Storage bucket. 71 | /// 72 | /// 73 | /// 74 | public async Task GetBucket(string id) 75 | { 76 | try 77 | { 78 | var result = await Helpers.MakeRequest(HttpMethod.Get, $"{Url}/bucket/{id}", null, Headers); 79 | return result; 80 | } 81 | catch (SupabaseStorageException ex) 82 | { 83 | if (ex.Reason == FailureHint.Reason.NotFound) 84 | return null; 85 | else 86 | throw; 87 | } 88 | } 89 | 90 | /// 91 | /// Creates a new Storage bucket 92 | /// 93 | /// 94 | /// 95 | /// Bucket Id 96 | public async Task CreateBucket(string id, BucketUpsertOptions? options = null) 97 | { 98 | options ??= new BucketUpsertOptions(); 99 | 100 | var data = new Bucket 101 | { 102 | Id = id, 103 | Name = id, 104 | Public = options.Public, 105 | FileSizeLimit = options.FileSizeLimit, 106 | AllowedMimes = options.AllowedMimes 107 | }; 108 | 109 | var result = await Helpers.MakeRequest(HttpMethod.Post, $"{Url}/bucket", data, Headers); 110 | 111 | return result?.Name!; 112 | } 113 | 114 | /// 115 | /// Updates a Storage bucket 116 | /// 117 | /// 118 | /// 119 | /// 120 | public async Task UpdateBucket(string id, BucketUpsertOptions? options = null) 121 | { 122 | options ??= new BucketUpsertOptions(); 123 | 124 | var data = new Bucket 125 | { 126 | Id = id, 127 | Public = options.Public, 128 | FileSizeLimit = options.FileSizeLimit, 129 | AllowedMimes = options.AllowedMimes 130 | }; 131 | 132 | var result = await Helpers.MakeRequest(HttpMethod.Put, $"{Url}/bucket/{id}", data, Headers); 133 | 134 | return result; 135 | } 136 | 137 | /// 138 | /// Removes all objects inside a single bucket. 139 | /// 140 | /// 141 | /// 142 | public Task EmptyBucket(string id) => 143 | Helpers.MakeRequest(HttpMethod.Post, $"{Url}/bucket/{id}/empty", null, Headers); 144 | 145 | /// 146 | /// Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. 147 | /// You must first 148 | /// 149 | /// 150 | /// 151 | public Task DeleteBucket(string id) => 152 | Helpers.MakeRequest(HttpMethod.Delete, $"{Url}/bucket/{id}", null, Headers); 153 | 154 | } 155 | } 156 | -------------------------------------------------------------------------------- /Storage/StorageFileApi.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Collections.Specialized; 4 | using System.IO; 5 | using System.Linq; 6 | using System.Net.Http; 7 | using System.Threading.Tasks; 8 | using System.Web; 9 | using Newtonsoft.Json; 10 | using Newtonsoft.Json.Converters; 11 | using Supabase.Storage.Exceptions; 12 | using Supabase.Storage.Extensions; 13 | using Supabase.Storage.Interfaces; 14 | using Supabase.Storage.Responses; 15 | 16 | namespace Supabase.Storage 17 | { 18 | public class StorageFileApi : IStorageFileApi 19 | { 20 | public ClientOptions Options { get; protected set; } 21 | protected string Url { get; set; } 22 | protected Dictionary Headers { get; set; } 23 | protected string? BucketId { get; set; } 24 | 25 | public StorageFileApi(string url, string bucketId, ClientOptions? options, 26 | Dictionary? headers = null) : this(url, headers, bucketId) 27 | { 28 | Options = options ?? new ClientOptions(); 29 | } 30 | 31 | public StorageFileApi(string url, Dictionary? headers = null, string? bucketId = null) 32 | { 33 | Url = url; 34 | BucketId = bucketId; 35 | Options ??= new ClientOptions(); 36 | Headers = headers ?? new Dictionary(); 37 | } 38 | 39 | /// 40 | /// A simple convenience function to get the URL for an asset in a public bucket.If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. 41 | /// This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. 42 | /// 43 | /// 44 | /// 45 | /// 46 | /// 47 | public string GetPublicUrl(string path, TransformOptions? transformOptions, DownloadOptions? downloadOptions = null) 48 | { 49 | var queryParams = HttpUtility.ParseQueryString(string.Empty); 50 | 51 | if (downloadOptions != null) 52 | queryParams.Add(downloadOptions.ToQueryCollection()); 53 | 54 | if (transformOptions == null) 55 | { 56 | var queryParamsString = queryParams.ToString(); 57 | return $"{Url}/object/public/{GetFinalPath(path)}?{queryParamsString}"; 58 | } 59 | 60 | queryParams.Add(transformOptions.ToQueryCollection()); 61 | var builder = new UriBuilder($"{Url}/render/image/public/{GetFinalPath(path)}") 62 | { 63 | Query = queryParams.ToString() 64 | }; 65 | 66 | return builder.ToString(); 67 | } 68 | 69 | /// 70 | /// Create signed url to download file without requiring permissions. This URL can be valid for a set number of seconds. 71 | /// 72 | /// The file path to be downloaded, including the current file name. For example `folder/image.png`. 73 | /// The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. 74 | /// 75 | /// 76 | /// 77 | public async Task CreateSignedUrl(string path, int expiresIn, TransformOptions? transformOptions = null, DownloadOptions? downloadOptions = null) 78 | { 79 | var body = new Dictionary { { "expiresIn", expiresIn } }; 80 | var url = $"{Url}/object/sign/{GetFinalPath(path)}"; 81 | 82 | if (transformOptions != null) 83 | { 84 | var transformOptionsJson = JsonConvert.SerializeObject(transformOptions, new StringEnumConverter()); 85 | var transformOptionsObj = JsonConvert.DeserializeObject>(transformOptionsJson); 86 | body.Add("transform", transformOptionsObj); 87 | } 88 | 89 | var response = await Helpers.MakeRequest(HttpMethod.Post, url, body, Headers); 90 | 91 | if (response == null || string.IsNullOrEmpty(response.SignedUrl)) 92 | throw new SupabaseStorageException( 93 | $"Signed Url for {path} returned empty, do you have permission?"); 94 | 95 | var downloadQueryParams = downloadOptions?.ToQueryCollection().ToString(); 96 | 97 | return $"{Url}{response.SignedUrl}?{downloadQueryParams}"; 98 | } 99 | 100 | /// 101 | /// Create signed URLs to download files without requiring permissions. These URLs can be valid for a set number of seconds. 102 | /// 103 | /// paths The file paths to be downloaded, including the current file names. For example [`folder/image.png`, 'folder2/image2.png']. 104 | /// The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. 105 | /// 106 | /// 107 | public async Task?> CreateSignedUrls(List paths, int expiresIn, DownloadOptions? downloadOptions = null) 108 | { 109 | var body = new Dictionary { { "expiresIn", expiresIn }, { "paths", paths } }; 110 | var response = await Helpers.MakeRequest>(HttpMethod.Post, 111 | $"{Url}/object/sign/{BucketId}", body, Headers); 112 | 113 | var downloadQueryParams = downloadOptions?.ToQueryCollection().ToString(); 114 | if (response != null) 115 | { 116 | foreach (var item in response) 117 | { 118 | if (string.IsNullOrEmpty(item.SignedUrl)) 119 | throw new SupabaseStorageException( 120 | $"Signed Url for {item.Path} returned empty, do you have permission?"); 121 | 122 | item.SignedUrl = $"{Url}{item.SignedUrl}?{downloadQueryParams}"; 123 | } 124 | } 125 | 126 | return response; 127 | } 128 | 129 | /// 130 | /// Lists all the files within a bucket. 131 | /// 132 | /// 133 | /// 134 | /// 135 | public async Task?> List(string path = "", SearchOptions? options = null) 136 | { 137 | options ??= new SearchOptions(); 138 | 139 | var json = JsonConvert.SerializeObject(options); 140 | var body = JsonConvert.DeserializeObject>(json); 141 | 142 | if (body != null) 143 | body.Add("prefix", string.IsNullOrEmpty(path) ? "" : path); 144 | 145 | var response = 146 | await Helpers.MakeRequest>(HttpMethod.Post, $"{Url}/object/list/{BucketId}", body, 147 | Headers); 148 | 149 | return response; 150 | } 151 | 152 | /// 153 | /// Uploads a file to an existing bucket. 154 | /// 155 | /// File Source Path 156 | /// The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. 157 | /// 158 | /// 159 | /// 160 | /// 161 | public async Task Upload(string localFilePath, string supabasePath, FileOptions? options = null, 162 | EventHandler? onProgress = null, bool inferContentType = true) 163 | { 164 | options ??= new FileOptions(); 165 | 166 | if (inferContentType) 167 | options.ContentType = MimeMapping.MimeUtility.GetMimeMapping(localFilePath); 168 | 169 | var result = await UploadOrUpdate(localFilePath, supabasePath, options, onProgress); 170 | return result; 171 | } 172 | 173 | /// 174 | /// Uploads a byte array to an existing bucket. 175 | /// 176 | /// 177 | /// The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. 178 | /// 179 | /// 180 | /// 181 | /// 182 | public async Task Upload(byte[] data, string supabasePath, FileOptions? options = null, 183 | EventHandler? onProgress = null, bool inferContentType = true) 184 | { 185 | options ??= new FileOptions(); 186 | 187 | if (inferContentType) 188 | options.ContentType = MimeMapping.MimeUtility.GetMimeMapping(supabasePath); 189 | 190 | var result = await UploadOrUpdate(data, supabasePath, options, onProgress); 191 | return result; 192 | } 193 | 194 | /// 195 | /// Uploads a file to using a pre-generated Signed Upload Url 196 | /// 197 | /// File Source Path 198 | /// 199 | /// 200 | /// 201 | /// 202 | /// 203 | public async Task UploadToSignedUrl(string localFilePath, UploadSignedUrl signedUrl, 204 | FileOptions? options = null, EventHandler? onProgress = null, bool inferContentType = true) 205 | { 206 | options ??= new FileOptions(); 207 | 208 | if (inferContentType) 209 | options.ContentType = MimeMapping.MimeUtility.GetMimeMapping(localFilePath); 210 | 211 | var headers = new Dictionary(Headers) 212 | { 213 | ["Authorization"] = $"Bearer {signedUrl.Token}", 214 | ["cache-control"] = $"max-age={options.CacheControl}", 215 | ["content-type"] = options.ContentType 216 | }; 217 | 218 | if (options.Upsert) 219 | headers.Add("x-upsert", options.Upsert.ToString().ToLower()); 220 | 221 | var progress = new Progress(); 222 | 223 | if (onProgress != null) 224 | progress.ProgressChanged += onProgress; 225 | 226 | await Helpers.HttpUploadClient!.UploadFileAsync(signedUrl.SignedUrl, localFilePath, headers, progress); 227 | 228 | return GetFinalPath(signedUrl.Key); 229 | } 230 | 231 | /// 232 | /// Uploads a byte array using a pre-generated Signed Upload Url 233 | /// 234 | /// 235 | /// 236 | /// 237 | /// 238 | /// 239 | /// 240 | public async Task UploadToSignedUrl(byte[] data, UploadSignedUrl signedUrl, FileOptions? options = null, 241 | EventHandler? onProgress = null, bool inferContentType = true) 242 | { 243 | options ??= new FileOptions(); 244 | 245 | if (inferContentType) 246 | options.ContentType = MimeMapping.MimeUtility.GetMimeMapping(signedUrl.Key); 247 | 248 | var headers = new Dictionary(Headers) 249 | { 250 | ["Authorization"] = $"Bearer {signedUrl.Token}", 251 | ["cache-control"] = $"max-age={options.CacheControl}", 252 | ["content-type"] = options.ContentType 253 | }; 254 | 255 | if (options.Upsert) 256 | headers.Add("x-upsert", options.Upsert.ToString().ToLower()); 257 | 258 | var progress = new Progress(); 259 | 260 | if (onProgress != null) 261 | progress.ProgressChanged += onProgress; 262 | 263 | await Helpers.HttpUploadClient!.UploadBytesAsync(signedUrl.SignedUrl, data, headers, progress); 264 | 265 | return GetFinalPath(signedUrl.Key); 266 | } 267 | 268 | 269 | /// 270 | /// Replaces an existing file at the specified path with a new one. 271 | /// 272 | /// File source path. 273 | /// The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. 274 | /// HTTP headers. 275 | /// 276 | /// 277 | public Task Update(string localFilePath, string supabasePath, FileOptions? options = null, 278 | EventHandler? onProgress = null) 279 | { 280 | options ??= new FileOptions(); 281 | return UploadOrUpdate(localFilePath, supabasePath, options, onProgress); 282 | } 283 | 284 | /// 285 | /// Replaces an existing file at the specified path with a new one. 286 | /// 287 | /// 288 | /// The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. 289 | /// HTTP headers. 290 | /// 291 | /// 292 | public Task Update(byte[] data, string supabasePath, FileOptions? options = null, 293 | EventHandler? onProgress = null) 294 | { 295 | options ??= new FileOptions(); 296 | return UploadOrUpdate(data, supabasePath, options, onProgress); 297 | } 298 | 299 | /// 300 | /// Moves an existing file to a new location, optionally allowing renaming. 301 | /// 302 | /// The original file path, including the current file name (e.g., `folder/image.png`). 303 | /// The target file path, including the new file name (e.g., `folder/image-copy.png`). 304 | /// Optional parameters for specifying the destination bucket and other settings. 305 | /// Returns a boolean value indicating whether the operation was successful. 306 | public async Task Move(string fromPath, string toPath, DestinationOptions? options = null) 307 | { 308 | var body = new Dictionary 309 | { 310 | { "bucketId", BucketId }, 311 | { "sourceKey", fromPath }, 312 | { "destinationKey", toPath }, 313 | { "destinationBucket", options?.DestinationBucket } 314 | }; 315 | await Helpers.MakeRequest(HttpMethod.Post, $"{Url}/object/move", body, Headers); 316 | return true; 317 | } 318 | 319 | /// 320 | /// Copies a file/object from one path to another within a bucket or across buckets. 321 | /// 322 | /// The source path of the file/object to copy. 323 | /// The destination path for the copied file/object. 324 | /// Optional parameters such as the destination bucket. 325 | /// True if the copy operation was successful. 326 | public async Task Copy(string fromPath, string toPath, DestinationOptions? options = null) 327 | { 328 | var body = new Dictionary 329 | { 330 | { "bucketId", BucketId }, 331 | { "sourceKey", fromPath }, 332 | { "destinationKey", toPath }, 333 | { "destinationBucket", options?.DestinationBucket } 334 | }; 335 | 336 | await Helpers.MakeRequest(HttpMethod.Post, $"{Url}/object/copy", body, Headers); 337 | return true; 338 | } 339 | 340 | /// 341 | /// Downloads a file from a private bucket. For public buckets, use 342 | /// 343 | /// 344 | /// 345 | /// 346 | /// 347 | /// 348 | public Task Download(string supabasePath, string localPath, TransformOptions? transformOptions = null, 349 | EventHandler? onProgress = null) 350 | { 351 | var url = transformOptions != null 352 | ? $"{Url}/render/image/authenticated/{GetFinalPath(supabasePath)}" 353 | : $"{Url}/object/{GetFinalPath(supabasePath)}"; 354 | return DownloadFile(url, localPath, transformOptions, onProgress); 355 | } 356 | 357 | /// 358 | /// Downloads a file from a private bucket. For public buckets, use 359 | /// 360 | /// 361 | /// 362 | /// 363 | /// 364 | public Task Download(string supabasePath, string localPath, EventHandler? onProgress = null) => 365 | Download(supabasePath, localPath, null, onProgress: onProgress); 366 | 367 | /// 368 | /// Downloads a byte array from a private bucket to be used programmatically. For public buckets 369 | /// 370 | /// 371 | /// 372 | /// 373 | /// 374 | public Task Download(string supabasePath, TransformOptions? transformOptions = null, 375 | EventHandler? onProgress = null) 376 | { 377 | var url = $"{Url}/object/{GetFinalPath(supabasePath)}"; 378 | return DownloadBytes(url, transformOptions, onProgress); 379 | } 380 | 381 | /// 382 | /// Downloads a byte array from a private bucket to be used programmatically. For public buckets 383 | /// 384 | /// 385 | /// 386 | /// 387 | public Task Download(string supabasePath, EventHandler? onProgress = null) => 388 | Download(supabasePath, transformOptions: null, onProgress: onProgress); 389 | 390 | /// 391 | /// Downloads a public file to the filesystem. This method DOES NOT VERIFY that the file is actually public. 392 | /// 393 | /// 394 | /// 395 | /// 396 | /// 397 | /// 398 | public Task DownloadPublicFile(string supabasePath, string localPath, 399 | TransformOptions? transformOptions = null, EventHandler? onProgress = null) 400 | { 401 | var url = GetPublicUrl(supabasePath, transformOptions); 402 | return DownloadFile(url, localPath, transformOptions, onProgress); 403 | } 404 | 405 | /// 406 | /// Downloads a byte array from a private bucket to be used programmatically. This method DOES NOT VERIFY that the file is actually public. 407 | /// 408 | /// 409 | /// 410 | /// 411 | /// 412 | public Task DownloadPublicFile(string supabasePath, TransformOptions? transformOptions = null, 413 | EventHandler? onProgress = null) 414 | { 415 | var url = GetPublicUrl(supabasePath, transformOptions); 416 | return DownloadBytes(url, transformOptions, onProgress); 417 | } 418 | 419 | /// 420 | /// Deletes file within the same bucket 421 | /// 422 | /// A path to delete, for example `folder/image.png`. 423 | /// 424 | public async Task Remove(string path) 425 | { 426 | var result = await Remove(new List { path }); 427 | return result?.FirstOrDefault(); 428 | } 429 | 430 | /// 431 | /// Deletes files within the same bucket 432 | /// 433 | /// An array of files to be deletes, including the path and file name. For example [`folder/image.png`]. 434 | /// 435 | public async Task?> Remove(List paths) 436 | { 437 | var data = new Dictionary { { "prefixes", paths } }; 438 | var response = 439 | await Helpers.MakeRequest>(HttpMethod.Delete, $"{Url}/object/{BucketId}", data, 440 | Headers); 441 | 442 | return response; 443 | } 444 | 445 | /// 446 | /// Creates an upload signed URL. Use it to upload a file straight to the bucket without credentials 447 | /// 448 | /// The file path, including the current file name. For example `folder/image.png`. 449 | /// 450 | public async Task CreateUploadSignedUrl(string supabasePath) 451 | { 452 | var path = GetFinalPath(supabasePath); 453 | 454 | var url = $"{Url}/object/upload/sign/{path}"; 455 | var response = 456 | await Helpers.MakeRequest(HttpMethod.Post, url, null, Headers); 457 | 458 | if (response == null || string.IsNullOrEmpty(response.Url) || !response.Url!.Contains("token")) 459 | throw new SupabaseStorageException( 460 | "Response did not return with expected data. Does this token have proper permission to generate a url?"); 461 | 462 | var generatedUri = new Uri($"{Url}{response.Url}"); 463 | var query = HttpUtility.ParseQueryString(generatedUri.Query); 464 | var token = query["token"]; 465 | 466 | return new UploadSignedUrl(generatedUri, token, supabasePath); 467 | } 468 | 469 | private async Task UploadOrUpdate(string localPath, string supabasePath, FileOptions options, 470 | EventHandler? onProgress = null) 471 | { 472 | Uri uri = new Uri($"{Url}/object/{GetFinalPath(supabasePath)}"); 473 | 474 | var headers = new Dictionary(Headers) 475 | { 476 | { "cache-control", $"max-age={options.CacheControl}" }, 477 | { "content-type", options.ContentType } 478 | }; 479 | 480 | if (options.Upsert) 481 | headers.Add("x-upsert", options.Upsert.ToString().ToLower()); 482 | 483 | var progress = new Progress(); 484 | 485 | if (onProgress != null) 486 | progress.ProgressChanged += onProgress; 487 | 488 | await Helpers.HttpUploadClient!.UploadFileAsync(uri, localPath, headers, progress); 489 | 490 | return GetFinalPath(supabasePath); 491 | } 492 | 493 | private async Task UploadOrUpdate(byte[] data, string supabasePath, FileOptions options, 494 | EventHandler? onProgress = null) 495 | { 496 | Uri uri = new Uri($"{Url}/object/{GetFinalPath(supabasePath)}"); 497 | 498 | var headers = new Dictionary(Headers) 499 | { 500 | { "cache-control", $"max-age={options.CacheControl}" }, 501 | { "content-type", options.ContentType } 502 | }; 503 | 504 | if (options.Upsert) 505 | headers.Add("x-upsert", options.Upsert.ToString().ToLower()); 506 | 507 | var progress = new Progress(); 508 | 509 | if (onProgress != null) 510 | progress.ProgressChanged += onProgress; 511 | 512 | await Helpers.HttpUploadClient!.UploadBytesAsync(uri, data, headers, progress); 513 | 514 | return GetFinalPath(supabasePath); 515 | } 516 | 517 | private async Task DownloadFile(string url, string localPath, TransformOptions? transformOptions = null, 518 | EventHandler? onProgress = null) 519 | { 520 | var builder = new UriBuilder(url); 521 | var progress = new Progress(); 522 | 523 | if (transformOptions != null) 524 | builder.Query = transformOptions.ToQueryCollection().ToString(); 525 | 526 | if (onProgress != null) 527 | progress.ProgressChanged += onProgress; 528 | 529 | var stream = await Helpers.HttpDownloadClient!.DownloadDataAsync(builder.Uri, Headers, progress); 530 | 531 | using var fileStream = new FileStream(localPath, FileMode.OpenOrCreate, FileAccess.Write); 532 | 533 | stream.WriteTo(fileStream); 534 | 535 | return localPath; 536 | } 537 | 538 | private async Task DownloadBytes(string url, TransformOptions? transformOptions = null, 539 | EventHandler? onProgress = null) 540 | { 541 | var builder = new UriBuilder(url); 542 | var progress = new Progress(); 543 | 544 | if (transformOptions != null) 545 | builder.Query = transformOptions.ToQueryCollection().ToString(); 546 | 547 | if (onProgress != null) 548 | progress.ProgressChanged += onProgress; 549 | 550 | var stream = await Helpers.HttpDownloadClient!.DownloadDataAsync(builder.Uri, Headers, progress); 551 | 552 | return stream.ToArray(); 553 | } 554 | 555 | private string GetFinalPath(string path) => $"{BucketId}/{path}"; 556 | } 557 | } -------------------------------------------------------------------------------- /Storage/TransformOptions.cs: -------------------------------------------------------------------------------- 1 | using System.Runtime.Serialization; 2 | using Newtonsoft.Json; 3 | using Supabase.Core.Attributes; 4 | 5 | namespace Supabase.Storage 6 | { 7 | public class TransformOptions 8 | { 9 | /// 10 | /// The resize mode can be cover, contain or fill. Defaults to cover. 11 | /// - Cover resizes the image to maintain it's aspect ratio while filling the entire width and height. 12 | /// - Contain resizes the image to maintain it's aspect ratio while fitting the entire image within the width and height. 13 | /// - Fill resizes the image to fill the entire width and height.If the object's aspect ratio does not match the width and height, the image will be stretched to fit. 14 | /// 15 | public enum ResizeType 16 | { 17 | [MapTo("cover"), EnumMember(Value = "cover")] 18 | Cover, 19 | [MapTo("contain"), EnumMember(Value = "contain")] 20 | Contain, 21 | [MapTo("fill"), EnumMember(Value = "fill")] 22 | Fill 23 | } 24 | 25 | /// 26 | /// The width of the image in pixels. 27 | /// 28 | [JsonProperty("width")] 29 | public int? Width { get; set; } 30 | 31 | /// 32 | /// The height of the image in pixels. 33 | /// 34 | [JsonProperty("height")] 35 | public int? Height { get; set; } 36 | 37 | /// 38 | /// The resize mode can be cover, contain or fill. Defaults to cover. 39 | /// - Cover resizes the image to maintain it's aspect ratio while filling the entire width and height. 40 | /// - Contain resizes the image to maintain it's aspect ratio while fitting the entire image within the width and height. 41 | /// - Fill resizes the image to fill the entire width and height.If the object's aspect ratio does not match the width and height, the image will be stretched to fit. 42 | /// 43 | [JsonProperty("resize")] 44 | public ResizeType Resize { get; set; } = ResizeType.Cover; 45 | 46 | /// 47 | /// Set the quality of the returned image, this is percentage based, default 80 48 | /// 49 | [JsonProperty("quality")] 50 | public int Quality { get; set; } = 80; 51 | 52 | /// 53 | /// Specify the format of the image requested. 54 | /// 55 | /// When using 'origin' we force the format to be the same as the original image, 56 | /// bypassing automatic browser optimisation such as webp conversion 57 | /// 58 | [JsonProperty("format")] 59 | public string Format { get; set; } = "origin"; 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /Storage/UploadSignedUrl.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | namespace Supabase.Storage 3 | { 4 | /// 5 | /// Represents a Generated Upload Signed Url - can be used to upload a file without needing a logged in token or user. 6 | /// 7 | public class UploadSignedUrl 8 | { 9 | /// 10 | /// The Full Signed Url 11 | /// 12 | public Uri SignedUrl { get; } 13 | 14 | /// 15 | /// The generated token 16 | /// 17 | public string Token { get; } 18 | 19 | /// 20 | /// The Key that can be uploaded to (the supabase filename) 21 | /// 22 | public string Key { get; } 23 | 24 | public UploadSignedUrl(Uri signedUrl, string token, string key) 25 | { 26 | SignedUrl = signedUrl; 27 | Token = token; 28 | Key = key; 29 | } 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /StorageTests/Assets/supabase-csharp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/supabase-community/storage-csharp/83dcdfe6c3f153b63b1c493cfaf1d53b3ae9f737/StorageTests/Assets/supabase-csharp.png -------------------------------------------------------------------------------- /StorageTests/ClientTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System.Collections.Generic; 3 | 4 | namespace StorageTests; 5 | 6 | [TestClass] 7 | public class ClientTests 8 | { 9 | [TestMethod("Can use gettable headers")] 10 | public void CanUseGettableHeaders() 11 | { 12 | var client = new Supabase.Storage.Client("http://localhost:5000", new Dictionary { { "Testing", "1234" } }); 13 | 14 | client.GetHeaders = () => new Dictionary { { "Dynamic", "4567" }, { "Testing", "4567" } }; 15 | 16 | Assert.AreEqual("1234", client.Headers["Testing"]); 17 | Assert.AreEqual("4567", client.Headers["Dynamic"]); 18 | } 19 | } -------------------------------------------------------------------------------- /StorageTests/ExceptionTests.cs: -------------------------------------------------------------------------------- 1 | using System.Collections.Generic; 2 | using System.Threading.Tasks; 3 | using Microsoft.VisualStudio.TestTools.UnitTesting; 4 | using Supabase.Storage; 5 | using Supabase.Storage.Exceptions; 6 | 7 | namespace StorageTests; 8 | 9 | [TestClass] 10 | public class ExceptionTests 11 | { 12 | [TestMethod("Throws: Unauthorized Exception (No Authorization Header)")] 13 | public async Task ThrowsUnauthorizedExceptionNoAuthorization() 14 | { 15 | var noAuthorizationClient = new Client(Helpers.StorageUrl); 16 | 17 | var ex = await Assert.ThrowsExceptionAsync(() => 18 | noAuthorizationClient.CreateBucket("expected-to-fail")); 19 | 20 | Assert.IsTrue(ex.Reason == FailureHint.Reason.NotAuthorized); 21 | } 22 | 23 | [TestMethod("Throws Unauthorized Exception (Garbage Authorization)")] 24 | public async Task ThrowsUnauthorizedExceptionGarbageAuthorization() 25 | { 26 | var badAuthorization = new Client(Helpers.StorageUrl, new Dictionary 27 | { 28 | ["Authorization"] = "Bearer GarbageKey" 29 | }); 30 | 31 | var ex = await Assert.ThrowsExceptionAsync(() => 32 | badAuthorization.CreateBucket("expected-to-fail")); 33 | 34 | Assert.IsTrue(ex.Reason == FailureHint.Reason.NotAuthorized); 35 | } 36 | 37 | [TestMethod("Throws Unauthorized Exception (Bad Authorization)")] 38 | public async Task ThrowsUnauthorizedExceptionBadAuthorization() 39 | { 40 | var badAuthorization = new Client(Helpers.StorageUrl, new Dictionary 41 | { 42 | ["Authorization"] = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c" 43 | }); 44 | 45 | var ex = await Assert.ThrowsExceptionAsync(() => 46 | badAuthorization.CreateBucket("expected-to-fail")); 47 | 48 | Assert.IsTrue(ex.Reason == FailureHint.Reason.NotAuthorized); 49 | } 50 | } -------------------------------------------------------------------------------- /StorageTests/Helpers.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | namespace StorageTests 5 | { 6 | public static class Helpers 7 | { 8 | public static string SupabaseUrl => "http://127.0.0.1:54321/storage/v1"; 9 | public static string PublicKey => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0"; 10 | public static string ServiceKey => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU"; 11 | 12 | public static string StorageUrl => $"{SupabaseUrl}"; 13 | 14 | public static Supabase.Storage.Client GetServiceClient() 15 | { 16 | return new Supabase.Storage.Client(StorageUrl, new Dictionary 17 | { 18 | { "Authorization", $"Bearer {ServiceKey}" }, 19 | }); 20 | } 21 | 22 | public static Supabase.Storage.Client GetPublicClient() 23 | { 24 | return new Supabase.Storage.Client(StorageUrl, new Dictionary 25 | { 26 | { "Authorization", $"Bearer {PublicKey}" }, 27 | }); 28 | } 29 | } 30 | } 31 | 32 | -------------------------------------------------------------------------------- /StorageTests/StorageBucketAnonTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | using Supabase.Storage; 7 | using Supabase.Storage.Exceptions; 8 | 9 | namespace StorageTests; 10 | 11 | [TestClass] 12 | public class StorageBucketAnonTests 13 | { 14 | private Client AdminStorage => Helpers.GetServiceClient(); 15 | private Client Storage => Helpers.GetPublicClient(); 16 | 17 | [TestMethod("Bucket: Returns empty when attempting to List")] 18 | public async Task List() 19 | { 20 | var buckets = await Storage.ListBuckets(); 21 | 22 | Assert.IsNotNull(buckets); 23 | Assert.IsTrue(buckets.Count == 0); 24 | 25 | await Assert.ThrowsExceptionAsync(async () => 26 | { 27 | String newParentBucket = "parent"; 28 | 29 | if (await AdminStorage.GetBucket("parent") == null) 30 | newParentBucket = await AdminStorage.CreateBucket("parent"); 31 | 32 | await Storage.From(newParentBucket).Upload(new Byte[] { 0x0, 0x0, 0x0 }, $"child/test.bin"); 33 | }); 34 | } 35 | 36 | [TestMethod("Bucket: Returns null when attempting to Get")] 37 | public async Task Get() 38 | { 39 | var id = Guid.NewGuid().ToString(); 40 | await AdminStorage.CreateBucket(id); 41 | 42 | var result = await Storage.GetBucket(id); 43 | Assert.IsNull(result); 44 | 45 | await AdminStorage.DeleteBucket(id); 46 | } 47 | 48 | [TestMethod("Bucket: Throws when attempting to Create")] 49 | public async Task CreatePublic() 50 | { 51 | await Assert.ThrowsExceptionAsync(async () => 52 | { 53 | await Storage.CreateBucket("parent"); 54 | }); 55 | } 56 | 57 | [TestMethod("Bucket: Throws when attempting to Update")] 58 | public async Task Update() 59 | { 60 | var id = Guid.NewGuid().ToString(); 61 | await AdminStorage.CreateBucket(id); 62 | 63 | await Assert.ThrowsExceptionAsync(async () => 64 | { 65 | await Storage.UpdateBucket(id, new BucketUpsertOptions { Public = true }); 66 | }); 67 | 68 | await AdminStorage.DeleteBucket(id); 69 | } 70 | 71 | [TestMethod("Bucket: Throws when attempting to Empty")] 72 | public async Task Empty() 73 | { 74 | var id = Guid.NewGuid().ToString(); 75 | await AdminStorage.CreateBucket(id); 76 | 77 | await Assert.ThrowsExceptionAsync(async () => 78 | { 79 | await Storage.EmptyBucket(id); 80 | }); 81 | 82 | await AdminStorage.DeleteBucket(id); 83 | } 84 | 85 | [TestMethod("Bucket: Throws when attempting to Delete")] 86 | public async Task Delete() 87 | { 88 | var id = Guid.NewGuid().ToString(); 89 | await AdminStorage.CreateBucket(id); 90 | 91 | await Assert.ThrowsExceptionAsync(async () => 92 | { 93 | await Storage.DeleteBucket(id); 94 | }); 95 | 96 | await AdminStorage.DeleteBucket(id); 97 | } 98 | } -------------------------------------------------------------------------------- /StorageTests/StorageBucketTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Threading.Tasks; 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | using Supabase.Storage; 7 | using Supabase.Storage.Exceptions; 8 | 9 | namespace StorageTests; 10 | 11 | [TestClass] 12 | public class StorageBucketTests 13 | { 14 | Client Storage => Helpers.GetServiceClient(); 15 | 16 | [TestMethod("Bucket: List")] 17 | public async Task List() 18 | { 19 | var buckets = await Storage.ListBuckets(); 20 | 21 | Assert.IsNotNull(buckets); 22 | Assert.IsTrue(buckets.Count > 0); 23 | Assert.IsInstanceOfType(buckets, typeof(List)); 24 | 25 | if (await Storage.GetBucket("parent") != null) 26 | { 27 | await Storage.From("parent").Remove("child/test.bin"); 28 | await Storage.DeleteBucket("parent"); 29 | } 30 | 31 | var newParentBucket = await Storage.CreateBucket("parent"); 32 | Assert.IsNotNull(newParentBucket); 33 | await Storage.From(newParentBucket).Upload(new Byte[] { 0x0, 0x0, 0x0 }, $"child/test.bin"); 34 | 35 | var parentFileList = await Storage.From(newParentBucket).List(); 36 | Assert.IsNotNull(parentFileList); 37 | Assert.IsTrue(parentFileList.First().IsFolder); 38 | 39 | var childFileList = await Storage.From(newParentBucket).List("child"); 40 | Assert.IsNotNull(childFileList); 41 | Assert.IsFalse(childFileList.First().IsFolder); 42 | } 43 | 44 | [TestMethod("Bucket: Get")] 45 | public async Task Get() 46 | { 47 | var id = Guid.NewGuid().ToString(); 48 | await Storage.CreateBucket(id); 49 | var bucket = await Storage.GetBucket(id); 50 | 51 | Assert.IsInstanceOfType(bucket, typeof(Bucket)); 52 | 53 | var nonExisting = await Storage.GetBucket("I don't exist"); 54 | Assert.IsNull(nonExisting); 55 | 56 | await Storage.DeleteBucket(id); 57 | } 58 | 59 | [TestMethod("Bucket: Create, Private")] 60 | public async Task CreatePrivate() 61 | { 62 | var id = Guid.NewGuid().ToString(); 63 | var insertId = await Storage.CreateBucket(id); 64 | 65 | Assert.AreEqual(id, insertId); 66 | 67 | var bucket = await Storage.GetBucket(id); 68 | 69 | Assert.IsNotNull(bucket); 70 | Assert.IsFalse(bucket.Public); 71 | 72 | await Storage.DeleteBucket(id); 73 | } 74 | 75 | [TestMethod("Bucket: Create, Public")] 76 | public async Task CreatePublic() 77 | { 78 | var id = Guid.NewGuid().ToString(); 79 | await Storage.CreateBucket(id, new BucketUpsertOptions { Public = true }); 80 | 81 | var bucket = await Storage.GetBucket(id); 82 | 83 | Assert.IsNotNull(bucket); 84 | Assert.IsTrue(bucket.Public); 85 | 86 | var ex = await Assert.ThrowsExceptionAsync(() => Storage.CreateBucket(id)); 87 | Assert.IsTrue(ex.Reason == FailureHint.Reason.AlreadyExists); 88 | 89 | await Storage.DeleteBucket(id); 90 | } 91 | 92 | [TestMethod("Bucket: Update")] 93 | public async Task Update() 94 | { 95 | var id = Guid.NewGuid().ToString(); 96 | await Storage.CreateBucket(id); 97 | 98 | var privateBucket = await Storage.GetBucket(id); 99 | Assert.IsNotNull(privateBucket); 100 | Assert.IsFalse(privateBucket.Public); 101 | 102 | await Storage.UpdateBucket(id, new BucketUpsertOptions { Public = true }); 103 | 104 | var nowPublicBucket = await Storage.GetBucket(id); 105 | Assert.IsNotNull(nowPublicBucket); 106 | Assert.IsTrue(nowPublicBucket.Public); 107 | 108 | await Storage.DeleteBucket(id); 109 | } 110 | 111 | [TestMethod("Bucket: Empty")] 112 | public async Task Empty() 113 | { 114 | var id = Guid.NewGuid().ToString(); 115 | await Storage.CreateBucket(id); 116 | 117 | for (var i = 0; i < 5; i++) 118 | { 119 | await Storage.From(id).Upload(new Byte[] { 0x0, 0x0, 0x0 }, $"test-{i}.bin"); 120 | } 121 | 122 | var initialList = await Storage.From(id).List(); 123 | 124 | Assert.IsNotNull(initialList); 125 | Assert.IsTrue(initialList.Count > 0); 126 | 127 | await Storage.EmptyBucket(id); 128 | 129 | var listAfterEmpty = await Storage.From(id).List(); 130 | 131 | Assert.IsNotNull(listAfterEmpty); 132 | Assert.IsTrue(listAfterEmpty.Count == 0); 133 | 134 | await Storage.DeleteBucket(id); 135 | } 136 | 137 | [TestMethod("Bucket: Delete, Throws Error if Not Empty")] 138 | public async Task DeleteThrows() 139 | { 140 | var id = Guid.NewGuid().ToString(); 141 | await Storage.CreateBucket(id); 142 | 143 | for (var i = 0; i < 5; i++) 144 | { 145 | await Storage.From(id).Upload(new Byte[] { 0x0, 0x0, 0x0 }, $"test-{i}.bin"); 146 | } 147 | 148 | await Assert.ThrowsExceptionAsync(async () => 149 | { 150 | await Storage.DeleteBucket(id); 151 | }); 152 | } 153 | 154 | [TestMethod("Bucket: Delete")] 155 | public async Task Delete() 156 | { 157 | var id = Guid.NewGuid().ToString(); 158 | await Storage.CreateBucket(id); 159 | 160 | for (var i = 0; i < 5; i++) 161 | { 162 | await Storage.From(id).Upload(new Byte[] { 0x0, 0x0, 0x0 }, $"test-{i}.bin"); 163 | } 164 | 165 | await Storage.EmptyBucket(id); 166 | await Storage.DeleteBucket(id); 167 | 168 | Assert.IsNull(await Storage.GetBucket(id)); 169 | } 170 | } -------------------------------------------------------------------------------- /StorageTests/StorageClientTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.VisualStudio.TestTools.UnitTesting; 2 | using System.Collections.Generic; 3 | 4 | namespace StorageTests; 5 | 6 | [TestClass] 7 | public class StorageClientTests 8 | { 9 | [TestMethod("Can use gettable headers")] 10 | public void CanUseGettableHeaders() 11 | { 12 | var initialHeaders = new Dictionary { { "Testing", "1234" } }; 13 | 14 | var client = new Supabase.Storage.Client("http://localhost:5000", initialHeaders) 15 | { 16 | GetHeaders = () => new Dictionary 17 | { 18 | ["Dynamic"] = "4567", 19 | ["Testing"] = "4567" 20 | } 21 | }; 22 | 23 | Assert.AreEqual("1234", client.Headers["Testing"]); 24 | Assert.AreEqual("4567", client.Headers["Dynamic"]); 25 | } 26 | } -------------------------------------------------------------------------------- /StorageTests/StorageFileAnonTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Threading.Tasks; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | using Supabase.Storage; 9 | using Supabase.Storage.Exceptions; 10 | using Supabase.Storage.Interfaces; 11 | 12 | namespace StorageTests; 13 | 14 | [TestClass] 15 | public class StorageFileAnonTests 16 | { 17 | Client AdminStorage => Helpers.GetServiceClient(); 18 | private Client Storage => Helpers.GetPublicClient(); 19 | 20 | private string _bucketId = string.Empty; 21 | private IStorageFileApi _adminBucket = null!; 22 | private IStorageFileApi _bucket = null!; 23 | 24 | [TestInitialize] 25 | public async Task InitializeTest() 26 | { 27 | _bucketId = Guid.NewGuid().ToString(); 28 | 29 | if (_bucket == null && await Storage.GetBucket(_bucketId) == null) 30 | { 31 | await AdminStorage.CreateBucket(_bucketId, new BucketUpsertOptions { Public = false }); 32 | } 33 | 34 | _adminBucket = AdminStorage.From(_bucketId); 35 | _bucket = Storage.From(_bucketId); 36 | } 37 | 38 | [TestCleanup] 39 | public async Task TestCleanup() 40 | { 41 | var files = await _adminBucket.List(); 42 | 43 | Assert.IsNotNull(files); 44 | 45 | foreach (var file in files) 46 | { 47 | if (file.Name is not null) 48 | await _adminBucket.Remove(new List { file.Name }); 49 | } 50 | 51 | await AdminStorage.DeleteBucket(_bucketId); 52 | } 53 | 54 | [TestMethod("File: Throws attempting to Upload File")] 55 | public async Task UploadFile() 56 | { 57 | var asset = "supabase-csharp.png"; 58 | var name = $"{Guid.NewGuid()}.png"; 59 | var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)?.Replace("file:", ""); 60 | 61 | Assert.IsNotNull(basePath); 62 | 63 | var imagePath = Path.Combine(basePath, "Assets", asset); 64 | 65 | await Assert.ThrowsExceptionAsync(async () => 66 | { 67 | await _bucket.Upload(imagePath, name); 68 | }); 69 | } 70 | 71 | [TestMethod("File: Throws attempting to Upload Arbitrary Byte Array")] 72 | public async Task UploadArbitraryByteArray() 73 | { 74 | var name = $"{Guid.NewGuid()}.bin"; 75 | 76 | await Assert.ThrowsExceptionAsync(async () => 77 | { 78 | await _bucket.Upload(new Byte[] { 0x0, 0x0, 0x0 }, name); 79 | }); 80 | } 81 | 82 | [TestMethod("File: Throws attempting to Download")] 83 | public async Task DownloadFile() 84 | { 85 | var tsc = new TaskCompletionSource(); 86 | 87 | var asset = "supabase-csharp.png"; 88 | var name = $"{Guid.NewGuid()}.png"; 89 | var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)?.Replace("file:", ""); 90 | Assert.IsNotNull(basePath); 91 | 92 | var imagePath = Path.Combine(basePath, "Assets", asset); 93 | 94 | await _adminBucket.Upload(imagePath, name); 95 | 96 | var downloadPath = Path.Combine(basePath, name); 97 | 98 | await Assert.ThrowsExceptionAsync(async () => 99 | { 100 | await _bucket.Download(name, downloadPath, null); 101 | }); 102 | 103 | await _adminBucket.Remove(new List { name }); 104 | } 105 | 106 | [TestMethod("File: Throws attempting to Download Bytes")] 107 | public async Task DownloadBytes() 108 | { 109 | var data = new Byte[] { 0x0 }; 110 | var name = $"{Guid.NewGuid()}.bin"; 111 | 112 | await _adminBucket.Upload(data, name); 113 | 114 | await Assert.ThrowsExceptionAsync(async () => 115 | { 116 | await _bucket.Download(name, null); 117 | }); 118 | 119 | await _adminBucket.Remove(new List { name }); 120 | } 121 | 122 | [TestMethod("File: Throws attempting to Rename")] 123 | public async Task Move() 124 | { 125 | var name = $"{Guid.NewGuid()}.bin"; 126 | await _adminBucket.Upload(new Byte[] { 0x0, 0x1 }, name); 127 | 128 | await Assert.ThrowsExceptionAsync(async () => 129 | { 130 | await _bucket.Move(name, "new-file.bin"); 131 | }); 132 | } 133 | 134 | [TestMethod("File: Throws attempting to Copy")] 135 | public async Task Copy() 136 | { 137 | var name = $"{Guid.NewGuid()}.bin"; 138 | await _adminBucket.Upload(new Byte[] { 0x0, 0x1 }, name); 139 | 140 | await Assert.ThrowsExceptionAsync(async () => 141 | { 142 | await _bucket.Copy(name, "new-file.bin"); 143 | }); 144 | } 145 | 146 | [TestMethod("File: Get Public Link")] 147 | public async Task GetPublicLink() 148 | { 149 | var name = $"{Guid.NewGuid()}.bin"; 150 | await _adminBucket.Upload(new Byte[] { 0x0, 0x1 }, name); 151 | var url = _bucket.GetPublicUrl(name); 152 | await _adminBucket.Remove(new List { name }); 153 | 154 | Assert.IsNotNull(url); 155 | } 156 | 157 | [TestMethod("File: Throws attempting to Get Signed Link")] 158 | public async Task GetSignedLink() 159 | { 160 | var name = $"{Guid.NewGuid()}.bin"; 161 | await _adminBucket.Upload(new Byte[] { 0x0, 0x1 }, name); 162 | 163 | await Assert.ThrowsExceptionAsync(async () => 164 | { 165 | var url = await _bucket.CreateSignedUrl(name, 3600); 166 | }); 167 | 168 | await _adminBucket.Remove(new List { name }); 169 | } 170 | 171 | [TestMethod("File: Throws attempting to Get Multiple Signed Links")] 172 | public async Task GetMultipleSignedLinks() 173 | { 174 | var name1 = $"{Guid.NewGuid()}.bin"; 175 | await _adminBucket.Upload(new Byte[] { 0x0, 0x1 }, name1); 176 | 177 | var name2 = $"{Guid.NewGuid()}.bin"; 178 | await _adminBucket.Upload(new Byte[] { 0x0, 0x1 }, name2); 179 | 180 | await Assert.ThrowsExceptionAsync(async () => 181 | { 182 | await _bucket.CreateSignedUrls(new List { name1, name2 }, 3600); 183 | }); 184 | 185 | await _adminBucket.Remove(new List { name1 }); 186 | } 187 | 188 | [TestMethod("File: Throws attempting to Create Signed Upload Url")] 189 | public async Task CanCreateSignedUploadUrl() 190 | { 191 | var name1 = $"{Guid.NewGuid()}.bin"; 192 | await _adminBucket.Upload(new Byte[] { 0x0, 0x1 }, name1); 193 | 194 | var name2 = $"{Guid.NewGuid()}.bin"; 195 | await _adminBucket.Upload(new Byte[] { 0x0, 0x1 }, name2); 196 | 197 | await Assert.ThrowsExceptionAsync(async () => 198 | { 199 | await _bucket.CreateSignedUrls(new List { name1, name2 }, 3600); 200 | }); 201 | } 202 | } -------------------------------------------------------------------------------- /StorageTests/StorageFileTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.IO; 4 | using System.Linq; 5 | using System.Reflection; 6 | using System.Threading.Tasks; 7 | using Microsoft.VisualStudio.TestTools.UnitTesting; 8 | using Supabase.Storage; 9 | using Supabase.Storage.Interfaces; 10 | 11 | namespace StorageTests; 12 | 13 | [TestClass] 14 | public class StorageFileTests 15 | { 16 | Client Storage => Helpers.GetServiceClient(); 17 | 18 | private string _bucketId = string.Empty; 19 | private IStorageFileApi _bucket = null!; 20 | 21 | [TestInitialize] 22 | public async Task InitializeTest() 23 | { 24 | _bucketId = Guid.NewGuid().ToString(); 25 | 26 | var exists = await Storage.GetBucket(_bucketId); 27 | if (exists == null) 28 | { 29 | await Storage.CreateBucket(_bucketId, new BucketUpsertOptions { Public = true }); 30 | } 31 | 32 | _bucket = Storage.From(_bucketId); 33 | } 34 | 35 | [TestCleanup] 36 | public async Task TestCleanup() 37 | { 38 | var files = await _bucket.List(); 39 | 40 | Assert.IsNotNull(files); 41 | 42 | foreach (var file in files) 43 | { 44 | if (file.Name is not null) 45 | await _bucket.Remove(new List { file.Name }); 46 | } 47 | 48 | await Storage.DeleteBucket(_bucketId); 49 | } 50 | 51 | [TestMethod("File: Upload File")] 52 | public async Task UploadFile() 53 | { 54 | var didTriggerProgress = new TaskCompletionSource(); 55 | 56 | var asset = "supabase-csharp.png"; 57 | var name = $"{Guid.NewGuid()}.png"; 58 | var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)?.Replace("file:", ""); 59 | 60 | Assert.IsNotNull(basePath); 61 | 62 | var imagePath = Path.Combine(basePath, "Assets", asset); 63 | 64 | await _bucket.Upload(imagePath, name, null, (_, _) => { didTriggerProgress.TrySetResult(true); }); 65 | 66 | var list = await _bucket.List(); 67 | 68 | Assert.IsNotNull(list); 69 | 70 | var existing = list.Find(item => item.Name == name); 71 | Assert.IsNotNull(existing); 72 | 73 | var sentProgressEvent = await didTriggerProgress.Task; 74 | Assert.IsTrue(sentProgressEvent); 75 | 76 | await _bucket.Remove(new List { name }); 77 | } 78 | 79 | [TestMethod("File: Upload Arbitrary Byte Array")] 80 | public async Task UploadArbitraryByteArray() 81 | { 82 | var tsc = new TaskCompletionSource(); 83 | 84 | var name = $"{Guid.NewGuid()}.bin"; 85 | 86 | await _bucket.Upload(new Byte[] { 0x0, 0x0, 0x0 }, name, null, (_, _) => tsc.TrySetResult(true)); 87 | 88 | var list = await _bucket.List(); 89 | Assert.IsNotNull(list); 90 | 91 | var existing = list.Find(item => item.Name == name); 92 | Assert.IsNotNull(existing); 93 | 94 | var sentProgressEvent = await tsc.Task; 95 | Assert.IsTrue(sentProgressEvent); 96 | 97 | await _bucket.Remove(new List { name }); 98 | } 99 | 100 | [TestMethod("File: Download")] 101 | public async Task DownloadFile() 102 | { 103 | var tsc = new TaskCompletionSource(); 104 | 105 | var asset = "supabase-csharp.png"; 106 | var name = $"{Guid.NewGuid()}.png"; 107 | var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)?.Replace("file:", ""); 108 | Assert.IsNotNull(basePath); 109 | 110 | var imagePath = Path.Combine(basePath, "Assets", asset); 111 | 112 | await _bucket.Upload(imagePath, name); 113 | 114 | var downloadPath = Path.Combine(basePath, name); 115 | await _bucket.Download(name, downloadPath, (_, _) => tsc.TrySetResult(true)); 116 | 117 | var sentProgressEvent = await tsc.Task; 118 | Assert.IsTrue(sentProgressEvent); 119 | 120 | Assert.IsTrue(File.Exists(downloadPath)); 121 | 122 | await _bucket.Remove(new List { name }); 123 | } 124 | 125 | [TestMethod("File: Download Bytes")] 126 | public async Task DownloadBytes() 127 | { 128 | var tsc = new TaskCompletionSource(); 129 | 130 | var data = new Byte[] { 0x0 }; 131 | var name = $"{Guid.NewGuid()}.bin"; 132 | 133 | await _bucket.Upload(data, name); 134 | 135 | var result = await _bucket.Download(name, (_, _) => tsc.TrySetResult(true)); 136 | 137 | var sentProgressEvent = await tsc.Task; 138 | 139 | Assert.IsTrue(sentProgressEvent); 140 | Assert.IsTrue(data.SequenceEqual(result)); 141 | 142 | await _bucket.Remove(new List { name }); 143 | } 144 | 145 | [TestMethod("File: Rename")] 146 | public async Task Move() 147 | { 148 | var name = $"{Guid.NewGuid()}.bin"; 149 | await _bucket.Upload(new Byte[] { 0x0, 0x1 }, name); 150 | await _bucket.Move(name, "new-file.bin"); 151 | var items = await _bucket.List(); 152 | 153 | Assert.IsNotNull(items); 154 | 155 | Assert.IsNotNull(items.Find((f) => f.Name == "new-file.bin")); 156 | Assert.IsNull(items.Find((f) => f.Name == name)); 157 | } 158 | 159 | [TestMethod("File: Copy")] 160 | public async Task Copy() 161 | { 162 | var name = $"{Guid.NewGuid()}.bin"; 163 | await _bucket.Upload([0x0, 0x1], name); 164 | await _bucket.Copy(name, "new-file.bin"); 165 | var items = await _bucket.List(); 166 | 167 | Assert.IsNotNull(items); 168 | 169 | Assert.IsNotNull(items.Find((f) => f.Name == "new-file.bin")); 170 | Assert.IsNotNull(items.Find((f) => f.Name == name)); 171 | } 172 | 173 | [TestMethod("File: Copy to another Bucket")] 174 | public async Task CopyToAnotherBucket() 175 | { 176 | await Storage.CreateBucket("copyfile", new BucketUpsertOptions { Public = true }); 177 | var localBucket = Storage.From("copyfile"); 178 | 179 | var name = $"{Guid.NewGuid()}.bin"; 180 | await _bucket.Upload([0x0, 0x1], name); 181 | 182 | await _bucket.Copy(name, "new-file.bin", new DestinationOptions { DestinationBucket = "copyfile" }); 183 | var items = await _bucket.List(); 184 | var copied = await localBucket.List(); 185 | 186 | Assert.IsNotNull(items); 187 | Assert.IsNotNull(copied); 188 | 189 | Assert.IsNotNull(copied.Find((f) => f.Name == "new-file.bin")); 190 | Assert.IsNotNull(items.Find((f) => f.Name == name)); 191 | 192 | foreach (var file in copied) 193 | { 194 | if (file.Name is not null) 195 | await localBucket.Remove(new List { file.Name }); 196 | } 197 | 198 | await Storage.DeleteBucket("copyfile"); 199 | } 200 | 201 | [TestMethod("File: Get Public Link")] 202 | public async Task GetPublicLink() 203 | { 204 | var name = $"{Guid.NewGuid()}.bin"; 205 | await _bucket.Upload(new Byte[] { 0x0, 0x1 }, name); 206 | var url = _bucket.GetPublicUrl(name); 207 | await _bucket.Remove(new List { name }); 208 | 209 | Assert.IsNotNull(url); 210 | } 211 | 212 | [TestMethod("File: Get Public Link with download options")] 213 | public async Task GetPublicLinkWithDownloadOptions() 214 | { 215 | var name = $"{Guid.NewGuid()}.bin"; 216 | await _bucket.Upload(new Byte[] { 0x0, 0x1 }, name); 217 | var url = _bucket.GetPublicUrl(name, null, new DownloadOptions { FileName = "custom-file.png"}); 218 | await _bucket.Remove(new List { name }); 219 | 220 | Assert.IsNotNull(url); 221 | StringAssert.Contains(url, "download=custom-file.png"); 222 | } 223 | 224 | [TestMethod("File: Get Public Link with download and transform options")] 225 | public async Task GetPublicLinkWithDownloadAndTransformOptions() 226 | { 227 | var name = $"{Guid.NewGuid()}.bin"; 228 | await _bucket.Upload(new Byte[] { 0x0, 0x1 }, name); 229 | var url = _bucket.GetPublicUrl(name, new TransformOptions { Height = 100, Width = 100}, DownloadOptions.UseOriginalFileName); 230 | await _bucket.Remove(new List { name }); 231 | 232 | Assert.IsNotNull(url); 233 | StringAssert.Contains(url, "download=true"); 234 | } 235 | 236 | [TestMethod("File: Get Signed Link")] 237 | public async Task GetSignedLink() 238 | { 239 | var name = $"{Guid.NewGuid()}.bin"; 240 | await _bucket.Upload(new Byte[] { 0x0, 0x1 }, name); 241 | 242 | var url = await _bucket.CreateSignedUrl(name, 3600); 243 | Assert.IsTrue(Uri.IsWellFormedUriString(url, UriKind.Absolute)); 244 | 245 | await _bucket.Remove(new List { name }); 246 | } 247 | 248 | [TestMethod("File: Get Signed Link with transform options")] 249 | public async Task GetSignedLinkWithTransformOptions() 250 | { 251 | var name = $"{Guid.NewGuid()}.bin"; 252 | await _bucket.Upload(new Byte[] { 0x0, 0x1 }, name); 253 | 254 | var url = await _bucket.CreateSignedUrl(name, 3600, new TransformOptions { Width = 100, Height = 100 }); 255 | Assert.IsTrue(Uri.IsWellFormedUriString(url, UriKind.Absolute)); 256 | 257 | await _bucket.Remove(new List { name }); 258 | } 259 | 260 | [TestMethod("File: Get Signed Link with download options")] 261 | public async Task GetSignedLinkWithDownloadOptions() 262 | { 263 | var name = $"{Guid.NewGuid()}.bin"; 264 | await _bucket.Upload(new Byte[] { 0x0, 0x1 }, name); 265 | 266 | var url = await _bucket.CreateSignedUrl(name, 3600, null, new DownloadOptions { FileName = "custom-file.png"}); 267 | Assert.IsTrue(Uri.IsWellFormedUriString(url, UriKind.Absolute)); 268 | StringAssert.Contains(url, "download=custom-file.png"); 269 | 270 | await _bucket.Remove(new List { name }); 271 | } 272 | 273 | [TestMethod("File: Get Multiple Signed Links")] 274 | public async Task GetMultipleSignedLinks() 275 | { 276 | var name1 = $"{Guid.NewGuid()}.bin"; 277 | await _bucket.Upload(new Byte[] { 0x0, 0x1 }, name1); 278 | 279 | var name2 = $"{Guid.NewGuid()}.bin"; 280 | await _bucket.Upload(new Byte[] { 0x0, 0x1 }, name2); 281 | 282 | var urls = await _bucket.CreateSignedUrls(new List { name1, name2 }, 3600, DownloadOptions.UseOriginalFileName); 283 | 284 | Assert.IsNotNull(urls); 285 | 286 | foreach (var response in urls) 287 | { 288 | Assert.IsTrue(Uri.IsWellFormedUriString($"{response.SignedUrl}", UriKind.Absolute)); 289 | StringAssert.Contains(response.SignedUrl, "download=true"); 290 | } 291 | 292 | await _bucket.Remove(new List { name1 }); 293 | } 294 | 295 | [TestMethod("File: Can Create Signed Upload Url")] 296 | public async Task CanCreateSignedUploadUrl() 297 | { 298 | var result = await _bucket.CreateUploadSignedUrl("test.png"); 299 | Assert.IsTrue(Uri.IsWellFormedUriString(result.SignedUrl.ToString(), UriKind.Absolute)); 300 | } 301 | } -------------------------------------------------------------------------------- /StorageTests/StorageTests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | net8.0 5 | false 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | runtime; build; native; contentfiles; analyzers; buildtransitive 15 | all 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | PreserveNewest 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /StorageTests/db/00-schema.sql: -------------------------------------------------------------------------------- 1 | -- Set up reatime 2 | create publication supabase_realtime for all tables; 3 | 4 | -- Supabase super admin 5 | create user supabase_admin; 6 | alter user supabase_admin with superuser createdb createrole replication bypassrls; 7 | 8 | 9 | -- Extension namespacing 10 | create schema extensions; 11 | create extension if not exists "uuid-ossp" with schema extensions; 12 | create extension if not exists pgcrypto with schema extensions; 13 | -- create extension if not exists pgjwt with schema extensions; 14 | 15 | -- Set up auth roles for the developer 16 | create role anon nologin noinherit; 17 | create role authenticated nologin noinherit; -- "logged in" user: web_user, app_user, etc 18 | create role service_role nologin noinherit bypassrls; -- allow developers to create JWT's that bypass their policies 19 | 20 | create user authenticator noinherit; 21 | grant anon to authenticator; 22 | grant authenticated to authenticator; 23 | grant service_role to authenticator; 24 | grant supabase_admin to authenticator; 25 | 26 | grant usage on schema public to postgres, anon, authenticated, service_role; 27 | alter default privileges in schema public grant all on tables to postgres, anon, authenticated, service_role; 28 | alter default privileges in schema public grant all on functions to postgres, anon, authenticated, service_role; 29 | alter default privileges in schema public grant all on sequences to postgres, anon, authenticated, service_role; 30 | 31 | -- Set up namespacing 32 | alter user supabase_admin SET search_path TO public, extensions; -- don't include the "auth" schema 33 | 34 | -- These are required so that the users receive grants whenever "supabase_admin" creates tables/function 35 | alter default privileges for user supabase_admin in schema public grant all 36 | on sequences to postgres, anon, authenticated, service_role; 37 | alter default privileges for user supabase_admin in schema public grant all 38 | on tables to postgres, anon, authenticated, service_role; 39 | alter default privileges for user supabase_admin in schema public grant all 40 | on functions to postgres, anon, authenticated, service_role; -------------------------------------------------------------------------------- /StorageTests/db/01-auth-schema.sql: -------------------------------------------------------------------------------- 1 |  2 | CREATE SCHEMA IF NOT EXISTS auth AUTHORIZATION supabase_admin; 3 | 4 | -- auth.users definition 5 | 6 | CREATE TABLE auth.users ( 7 | instance_id uuid NULL, 8 | id uuid NOT NULL UNIQUE, 9 | aud varchar(255) NULL, 10 | "role" varchar(255) NULL, 11 | email varchar(255) NULL UNIQUE, 12 | encrypted_password varchar(255) NULL, 13 | confirmed_at timestamptz NULL, 14 | invited_at timestamptz NULL, 15 | confirmation_token varchar(255) NULL, 16 | confirmation_sent_at timestamptz NULL, 17 | recovery_token varchar(255) NULL, 18 | recovery_sent_at timestamptz NULL, 19 | email_change_token varchar(255) NULL, 20 | email_change varchar(255) NULL, 21 | email_change_sent_at timestamptz NULL, 22 | last_sign_in_at timestamptz NULL, 23 | raw_app_meta_data jsonb NULL, 24 | raw_user_meta_data jsonb NULL, 25 | is_super_admin bool NULL, 26 | created_at timestamptz NULL, 27 | updated_at timestamptz NULL, 28 | CONSTRAINT users_pkey PRIMARY KEY (id) 29 | ); 30 | CREATE INDEX users_instance_id_email_idx ON auth.users USING btree (instance_id, email); 31 | CREATE INDEX users_instance_id_idx ON auth.users USING btree (instance_id); 32 | 33 | -- auth.refresh_tokens definition 34 | 35 | CREATE TABLE auth.refresh_tokens ( 36 | instance_id uuid NULL, 37 | id bigserial NOT NULL, 38 | "token" varchar(255) NULL, 39 | user_id varchar(255) NULL, 40 | revoked bool NULL, 41 | created_at timestamptz NULL, 42 | updated_at timestamptz NULL, 43 | CONSTRAINT refresh_tokens_pkey PRIMARY KEY (id) 44 | ); 45 | CREATE INDEX refresh_tokens_instance_id_idx ON auth.refresh_tokens USING btree (instance_id); 46 | CREATE INDEX refresh_tokens_instance_id_user_id_idx ON auth.refresh_tokens USING btree (instance_id, user_id); 47 | CREATE INDEX refresh_tokens_token_idx ON auth.refresh_tokens USING btree (token); 48 | 49 | -- auth.instances definition 50 | 51 | CREATE TABLE auth.instances ( 52 | id uuid NOT NULL, 53 | uuid uuid NULL, 54 | raw_base_config text NULL, 55 | created_at timestamptz NULL, 56 | updated_at timestamptz NULL, 57 | CONSTRAINT instances_pkey PRIMARY KEY (id) 58 | ); 59 | 60 | -- auth.audit_log_entries definition 61 | 62 | CREATE TABLE auth.audit_log_entries ( 63 | instance_id uuid NULL, 64 | id uuid NOT NULL, 65 | payload json NULL, 66 | created_at timestamptz NULL, 67 | CONSTRAINT audit_log_entries_pkey PRIMARY KEY (id) 68 | ); 69 | CREATE INDEX audit_logs_instance_id_idx ON auth.audit_log_entries USING btree (instance_id); 70 | 71 | -- auth.schema_migrations definition 72 | 73 | CREATE TABLE auth.schema_migrations ( 74 | "version" varchar(255) NOT NULL, 75 | CONSTRAINT schema_migrations_pkey PRIMARY KEY ("version") 76 | ); 77 | 78 | INSERT INTO auth.schema_migrations (version) 79 | VALUES ('20171026211738'), 80 | ('20171026211808'), 81 | ('20171026211834'), 82 | ('20180103212743'), 83 | ('20180108183307'), 84 | ('20180119214651'), 85 | ('20180125194653'); 86 | 87 | -- Gets the User ID from the request cookie 88 | create or replace function auth.uid() returns uuid as $$ 89 | select nullif(current_setting('request.jwt.claim.sub', true), '')::uuid; 90 | $$ language sql stable; 91 | 92 | -- Gets the User ID from the request cookie 93 | create or replace function auth.role() returns text as $$ 94 | select nullif(current_setting('request.jwt.claim.role', true), '')::text; 95 | $$ language sql stable; 96 | 97 | -- Supabase super admin 98 | CREATE USER supabase_auth_admin NOINHERIT CREATEROLE LOGIN NOREPLICATION; 99 | GRANT ALL PRIVILEGES ON SCHEMA auth TO supabase_auth_admin; 100 | GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA auth TO supabase_auth_admin; 101 | GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA auth TO supabase_auth_admin; 102 | ALTER USER supabase_auth_admin SET search_path = "auth"; 103 | -------------------------------------------------------------------------------- /StorageTests/db/02-storage-schema.sql: -------------------------------------------------------------------------------- 1 | CREATE SCHEMA IF NOT EXISTS storage AUTHORIZATION supabase_admin; 2 | 3 | grant usage on schema storage to postgres, anon, authenticated, service_role; 4 | alter default privileges in schema storage grant all on tables to postgres, anon, authenticated, service_role; 5 | alter default privileges in schema storage grant all on functions to postgres, anon, authenticated, service_role; 6 | alter default privileges in schema storage grant all on sequences to postgres, anon, authenticated, service_role; 7 | 8 | DROP TABLE IF EXISTS "storage"."buckets"; 9 | CREATE TABLE "storage"."buckets" ( 10 | "id" text not NULL, 11 | "name" text NOT NULL, 12 | "owner" uuid, 13 | "created_at" timestamptz DEFAULT now(), 14 | "updated_at" timestamptz DEFAULT now(), 15 | CONSTRAINT "buckets_owner_fkey" FOREIGN KEY ("owner") REFERENCES "auth"."users"("id"), 16 | PRIMARY KEY ("id") 17 | ); 18 | CREATE UNIQUE INDEX "bname" ON "storage"."buckets" USING BTREE ("name"); 19 | 20 | DROP TABLE IF EXISTS "storage"."objects"; 21 | CREATE TABLE "storage"."objects" ( 22 | "id" uuid NOT NULL DEFAULT extensions.uuid_generate_v4(), 23 | "bucket_id" text, 24 | "name" text, 25 | "owner" uuid, 26 | "created_at" timestamptz DEFAULT now(), 27 | "updated_at" timestamptz DEFAULT now(), 28 | "last_accessed_at" timestamptz DEFAULT now(), 29 | "metadata" jsonb, 30 | CONSTRAINT "objects_bucketId_fkey" FOREIGN KEY ("bucket_id") REFERENCES "storage"."buckets"("id"), 31 | CONSTRAINT "objects_owner_fkey" FOREIGN KEY ("owner") REFERENCES "auth"."users"("id"), 32 | PRIMARY KEY ("id") 33 | ); 34 | CREATE UNIQUE INDEX "bucketid_objname" ON "storage"."objects" USING BTREE ("bucket_id","name"); 35 | CREATE INDEX name_prefix_search ON storage.objects(name text_pattern_ops); 36 | 37 | ALTER TABLE storage.objects ENABLE ROW LEVEL SECURITY; 38 | 39 | CREATE OR REPLACE FUNCTION storage.foldername(name text) 40 | RETURNS text[] 41 | LANGUAGE plpgsql 42 | AS $function$ 43 | DECLARE 44 | _parts text[]; 45 | BEGIN 46 | select string_to_array(name, '/') into _parts; 47 | return _parts[1:array_length(_parts,1)-1]; 48 | END 49 | $function$; 50 | 51 | CREATE OR REPLACE FUNCTION storage.filename(name text) 52 | RETURNS text 53 | LANGUAGE plpgsql 54 | AS $function$ 55 | DECLARE 56 | _parts text[]; 57 | BEGIN 58 | select string_to_array(name, '/') into _parts; 59 | return _parts[array_length(_parts,1)]; 60 | END 61 | $function$; 62 | 63 | CREATE OR REPLACE FUNCTION storage.extension(name text) 64 | RETURNS text 65 | LANGUAGE plpgsql 66 | AS $function$ 67 | DECLARE 68 | _parts text[]; 69 | _filename text; 70 | BEGIN 71 | select string_to_array(name, '/') into _parts; 72 | select _parts[array_length(_parts,1)] into _filename; 73 | -- @todo return the last part instead of 2 74 | return split_part(_filename, '.', 2); 75 | END 76 | $function$; 77 | 78 | -- @todo can this query be optimised further? 79 | CREATE OR REPLACE FUNCTION storage.search(prefix text, bucketname text, limits int DEFAULT 100, levels int DEFAULT 1, offsets int DEFAULT 0) 80 | RETURNS TABLE ( 81 | name text, 82 | id uuid, 83 | updated_at TIMESTAMPTZ, 84 | created_at TIMESTAMPTZ, 85 | last_accessed_at TIMESTAMPTZ, 86 | metadata jsonb 87 | ) 88 | LANGUAGE plpgsql 89 | AS $function$ 90 | DECLARE 91 | _bucketId text; 92 | BEGIN 93 | select buckets."id" from buckets where buckets.name=bucketname limit 1 into _bucketId; 94 | return query 95 | with files_folders as ( 96 | select ((string_to_array(objects.name, '/'))[levels]) as folder 97 | from objects 98 | where objects.name ilike prefix || '%' 99 | and bucket_id = _bucketId 100 | GROUP by folder 101 | limit limits 102 | offset offsets 103 | ) 104 | select files_folders.folder as name, objects.id, objects.updated_at, objects.created_at, objects.last_accessed_at, objects.metadata from files_folders 105 | left join objects 106 | on prefix || files_folders.folder = objects.name 107 | where objects.id is null or objects.bucket_id=_bucketId; 108 | END 109 | $function$; 110 | 111 | -- Supabase super admin 112 | CREATE USER supabase_storage_admin NOINHERIT CREATEROLE LOGIN NOREPLICATION; 113 | GRANT ALL PRIVILEGES ON SCHEMA storage TO supabase_storage_admin; 114 | GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA storage TO supabase_storage_admin; 115 | GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA storage TO supabase_storage_admin; 116 | ALTER USER supabase_storage_admin SET search_path = "storage"; 117 | -------------------------------------------------------------------------------- /StorageTests/db/03-dummy-data.sql: -------------------------------------------------------------------------------- 1 | -- insert users 2 | INSERT INTO "auth"."users" ("instance_id", "id", "aud", "role", "email", "encrypted_password", "confirmed_at", "invited_at", "confirmation_token", "confirmation_sent_at", "recovery_token", "recovery_sent_at", "email_change_token", "email_change", "email_change_sent_at", "last_sign_in_at", "raw_app_meta_data", "raw_user_meta_data", "is_super_admin", "created_at", "updated_at") VALUES 3 | ('00000000-0000-0000-0000-000000000000', '317eadce-631a-4429-a0bb-f19a7a517b4a', 'authenticated', 'authenticated', 'inian+user2@supabase.io', '', NULL, '2021-02-17 04:41:13.408828+00', '541rn7rTZPGeGCYsp0a38g', '2021-02-17 04:41:13.408828+00', '', NULL, '', '', NULL, NULL, '{"provider": "email"}', 'null', 'f', '2021-02-17 04:41:13.406912+00', '2021-02-17 04:41:13.406919+00'), 4 | ('00000000-0000-0000-0000-000000000000', '4d56e902-f0a0-4662-8448-a4d9e643c142', 'authenticated', 'authenticated', 'inian+user1@supabase.io', '', NULL, '2021-02-17 04:40:58.570482+00', 'U1HvzExEO3l7JzP-4tTxJA', '2021-02-17 04:40:58.570482+00', '', NULL, '', '', NULL, NULL, '{"provider": "email"}', 'null', 'f', '2021-02-17 04:40:58.568637+00', '2021-02-17 04:40:58.568642+00'), 5 | ('00000000-0000-0000-0000-000000000000', 'd8c7bce9-cfeb-497b-bd61-e66ce2cbdaa2', 'authenticated', 'authenticated', 'inian+admin@supabase.io', '', NULL, '2021-02-17 04:40:42.901743+00', '3EG99GjT_e3NC4eGEBXOjw', '2021-02-17 04:40:42.901743+00', '', NULL, '', '', NULL, NULL, '{"provider": "email"}', 'null', 'f', '2021-02-17 04:40:42.890632+00', '2021-02-17 04:40:42.890637+00'); 6 | 7 | -- insert buckets 8 | INSERT INTO "storage"."buckets" ("id", "name", "owner", "created_at", "updated_at") VALUES 9 | ('bucket2', 'bucket2', '4d56e902-f0a0-4662-8448-a4d9e643c142', '2021-02-17 04:43:32.770206+00', '2021-02-17 04:43:32.770206+00'), 10 | ('bucket3', 'bucket3', '4d56e902-f0a0-4662-8448-a4d9e643c142', '2021-02-17 04:43:32.770206+00', '2021-02-17 04:43:32.770206+00'), 11 | ('bucket4', 'bucket4', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-25 09:23:01.58385+00', '2021-02-25 09:23:01.58385+00'), 12 | ('bucket5', 'bucket5', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-27 03:04:25.6386+00', '2021-02-27 03:04:25.6386+00'), 13 | ('public-bucket', 'public-bucket', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-27 03:04:25.6386+00', '2021-02-27 03:04:25.6386+00'); 14 | 15 | 16 | -- insert objects 17 | INSERT INTO "storage"."objects" ("id", "bucket_id", "name", "owner", "created_at", "updated_at", "last_accessed_at", "metadata") VALUES 18 | ('03e458f9-892f-4db2-8cb9-d3401a689e25', 'bucket2', 'public/sadcat-upload23.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-03-04 08:26:08.553748+00', '2021-03-04 08:26:08.553748+00', '2021-03-04 08:26:08.553748+00', '{"mimetype": "image/svg+xml", "size": 1234}'), 19 | ('070825af-a11d-44fe-9f1d-abdc76f686f2', 'bucket2', 'public/sadcat-upload.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-03-02 16:31:11.115996+00', '2021-03-02 16:31:11.115996+00', '2021-03-02 16:31:11.115996+00', '{"mimetype": "image/png", "size": 1234}'), 20 | ('0cac5609-11e1-4f21-b486-d0eeb60909f6', 'bucket2', 'curlimage.jpg', 'd8c7bce9-cfeb-497b-bd61-e66ce2cbdaa2', '2021-02-23 11:05:16.625075+00', '2021-02-23 11:05:16.625075+00', '2021-02-23 11:05:16.625075+00', '{"size": 1234}'), 21 | ('147c6795-94d5-4008-9d81-f7ba3b4f8a9f', 'bucket2', 'folder/only_uid.jpg', 'd8c7bce9-cfeb-497b-bd61-e66ce2cbdaa2', '2021-02-17 10:36:01.504227+00', '2021-02-17 11:03:03.049618+00', '2021-02-17 10:36:01.504227+00', '{"size": 1234}'), 22 | ('65a3aa9c-0ff2-4adc-85d0-eab673c27443', 'bucket2', 'authenticated/casestudy.png', 'd8c7bce9-cfeb-497b-bd61-e66ce2cbdaa2', '2021-02-17 10:42:19.366559+00', '2021-02-17 11:03:30.025116+00', '2021-02-17 10:42:19.366559+00', '{"size": 1234}'), 23 | ('10ABE273-D77A-4BDA-B410-6FC0CA3E6ADC', 'bucket2', 'authenticated/cat.jpg', 'd8c7bce9-cfeb-497b-bd61-e66ce2cbdaa2', '2021-02-17 10:42:19.366559+00', '2021-02-17 11:03:30.025116+00', '2021-02-17 10:42:19.366559+00', '{"size": 1234}'), 24 | ('1edccac7-0876-4e9f-89da-a08d2a5f654b', 'bucket2', 'authenticated/delete.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-03-02 16:31:11.115996+00', '2021-03-02 16:31:11.115996+00', '2021-03-02 16:31:11.115996+00', '{"mimetype": "image/png", "size": 1234}'), 25 | ('1a911f3c-8c1d-4661-93c1-8e065e4d757e', 'bucket2', 'authenticated/delete1.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-22 22:29:15.14732+00', '2021-02-22 22:29:15.14732+00', '2021-03-02 09:32:17.116+00', '{"mimetype": "image/png", "size": 1234}'), 26 | ('372d5d74-e24d-49dc-abe8-47d7eb226a2e', 'bucket2', 'authenticated/delete-multiple1.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-22 22:29:15.14732+00', '2021-02-22 22:29:15.14732+00', '2021-03-02 09:32:17.116+00', '{"mimetype": "image/png", "size": 1234}'), 27 | ('34811c1b-85e5-4eb6-a5e3-d607b2f6986e', 'bucket2', 'authenticated/delete-multiple2.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-22 22:29:15.14732+00', '2021-02-22 22:29:15.14732+00', '2021-03-02 09:32:17.116+00', '{"mimetype": "image/png", "size": 1234}'), 28 | ('45950ff2-d3a8-4add-8e49-bafc01198340', 'bucket2', 'authenticated/delete-multiple3.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-22 22:29:15.14732+00', '2021-02-22 22:29:15.14732+00', '2021-03-02 09:32:17.116+00', '{"mimetype": "image/png", "size": 1234}'), 29 | ('469b0216-5419-41f6-9a37-2abfd7fad29c', 'bucket2', 'authenticated/delete-multiple4.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-22 22:29:15.14732+00', '2021-02-22 22:29:15.14732+00', '2021-03-02 09:32:17.116+00', '{"mimetype": "image/png", "size": 1234}'), 30 | ('55930619-a668-4dbc-aea3-b93dfe101e7f', 'bucket2', 'authenticated/delete-multiple7.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-22 22:29:15.14732+00', '2021-02-22 22:29:15.14732+00', '2021-03-02 09:32:17.116+00', '{"mimetype": "image/png", "size": 1234}'), 31 | ('D1CE4E4F-03E2-473D-858B-301D7989B581', 'bucket2', 'authenticated/move-orig.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-22 22:29:15.14732+00', '2021-02-22 22:29:15.14732+00', '2021-03-02 09:32:17.116+00', '{"mimetype": "image/png", "size": 1234}'), 32 | ('222b3d1e-bc17-414c-b336-47894aa4d697', 'bucket2', 'authenticated/move-orig-2.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-22 22:29:15.14732+00', '2021-02-22 22:29:15.14732+00', '2021-03-02 09:32:17.116+00', '{"mimetype": "image/png", "size": 1234}'), 33 | ('8f7d643d-1e82-4d39-ae39-d9bd6b0cfe9c', 'bucket2', 'authenticated/move-orig-3.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-02-22 22:29:15.14732+00', '2021-02-22 22:29:15.14732+00', '2021-03-02 09:32:17.116+00', '{"mimetype": "image/png", "size": 1234}'), 34 | ('8377527d-3518-4dc8-8290-c6926470e795', 'bucket2', 'folder/subfolder/public-all-permissions.png', 'd8c7bce9-cfeb-497b-bd61-e66ce2cbdaa2', '2021-02-17 10:26:42.791214+00', '2021-02-17 11:03:30.025116+00', '2021-02-17 10:26:42.791214+00', '{"size": 1234}'), 35 | ('b39ae4ab-802b-4c42-9271-3f908c34363c', 'bucket2', 'private/sadcat-upload3.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-03-01 08:53:29.567975+00', '2021-03-01 08:53:29.567975+00', '2021-03-01 08:53:29.567975+00', '{"mimetype": "image/svg+xml", "size": 1234}'), 36 | ('8098E1AC-C744-4368-86DF-71B60CCDE221', 'bucket3', 'sadcat-upload3.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-03-01 08:53:29.567975+00', '2021-03-01 08:53:29.567975+00', '2021-03-01 08:53:29.567975+00', '{"mimetype": "image/svg+xml", "size": 1234}'), 37 | ('D3EB488E-94F4-46CD-86D3-242C13B95BAC', 'bucket3', 'sadcat-upload2.png', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-03-01 08:53:29.567975+00', '2021-03-01 08:53:29.567975+00', '2021-03-01 08:53:29.567975+00', '{"mimetype": "image/svg+xml", "size": 1234}'), 38 | ('746180e8-8029-4134-8a21-48ab35485d81', 'public-bucket', 'favicon.ico', '317eadce-631a-4429-a0bb-f19a7a517b4a', '2021-03-01 08:53:29.567975+00', '2021-03-01 08:53:29.567975+00', '2021-03-01 08:53:29.567975+00', '{"mimetype": "image/svg+xml", "size": 1234}'); 39 | ; 40 | 41 | -- add policies 42 | -- allows user to CRUD all buckets 43 | CREATE POLICY crud_buckets ON storage.buckets for all USING (auth.uid() = '317eadce-631a-4429-a0bb-f19a7a517b4a'); 44 | -- allow public CRUD acccess to the public folder in bucket2 45 | CREATE POLICY crud_public_folder ON storage.objects for all USING (bucket_id='bucket2' and (storage.foldername(name))[1] = 'public'); 46 | -- allow public CRUD acccess to a particular file in bucket2 47 | CREATE POLICY crud_public_file ON storage.objects for all USING (bucket_id='bucket2' and name = 'folder/subfolder/public-all-permissions.png'); 48 | -- allow public CRUD acccess to a folder in bucket2 to a user with a given id 49 | CREATE POLICY crud_uid_folder ON storage.objects for all USING (bucket_id='bucket2' and (storage.foldername(name))[1] = 'only_uid' and auth.uid() = 'd8c7bce9-cfeb-497b-bd61-e66ce2cbdaa2'); 50 | -- allow public CRUD acccess to a file in bucket2 to a user with a given id 51 | CREATE POLICY crud_uid_file ON storage.objects for all USING (bucket_id='bucket2' and name = 'folder/only_uid.jpg' and auth.uid() = 'd8c7bce9-cfeb-497b-bd61-e66ce2cbdaa2'); 52 | -- allow CRUD acccess to a folder in bucket2 to all authenticated users 53 | CREATE POLICY authenticated_folder ON storage.objects for all USING (bucket_id='bucket2' and (storage.foldername(name))[1] = 'authenticated' and auth.role() = 'authenticated'); 54 | -- allow CRUD access to a folder in bucket2 to its owners 55 | CREATE POLICY crud_owner_only ON storage.objects for all USING (bucket_id='bucket2' and (storage.foldername(name))[1] = 'only_owner' and owner = auth.uid()); 56 | -- allow CRUD access to bucket4 57 | CREATE POLICY open_all_update ON storage.objects for all WITH CHECK (bucket_id='bucket4'); -------------------------------------------------------------------------------- /Supabase.Storage.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio Version 17 3 | VisualStudioVersion = 17.8.34330.188 4 | MinimumVisualStudioVersion = 10.0.40219.1 5 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F94175FC-DE2B-4DBC-9C79-2A97B8489412}" 6 | ProjectSection(SolutionItems) = preProject 7 | .gitignore = .gitignore 8 | CHANGELOG.md = CHANGELOG.md 9 | docker-compose.yml = docker-compose.yml 10 | README.md = README.md 11 | EndProjectSection 12 | EndProject 13 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = ".github", ".github", "{43FFFE0C-91D2-43AB-913F-B3824702AE49}" 14 | EndProject 15 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "workflows", "workflows", "{5B805377-7615-441C-86B1-4BE203B0289B}" 16 | ProjectSection(SolutionItems) = preProject 17 | .github\workflows\build-and-test.yml = .github\workflows\build-and-test.yml 18 | .github\workflows\build-documentation.yaml = .github\workflows\build-documentation.yaml 19 | .github\workflows\release.yml = .github\workflows\release.yml 20 | EndProjectSection 21 | EndProject 22 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Storage", "Storage\Storage.csproj", "{4D1E857D-133C-4BF9-82C6-414416D69ACD}" 23 | EndProject 24 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "StorageTests", "StorageTests\StorageTests.csproj", "{B23C82F8-01DF-4982-A13B-7CC27A2F7CF5}" 25 | EndProject 26 | Global 27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 28 | Debug|Any CPU = Debug|Any CPU 29 | Release|Any CPU = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 32 | {4D1E857D-133C-4BF9-82C6-414416D69ACD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {4D1E857D-133C-4BF9-82C6-414416D69ACD}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {4D1E857D-133C-4BF9-82C6-414416D69ACD}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {4D1E857D-133C-4BF9-82C6-414416D69ACD}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {B23C82F8-01DF-4982-A13B-7CC27A2F7CF5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {B23C82F8-01DF-4982-A13B-7CC27A2F7CF5}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {B23C82F8-01DF-4982-A13B-7CC27A2F7CF5}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {B23C82F8-01DF-4982-A13B-7CC27A2F7CF5}.Release|Any CPU.Build.0 = Release|Any CPU 40 | EndGlobalSection 41 | GlobalSection(SolutionProperties) = preSolution 42 | HideSolutionNode = FALSE 43 | EndGlobalSection 44 | GlobalSection(NestedProjects) = preSolution 45 | {43FFFE0C-91D2-43AB-913F-B3824702AE49} = {F94175FC-DE2B-4DBC-9C79-2A97B8489412} 46 | {5B805377-7615-441C-86B1-4BE203B0289B} = {43FFFE0C-91D2-43AB-913F-B3824702AE49} 47 | EndGlobalSection 48 | GlobalSection(MonoDevelopProperties) = preSolution 49 | version = 1.0.2 50 | EndGlobalSection 51 | EndGlobal 52 | -------------------------------------------------------------------------------- /prepare-infra.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | git clone https://github.com/supabase/storage .storage-server 4 | cd .storage-server 5 | 6 | git fetch --all --tags 7 | git checkout tags/v1.0.10 -b v1.0.10-branch 8 | 9 | cp .env.sample .env && cp .env.test.sample .env.test 10 | 11 | npm install 12 | npm run infra:restart 13 | npm run build 14 | 15 | cmd="npm run start"; 16 | eval "${cmd}" &>/dev/null & disown; -------------------------------------------------------------------------------- /release-please-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "packages": { 3 | ".": { 4 | "changelog-path": "CHANGELOG.md", 5 | "bump-minor-pre-major": false, 6 | "bump-patch-for-minor-pre-major": false, 7 | "draft": false, 8 | "prerelease": false, 9 | "release-type": "simple", 10 | "extra-files": [ 11 | "Storage/Storage.csproj" 12 | ] 13 | } 14 | }, 15 | "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json" 16 | } -------------------------------------------------------------------------------- /supabase/.gitignore: -------------------------------------------------------------------------------- 1 | # Supabase 2 | .branches 3 | .temp 4 | 5 | # dotenvx 6 | .env.keys 7 | .env.local 8 | .env.*.local 9 | -------------------------------------------------------------------------------- /supabase/config.toml: -------------------------------------------------------------------------------- 1 | # For detailed configuration reference documentation, visit: 2 | # https://supabase.com/docs/guides/local-development/cli/config 3 | # A string used to distinguish different Supabase projects on the same host. Defaults to the 4 | # working directory name when running `supabase init`. 5 | project_id = "storage-csharp" 6 | 7 | [api] 8 | enabled = true 9 | # Port to use for the API URL. 10 | port = 54321 11 | # Schemas to expose in your API. Tables, views and stored procedures in this schema will get API 12 | # endpoints. `public` and `graphql_public` schemas are included by default. 13 | schemas = ["public", "graphql_public"] 14 | # Extra schemas to add to the search_path of every request. 15 | extra_search_path = ["public", "extensions"] 16 | # The maximum number of rows returns from a view, table, or stored procedure. Limits payload size 17 | # for accidental or malicious requests. 18 | max_rows = 1000 19 | 20 | [api.tls] 21 | # Enable HTTPS endpoints locally using a self-signed certificate. 22 | enabled = false 23 | 24 | [db] 25 | # Port to use for the local database URL. 26 | port = 54322 27 | # Port used by db diff command to initialize the shadow database. 28 | shadow_port = 54320 29 | # The database major version to use. This has to be the same as your remote database's. Run `SHOW 30 | # server_version;` on the remote database to check. 31 | major_version = 15 32 | 33 | [db.pooler] 34 | enabled = false 35 | # Port to use for the local connection pooler. 36 | port = 54329 37 | # Specifies when a server connection can be reused by other clients. 38 | # Configure one of the supported pooler modes: `transaction`, `session`. 39 | pool_mode = "transaction" 40 | # How many server connections to allow per user/database pair. 41 | default_pool_size = 20 42 | # Maximum number of client connections allowed. 43 | max_client_conn = 100 44 | 45 | # [db.vault] 46 | # secret_key = "env(SECRET_VALUE)" 47 | 48 | [db.migrations] 49 | # Specifies an ordered list of schema files that describe your database. 50 | # Supports glob patterns relative to supabase directory: "./schemas/*.sql" 51 | schema_paths = [] 52 | 53 | [db.seed] 54 | # If enabled, seeds the database after migrations during a db reset. 55 | enabled = true 56 | # Specifies an ordered list of seed files to load during db reset. 57 | # Supports glob patterns relative to supabase directory: "./seeds/*.sql" 58 | sql_paths = ["./seed.sql"] 59 | 60 | [realtime] 61 | enabled = true 62 | # Bind realtime via either IPv4 or IPv6. (default: IPv4) 63 | # ip_version = "IPv6" 64 | # The maximum length in bytes of HTTP request headers. (default: 4096) 65 | # max_header_length = 4096 66 | 67 | [studio] 68 | enabled = true 69 | # Port to use for Supabase Studio. 70 | port = 54323 71 | # External URL of the API server that frontend connects to. 72 | api_url = "http://127.0.0.1" 73 | # OpenAI API Key to use for Supabase AI in the Supabase Studio. 74 | openai_api_key = "env(OPENAI_API_KEY)" 75 | 76 | # Email testing server. Emails sent with the local dev setup are not actually sent - rather, they 77 | # are monitored, and you can view the emails that would have been sent from the web interface. 78 | [inbucket] 79 | enabled = true 80 | # Port to use for the email testing server web interface. 81 | port = 54324 82 | # Uncomment to expose additional ports for testing user applications that send emails. 83 | # smtp_port = 54325 84 | # pop3_port = 54326 85 | # admin_email = "admin@email.com" 86 | # sender_name = "Admin" 87 | 88 | [storage] 89 | enabled = true 90 | # The maximum file size allowed (e.g. "5MB", "500KB"). 91 | file_size_limit = "50MiB" 92 | 93 | # Image transformation API is available to Supabase Pro plan. 94 | # [storage.image_transformation] 95 | # enabled = true 96 | 97 | # Uncomment to configure local storage buckets 98 | # [storage.buckets.images] 99 | # public = false 100 | # file_size_limit = "50MiB" 101 | # allowed_mime_types = ["image/png", "image/jpeg"] 102 | # objects_path = "./images" 103 | 104 | [auth] 105 | enabled = true 106 | # The base URL of your website. Used as an allow-list for redirects and for constructing URLs used 107 | # in emails. 108 | site_url = "http://127.0.0.1:3000" 109 | # A list of *exact* URLs that auth providers are permitted to redirect to post authentication. 110 | additional_redirect_urls = ["https://127.0.0.1:3000"] 111 | # How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week). 112 | jwt_expiry = 3600 113 | # If disabled, the refresh token will never expire. 114 | enable_refresh_token_rotation = true 115 | # Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. 116 | # Requires enable_refresh_token_rotation = true. 117 | refresh_token_reuse_interval = 10 118 | # Allow/disallow new user signups to your project. 119 | enable_signup = true 120 | # Allow/disallow anonymous sign-ins to your project. 121 | enable_anonymous_sign_ins = false 122 | # Allow/disallow testing manual linking of accounts 123 | enable_manual_linking = false 124 | # Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more. 125 | minimum_password_length = 6 126 | # Passwords that do not meet the following requirements will be rejected as weak. Supported values 127 | # are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols` 128 | password_requirements = "" 129 | 130 | [auth.rate_limit] 131 | # Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled. 132 | email_sent = 2 133 | # Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled. 134 | sms_sent = 30 135 | # Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true. 136 | anonymous_users = 30 137 | # Number of sessions that can be refreshed in a 5 minute interval per IP address. 138 | token_refresh = 150 139 | # Number of sign up and sign-in requests that can be made in a 5 minute interval per IP address (excludes anonymous users). 140 | sign_in_sign_ups = 30 141 | # Number of OTP / Magic link verifications that can be made in a 5 minute interval per IP address. 142 | token_verifications = 30 143 | 144 | # Configure one of the supported captcha providers: `hcaptcha`, `turnstile`. 145 | # [auth.captcha] 146 | # enabled = true 147 | # provider = "hcaptcha" 148 | # secret = "" 149 | 150 | [auth.email] 151 | # Allow/disallow new user signups via email to your project. 152 | enable_signup = true 153 | # If enabled, a user will be required to confirm any email change on both the old, and new email 154 | # addresses. If disabled, only the new email is required to confirm. 155 | double_confirm_changes = true 156 | # If enabled, users need to confirm their email address before signing in. 157 | enable_confirmations = false 158 | # If enabled, users will need to reauthenticate or have logged in recently to change their password. 159 | secure_password_change = false 160 | # Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email. 161 | max_frequency = "1s" 162 | # Number of characters used in the email OTP. 163 | otp_length = 6 164 | # Number of seconds before the email OTP expires (defaults to 1 hour). 165 | otp_expiry = 3600 166 | 167 | # Use a production-ready SMTP server 168 | # [auth.email.smtp] 169 | # enabled = true 170 | # host = "smtp.sendgrid.net" 171 | # port = 587 172 | # user = "apikey" 173 | # pass = "env(SENDGRID_API_KEY)" 174 | # admin_email = "admin@email.com" 175 | # sender_name = "Admin" 176 | 177 | # Uncomment to customize email template 178 | # [auth.email.template.invite] 179 | # subject = "You have been invited" 180 | # content_path = "./supabase/templates/invite.html" 181 | 182 | [auth.sms] 183 | # Allow/disallow new user signups via SMS to your project. 184 | enable_signup = false 185 | # If enabled, users need to confirm their phone number before signing in. 186 | enable_confirmations = false 187 | # Template for sending OTP to users 188 | template = "Your code is {{ .Code }}" 189 | # Controls the minimum amount of time that must pass before sending another sms otp. 190 | max_frequency = "5s" 191 | 192 | # Use pre-defined map of phone number to OTP for testing. 193 | # [auth.sms.test_otp] 194 | # 4152127777 = "123456" 195 | 196 | # Configure logged in session timeouts. 197 | # [auth.sessions] 198 | # Force log out after the specified duration. 199 | # timebox = "24h" 200 | # Force log out if the user has been inactive longer than the specified duration. 201 | # inactivity_timeout = "8h" 202 | 203 | # This hook runs before a token is issued and allows you to add additional claims based on the authentication method used. 204 | # [auth.hook.custom_access_token] 205 | # enabled = true 206 | # uri = "pg-functions:////" 207 | 208 | # Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`. 209 | [auth.sms.twilio] 210 | enabled = false 211 | account_sid = "" 212 | message_service_sid = "" 213 | # DO NOT commit your Twilio auth token to git. Use environment variable substitution instead: 214 | auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)" 215 | 216 | # Multi-factor-authentication is available to Supabase Pro plan. 217 | [auth.mfa] 218 | # Control how many MFA factors can be enrolled at once per user. 219 | max_enrolled_factors = 10 220 | 221 | # Control MFA via App Authenticator (TOTP) 222 | [auth.mfa.totp] 223 | enroll_enabled = false 224 | verify_enabled = false 225 | 226 | # Configure MFA via Phone Messaging 227 | [auth.mfa.phone] 228 | enroll_enabled = false 229 | verify_enabled = false 230 | otp_length = 6 231 | template = "Your code is {{ .Code }}" 232 | max_frequency = "5s" 233 | 234 | # Configure MFA via WebAuthn 235 | # [auth.mfa.web_authn] 236 | # enroll_enabled = true 237 | # verify_enabled = true 238 | 239 | # Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`, 240 | # `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`, 241 | # `twitter`, `slack`, `spotify`, `workos`, `zoom`. 242 | [auth.external.apple] 243 | enabled = false 244 | client_id = "" 245 | # DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead: 246 | secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)" 247 | # Overrides the default auth redirectUrl. 248 | redirect_uri = "" 249 | # Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure, 250 | # or any other third-party OIDC providers. 251 | url = "" 252 | # If enabled, the nonce check will be skipped. Required for local sign in with Google auth. 253 | skip_nonce_check = false 254 | 255 | # Use Firebase Auth as a third-party provider alongside Supabase Auth. 256 | [auth.third_party.firebase] 257 | enabled = false 258 | # project_id = "my-firebase-project" 259 | 260 | # Use Auth0 as a third-party provider alongside Supabase Auth. 261 | [auth.third_party.auth0] 262 | enabled = false 263 | # tenant = "my-auth0-tenant" 264 | # tenant_region = "us" 265 | 266 | # Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth. 267 | [auth.third_party.aws_cognito] 268 | enabled = false 269 | # user_pool_id = "my-user-pool-id" 270 | # user_pool_region = "us-east-1" 271 | 272 | # Use Clerk as a third-party provider alongside Supabase Auth. 273 | [auth.third_party.clerk] 274 | enabled = false 275 | # Obtain from https://clerk.com/setup/supabase 276 | # domain = "example.clerk.accounts.dev" 277 | 278 | [edge_runtime] 279 | enabled = true 280 | # Configure one of the supported request policies: `oneshot`, `per_worker`. 281 | # Use `oneshot` for hot reload, or `per_worker` for load testing. 282 | policy = "oneshot" 283 | # Port to attach the Chrome inspector for debugging edge functions. 284 | inspector_port = 8083 285 | # The Deno major version to use. 286 | deno_version = 1 287 | 288 | # [edge_runtime.secrets] 289 | # secret_key = "env(SECRET_VALUE)" 290 | 291 | [analytics] 292 | enabled = true 293 | port = 54327 294 | # Configure one of the supported backends: `postgres`, `bigquery`. 295 | backend = "postgres" 296 | 297 | # Experimental features may be deprecated any time 298 | [experimental] 299 | # Configures Postgres storage engine to use OrioleDB (S3) 300 | orioledb_version = "" 301 | # Configures S3 bucket URL, eg. .s3-.amazonaws.com 302 | s3_host = "env(S3_HOST)" 303 | # Configures S3 bucket region, eg. us-east-1 304 | s3_region = "env(S3_REGION)" 305 | # Configures AWS_ACCESS_KEY_ID for S3 bucket 306 | s3_access_key = "env(S3_ACCESS_KEY)" 307 | # Configures AWS_SECRET_ACCESS_KEY for S3 bucket 308 | s3_secret_key = "env(S3_SECRET_KEY)" 309 | --------------------------------------------------------------------------------