diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1c702b5 --- /dev/null +++ b/.gitignore @@ -0,0 +1,289 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +x64/ +x86/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ + +# Visual Studio 2015 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUNIT +*.VisualState.xml +TestResult.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ +**/Properties/launchSettings.json + +# VS Code +.vscode/ + +*_i.c +*_p.c +*_i.h +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# JustCode is a .NET coding add-in +.JustCode + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# TODO: Comment the next line if you want to checkin your web deploy settings +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# The packages folder can be ignored because of Package Restore +**/packages/* +# except build/, which is used as an MSBuild target. +!**/packages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/packages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +*.mdf +*.ldf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Typescript v1 declaration files +typings/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# JetBrains Rider +.idea/ +*.sln.iml + +# CodeRush +.cr/ + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs \ No newline at end of file diff --git a/BasicAuthenticationHandler.cs b/BasicAuthenticationHandler.cs new file mode 100644 index 0000000..d75aa94 --- /dev/null +++ b/BasicAuthenticationHandler.cs @@ -0,0 +1,70 @@ +using System; +using System.Net; +using System.Net.Http.Headers; +using System.Security.Claims; +using System.Text; +using System.Text.Encodings.Web; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authentication; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; + +public class BasicAuthenticationHandler : AuthenticationHandler +{ + public BasicAuthenticationHandler(IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) : base(options, logger, encoder, clock) + { + } + + protected override async Task HandleAuthenticateAsync() + { + return await Task.Run(() => + { + if (!Request.Headers.ContainsKey("Authorization")) + { + return AuthenticateResult.Fail("Missing Authorization header"); + } + + try + { + var auth = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); + + + if (auth.Scheme != "Basic") + { + return AuthenticateResult.Fail("Invalid Authorization scheme"); + } + + var credentialBytes = Convert.FromBase64String(auth.Parameter ?? ""); + var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':', 2); + + var username = credentials[0]; + var password = credentials[1]; + + // You would normally check the credentials against a database or other + // authentication source here. For demonstration purposes, we're just + // checking against a hardcoded username and password. + + if (username == "76x8h9rPcsnAb7VTFXZAsg687JutpAHTpmg4xWNWpGQx75rARg8Ak7JeCt46tYcg6rNnZJfjXe7MW8mJ9Nc2sFJJ9ch5vUZJQmTsrWtsZm97QdD2bL5aprtdPtC6C9Vjtccg4VAbMtgcKVWANyvhkpgN3fwjNmMjfcRatbTFcAr29Mm8wppQgyKz4r5ztfSxgPjqwM6TTRH9VCtjaJ7grkZCzrMbnxWDsFjdEBAQEMMRhp9EYbdTYtMArevHKKAEA3HUX7kj6LpU7B6r3nvANnuVPBapmbDC7fK8uAkRFHNtPC85fFQXr2bSTsLJXUFUswQqDyKKndJDjTyMnV9dNNeABruMkALqan9tEq3vmju3LK2rTuQXxvayr24sNzEesTqTbDsmVytYCcDMspdBxMYVZCBm6ECmzhKS6jWE23TazFEDshFqC429s97LuyaWjAGGQe3dgvPwmceFTWjxjqK68hZ8uGcn57j5LNsNCvUdWCFUcp4E9LB4EfD62YbA") + { + var claims = new[] { + new Claim(ClaimTypes.NameIdentifier, username), + new Claim(ClaimTypes.Name, username) + }; + + var identity = new ClaimsIdentity(claims, Scheme.Name); + var principal = new ClaimsPrincipal(identity); + var ticket = new AuthenticationTicket(principal, Scheme.Name); + + return AuthenticateResult.Success(ticket); + } + + return AuthenticateResult.Fail("Invalid username or password"); + } + catch + { + return AuthenticateResult.Fail("Invalid Authorization header"); + } + + }); + } +} diff --git a/Controllers/Update.cs b/Controllers/Update.cs new file mode 100644 index 0000000..29825a2 --- /dev/null +++ b/Controllers/Update.cs @@ -0,0 +1,107 @@ +using System; +using System.Collections.Generic; +using System.IO.Compression; +using System.Linq; +using System.Net.Http.Headers; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Mvc; + +using SysIO = System.IO; + +namespace MUpdater.Controllers +{ + [ApiController] + [Route("[controller]")] + [Authorize] + public class UpdateController : ControllerBase + { + IConfiguration config; + public UpdateController(IConfiguration pConfiguration) + { + config = pConfiguration; + if (config["RepoPath"] is string path) + { + base_path = path; + } + if (!SysIO.Directory.Exists(base_path)) + { + SysIO.Directory.CreateDirectory(base_path); + } + } + private string base_path = "repo"; + + + + [HttpPost("{pScope}/Info")] + public IActionResult LatestFileInfo(string pScope, [FromBody] List pFiles) + { + string path = $"{base_path}/{pScope}"; + if (!SysIO.Directory.Exists(path)) return NotFound(); + + + var data = Directory.EnumerateFiles(path, "*.*", new EnumerationOptions() { RecurseSubdirectories = true }) + .Select(x => x.Replace("\\", "/").Replace(path, "")) + .Where(x => pFiles.Count == 0 | (pFiles.Count > 0 && pFiles.Any(y => x == y.Replace("\\", "/")))) + .Select(x => + { + var info = new FileInfo(x); + return new + { + FileName = x.Replace("\\", "/").Replace(path, ""), + info.LastWriteTime, + info.LastAccessTime + }; + + }); + + return Content(System.Text.Json.JsonSerializer.Serialize(data, new JsonSerializerOptions() { ReferenceHandler = ReferenceHandler.IgnoreCycles }), "application/json"); + } + + [HttpPost("{pScope}/Fetch")] + public async Task FetchFilesAsync(string pScope, [FromBody] List pFiles) + { + string path = $"{base_path}/{pScope}"; + if (!SysIO.Directory.Exists(path)) return NotFound(); + + var files = Directory.EnumerateFiles(path, "*.*", new EnumerationOptions() { RecurseSubdirectories = true }) + .Where(x => pFiles.Count == 0 | (pFiles.Count > 0 && pFiles.Any(y => x.Replace("\\", "/").Replace(path, "") == y.Replace("\\", "/")))).ToList() + .Select(x => new FileInfo(x).FullName); + + + return await ZipedUpdateResult(pScope, files); + + } + + public async Task ZipedUpdateResult(string pScope, IEnumerable pFiles) + { + string path = $"{base_path}/{pScope}"; + using (var zip_stream = new MemoryStream()) + { + using (var archive = new ZipArchive(zip_stream, ZipArchiveMode.Create, true)) + { + foreach (var file in pFiles) + { + // Add the file to the zip archive + var name = file.Replace(new DirectoryInfo(path).FullName + "\\", ""); + var entry = archive.CreateEntry(name + ".mbooks"); + + using (var entry_stream = entry.Open()) + { + using var ms = new MemoryStream(SysIO.File.ReadAllBytes(file)); + await ms.CopyToAsync(entry_stream); + } + } + } + + var zip_file = $"{pScope}.zip"; + return File(zip_stream.ToArray(), "application/zip", zip_file); + + } + } + + + } +} \ No newline at end of file diff --git a/MUpdater.csproj b/MUpdater.csproj new file mode 100644 index 0000000..60bf9ea --- /dev/null +++ b/MUpdater.csproj @@ -0,0 +1,13 @@ + + + + net6.0 + enable + enable + + + + + + + diff --git a/Program.cs b/Program.cs new file mode 100644 index 0000000..54aaa92 --- /dev/null +++ b/Program.cs @@ -0,0 +1,48 @@ +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authorization; + +internal class Program +{ + private static void Main(string[] args) + { + var builder = WebApplication.CreateBuilder(args); + + // Add services to the container. + + builder.Services.AddControllers(); + // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle + builder.Services.AddEndpointsApiExplorer(); + builder.Services.AddSwaggerGen(); + + + var services = builder.Services; + // Configure basic authentication + services.AddAuthentication("BasicAuthentication") + .AddScheme("BasicAuthentication", null); + + // Configure authorization policy + services.AddAuthorization(); + + var app = builder.Build(); + + + + + // Configure the HTTP request pipeline. + if (app.Environment.IsDevelopment()) + { + app.UseSwagger(); + app.UseSwaggerUI(); + } + + + app.UseHttpsRedirection(); + + app.UseAuthentication(); + app.UseAuthorization(); + + app.MapControllers(); + + app.Run(); + } +} \ No newline at end of file diff --git a/appsettings.Development.json b/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/appsettings.json b/appsettings.json new file mode 100644 index 0000000..10f68b8 --- /dev/null +++ b/appsettings.json @@ -0,0 +1,9 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "AllowedHosts": "*" +} diff --git a/repo/HSQ/MBooksRelay.deps.json b/repo/HSQ/MBooksRelay.deps.json new file mode 100644 index 0000000..dd70c54 --- /dev/null +++ b/repo/HSQ/MBooksRelay.deps.json @@ -0,0 +1,41 @@ + { + "runtimeTarget": { + "name": ".NETCoreApp,Version=v6.0", + "signature": "" + }, + "compilationOptions": {}, + "targets": { + ".NETCoreApp,Version=v6.0": { + "MBooksRelay/1.0.0": { + "dependencies": { + "NetCoreServer": "6.7.0" + }, + "runtime": { + "MBooksRelay.dll": {} + } + }, + "NetCoreServer/6.7.0": { + "runtime": { + "lib/net6.0/NetCoreServer.dll": { + "assemblyVersion": "6.7.0.0", + "fileVersion": "6.7.0.0" + } + } + } + } + }, + "libraries": { + "MBooksRelay/1.0.0": { + "type": "project", + "serviceable": false, + "sha512": "" + }, + "NetCoreServer/6.7.0": { + "type": "package", + "serviceable": true, + "sha512": "sha512-chLd65iEmnD2n+H/Kv6ZR9QrDvCE045t8+LHK5enNq26iPXFkg45mJb3YZVFZuH5QHgv/7Fd63LB0MIn24bwEA==", + "path": "netcoreserver/6.7.0", + "hashPath": "netcoreserver.6.7.0.nupkg.sha512" + } + } +} \ No newline at end of file diff --git a/repo/HSQ/MBooksRelay.dll b/repo/HSQ/MBooksRelay.dll new file mode 100644 index 0000000..4428d6c Binary files /dev/null and b/repo/HSQ/MBooksRelay.dll differ diff --git a/repo/HSQ/MBooksRelay.exe b/repo/HSQ/MBooksRelay.exe new file mode 100644 index 0000000..993ec05 Binary files /dev/null and b/repo/HSQ/MBooksRelay.exe differ diff --git a/repo/HSQ/MBooksRelay.runtimeconfig.json b/repo/HSQ/MBooksRelay.runtimeconfig.json new file mode 100644 index 0000000..4986d16 --- /dev/null +++ b/repo/HSQ/MBooksRelay.runtimeconfig.json @@ -0,0 +1,9 @@ +{ + "runtimeOptions": { + "tfm": "net6.0", + "framework": { + "name": "Microsoft.NETCore.App", + "version": "6.0.0" + } + } +} \ No newline at end of file diff --git a/repo/HSQ/NetCoreServer.dll b/repo/HSQ/NetCoreServer.dll new file mode 100644 index 0000000..7873af0 Binary files /dev/null and b/repo/HSQ/NetCoreServer.dll differ