Skip to content
This repository has been archived by the owner on Jan 30, 2024. It is now read-only.

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
dkackman committed Nov 25, 2023
1 parent aaed6a7 commit 65f307b
Show file tree
Hide file tree
Showing 18 changed files with 747 additions and 2 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

[*]
indent_style = space
indent_size = 4
end_of_line = crlf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
11 changes: 11 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/github/administering-a-repository/configuration-options-for-dependency-updates

version: 2
updates:
- package-ecosystem: "nuget" # See documentation for possible values
directory: "/Web2Gateway" # Location of package manifests
schedule:
interval: "weekly"
57 changes: 57 additions & 0 deletions .github/workflows/main_g2to3.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
# Docs for the Azure Web Apps Deploy action: https://github.com/Azure/webapps-deploy
# More GitHub Actions for Azure: https://github.com/Azure/actions

name: Build and deploy ASP.Net Core app to Azure Web App - g2to3

on:
push:
branches:
- main
workflow_dispatch:

jobs:
build:
runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4

- name: Set up .NET Core
uses: actions/setup-dotnet@v1
with:
dotnet-version: '7.x'
include-prerelease: true

- name: Build with dotnet
run: dotnet build --configuration Release

- name: dotnet publish
run: dotnet publish -c Release -o ${{env.DOTNET_ROOT}}/myapp

- name: Upload artifact for deployment job
uses: actions/upload-artifact@v3
with:
name: .net-app
path: ${{env.DOTNET_ROOT}}/myapp

deploy:
runs-on: ubuntu-latest
needs: build
environment:
name: 'Production'
url: ${{ steps.deploy-to-webapp.outputs.webapp-url }}

steps:
- name: Download artifact from build job
uses: actions/download-artifact@v3
with:
name: .net-app

- name: Deploy to Azure Web App
id: deploy-to-webapp
uses: azure/webapps-deploy@v2
with:
app-name: 'g2to3'
slot-name: 'Production'
publish-profile: ${{ secrets.AZUREAPPSERVICE_PUBLISHPROFILE_1FC60C31816144F3BEBD557C2BD0ED69 }}
package: .
41 changes: 41 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/dotnet/vscode-csharp/blob/main/debugger-launchjson.md.
"name": ".NET Core Launch (web)",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Web2Gateway/bin/Debug/net8.0/Web2Gateway.dll",
"args": [
//"C:\\Users\\don\\.g2to3\\appsettings.json"
],
"cwd": "${workspaceFolder}/Web2Gateway",
"stopAtEntry": false,
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser
"serverReadyAction": {
"action": "openExternally",
"pattern": "\\bNow listening on:\\s+http://\\S+:([0-9]+)",
"uriFormat": "http://localhost:%s"
},
"env": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"sourceFileMap": {
"/Views": "${workspaceFolder}/Views"
}
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach"
}
]
}
5 changes: 5 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"cSpell.words": [
"referer"
]
}
41 changes: 41 additions & 0 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build",
"command": "dotnet",
"type": "process",
"args": [
"build",
"${workspaceFolder}/Web2Gateway.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary;ForceNoAlign"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/Web2Gateway.sln",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary;ForceNoAlign"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"--project",
"${workspaceFolder}/Web2Gateway.sln"
],
"problemMatcher": "$msCompile"
}
]
}
3 changes: 1 addition & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
# Web2Gateway
chia data layer web2 gateway
# Chia Web2Gateway
25 changes: 25 additions & 0 deletions Web2Gateway.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.002.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Web2Gateway", "Web2Gateway\Web2Gateway.csproj", "{DECF587E-5841-468D-AC62-F418562C8E36}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{DECF587E-5841-468D-AC62-F418562C8E36}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{DECF587E-5841-468D-AC62-F418562C8E36}.Debug|Any CPU.Build.0 = Debug|Any CPU
{DECF587E-5841-468D-AC62-F418562C8E36}.Release|Any CPU.ActiveCfg = Release|Any CPU
{DECF587E-5841-468D-AC62-F418562C8E36}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {B274398D-3BFC-465C-95C0-D55C1DD4A194}
EndGlobalSection
EndGlobal
151 changes: 151 additions & 0 deletions Web2Gateway/Api.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
using Web2Gateway;
using System.Text.RegularExpressions;

internal static class Api
{
public static WebApplication ConfigureApi(this WebApplication app, ILogger logger)
{
app.MapGet("/", () => Results.Redirect("/.well-known", true));
app.MapGet("/.well-known", () =>
{
var g223 = app.Services.GetRequiredService<G2To3Service>();
return g223.GetWellKnown();
})
.WithName(".well-known")
.WithOpenApi();

app.MapGet("/{storeId}", async (HttpContext httpContext, string storeId, bool? showKeys, CancellationToken cancellationToken) =>
{
try
{
storeId = storeId.TrimEnd('/');

// A referrer indicates that the user is trying to access the store from a website
// we want to redirect them so that the URL includes the storeId in the path
var referer = httpContext.Request.Headers["referer"].ToString();
if (!string.IsNullOrEmpty(referer) && referer.Contains(storeId))
{
httpContext.Response.Headers["Location"] = $"{referer}/{storeId}";
return Results.Redirect($"{referer}/{storeId}", true);
}

var g223 = app.Services.GetRequiredService<G2To3Service>();
var keys = await g223.GetKeys(storeId, cancellationToken);

if (keys is not null)
{
var decodedKeys = keys.Select(key => HexUtils.FromHex(key)).ToList();

// the key represents a SPA app, so we want to return the index.html
if (decodedKeys != null && decodedKeys.Count > 0 && decodedKeys.Contains("index.html") && showKeys != true)
{
var html = await g223.GetValueAsHtml(storeId, cancellationToken);
return Results.Content(html, "text/html");
}

return Results.Ok(decodedKeys);
}

return Results.NotFound();
}
catch (InvalidOperationException ex)
{
logger.LogError(ex, "{Message}", ex.Message);
return Results.StatusCode(StatusCodes.Status500InternalServerError);
}
catch (Exception ex)
{
logger.LogError(ex, "{Message}", ex.Message);
return Results.StatusCode(StatusCodes.Status503ServiceUnavailable);
}
})
.WithName("{storeId}")
.WithOpenApi();

app.MapGet("/{storeId}/{*catchAll}", async (HttpContext httpContext, string storeId, string catchAll, CancellationToken cancellationToken) =>
{
try
{
var key = catchAll;
// Remove everything after the first '#'
if (key.Contains('#'))
{
key = key.Split('#')[0];
}
key = key.TrimEnd('/');

// A referrer indicates that the user is trying to access the store from a website
// we want to redirect them so that the URL includes the storeId in the path
var referer = httpContext.Request.Headers["referer"].ToString();
if (!string.IsNullOrEmpty(referer) && !referer.Contains(storeId))
{
key = key.TrimStart('/');
httpContext.Response.Headers["Location"] = $"{referer}/{storeId}/{key}";

return Results.Redirect($"{referer}/{storeId}/{key}", true);
}

var hexKey = HexUtils.ToHex(key);
var g223 = app.Services.GetRequiredService<G2To3Service>();
var rawValue = await g223.GetValue(storeId, hexKey, cancellationToken);
if (rawValue is null)
{
Console.WriteLine($"couldn't find: {key}");

return Results.NotFound();
}
Console.WriteLine($"found: {key}");
var decodedValue = HexUtils.FromHex(rawValue);
var fileExtension = Path.GetExtension(key);

if (Utils.TryParseJson(decodedValue, out var json) && json?.type == "multipart")
{
string mimeType = Utils.GetMimeType(fileExtension) ?? "application/octet-stream";
var bytes = await g223.GetValuesAsBytes(storeId, json, cancellationToken);

return Results.File(bytes, mimeType);
}
else if (!string.IsNullOrEmpty(fileExtension))
{
string mimeType = Utils.GetMimeType(fileExtension) ?? "application/octet-stream";

return Results.File(Convert.FromHexString(rawValue), mimeType);
}
else if (json is not null)
{
return Results.Ok(json);
}
else if (Utils.IsBase64Image(decodedValue))
{
// figure out the mime type
var regex = new Regex(@"[^:]\w+\/[\w-+\d.]+(?=;|,)");
var match = regex.Match(decodedValue);

// convert the base64 string to a byte array
string base64Image = decodedValue.Split(";base64,")[^1];
byte[] imageBuffer = Convert.FromBase64String(base64Image);

return Results.File(imageBuffer, match.Value);
}
else
{
return Results.Content(decodedValue);
}
}
catch (InvalidOperationException ex)
{
logger.LogError(ex, "{Message}", ex.Message);
return Results.StatusCode(StatusCodes.Status500InternalServerError);
}
catch (Exception ex)
{
logger.LogError(ex, "{Message}", ex.Message);
return Results.StatusCode(StatusCodes.Status503ServiceUnavailable);
}
})
.WithName("{storeId}/*")
.WithOpenApi();

return app;
}
}
Loading

0 comments on commit 65f307b

Please sign in to comment.