Skip to content

Commit

Permalink
com.utilities.rest 2.2.1 (#46)
Browse files Browse the repository at this point in the history
- Fixed DownloadHandlerCallback not properly filling response data
- Refactor DownloadHandlerCallback signature to invoke Response
  • Loading branch information
StephenHodgson authored Oct 27, 2023
1 parent 0603484 commit ad9c8a9
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 40 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -4,58 +4,51 @@
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using Utilities.Async;

namespace Utilities.WebRequestRest
{
internal class DownloadHandlerCallback : DownloadHandlerScript
{
public DownloadHandlerCallback(UnityWebRequest webRequest, int bufferSize = kEventChunkSize)
{
this.webRequest = webRequest;
eventChunkSize = bufferSize;
stream = new MemoryStream();
}

internal const int kEventChunkSize = 512;

private readonly MemoryStream stream = new MemoryStream();
private readonly int eventChunkSize;
private readonly MemoryStream stream;
private readonly UnityWebRequest webRequest;

private long streamPosition;

private long StreamOffset => stream.Length - streamPosition;

private int eventChunkSize = kEventChunkSize;

public int EventChunkSize
{
get => eventChunkSize;
set
{
if (value < 1)
{
throw new InvalidOperationException($"{nameof(EventChunkSize)} must be greater than 1!");
}

eventChunkSize = value;
}
}
public Action<Response> OnDataReceived { get; set; }

public UnityWebRequest UnityWebRequest { get; set; }
protected override byte[] GetData() => stream?.ToArray();

public Action<UnityWebRequest, byte[]> OnDataReceived { get; set; }
protected override string GetText() => null;

protected override bool ReceiveData(byte[] unprocessedData, int dataLength)
{
var offset = unprocessedData.Length - dataLength;

try
{
var offset = unprocessedData.Length - dataLength;
stream.Position = stream.Length;
stream.Write(unprocessedData, offset, dataLength);

if (StreamOffset >= EventChunkSize)
if (StreamOffset >= eventChunkSize)
{
var multiplier = StreamOffset / EventChunkSize;
var bytesToRead = EventChunkSize * multiplier;
var multiplier = StreamOffset / eventChunkSize;
var bytesToRead = eventChunkSize * multiplier;
stream.Position = streamPosition;
var buffer = new byte[bytesToRead];
var bytesRead = stream.Read(buffer, 0, (int)bytesToRead);
streamPosition += bytesRead;
OnDataReceived?.Invoke(UnityWebRequest, buffer);
OnDataReceived?.Invoke(new Response(webRequest.url, true, null, buffer, webRequest.responseCode, webRequest.GetResponseHeaders()));
}
}
catch (Exception e)
Expand All @@ -76,7 +69,7 @@ protected override void CompleteContent()
var buffer = new byte[StreamOffset];
var bytesRead = stream.Read(buffer);
streamPosition += bytesRead;
OnDataReceived.Invoke(UnityWebRequest, buffer);
OnDataReceived?.Invoke(new Response(webRequest.url, true, null, buffer, webRequest.responseCode, webRequest.GetResponseHeaders()));
}
}
catch (Exception e)
Expand Down
25 changes: 12 additions & 13 deletions Utilities.Rest/Packages/com.utilities.rest/Runtime/Rest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,21 @@ public static async Task<Response> GetAsync(
/// </summary>
/// <param name="query">Finalized Endpoint Query with parameters.</param>
/// <param name="dataReceivedEventCallback"><see cref="Action{T}"/> data received event callback.</param>
/// <param name="eventChunkSize"></param>
/// <param name="parameters">Optional, <see cref="RestParameters"/>.</param>
/// <param name="cancellationToken">Optional, <see cref="CancellationToken"/>.</param>
/// <returns>The response data.</returns>
public static async Task<Response> GetAsync(
string query,
Action<UnityWebRequest, byte[]> dataReceivedEventCallback,
Action<Response> dataReceivedEventCallback,
int? eventChunkSize = null,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
{
using var webRequest = UnityWebRequest.Get(query);
using var downloadHandler = new DownloadHandlerCallback();
using var downloadHandler = eventChunkSize.HasValue
? new DownloadHandlerCallback(webRequest, eventChunkSize.Value)
: new DownloadHandlerCallback(webRequest);
downloadHandler.OnDataReceived += dataReceivedEventCallback;

try
Expand Down Expand Up @@ -225,7 +229,7 @@ public static async Task<Response> PostAsync(
public static async Task<Response> PostAsync(
string query,
string jsonData,
Action<UnityWebRequest, byte[]> dataReceivedEventCallback,
Action<Response> dataReceivedEventCallback,
int? eventChunkSize = null,
RestParameters parameters = null,
CancellationToken cancellationToken = default)
Expand All @@ -238,14 +242,9 @@ public static async Task<Response> PostAsync(
var data = new UTF8Encoding().GetBytes(jsonData);
using var uploadHandler = new UploadHandlerRaw(data);
webRequest.uploadHandler = uploadHandler;
using var downloadHandler = new DownloadHandlerCallback();
downloadHandler.UnityWebRequest = webRequest;

if (eventChunkSize.HasValue)
{
downloadHandler.EventChunkSize = eventChunkSize.Value;
}

using var downloadHandler = eventChunkSize.HasValue
? new DownloadHandlerCallback(webRequest, eventChunkSize.Value)
: new DownloadHandlerCallback(webRequest);
downloadHandler.OnDataReceived += dataReceivedEventCallback;
webRequest.downloadHandler = downloadHandler;
webRequest.SetRequestHeader("Content-Type", "application/json");
Expand Down Expand Up @@ -1082,11 +1081,11 @@ UnityWebRequest.Result.ConnectionError or
return webRequest.downloadHandler switch
{
DownloadHandlerFile => new Response(webRequest.url, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerScript => new Response(webRequest.url, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerTexture => new Response(webRequest.url, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerAudioClip => new Response(webRequest.url, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerAssetBundle => new Response(webRequest.url, false, null, null, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerBuffer bufferDownloadHandler => new Response(webRequest.url, false, bufferDownloadHandler.text, bufferDownloadHandler.data, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
DownloadHandlerScript scriptDownloadHandler => new Response(webRequest.url, false, scriptDownloadHandler.text, scriptDownloadHandler.data, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}"),
_ => new Response(webRequest.url, false, webRequest.responseCode == 401 ? "Invalid Credentials" : webRequest.downloadHandler?.text, webRequest.downloadHandler?.data, webRequest.responseCode, responseHeaders, $"{webRequest.error}\n{webRequest.downloadHandler?.error}")
};
}
Expand All @@ -1099,11 +1098,11 @@ UnityWebRequest.Result.ConnectionError or
return webRequest.downloadHandler switch
{
DownloadHandlerFile => new Response(webRequest.url, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerScript => new Response(webRequest.url, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerTexture => new Response(webRequest.url, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerAudioClip => new Response(webRequest.url, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerAssetBundle => new Response(webRequest.url, true, null, null, webRequest.responseCode, responseHeaders),
DownloadHandlerBuffer bufferDownloadHandler => new Response(webRequest.url, true, bufferDownloadHandler.text, bufferDownloadHandler.data, webRequest.responseCode, responseHeaders),
DownloadHandlerScript scriptDownloadHandler => new Response(webRequest.url, true, scriptDownloadHandler.text, scriptDownloadHandler.data, webRequest.responseCode, responseHeaders),
_ => new Response(webRequest.url, true, webRequest.downloadHandler?.text, webRequest.downloadHandler?.data, webRequest.responseCode, responseHeaders)
};

Expand Down
2 changes: 1 addition & 1 deletion Utilities.Rest/Packages/com.utilities.rest/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"displayName": "Utilities.Rest",
"description": "This package contains useful RESTful utilities for the Unity Game Engine.",
"keywords": [],
"version": "2.2.0",
"version": "2.2.1",
"unity": "2021.3",
"documentationUrl": "https://github.com/RageAgainstThePixel/com.utilities.rest#documentation",
"changelogUrl": "https://github.com/RageAgainstThePixel/com.utilities.rest/releases",
Expand Down

0 comments on commit ad9c8a9

Please sign in to comment.