// SPDX-FileCopyrightText: 2023 Unity Technologies and the glTFast authors
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Serialization;
namespace GLTFast.Loading
{
///
/// Represents an HTTP request header key-value pair
///
[Serializable]
public struct HttpHeader
{
///
/// HTTP header key/name
///
public string Key => key;
///
/// HTTP header value
///
public string Value => value;
[SerializeField] string key;
[SerializeField] string value;
///
/// Creates a new HTTP header entry
///
/// Identifier
/// Value
public HttpHeader(string key, string value)
{
this.key = key;
this.value = value;
}
}
///
/// DownloadProvider that sends HTTP request with custom header entries
///
public class CustomHeaderDownloadProvider : IDownloadProvider
{
HttpHeader[] m_Headers;
///
/// Creates a new CustomHeaderDownloadProvider with a given set of HTTP request header entries
///
/// HTTP request header entries to send
public CustomHeaderDownloadProvider(HttpHeader[] headers)
{
m_Headers = headers;
}
///
public async Task Request(Uri url)
{
var req = new CustomHeaderDownload(url, RegisterHttpHeaders);
await req.WaitAsync();
return req;
}
///
#pragma warning disable CS1998
public async Task RequestTexture(Uri url, bool nonReadable)
{
#pragma warning restore CS1998
#if UNITY_WEBREQUEST_TEXTURE
var req = new CustomHeaderTextureDownload(url,nonReadable,RegisterHttpHeaders);
await req.WaitAsync();
return req;
#else
return null;
#endif
}
void RegisterHttpHeaders(UnityWebRequest request)
{
if (m_Headers != null)
{
foreach (var header in m_Headers)
{
request.SetRequestHeader(header.Key, header.Value);
}
}
}
}
///
/// Download that allows modifying the HTTP request before it's sent
///
public class CustomHeaderDownload : AwaitableDownload
{
///
/// Constructs an with a modifier
///
/// URI to request
/// Callback that modifies the UnityWebRequest before it's sent
public CustomHeaderDownload(Uri url, Action editor)
{
m_Request = UnityWebRequest.Get(url);
editor(m_Request);
m_AsyncOperation = m_Request.SendWebRequest();
}
}
#if UNITY_WEBREQUEST_TEXTURE
///
/// Texture download that allows modifying the HTTP request before it's sent
///
public class CustomHeaderTextureDownload : AwaitableTextureDownload {
///
/// Constructs an with a modifier
///
/// URI to request
/// If true, resulting texture is not readable (uses less memory)
/// Callback that modifies the UnityWebRequest before it's sent
public CustomHeaderTextureDownload(Uri url, bool nonReadable, Action editor) {
m_Request = CreateRequest(url,nonReadable);
editor(m_Request);
m_AsyncOperation = m_Request.SendWebRequest();
}
}
#endif
}