From c39cf08475017cf02a363e43ac65f571c5671286 Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Tue, 20 May 2025 22:47:13 -0300 Subject: [PATCH 01/10] feat: implement partially method copy --- Storage/DestinationOptions.cs | 12 + Storage/Exceptions/FailureHint.cs | 2 + Storage/Interfaces/IStorageFileApi.cs | 3 +- Storage/StorageFileApi.cs | 35 ++- StorageTests/Helpers.cs | 6 +- StorageTests/StorageFileAnonTests.cs | 14 +- StorageTests/StorageFileTests.cs | 14 ++ supabase/.gitignore | 8 + supabase/config.toml | 308 ++++++++++++++++++++++++++ 9 files changed, 391 insertions(+), 11 deletions(-) create mode 100644 Storage/DestinationOptions.cs create mode 100644 supabase/.gitignore create mode 100644 supabase/config.toml diff --git a/Storage/DestinationOptions.cs b/Storage/DestinationOptions.cs new file mode 100644 index 0000000..0f749c5 --- /dev/null +++ b/Storage/DestinationOptions.cs @@ -0,0 +1,12 @@ +namespace Supabase.Storage; + +/// +/// Represents the options for a destination in the context of Supabase Storage. +/// +public class DestinationOptions +{ + /// + /// Gets or sets the name of the destination bucket in the context of Supabase Storage. + /// + public string? DestinationBucket { get; set; } +} \ No newline at end of file diff --git a/Storage/Exceptions/FailureHint.cs b/Storage/Exceptions/FailureHint.cs index c98f680..88bf91b 100644 --- a/Storage/Exceptions/FailureHint.cs +++ b/Storage/Exceptions/FailureHint.cs @@ -27,6 +27,8 @@ 400 when storageException.Content.ToLower().Contains("malformed") => NotAuthoriz 400 when storageException.Content.ToLower().Contains("invalid signature") => NotAuthorized, 400 when storageException.Content.ToLower().Contains("invalid") => InvalidInput, 401 => NotAuthorized, + 403 when storageException.Content.ToLower().Contains("invalid compact jws") => NotAuthorized, + 403 when storageException.Content.ToLower().Contains("signature verification failed") => NotAuthorized, 404 when storageException.Content.ToLower().Contains("not found") => NotFound, 409 when storageException.Content.ToLower().Contains("exists") => AlreadyExists, 500 => Internal, diff --git a/Storage/Interfaces/IStorageFileApi.cs b/Storage/Interfaces/IStorageFileApi.cs index 03e94cc..3aaaecc 100644 --- a/Storage/Interfaces/IStorageFileApi.cs +++ b/Storage/Interfaces/IStorageFileApi.cs @@ -18,7 +18,8 @@ public interface IStorageFileApi Task DownloadPublicFile(string supabasePath, string localPath, TransformOptions? transformOptions = null, EventHandler? onProgress = null); string GetPublicUrl(string path, TransformOptions? transformOptions = null); Task?> List(string path = "", SearchOptions? options = null); - Task Move(string fromPath, string toPath); + Task Move(string fromPath, string toPath, DestinationOptions? options = null); + Task Copy(string fromPath, string toPath, DestinationOptions? options = null); Task Remove(string path); Task?> Remove(List paths); Task Update(byte[] data, string supabasePath, FileOptions? options = null, EventHandler? onProgress = null); diff --git a/Storage/StorageFileApi.cs b/Storage/StorageFileApi.cs index 0f2aa0a..f14320f 100644 --- a/Storage/StorageFileApi.cs +++ b/Storage/StorageFileApi.cs @@ -281,23 +281,46 @@ public Task Update(byte[] data, string supabasePath, FileOptions? option } /// - /// Moves an existing file, optionally renaming it at the same time. + /// Moves an existing file to a new location, optionally allowing renaming. /// - /// The original file path, including the current file name. For example `folder/image.png`. - /// The new file path, including the new file name. For example `folder/image-copy.png`. - /// - public async Task Move(string fromPath, string toPath) + /// The original file path, including the current file name (e.g., `folder/image.png`). + /// The target file path, including the new file name (e.g., `folder/image-copy.png`). + /// Optional parameters for specifying the destination bucket and other settings. + /// Returns a boolean value indicating whether the operation was successful. + public async Task Move(string fromPath, string toPath, DestinationOptions? options = null) { var body = new Dictionary { { "bucketId", BucketId }, { "sourceKey", fromPath }, - { "destinationKey", toPath } + { "destinationKey", toPath }, + { "destinationBucket", options?.DestinationBucket } }; await Helpers.MakeRequest(HttpMethod.Post, $"{Url}/object/move", body, Headers); return true; } + /// + /// Copies a file/object from one path to another within a bucket or across buckets. + /// + /// The source path of the file/object to copy. + /// The destination path for the copied file/object. + /// Optional parameters such as the destination bucket. + /// True if the copy operation was successful. + public async Task Copy(string fromPath, string toPath, DestinationOptions? options = null) + { + var body = new Dictionary + { + { "bucketId", BucketId }, + { "sourceKey", fromPath }, + { "destinationKey", toPath }, + { "destinationBucket", options?.DestinationBucket } + }; + + await Helpers.MakeRequest(HttpMethod.Post, $"{Url}/object/copy", body, Headers); + return true; + } + /// /// Downloads a file from a private bucket. For public buckets, use /// diff --git a/StorageTests/Helpers.cs b/StorageTests/Helpers.cs index 34d5a32..7b930ef 100644 --- a/StorageTests/Helpers.cs +++ b/StorageTests/Helpers.cs @@ -5,9 +5,9 @@ namespace StorageTests { public static class Helpers { - public static string SupabaseUrl => "http://localhost:5000"; - public static string ServiceKey => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaWF0IjoxNjEzNTMxOTg1LCJleHAiOjE5MjkxMDc5ODV9.th84OKK0Iz8QchDyXZRrojmKSEZ-OuitQm_5DvLiSIc"; - public static string PublicKey => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJhdXRoZW50aWNhdGVkIiwic3ViIjoiMzE3ZWFkY2UtNjMxYS00NDI5LWEwYmItZjE5YTdhNTE3YjRhIiwiZW1haWwiOiJpbmlhbit0ZXN0MUBzdXBhYmFzZS5pbyIsImV4cCI6MTkzOTEwNzk4NSwiYXBwX21ldGFkYXRhIjp7InByb3ZpZGVyIjoiZW1haWwifSwidXNlcl9tZXRhZGF0YSI6e30sInJvbGUiOiJhdXRoZW50aWNhdGVkIn0.E-x3oYcHIjFCdUO1M3wKDl1Ln32mik0xdHT2PjrvN70"; + public static string SupabaseUrl => "http://127.0.0.1:54321/storage/v1"; + public static string PublicKey => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6ImFub24iLCJleHAiOjE5ODM4MTI5OTZ9.CRXP1A7WOeoJeXxjNni43kdQwgnWNReilDMblYTn_I0"; + public static string ServiceKey => "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZS1kZW1vIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImV4cCI6MTk4MzgxMjk5Nn0.EGIM96RAZx35lJzdJsyH-qQwv8Hdp7fsn3W0YpN81IU"; public static string StorageUrl => $"{SupabaseUrl}"; diff --git a/StorageTests/StorageFileAnonTests.cs b/StorageTests/StorageFileAnonTests.cs index 09c66b3..1943788 100644 --- a/StorageTests/StorageFileAnonTests.cs +++ b/StorageTests/StorageFileAnonTests.cs @@ -28,7 +28,7 @@ public async Task InitializeTest() if (_bucket == null && await Storage.GetBucket(_bucketId) == null) { - await AdminStorage.CreateBucket(_bucketId, new BucketUpsertOptions { Public = true }); + await AdminStorage.CreateBucket(_bucketId, new BucketUpsertOptions { Public = false }); } _adminBucket = AdminStorage.From(_bucketId); @@ -131,6 +131,18 @@ await Assert.ThrowsExceptionAsync(async () => }); } + [TestMethod("File: Throws attempting to Copy")] + public async Task Copy() + { + var name = $"{Guid.NewGuid()}.bin"; + await _adminBucket.Upload(new Byte[] { 0x0, 0x1 }, name); + + await Assert.ThrowsExceptionAsync(async () => + { + await _bucket.Copy(name, "new-file.bin"); + }); + } + [TestMethod("File: Get Public Link")] public async Task GetPublicLink() { diff --git a/StorageTests/StorageFileTests.cs b/StorageTests/StorageFileTests.cs index a5b0299..1be5d59 100644 --- a/StorageTests/StorageFileTests.cs +++ b/StorageTests/StorageFileTests.cs @@ -155,6 +155,20 @@ public async Task Move() Assert.IsNotNull(items.Find((f) => f.Name == "new-file.bin")); Assert.IsNull(items.Find((f) => f.Name == name)); } + + [TestMethod("File: Copy")] + public async Task Copy() + { + var name = $"{Guid.NewGuid()}.bin"; + await _bucket.Upload([0x0, 0x1], name); + await _bucket.Copy(name, "new-file.bin"); + var items = await _bucket.List(); + + Assert.IsNotNull(items); + + Assert.IsNotNull(items.Find((f) => f.Name == "new-file.bin")); + Assert.IsNotNull(items.Find((f) => f.Name == name)); + } [TestMethod("File: Get Public Link")] public async Task GetPublicLink() diff --git a/supabase/.gitignore b/supabase/.gitignore new file mode 100644 index 0000000..ad9264f --- /dev/null +++ b/supabase/.gitignore @@ -0,0 +1,8 @@ +# Supabase +.branches +.temp + +# dotenvx +.env.keys +.env.local +.env.*.local diff --git a/supabase/config.toml b/supabase/config.toml new file mode 100644 index 0000000..664c787 --- /dev/null +++ b/supabase/config.toml @@ -0,0 +1,308 @@ +# For detailed configuration reference documentation, visit: +# https://supabase.com/docs/guides/local-development/cli/config +# A string used to distinguish different Supabase projects on the same host. Defaults to the +# working directory name when running `supabase init`. +project_id = "storage-csharp" + +[api] +enabled = true +# Port to use for the API URL. +port = 54321 +# Schemas to expose in your API. Tables, views and stored procedures in this schema will get API +# endpoints. `public` and `graphql_public` schemas are included by default. +schemas = ["public", "graphql_public"] +# Extra schemas to add to the search_path of every request. +extra_search_path = ["public", "extensions"] +# The maximum number of rows returns from a view, table, or stored procedure. Limits payload size +# for accidental or malicious requests. +max_rows = 1000 + +[api.tls] +# Enable HTTPS endpoints locally using a self-signed certificate. +enabled = false + +[db] +# Port to use for the local database URL. +port = 54322 +# Port used by db diff command to initialize the shadow database. +shadow_port = 54320 +# The database major version to use. This has to be the same as your remote database's. Run `SHOW +# server_version;` on the remote database to check. +major_version = 15 + +[db.pooler] +enabled = false +# Port to use for the local connection pooler. +port = 54329 +# Specifies when a server connection can be reused by other clients. +# Configure one of the supported pooler modes: `transaction`, `session`. +pool_mode = "transaction" +# How many server connections to allow per user/database pair. +default_pool_size = 20 +# Maximum number of client connections allowed. +max_client_conn = 100 + +# [db.vault] +# secret_key = "env(SECRET_VALUE)" + +[db.migrations] +# Specifies an ordered list of schema files that describe your database. +# Supports glob patterns relative to supabase directory: "./schemas/*.sql" +schema_paths = [] + +[db.seed] +# If enabled, seeds the database after migrations during a db reset. +enabled = true +# Specifies an ordered list of seed files to load during db reset. +# Supports glob patterns relative to supabase directory: "./seeds/*.sql" +sql_paths = ["./seed.sql"] + +[realtime] +enabled = true +# Bind realtime via either IPv4 or IPv6. (default: IPv4) +# ip_version = "IPv6" +# The maximum length in bytes of HTTP request headers. (default: 4096) +# max_header_length = 4096 + +[studio] +enabled = true +# Port to use for Supabase Studio. +port = 54323 +# External URL of the API server that frontend connects to. +api_url = "http://127.0.0.1" +# OpenAI API Key to use for Supabase AI in the Supabase Studio. +openai_api_key = "env(OPENAI_API_KEY)" + +# Email testing server. Emails sent with the local dev setup are not actually sent - rather, they +# are monitored, and you can view the emails that would have been sent from the web interface. +[inbucket] +enabled = true +# Port to use for the email testing server web interface. +port = 54324 +# Uncomment to expose additional ports for testing user applications that send emails. +# smtp_port = 54325 +# pop3_port = 54326 +# admin_email = "admin@email.com" +# sender_name = "Admin" + +[storage] +enabled = true +# The maximum file size allowed (e.g. "5MB", "500KB"). +file_size_limit = "50MiB" + +# Image transformation API is available to Supabase Pro plan. +# [storage.image_transformation] +# enabled = true + +# Uncomment to configure local storage buckets +# [storage.buckets.images] +# public = false +# file_size_limit = "50MiB" +# allowed_mime_types = ["image/png", "image/jpeg"] +# objects_path = "./images" + +[auth] +enabled = true +# The base URL of your website. Used as an allow-list for redirects and for constructing URLs used +# in emails. +site_url = "http://127.0.0.1:3000" +# A list of *exact* URLs that auth providers are permitted to redirect to post authentication. +additional_redirect_urls = ["https://127.0.0.1:3000"] +# How long tokens are valid for, in seconds. Defaults to 3600 (1 hour), maximum 604,800 (1 week). +jwt_expiry = 3600 +# If disabled, the refresh token will never expire. +enable_refresh_token_rotation = true +# Allows refresh tokens to be reused after expiry, up to the specified interval in seconds. +# Requires enable_refresh_token_rotation = true. +refresh_token_reuse_interval = 10 +# Allow/disallow new user signups to your project. +enable_signup = true +# Allow/disallow anonymous sign-ins to your project. +enable_anonymous_sign_ins = false +# Allow/disallow testing manual linking of accounts +enable_manual_linking = false +# Passwords shorter than this value will be rejected as weak. Minimum 6, recommended 8 or more. +minimum_password_length = 6 +# Passwords that do not meet the following requirements will be rejected as weak. Supported values +# are: `letters_digits`, `lower_upper_letters_digits`, `lower_upper_letters_digits_symbols` +password_requirements = "" + +[auth.rate_limit] +# Number of emails that can be sent per hour. Requires auth.email.smtp to be enabled. +email_sent = 2 +# Number of SMS messages that can be sent per hour. Requires auth.sms to be enabled. +sms_sent = 30 +# Number of anonymous sign-ins that can be made per hour per IP address. Requires enable_anonymous_sign_ins = true. +anonymous_users = 30 +# Number of sessions that can be refreshed in a 5 minute interval per IP address. +token_refresh = 150 +# Number of sign up and sign-in requests that can be made in a 5 minute interval per IP address (excludes anonymous users). +sign_in_sign_ups = 30 +# Number of OTP / Magic link verifications that can be made in a 5 minute interval per IP address. +token_verifications = 30 + +# Configure one of the supported captcha providers: `hcaptcha`, `turnstile`. +# [auth.captcha] +# enabled = true +# provider = "hcaptcha" +# secret = "" + +[auth.email] +# Allow/disallow new user signups via email to your project. +enable_signup = true +# If enabled, a user will be required to confirm any email change on both the old, and new email +# addresses. If disabled, only the new email is required to confirm. +double_confirm_changes = true +# If enabled, users need to confirm their email address before signing in. +enable_confirmations = false +# If enabled, users will need to reauthenticate or have logged in recently to change their password. +secure_password_change = false +# Controls the minimum amount of time that must pass before sending another signup confirmation or password reset email. +max_frequency = "1s" +# Number of characters used in the email OTP. +otp_length = 6 +# Number of seconds before the email OTP expires (defaults to 1 hour). +otp_expiry = 3600 + +# Use a production-ready SMTP server +# [auth.email.smtp] +# enabled = true +# host = "smtp.sendgrid.net" +# port = 587 +# user = "apikey" +# pass = "env(SENDGRID_API_KEY)" +# admin_email = "admin@email.com" +# sender_name = "Admin" + +# Uncomment to customize email template +# [auth.email.template.invite] +# subject = "You have been invited" +# content_path = "./supabase/templates/invite.html" + +[auth.sms] +# Allow/disallow new user signups via SMS to your project. +enable_signup = false +# If enabled, users need to confirm their phone number before signing in. +enable_confirmations = false +# Template for sending OTP to users +template = "Your code is {{ .Code }}" +# Controls the minimum amount of time that must pass before sending another sms otp. +max_frequency = "5s" + +# Use pre-defined map of phone number to OTP for testing. +# [auth.sms.test_otp] +# 4152127777 = "123456" + +# Configure logged in session timeouts. +# [auth.sessions] +# Force log out after the specified duration. +# timebox = "24h" +# Force log out if the user has been inactive longer than the specified duration. +# inactivity_timeout = "8h" + +# This hook runs before a token is issued and allows you to add additional claims based on the authentication method used. +# [auth.hook.custom_access_token] +# enabled = true +# uri = "pg-functions:////" + +# Configure one of the supported SMS providers: `twilio`, `twilio_verify`, `messagebird`, `textlocal`, `vonage`. +[auth.sms.twilio] +enabled = false +account_sid = "" +message_service_sid = "" +# DO NOT commit your Twilio auth token to git. Use environment variable substitution instead: +auth_token = "env(SUPABASE_AUTH_SMS_TWILIO_AUTH_TOKEN)" + +# Multi-factor-authentication is available to Supabase Pro plan. +[auth.mfa] +# Control how many MFA factors can be enrolled at once per user. +max_enrolled_factors = 10 + +# Control MFA via App Authenticator (TOTP) +[auth.mfa.totp] +enroll_enabled = false +verify_enabled = false + +# Configure MFA via Phone Messaging +[auth.mfa.phone] +enroll_enabled = false +verify_enabled = false +otp_length = 6 +template = "Your code is {{ .Code }}" +max_frequency = "5s" + +# Configure MFA via WebAuthn +# [auth.mfa.web_authn] +# enroll_enabled = true +# verify_enabled = true + +# Use an external OAuth provider. The full list of providers are: `apple`, `azure`, `bitbucket`, +# `discord`, `facebook`, `github`, `gitlab`, `google`, `keycloak`, `linkedin_oidc`, `notion`, `twitch`, +# `twitter`, `slack`, `spotify`, `workos`, `zoom`. +[auth.external.apple] +enabled = false +client_id = "" +# DO NOT commit your OAuth provider secret to git. Use environment variable substitution instead: +secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)" +# Overrides the default auth redirectUrl. +redirect_uri = "" +# Overrides the default auth provider URL. Used to support self-hosted gitlab, single-tenant Azure, +# or any other third-party OIDC providers. +url = "" +# If enabled, the nonce check will be skipped. Required for local sign in with Google auth. +skip_nonce_check = false + +# Use Firebase Auth as a third-party provider alongside Supabase Auth. +[auth.third_party.firebase] +enabled = false +# project_id = "my-firebase-project" + +# Use Auth0 as a third-party provider alongside Supabase Auth. +[auth.third_party.auth0] +enabled = false +# tenant = "my-auth0-tenant" +# tenant_region = "us" + +# Use AWS Cognito (Amplify) as a third-party provider alongside Supabase Auth. +[auth.third_party.aws_cognito] +enabled = false +# user_pool_id = "my-user-pool-id" +# user_pool_region = "us-east-1" + +# Use Clerk as a third-party provider alongside Supabase Auth. +[auth.third_party.clerk] +enabled = false +# Obtain from https://clerk.com/setup/supabase +# domain = "example.clerk.accounts.dev" + +[edge_runtime] +enabled = true +# Configure one of the supported request policies: `oneshot`, `per_worker`. +# Use `oneshot` for hot reload, or `per_worker` for load testing. +policy = "oneshot" +# Port to attach the Chrome inspector for debugging edge functions. +inspector_port = 8083 +# The Deno major version to use. +deno_version = 1 + +# [edge_runtime.secrets] +# secret_key = "env(SECRET_VALUE)" + +[analytics] +enabled = true +port = 54327 +# Configure one of the supported backends: `postgres`, `bigquery`. +backend = "postgres" + +# Experimental features may be deprecated any time +[experimental] +# Configures Postgres storage engine to use OrioleDB (S3) +orioledb_version = "" +# Configures S3 bucket URL, eg. .s3-.amazonaws.com +s3_host = "env(S3_HOST)" +# Configures S3 bucket region, eg. us-east-1 +s3_region = "env(S3_REGION)" +# Configures AWS_ACCESS_KEY_ID for S3 bucket +s3_access_key = "env(S3_ACCESS_KEY)" +# Configures AWS_SECRET_ACCESS_KEY for S3 bucket +s3_secret_key = "env(S3_SECRET_KEY)" From dc81adbb6d81b100bd39763f544e595d27e4ca47 Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Thu, 22 May 2025 21:14:10 -0300 Subject: [PATCH 02/10] test: increment unit test --- StorageTests/StorageFileTests.cs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/StorageTests/StorageFileTests.cs b/StorageTests/StorageFileTests.cs index 1be5d59..e56e16f 100644 --- a/StorageTests/StorageFileTests.cs +++ b/StorageTests/StorageFileTests.cs @@ -169,6 +169,34 @@ public async Task Copy() Assert.IsNotNull(items.Find((f) => f.Name == "new-file.bin")); Assert.IsNotNull(items.Find((f) => f.Name == name)); } + + [TestMethod("File: Copy to another Bucket")] + public async Task CopyToAnotherBucket() + { + await Storage.CreateBucket("copyfile", new BucketUpsertOptions { Public = true }); + var localBucket = Storage.From("copyfile"); + + var name = $"{Guid.NewGuid()}.bin"; + await _bucket.Upload([0x0, 0x1], name); + + await _bucket.Copy(name, "new-file.bin", new DestinationOptions { DestinationBucket = "copyfile" }); + var items = await _bucket.List(); + var copied = await localBucket.List(); + + Assert.IsNotNull(items); + Assert.IsNotNull(copied); + + Assert.IsNotNull(copied.Find((f) => f.Name == "new-file.bin")); + Assert.IsNotNull(items.Find((f) => f.Name == name)); + + foreach (var file in copied) + { + if (file.Name is not null) + await localBucket.Remove(new List { file.Name }); + } + + await Storage.DeleteBucket("copyfile"); + } [TestMethod("File: Get Public Link")] public async Task GetPublicLink() From 677d64ab9c6465159775d66be8340d201acd0213 Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Thu, 22 May 2025 21:14:40 -0300 Subject: [PATCH 03/10] chore: implement supabase stack --- .github/workflows/build-and-test.yml | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/.github/workflows/build-and-test.yml b/.github/workflows/build-and-test.yml index c649c9d..93dd9b5 100644 --- a/.github/workflows/build-and-test.yml +++ b/.github/workflows/build-and-test.yml @@ -28,9 +28,16 @@ jobs: - name: Build run: dotnet build --configuration Release --no-restore + + - uses: supabase/setup-cli@v1 + with: + version: latest + + - name: Start supabase + run: supabase start - - name: Initialize Testing Stack - run: chmod +x ./prepare-infra.sh && ./prepare-infra.sh && sleep 5 +# - name: Initialize Testing Stack +# run: chmod +x ./prepare-infra.sh && ./prepare-infra.sh && sleep 5 - name: Test run: dotnet test --no-restore From e8522ca8c160ffe459259edf1374fd3388c596a3 Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Thu, 22 May 2025 21:15:36 -0300 Subject: [PATCH 04/10] chore: automate release with release-please --- .github/workflows/release.yml | 19 +++++++++++++++++-- .release-please-manifest.json | 3 +++ Storage/Storage.csproj | 4 +++- release-please-config.json | 16 ++++++++++++++++ 4 files changed, 39 insertions(+), 3 deletions(-) create mode 100644 .release-please-manifest.json create mode 100644 release-please-config.json diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 72f852b..7808703 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,12 +1,27 @@ -name: Publish NuGet Package +name: Release - Publish NuGet Package on: push: branches: - - release/* # Default release branch + - master jobs: + release-please: + runs-on: ubuntu-latest + permissions: + contents: write + pull-requests: write + issues: write + steps: + - uses: googleapis/release-please-action@v4 + with: + target-branch: ${{ github.ref_name }} + manifest-file: .release-please-manifest.json + config-file: release-please-config.json + publish: + needs: release-please + if: ${{ github.repository_owner == 'supabase-community' && startsWith(github.event.head_commit.message, 'chore(master)') && github.ref == 'refs/heads/master' && github.event_name == 'push' }} name: build, pack & publish runs-on: ubuntu-latest steps: diff --git a/.release-please-manifest.json b/.release-please-manifest.json new file mode 100644 index 0000000..4c4f7f2 --- /dev/null +++ b/.release-please-manifest.json @@ -0,0 +1,3 @@ +{ + ".": "2.0.2" +} \ No newline at end of file diff --git a/Storage/Storage.csproj b/Storage/Storage.csproj index 255856c..a2ad13e 100644 --- a/Storage/Storage.csproj +++ b/Storage/Storage.csproj @@ -16,8 +16,10 @@ Supabase Storage https://avatars.githubusercontent.com/u/54469796?s=200&v=4 supabase, storage + 2.0.2 2.0.2 + https://github.com/supabase-community/storage-csharp git true @@ -33,7 +35,7 @@ - 2.0.2 + 2.0.2 $(VersionPrefix) diff --git a/release-please-config.json b/release-please-config.json new file mode 100644 index 0000000..39177d2 --- /dev/null +++ b/release-please-config.json @@ -0,0 +1,16 @@ +{ + "packages": { + ".": { + "changelog-path": "CHANGELOG.md", + "bump-minor-pre-major": false, + "bump-patch-for-minor-pre-major": false, + "draft": false, + "prerelease": false, + "release-type": "simple", + "extra-files": [ + "Storage/Storage.csproj" + ] + } + }, + "$schema": "https://raw.githubusercontent.com/googleapis/release-please/main/schemas/config.json" +} \ No newline at end of file From 0890434d61247b031efadc8e937be753ab5334d8 Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Fri, 23 May 2025 18:04:38 -0300 Subject: [PATCH 05/10] feat: format class --- Storage/Exceptions/FailureHint.cs | 68 +++++++++++++++---------------- 1 file changed, 34 insertions(+), 34 deletions(-) diff --git a/Storage/Exceptions/FailureHint.cs b/Storage/Exceptions/FailureHint.cs index 88bf91b..4bfd3a8 100644 --- a/Storage/Exceptions/FailureHint.cs +++ b/Storage/Exceptions/FailureHint.cs @@ -4,37 +4,37 @@ namespace Supabase.Storage.Exceptions { public static class FailureHint - { - public enum Reason - { - Unknown, - NotAuthorized, - Internal, - NotFound, - AlreadyExists, - InvalidInput - } - - public static Reason DetectReason(SupabaseStorageException storageException) - { - if (storageException.Content == null) - return Unknown; - - return storageException.StatusCode switch - { - 400 when storageException.Content.ToLower().Contains("authorization") => NotAuthorized, - 400 when storageException.Content.ToLower().Contains("malformed") => NotAuthorized, - 400 when storageException.Content.ToLower().Contains("invalid signature") => NotAuthorized, - 400 when storageException.Content.ToLower().Contains("invalid") => InvalidInput, - 401 => NotAuthorized, - 403 when storageException.Content.ToLower().Contains("invalid compact jws") => NotAuthorized, - 403 when storageException.Content.ToLower().Contains("signature verification failed") => NotAuthorized, - 404 when storageException.Content.ToLower().Contains("not found") => NotFound, - 409 when storageException.Content.ToLower().Contains("exists") => AlreadyExists, - 500 => Internal, - _ => Unknown - }; - } - } - -} \ No newline at end of file + { + public enum Reason + { + Unknown, + NotAuthorized, + Internal, + NotFound, + AlreadyExists, + InvalidInput + } + + public static Reason DetectReason(SupabaseStorageException storageException) + { + if (storageException.Content == null) + return Unknown; + + return storageException.StatusCode switch + { + 400 when storageException.Content.ToLower().Contains("authorization") => NotAuthorized, + 400 when storageException.Content.ToLower().Contains("malformed") => NotAuthorized, + 400 when storageException.Content.ToLower().Contains("invalid signature") => NotAuthorized, + 400 when storageException.Content.ToLower().Contains("invalid") => InvalidInput, + 401 => NotAuthorized, + 403 when storageException.Content.ToLower().Contains("invalid compact jws") => NotAuthorized, + 403 when storageException.Content.ToLower().Contains("signature verification failed") => NotAuthorized, + 404 when storageException.Content.ToLower().Contains("not found") => NotFound, + 409 when storageException.Content.ToLower().Contains("exists") => AlreadyExists, + 500 => Internal, + _ => Unknown + }; + } + } + +} From db1c59294ecb9d60c6104c99331e82810e2ae7fd Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Tue, 27 May 2025 21:23:27 -0300 Subject: [PATCH 06/10] feat: add find method --- Storage/FileOptions.cs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/Storage/FileOptions.cs b/Storage/FileOptions.cs index 7480392..f633da3 100644 --- a/Storage/FileOptions.cs +++ b/Storage/FileOptions.cs @@ -1,4 +1,5 @@ -using Newtonsoft.Json; +using System.Collections.Generic; +using Newtonsoft.Json; namespace Supabase.Storage { @@ -12,5 +13,14 @@ public class FileOptions [JsonProperty("upsert")] public bool Upsert { get; set; } + + [JsonProperty("duplex")] + public string? Duplex { get; set; } + + [JsonProperty("metadata")] + public Dictionary? Metadata { get; set; } + + [JsonProperty("headers")] + public Dictionary? Headers { get; set; } } } From d4e2519b65f3fb03e07676a58037667544ca91ec Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Tue, 27 May 2025 21:24:30 -0300 Subject: [PATCH 07/10] feat: implement method find --- Storage/FileObjectV2.cs | 49 +++++++++++++++++++++++++++ Storage/Interfaces/IStorageFileApi.cs | 1 + Storage/StorageFileApi.cs | 37 ++++++++++++++++++++ 3 files changed, 87 insertions(+) create mode 100644 Storage/FileObjectV2.cs diff --git a/Storage/FileObjectV2.cs b/Storage/FileObjectV2.cs new file mode 100644 index 0000000..7cbc181 --- /dev/null +++ b/Storage/FileObjectV2.cs @@ -0,0 +1,49 @@ +using System; +using System.Collections.Generic; +using Newtonsoft.Json; + +namespace Supabase.Storage +{ + public class FileObjectV2 + { + + [JsonProperty("id")] + public string Id { get; set; } + + [JsonProperty("version")] + public string Version { get; set; } + + [JsonProperty("name")] + public string? Name { get; set; } + + [JsonProperty("bucket_id")] + public string? BucketId { get; set; } + + [JsonProperty("updated_at")] + public DateTime? UpdatedAt { get; set; } + + [JsonProperty("created_at")] + public DateTime? CreatedAt { get; set; } + + [JsonProperty("last_accessed_at")] + public DateTime? LastAccessedAt { get; set; } + + [JsonProperty("size")] + public int? Size { get; set; } + + [JsonProperty("cache_control")] + public string? CacheControl { get; set; } + + [JsonProperty("content_type")] + public string? ContentType { get; set; } + + [JsonProperty("etag")] + public string? Etag { get; set; } + + [JsonProperty("last_modified")] + public DateTime? LastModified { get; set; } + + [JsonProperty("metadata")] + public Dictionary? Metadata { get; set; } + } +} diff --git a/Storage/Interfaces/IStorageFileApi.cs b/Storage/Interfaces/IStorageFileApi.cs index 3aaaecc..7d34c72 100644 --- a/Storage/Interfaces/IStorageFileApi.cs +++ b/Storage/Interfaces/IStorageFileApi.cs @@ -18,6 +18,7 @@ public interface IStorageFileApi Task DownloadPublicFile(string supabasePath, string localPath, TransformOptions? transformOptions = null, EventHandler? onProgress = null); string GetPublicUrl(string path, TransformOptions? transformOptions = null); Task?> List(string path = "", SearchOptions? options = null); + Task Find(string path); Task Move(string fromPath, string toPath, DestinationOptions? options = null); Task Copy(string fromPath, string toPath, DestinationOptions? options = null); Task Remove(string path); diff --git a/Storage/StorageFileApi.cs b/Storage/StorageFileApi.cs index f14320f..ba03048 100644 --- a/Storage/StorageFileApi.cs +++ b/Storage/StorageFileApi.cs @@ -132,6 +132,19 @@ await Helpers.MakeRequest>(HttpMethod.Post, $"{Url}/object/list return response; } + + /// + /// Retrieves the details of an existing file. + /// + /// + /// + public async Task Find(string path) + { + var response = + await Helpers.MakeRequest(HttpMethod.Get, $"{Url}/object/info/{BucketId}/{path}", null, Headers); + + return response; + } /// /// Uploads a file to an existing bucket. @@ -464,6 +477,14 @@ private async Task UploadOrUpdate(string localPath, string supabasePath, if (options.Upsert) headers.Add("x-upsert", options.Upsert.ToString().ToLower()); + if (options.Metadata != null) + headers.Add("x-metadata", ParseMetadata(options.Metadata)); + + options.Headers?.ToList().ForEach(x => headers.Add(x.Key, x.Value)); + + // if (options.Duplex != null) + // headers.Add("x-duplex", options.Duplex.ToLower()); + var progress = new Progress(); if (onProgress != null) @@ -474,6 +495,14 @@ private async Task UploadOrUpdate(string localPath, string supabasePath, return GetFinalPath(supabasePath); } + private static string ParseMetadata(Dictionary metadata) + { + var json = JsonConvert.SerializeObject(metadata); + var base64 = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(json)); + + return base64; + } + private async Task UploadOrUpdate(byte[] data, string supabasePath, FileOptions options, EventHandler? onProgress = null) { @@ -488,6 +517,14 @@ private async Task UploadOrUpdate(byte[] data, string supabasePath, File if (options.Upsert) headers.Add("x-upsert", options.Upsert.ToString().ToLower()); + if (options.Metadata != null) + headers.Add("x-metadata", ParseMetadata(options.Metadata)); + + options.Headers?.ToList().ForEach(x => headers.Add(x.Key, x.Value)); + + if (options.Duplex != null) + headers.Add("x-duplex", options.Duplex.ToLower()); + var progress = new Progress(); if (onProgress != null) From 66b91602c581bc1e8af2cec8fb48b1422c807783 Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Tue, 27 May 2025 21:24:45 -0300 Subject: [PATCH 08/10] test: improve unit tests --- StorageTests/StorageFileTests.cs | 48 +++++++++++++++++++++++++++++++- 1 file changed, 47 insertions(+), 1 deletion(-) diff --git a/StorageTests/StorageFileTests.cs b/StorageTests/StorageFileTests.cs index e56e16f..bc15800 100644 --- a/StorageTests/StorageFileTests.cs +++ b/StorageTests/StorageFileTests.cs @@ -7,6 +7,7 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; using Supabase.Storage; using Supabase.Storage.Interfaces; +using FileOptions = Supabase.Storage.FileOptions; namespace StorageTests; @@ -75,6 +76,51 @@ public async Task UploadFile() await _bucket.Remove(new List { name }); } + + [TestMethod("File: Upload File With FileOptions")] + public async Task UploadFileWithFileOptions() + { + var didTriggerProgress = new TaskCompletionSource(); + + var asset = "supabase-csharp.png"; + var name = $"{Guid.NewGuid()}.png"; + var basePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)?.Replace("file:", ""); + + Assert.IsNotNull(basePath); + + var imagePath = Path.Combine(basePath, "Assets", asset); + + var metadata = new Dictionary + { + ["custom"] = "metadata", + ["local_file"] = "local_file" + }; + + var headers = new Dictionary + { + ["x-version"] = "123" + }; + + var options = new FileOptions + { + Duplex = "duplex", + Metadata = metadata, + Headers = headers, + }; + await _bucket.Upload(imagePath, name, options, (_, _) => { didTriggerProgress.TrySetResult(true); }); + + var item = await _bucket.Find(name); + + Assert.IsNotNull(item); + Assert.IsNotNull(item.Metadata); + Assert.AreEqual(metadata["custom"], item.Metadata["custom"]); + Assert.AreEqual(metadata["local_file"], item.Metadata["local_file"]); + + var sentProgressEvent = await didTriggerProgress.Task; + Assert.IsTrue(sentProgressEvent); + + await _bucket.Remove([name]); + } [TestMethod("File: Upload Arbitrary Byte Array")] public async Task UploadArbitraryByteArray() @@ -192,7 +238,7 @@ public async Task CopyToAnotherBucket() foreach (var file in copied) { if (file.Name is not null) - await localBucket.Remove(new List { file.Name }); + await localBucket.Remove([file.Name]); } await Storage.DeleteBucket("copyfile"); From 33dab88e2d25bd8cde6e7cce7c1bdce244540add Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Tue, 27 May 2025 21:32:55 -0300 Subject: [PATCH 09/10] feat: uncomment duplex options --- Storage/StorageFileApi.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Storage/StorageFileApi.cs b/Storage/StorageFileApi.cs index ba03048..fa0a6b6 100644 --- a/Storage/StorageFileApi.cs +++ b/Storage/StorageFileApi.cs @@ -482,8 +482,8 @@ private async Task UploadOrUpdate(string localPath, string supabasePath, options.Headers?.ToList().ForEach(x => headers.Add(x.Key, x.Value)); - // if (options.Duplex != null) - // headers.Add("x-duplex", options.Duplex.ToLower()); + if (options.Duplex != null) + headers.Add("x-duplex", options.Duplex.ToLower()); var progress = new Progress(); From 8dd1630fb1a175e6aba56df4cfaf00da21c291f0 Mon Sep 17 00:00:00 2001 From: Diego Santo Date: Wed, 28 May 2025 20:58:39 -0300 Subject: [PATCH 10/10] refactor: rename method to info --- Storage/Interfaces/IStorageFileApi.cs | 2 +- Storage/StorageFileApi.cs | 2 +- StorageTests/StorageFileTests.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/Storage/Interfaces/IStorageFileApi.cs b/Storage/Interfaces/IStorageFileApi.cs index 7d34c72..da54d8a 100644 --- a/Storage/Interfaces/IStorageFileApi.cs +++ b/Storage/Interfaces/IStorageFileApi.cs @@ -18,7 +18,7 @@ public interface IStorageFileApi Task DownloadPublicFile(string supabasePath, string localPath, TransformOptions? transformOptions = null, EventHandler? onProgress = null); string GetPublicUrl(string path, TransformOptions? transformOptions = null); Task?> List(string path = "", SearchOptions? options = null); - Task Find(string path); + Task Info(string path); Task Move(string fromPath, string toPath, DestinationOptions? options = null); Task Copy(string fromPath, string toPath, DestinationOptions? options = null); Task Remove(string path); diff --git a/Storage/StorageFileApi.cs b/Storage/StorageFileApi.cs index fa0a6b6..0ecd260 100644 --- a/Storage/StorageFileApi.cs +++ b/Storage/StorageFileApi.cs @@ -138,7 +138,7 @@ await Helpers.MakeRequest>(HttpMethod.Post, $"{Url}/object/list /// /// /// - public async Task Find(string path) + public async Task Info(string path) { var response = await Helpers.MakeRequest(HttpMethod.Get, $"{Url}/object/info/{BucketId}/{path}", null, Headers); diff --git a/StorageTests/StorageFileTests.cs b/StorageTests/StorageFileTests.cs index bc15800..9883d5c 100644 --- a/StorageTests/StorageFileTests.cs +++ b/StorageTests/StorageFileTests.cs @@ -109,7 +109,7 @@ public async Task UploadFileWithFileOptions() }; await _bucket.Upload(imagePath, name, options, (_, _) => { didTriggerProgress.TrySetResult(true); }); - var item = await _bucket.Find(name); + var item = await _bucket.Info(name); Assert.IsNotNull(item); Assert.IsNotNull(item.Metadata);