Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Appwrite/Appwrite.csproj
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netstandard2.0;net461</TargetFrameworks>
<TargetFrameworks>netstandard2.0;net462</TargetFrameworks>
<PackageId>Appwrite</PackageId>
<Version>0.13.0</Version>
<Version>0.14.0</Version>
<Authors>Appwrite Team</Authors>
<Company>Appwrite Team</Company>
<Description>
Expand All @@ -20,7 +20,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Text.Json" Version="9.0.5" />
<PackageReference Include="System.Net.Http" Version="4.3.4" />
<None Include="..\icon.png" Pack="true" PackagePath="$(PackageIcon)"/>
<None Include="..\README.md" Pack="true" PackagePath="$(PackageReadmeFile)"/>
Expand Down
150 changes: 102 additions & 48 deletions Appwrite/Client.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Appwrite.Converters;
using Appwrite.Extensions;
Expand All @@ -29,26 +27,28 @@ public class Client

private static readonly int ChunkSize = 5 * 1024 * 1024;

public static JsonSerializerSettings DeserializerSettings { get; set; } = new JsonSerializerSettings
public static JsonSerializerOptions DeserializerOptions { get; set; } = new JsonSerializerOptions
{
MetadataPropertyHandling = MetadataPropertyHandling.Ignore,
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter>
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
PropertyNameCaseInsensitive = true,
Converters =
{
new StringEnumConverter(new CamelCaseNamingStrategy()),
new ValueClassConverter()
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
new ValueClassConverter(),
new ObjectToInferredTypesConverter()
}
};

public static JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings
public static JsonSerializerOptions SerializerOptions { get; set; } = new JsonSerializerOptions
{
NullValueHandling = NullValueHandling.Ignore,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter>
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
Converters =
{
new StringEnumConverter(new CamelCaseNamingStrategy()),
new ValueClassConverter()
new JsonStringEnumConverter(JsonNamingPolicy.CamelCase),
new ValueClassConverter(),
new ObjectToInferredTypesConverter()
}
};

Expand All @@ -69,11 +69,12 @@ public Client(
_headers = new Dictionary<string, string>()
{
{ "content-type", "application/json" },
{ "user-agent" , "AppwriteDotNetSDK/0.13.0 (${Environment.OSVersion.Platform}; ${Environment.OSVersion.VersionString})"},
{ "user-agent" , $"AppwriteDotNetSDK/0.14.0 ({Environment.OSVersion.Platform}; {Environment.OSVersion.VersionString})"},
{ "x-sdk-name", ".NET" },
{ "x-sdk-platform", "server" },
{ "x-sdk-language", "dotnet" },
{ "x-sdk-version", "0.13.0"}, { "X-Appwrite-Response-Format", "1.7.0" }
{ "x-sdk-version", "0.14.0"},
{ "X-Appwrite-Response-Format", "1.7.0" }
};

_config = new Dictionary<string, string>();
Expand All @@ -82,8 +83,6 @@ public Client(
{
SetSelfSigned(true);
}

JsonConvert.DefaultSettings = () => DeserializerSettings;
}

public Client SetSelfSigned(bool selfSigned)
Expand Down Expand Up @@ -189,19 +188,23 @@ private HttpRequestMessage PrepareRequest(
{
if (parameter.Key == "file")
{
form.Add(((MultipartFormDataContent)parameters["file"]).First()!);
var fileContent = parameters["file"] as MultipartFormDataContent;
if (fileContent != null)
{
form.Add(fileContent.First()!);
}
}
else if (parameter.Value is IEnumerable<object> enumerable)
{
var list = new List<object>(enumerable);
for (int index = 0; index < list.Count; index++)
{
form.Add(new StringContent(list[index].ToString()!), $"{parameter.Key}[{index}]");
form.Add(new StringContent(list[index]?.ToString() ?? string.Empty), $"{parameter.Key}[{index}]");
}
}
else
{
form.Add(new StringContent(parameter.Value.ToString()!), parameter.Key);
form.Add(new StringContent(parameter.Value?.ToString() ?? string.Empty), parameter.Key);
}
}
request.Content = form;
Expand Down Expand Up @@ -274,16 +277,27 @@ public async Task<String> Redirect(
}

if (contentType.Contains("application/json")) {
message = JObject.Parse(text)["message"]!.ToString();
type = JObject.Parse(text)["type"]?.ToString() ?? string.Empty;
try
{
using var errorDoc = JsonDocument.Parse(text);
message = errorDoc.RootElement.GetProperty("message").GetString() ?? "";
if (errorDoc.RootElement.TryGetProperty("type", out var typeElement))
{
type = typeElement.GetString() ?? "";
}
}
catch
{
message = text;
}
} else {
message = text;
}

throw new AppwriteException(message, code, type, text);
}

return response.Headers.Location.OriginalString;
return response.Headers.Location?.OriginalString ?? string.Empty;
}

public Task<Dictionary<string, object?>> Call(
Expand Down Expand Up @@ -329,8 +343,19 @@ public async Task<T> Call<T>(
var type = "";

if (isJson) {
message = JObject.Parse(text)["message"]!.ToString();
type = JObject.Parse(text)["type"]?.ToString() ?? string.Empty;
try
{
using var errorDoc = JsonDocument.Parse(text);
message = errorDoc.RootElement.GetProperty("message").GetString() ?? "";
if (errorDoc.RootElement.TryGetProperty("type", out var typeElement))
{
type = typeElement.GetString() ?? "";
}
}
catch
{
message = text;
}
} else {
message = text;
}
Expand All @@ -342,13 +367,13 @@ public async Task<T> Call<T>(
{
var responseString = await response.Content.ReadAsStringAsync();

var dict = JsonConvert.DeserializeObject<Dictionary<string, object>>(
var dict = JsonSerializer.Deserialize<Dictionary<string, object>>(
responseString,
DeserializerSettings);
DeserializerOptions);

if (convert != null)
if (convert != null && dict != null)
{
return convert(dict!);
return convert(dict);
}

return (dict as T)!;
Expand All @@ -368,7 +393,16 @@ public async Task<T> ChunkedUpload<T>(
string? idParamName = null,
Action<UploadProgress>? onProgress = null) where T : class
{
if (string.IsNullOrEmpty(paramName))
throw new ArgumentException("Parameter name cannot be null or empty", nameof(paramName));

if (!parameters.ContainsKey(paramName))
throw new ArgumentException($"Parameter {paramName} not found", nameof(paramName));

var input = parameters[paramName] as InputFile;
if (input == null)
throw new ArgumentException($"Parameter {paramName} must be an InputFile", nameof(paramName));

var size = 0L;
switch(input.SourceType)
{
Expand All @@ -378,10 +412,16 @@ public async Task<T> ChunkedUpload<T>(
size = info.Length;
break;
case "stream":
size = (input.Data as Stream).Length;
var stream = input.Data as Stream;
if (stream == null)
throw new InvalidOperationException("Stream data is null");
size = stream.Length;
break;
case "bytes":
size = ((byte[])input.Data).Length;
var bytes = input.Data as byte[];
if (bytes == null)
throw new InvalidOperationException("Byte array data is null");
size = bytes.Length;
break;
};

Expand All @@ -395,10 +435,16 @@ public async Task<T> ChunkedUpload<T>(
{
case "path":
case "stream":
await (input.Data as Stream).ReadAsync(buffer, 0, (int)size);
var dataStream = input.Data as Stream;
if (dataStream == null)
throw new InvalidOperationException("Stream data is null");
await dataStream.ReadAsync(buffer, 0, (int)size);
break;
case "bytes":
buffer = (byte[])input.Data;
var dataBytes = input.Data as byte[];
if (dataBytes == null)
throw new InvalidOperationException("Byte array data is null");
buffer = dataBytes;
break;
}

Expand All @@ -424,14 +470,16 @@ public async Task<T> ChunkedUpload<T>(
// Make a request to check if a file already exists
var current = await Call<Dictionary<string, object?>>(
method: "GET",
path: $"{path}/{parameters[idParamName]}",
path: $"{path}/{parameters[idParamName!]}",
new Dictionary<string, string> { { "content-type", "application/json" } },
parameters: new Dictionary<string, object?>()
);
var chunksUploaded = (long)current["chunksUploaded"];
offset = chunksUploaded * ChunkSize;
if (current.TryGetValue("chunksUploaded", out var chunksUploadedValue) && chunksUploadedValue != null)
{
offset = Convert.ToInt64(chunksUploadedValue) * ChunkSize;
}
}
catch (Exception ex)
catch
{
// ignored as it mostly means file not found
}
Expand All @@ -444,6 +492,8 @@ public async Task<T> ChunkedUpload<T>(
case "path":
case "stream":
var stream = input.Data as Stream;
if (stream == null)
throw new InvalidOperationException("Stream data is null");
stream.Seek(offset, SeekOrigin.Begin);
await stream.ReadAsync(buffer, 0, ChunkSize);
break;
Expand Down Expand Up @@ -476,12 +526,12 @@ public async Task<T> ChunkedUpload<T>(
var id = result.ContainsKey("$id")
? result["$id"]?.ToString() ?? string.Empty
: string.Empty;
var chunksTotal = result.ContainsKey("chunksTotal")
? (long)result["chunksTotal"]
: 0;
var chunksUploaded = result.ContainsKey("chunksUploaded")
? (long)result["chunksUploaded"]
: 0;
var chunksTotal = result.TryGetValue("chunksTotal", out var chunksTotalValue) && chunksTotalValue != null
? Convert.ToInt64(chunksTotalValue)
: 0L;
var chunksUploaded = result.TryGetValue("chunksUploaded", out var chunksUploadedValue) && chunksUploadedValue != null
? Convert.ToInt64(chunksUploadedValue)
: 0L;

headers["x-appwrite-id"] = id;

Expand All @@ -494,7 +544,11 @@ public async Task<T> ChunkedUpload<T>(
chunksUploaded: chunksUploaded));
}

return converter(result);
// Convert to non-nullable dictionary for converter
var nonNullableResult = result.Where(kvp => kvp.Value != null)
.ToDictionary(kvp => kvp.Key, kvp => kvp.Value!);

return converter(nonNullableResult);
}
}
}
44 changes: 44 additions & 0 deletions Appwrite/Converters/ObjectToInferredTypesConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace Appwrite.Converters
{
public class ObjectToInferredTypesConverter : JsonConverter<object>
{
public override object Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
switch (reader.TokenType)
{
case JsonTokenType.True:
return true;
case JsonTokenType.False:
return false;
case JsonTokenType.Number:
if (reader.TryGetInt64(out long l))
{
return l;
}
return reader.GetDouble();
case JsonTokenType.String:
if (reader.TryGetDateTime(out DateTime datetime))
{
return datetime;
}
return reader.GetString()!;
case JsonTokenType.StartObject:
return JsonSerializer.Deserialize<Dictionary<string, object>>(ref reader, options)!;
case JsonTokenType.StartArray:
return JsonSerializer.Deserialize<object[]>(ref reader, options)!;
default:
return JsonDocument.ParseValue(ref reader).RootElement.Clone();
}
}

public override void Write(Utf8JsonWriter writer, object objectToWrite, JsonSerializerOptions options)
{
JsonSerializer.Serialize(writer, objectToWrite, objectToWrite.GetType(), options);
}
}
}
Loading