Skip to content

Instantly share code, notes, and snippets.

@paxbun
Last active May 27, 2022 08:09
Show Gist options
  • Save paxbun/afae156a4f9a3b0a02c785ed6e4cf326 to your computer and use it in GitHub Desktop.
Save paxbun/afae156a4f9a3b0a02c785ed6e4cf326 to your computer and use it in GitHub Desktop.
using System.Collections.Concurrent;
using System.Text.RegularExpressions;
WebApplicationBuilder builder = WebApplication.CreateBuilder(args);
builder.Services.AddCors(options =>
{
options.AddDefaultPolicy(policy =>
{
policy.AllowAnyHeader();
policy.AllowAnyMethod();
policy.AllowAnyOrigin();
});
});
Regex videoPattern = new(@"^/(.*)\.ism/(.*)$");
ConcurrentDictionary<string, (string contentType, byte[] bytes)> cache = new();
const string originalVideoPathPrefix = "https://unnormalslive-koct1.streaming.media.azure.net/.../....ism/";
async Task<(string contentType, byte[] bytes)> SendRequestToOriginal(string postfix)
{
if (cache.TryGetValue(postfix, out (string, byte[]) result))
return result;
using HttpClient client = new();
HttpResponseMessage response = await client.GetAsync(new Uri(originalVideoPathPrefix + postfix));
Stream stream = response.Content.ReadAsStream();
long numBytes = response.Content.Headers.ContentLength ?? 0;
byte[] bytes = new byte[numBytes];
long numBytesRead = 0;
while (numBytesRead < numBytes)
{
numBytesRead += await stream.ReadAsync(bytes, (int) numBytesRead, (int) (numBytes - numBytesRead));
}
string contentType = response.Content.Headers.ContentType?.ToString() ?? "";
cache[postfix] = (contentType, bytes);
return (contentType, bytes);
}
WebApplication app = builder.Build();
app.UseCors();
app.Run(async context =>
{
Match match = videoPattern.Match(context.Request.Path);
if (match.Success)
{
string postfix = match.Groups[2].Value;
var (contentType, bytes) = await SendRequestToOriginal(postfix);
Console.WriteLine("Processed: {0} {1}: {2}, {3} bytes", context.Request.Method, postfix, contentType,
bytes.Length);
context.Response.ContentType = contentType;
context.Response.ContentLength = bytes.Length;
await context.Response.BodyWriter.WriteAsync(bytes);
}
else
{
Console.WriteLine("Ignored: {0} {1}", context.Request.Method, context.Request.Path);
}
});
app.Run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment