using System.Text.Json; using Microsoft.Extensions.FileProviders; using Microsoft.AspNetCore.Hosting; using PlotLine.Services; using System.Security.Cryptography; if (args.Length != 3) throw new ArgumentException("Usage: PublicContent SOURCE_ROOT APPROVAL_JSON NEW_OUTPUT_DIRECTORY"); var root = Path.GetFullPath(args[0]); var approval = JsonDocument.Parse(File.ReadAllText(args[1])).RootElement; var commit = approval.GetProperty("sourceCommit").GetString()!; var actual = Git(root, "rev-parse", "HEAD").Trim(); if (commit != actual) throw new InvalidOperationException("Approval must name exact source commit."); if(!string.IsNullOrWhiteSpace(Git(root,"diff","HEAD","--","PlotLine/Help"))) throw new InvalidOperationException("Commit help changes before publication."); var output = Path.GetFullPath(args[2]); if (Directory.Exists(output)) throw new IOException("Output must be new."); var approved = approval.GetProperty("articles").EnumerateArray().Select(x=>x.GetString()!).ToHashSet(StringComparer.Ordinal); var help = new HelpService(new ContentEnvironment(Path.Combine(root,"PlotLine"))); var all = help.GetSourceArticles(); var audience = approval.TryGetProperty("audience", out var requestedAudience) ? requestedAudience.GetString() : "public"; if(audience is not ("public" or "application")) throw new InvalidDataException("Invalid publication audience."); if(approved.Except(all.Select(x=>x.Url)).Any()) throw new InvalidDataException("Unknown article in approval."); var articles = all.Where(x=>approved.Contains(x.Url) && (x.Visibility == "public" || (audience == "application" && x.Visibility == "administrator"))).ToArray(); if(all.Any(x=>x.Visibility is not ("public" or "administrator" or "internal"))) throw new InvalidDataException("Every source article needs explicit valid visibility."); foreach(var a in articles) { var date=Git(root,"log","-1","--format=%cI","--","PlotLine/Help/Articles/"+a.RelativePath).Trim(); if(!DateTimeOffset.TryParse(date,out var modified)) throw new InvalidDataException("Article needs committed modification date."); a.LastModifiedUtc=modified.UtcDateTime; } Directory.CreateDirectory(output); var options=new JsonSerializerOptions { WriteIndented=true }; File.WriteAllText(Path.Combine(output,"articles.json"),JsonSerializer.Serialize(articles,options)); var assetRoot=Path.Combine(root,"PlotLine","Help","Images"); var assets = articles.SelectMany(a => System.Text.RegularExpressions.Regex.Matches(a.MarkdownContent, @"!\[[^\]]*\]\(([^)]+)\)") .Select(m => m.Groups[1].Value).Concat(string.IsNullOrWhiteSpace(a.Screenshot) ? [] : new[] { a.Screenshot })) .Distinct(StringComparer.Ordinal).ToArray(); foreach(var asset in assets) { if(Path.IsPathRooted(asset) || asset.Contains("..") || asset.Contains('\\')) throw new InvalidDataException("Unsafe help asset."); var file=Path.Combine(assetRoot,asset); if(!File.Exists(file) || new FileInfo(file).LinkTarget is not null) throw new InvalidDataException("Approved article asset missing or linked."); var dest=Path.Combine(output,"assets",asset);Directory.CreateDirectory(Path.GetDirectoryName(dest)!);File.Copy(file,dest); } var files=Directory.EnumerateFiles(output,"*",SearchOption.AllDirectories).Order().ToDictionary(f=>Path.GetRelativePath(output,f).Replace('\\','/'),f=>Convert.ToHexString(SHA256.HashData(File.ReadAllBytes(f))).ToLowerInvariant()); File.WriteAllText(Path.Combine(output,"manifest.json"),JsonSerializer.Serialize(new {format=2,audience,sourceCommit=commit,channel=approval.GetProperty("channel").GetString(),version=approval.GetProperty("version").GetString(),files},options)); Console.WriteLine($"Published {articles.Length} approved articles to {output}"); static string Git(string root,params string[] arguments) { var start=new System.Diagnostics.ProcessStartInfo("git"){WorkingDirectory=root,RedirectStandardOutput=true};foreach(var a in arguments)start.ArgumentList.Add(a); using var p=System.Diagnostics.Process.Start(start)!;var result=p.StandardOutput.ReadToEnd();p.WaitForExit();if(p.ExitCode!=0)throw new IOException("Git failed.");return result; } sealed class ContentEnvironment(string root):IWebHostEnvironment { public string ContentRootPath {get;set;}=root; public string WebRootPath {get;set;}=Path.Combine(root,"wwwroot"); public string EnvironmentName {get;set;}="Development"; public string ApplicationName {get;set;}="PublicContent"; public IFileProvider ContentRootFileProvider {get;set;}=new NullFileProvider(); public IFileProvider WebRootFileProvider {get;set;}=new NullFileProvider(); }