-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
675 lines (574 loc) · 23.3 KB
/
Program.cs
File metadata and controls
675 lines (574 loc) · 23.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
using System.Diagnostics;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using System.Text.Json.Serialization;
using Markdig;
namespace ConfluencePublisher;
internal static class Program
{
internal static readonly Regex ImageRegex = new(@"!\[(?<alt>[^\]]*)\]\((?<url>[^)]+)\)", RegexOptions.Compiled);
internal static readonly Regex MermaidBlockRegex = new(@"```mermaid\s*(?<code>[\s\S]*?)```", RegexOptions.Compiled | RegexOptions.IgnoreCase);
internal static readonly Regex HtmlImgRegex = new(@"<img\b[^>]*\bsrc=""(?<src>[^""]+)""[^>]*>", RegexOptions.Compiled | RegexOptions.IgnoreCase);
public static async Task<int> Main(string[] args)
{
var options = Options.Load(args);
var logger = Logger.Create(options.LogFile);
logger.Info("Starting Confluence publish run.");
logger.Info($"Markdown: {options.MarkdownPath}");
logger.Info($"Base URL: {options.BaseUrl}");
logger.Info($"Space: {options.SpaceKey}");
logger.Info($"Title: {options.Title}");
if (string.IsNullOrWhiteSpace(options.MarkdownPath))
{
logger.Error("Missing --markdown argument.");
return 1;
}
if (!File.Exists(options.MarkdownPath))
{
logger.Error($"Markdown file not found: {options.MarkdownPath}");
return 1;
}
var credentials = Credentials.Load(options.CredentialsFile, logger);
credentials = credentials.OverrideWith(options);
if (!credentials.IsValid())
{
logger.Error("Missing credentials. Provide username/apiToken via credentials file or command line.");
return 1;
}
if (options.SaveCredentials)
{
credentials.Save(options.CredentialsFile, logger);
}
if (string.IsNullOrWhiteSpace(options.SpaceKey) || string.IsNullOrWhiteSpace(options.Title))
{
logger.Error("Missing required parameters: --space and --title are required.");
return 1;
}
var markdownText = await File.ReadAllTextAsync(options.MarkdownPath);
var markdownDir = Path.GetDirectoryName(Path.GetFullPath(options.MarkdownPath)) ?? Environment.CurrentDirectory;
var mermaidConverter = new MermaidConverter(options.MermaidCli, logger);
var mermaidResult = await mermaidConverter.ReplaceMermaidBlocksAsync(markdownText);
var attachments = new Dictionary<string, AttachmentInfo>(StringComparer.OrdinalIgnoreCase);
foreach (var mermaidAttachment in mermaidResult.Attachments)
{
attachments[mermaidAttachment.FileName] = mermaidAttachment;
}
var imageMappings = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
foreach (Match match in ImageRegex.Matches(mermaidResult.Markdown))
{
var url = match.Groups["url"].Value.Trim();
if (string.IsNullOrWhiteSpace(url))
{
continue;
}
if (url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) ||
url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
{
continue;
}
if (url.StartsWith("attachment:", StringComparison.OrdinalIgnoreCase))
{
var attachmentName = url.Substring("attachment:".Length);
imageMappings[url] = attachmentName;
continue;
}
var imagePath = Path.IsPathRooted(url) ? url : Path.GetFullPath(Path.Combine(markdownDir, url));
if (!File.Exists(imagePath))
{
logger.Warn($"Image not found, skipping: {imagePath}");
continue;
}
var attachmentFileName = Path.GetFileName(imagePath);
attachmentFileName = EnsureUniqueFileName(attachmentFileName, attachments);
attachments[attachmentFileName] = new AttachmentInfo(imagePath, attachmentFileName, false);
imageMappings[url] = attachmentFileName;
imageMappings[EscapeUriForMatch(url)] = attachmentFileName;
}
var html = Markdown.ToHtml(mermaidResult.Markdown, new MarkdownPipelineBuilder().UseAdvancedExtensions().Build());
var confluenceStorage = ConvertImagesToConfluenceStorage(html, imageMappings);
using var client = new ConfluenceClient(credentials, logger);
var pageId = options.PageId;
if (string.IsNullOrWhiteSpace(pageId))
{
var existingPage = await client.GetPageByTitleAsync(options.SpaceKey, options.Title);
pageId = existingPage?.Id;
}
if (string.IsNullOrWhiteSpace(pageId))
{
logger.Info("Page not found, creating new page.");
var createdPage = await client.CreatePageAsync(options.SpaceKey, options.Title, options.ParentId, "<p>Publishing content...</p>");
pageId = createdPage.Id;
}
else
{
logger.Info($"Using existing page ID: {pageId}");
}
foreach (var attachment in attachments.Values)
{
await client.UploadAttachmentAsync(pageId, attachment);
}
var updatedPage = await client.UpdatePageAsync(pageId, options.SpaceKey, options.Title, options.ParentId, confluenceStorage);
logger.Info($"Published page ID {updatedPage.Id} at version {updatedPage.Version?.Number}.");
logger.Info("Publish run completed.");
return 0;
}
private static string EnsureUniqueFileName(string fileName, Dictionary<string, AttachmentInfo> attachments)
{
if (!attachments.ContainsKey(fileName))
{
return fileName;
}
var baseName = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
var index = 1;
string candidate;
do
{
candidate = $"{baseName}-{index}{extension}";
index++;
} while (attachments.ContainsKey(candidate));
return candidate;
}
private static string EscapeUriForMatch(string url)
{
try
{
return Uri.EscapeUriString(url);
}
catch
{
return url;
}
}
private static string ConvertImagesToConfluenceStorage(string html, Dictionary<string, string> imageMappings)
{
if (imageMappings.Count == 0)
{
return html;
}
return HtmlImgRegex.Replace(html, match =>
{
var src = match.Groups["src"].Value;
if (!imageMappings.TryGetValue(src, out var attachmentName))
{
return match.Value;
}
return $"<ac:image><ri:attachment ri:filename=\"{EscapeAttribute(attachmentName)}\" /></ac:image>";
});
}
private static string EscapeAttribute(string value)
{
return System.Security.SecurityElement.Escape(value) ?? value;
}
}
internal sealed class Options
{
public string MarkdownPath { get; private set; } = string.Empty;
public string BaseUrl { get; private set; } = string.Empty;
public string SpaceKey { get; private set; } = string.Empty;
public string Title { get; private set; } = string.Empty;
public string ParentId { get; private set; } = string.Empty;
public string PageId { get; private set; } = string.Empty;
public string Username { get; private set; } = string.Empty;
public string ApiToken { get; private set; } = string.Empty;
public string CredentialsFile { get; private set; } = "credentials.json";
public string LogFile { get; private set; } = string.Empty;
public string MermaidCli { get; private set; } = "mmdc";
public bool SaveCredentials { get; private set; }
public static Options Load(string[] args)
{
var options = new Options();
var argMap = ParseArgs(args);
options.MarkdownPath = GetArg(argMap, "markdown") ?? options.MarkdownPath;
options.BaseUrl = GetArg(argMap, "base-url") ?? options.BaseUrl;
options.SpaceKey = GetArg(argMap, "space") ?? options.SpaceKey;
options.Title = GetArg(argMap, "title") ?? options.Title;
options.ParentId = GetArg(argMap, "parent-id") ?? options.ParentId;
options.PageId = GetArg(argMap, "page-id") ?? options.PageId;
options.Username = GetArg(argMap, "username") ?? options.Username;
options.ApiToken = GetArg(argMap, "api-token") ?? options.ApiToken;
options.CredentialsFile = GetArg(argMap, "credentials-file") ?? options.CredentialsFile;
options.LogFile = GetArg(argMap, "log-file") ?? options.LogFile;
options.MermaidCli = GetArg(argMap, "mermaid-cli") ?? options.MermaidCli;
options.SaveCredentials = argMap.ContainsKey("save-credentials");
if (string.IsNullOrWhiteSpace(options.LogFile))
{
var logDir = Path.Combine(Environment.CurrentDirectory, "logs");
Directory.CreateDirectory(logDir);
options.LogFile = Path.Combine(logDir, $"publish-{DateTime.UtcNow:yyyyMMdd-HHmmss}.log");
}
return options;
}
private static Dictionary<string, string> ParseArgs(string[] args)
{
var map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < args.Length; i++)
{
var arg = args[i];
if (!arg.StartsWith("--", StringComparison.Ordinal))
{
continue;
}
var key = arg.Substring(2);
if (i + 1 < args.Length && !args[i + 1].StartsWith("--", StringComparison.Ordinal))
{
map[key] = args[i + 1];
i++;
}
else
{
map[key] = string.Empty;
}
}
return map;
}
private static string? GetArg(Dictionary<string, string> args, string key)
{
return args.TryGetValue(key, out var value) ? value : null;
}
}
internal sealed class Credentials
{
public string BaseUrl { get; init; } = string.Empty;
public string Username { get; init; } = string.Empty;
public string ApiToken { get; init; } = string.Empty;
public bool IsValid()
{
return !string.IsNullOrWhiteSpace(BaseUrl) &&
!string.IsNullOrWhiteSpace(Username) &&
!string.IsNullOrWhiteSpace(ApiToken);
}
public static Credentials Load(string filePath, Logger logger)
{
try
{
if (!File.Exists(filePath))
{
logger.Info($"Credentials file not found: {filePath}");
return new Credentials();
}
var json = File.ReadAllText(filePath);
var creds = JsonSerializer.Deserialize<Credentials>(json);
return creds ?? new Credentials();
}
catch (Exception ex)
{
logger.Warn($"Failed to load credentials file: {ex.Message}");
return new Credentials();
}
}
public Credentials OverrideWith(Options options)
{
return new Credentials
{
BaseUrl = string.IsNullOrWhiteSpace(options.BaseUrl) ? BaseUrl : options.BaseUrl,
Username = string.IsNullOrWhiteSpace(options.Username) ? Username : options.Username,
ApiToken = string.IsNullOrWhiteSpace(options.ApiToken) ? ApiToken : options.ApiToken
};
}
public void Save(string filePath, Logger logger)
{
try
{
var json = JsonSerializer.Serialize(this, new JsonSerializerOptions { WriteIndented = true });
File.WriteAllText(filePath, json);
logger.Info($"Saved credentials to {filePath}");
}
catch (Exception ex)
{
logger.Warn($"Failed to save credentials file: {ex.Message}");
}
}
}
internal sealed class Logger
{
private readonly string _logFile;
private readonly object _lock = new();
private Logger(string logFile)
{
_logFile = logFile;
}
public static Logger Create(string logFile)
{
Directory.CreateDirectory(Path.GetDirectoryName(logFile) ?? Environment.CurrentDirectory);
return new Logger(logFile);
}
public void Info(string message) => Write("INFO", message);
public void Warn(string message) => Write("WARN", message);
public void Error(string message) => Write("ERROR", message);
private void Write(string level, string message)
{
var line = $"{DateTime.UtcNow:O} [{level}] {message}";
lock (_lock)
{
Console.WriteLine(line);
File.AppendAllText(_logFile, line + Environment.NewLine);
}
}
}
internal sealed record AttachmentInfo(string SourcePath, string FileName, bool IsMermaid);
internal sealed class MermaidConversionResult
{
public MermaidConversionResult(string markdown, List<AttachmentInfo> attachments)
{
Markdown = markdown;
Attachments = attachments;
}
public string Markdown { get; }
public List<AttachmentInfo> Attachments { get; }
}
internal sealed class MermaidConverter
{
private readonly string _mermaidCli;
private readonly Logger _logger;
public MermaidConverter(string mermaidCli, Logger logger)
{
_mermaidCli = string.IsNullOrWhiteSpace(mermaidCli) ? "mmdc" : mermaidCli;
_logger = logger;
}
public async Task<MermaidConversionResult> ReplaceMermaidBlocksAsync(string markdown)
{
var attachments = new List<AttachmentInfo>();
var matches = Program.MermaidBlockRegex.Matches(markdown);
if (matches.Count == 0)
{
return new MermaidConversionResult(markdown, attachments);
}
var builder = new StringBuilder(markdown.Length);
var lastIndex = 0;
var index = 1;
foreach (Match match in matches)
{
builder.Append(markdown, lastIndex, match.Index - lastIndex);
lastIndex = match.Index + match.Length;
var code = match.Groups["code"].Value.Trim();
if (string.IsNullOrWhiteSpace(code))
{
builder.Append(match.Value);
continue;
}
var outputFileName = $"mermaid-diagram-{index}.png";
var tempDir = Path.Combine(Path.GetTempPath(), "confluence-publisher");
Directory.CreateDirectory(tempDir);
var inputPath = Path.Combine(tempDir, $"mermaid-{Guid.NewGuid()}.mmd");
var outputPath = Path.Combine(tempDir, outputFileName);
await File.WriteAllTextAsync(inputPath, code);
if (await RenderMermaidAsync(inputPath, outputPath))
{
attachments.Add(new AttachmentInfo(outputPath, outputFileName, true));
builder.Append($"");
index++;
}
else
{
_logger.Warn("Mermaid conversion failed; leaving code block untouched.");
builder.Append(match.Value);
}
}
builder.Append(markdown, lastIndex, markdown.Length - lastIndex);
return new MermaidConversionResult(builder.ToString(), attachments);
}
private async Task<bool> RenderMermaidAsync(string inputPath, string outputPath)
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = _mermaidCli,
Arguments = $"-i \"{inputPath}\" -o \"{outputPath}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = Process.Start(startInfo);
if (process == null)
{
_logger.Warn("Failed to start mermaid-cli process.");
return false;
}
var stdout = await process.StandardOutput.ReadToEndAsync();
var stderr = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
if (process.ExitCode != 0)
{
_logger.Warn($"mermaid-cli failed with exit code {process.ExitCode}: {stderr}");
return false;
}
if (!File.Exists(outputPath))
{
_logger.Warn("mermaid-cli reported success but output file is missing.");
return false;
}
if (!string.IsNullOrWhiteSpace(stdout))
{
_logger.Info(stdout.Trim());
}
return true;
}
catch (Exception ex)
{
_logger.Warn($"mermaid-cli error: {ex.Message}");
return false;
}
}
}
internal sealed class ConfluenceClient : IDisposable
{
private readonly HttpClient _httpClient;
private readonly Logger _logger;
public ConfluenceClient(Credentials credentials, Logger logger)
{
_logger = logger;
_httpClient = new HttpClient { BaseAddress = new Uri(credentials.BaseUrl.TrimEnd('/') + "/") };
var auth = Convert.ToBase64String(Encoding.UTF8.GetBytes($"{credentials.Username}:{credentials.ApiToken}"));
_httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", auth);
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<ConfluencePage?> GetPageByTitleAsync(string spaceKey, string title)
{
var url = $"rest/api/content?title={Uri.EscapeDataString(title)}&spaceKey={Uri.EscapeDataString(spaceKey)}&expand=version";
var response = await _httpClient.GetAsync(url);
var body = await response.Content.ReadAsStringAsync();
_logger.Info($"GET {url} -> {(int)response.StatusCode} {response.ReasonPhrase}");
if (!response.IsSuccessStatusCode)
{
_logger.Warn(body);
return null;
}
var result = JsonSerializer.Deserialize<ConfluenceSearchResult>(body);
return result?.Results?.FirstOrDefault();
}
public async Task<ConfluencePage> CreatePageAsync(string spaceKey, string title, string parentId, string bodyStorage)
{
var payload = new
{
type = "page",
title,
space = new { key = spaceKey },
ancestors = string.IsNullOrWhiteSpace(parentId) ? null : new[] { new { id = parentId } },
body = new
{
storage = new
{
value = bodyStorage,
representation = "storage"
}
}
};
var response = await _httpClient.PostAsync("rest/api/content", SerializeJson(payload));
var body = await response.Content.ReadAsStringAsync();
_logger.Info($"POST rest/api/content -> {(int)response.StatusCode} {response.ReasonPhrase}");
if (!response.IsSuccessStatusCode)
{
throw new InvalidOperationException($"Failed to create page: {body}");
}
return JsonSerializer.Deserialize<ConfluencePage>(body) ?? throw new InvalidOperationException("Missing create page response.");
}
public async Task<ConfluencePage> UpdatePageAsync(string pageId, string spaceKey, string title, string parentId, string bodyStorage)
{
var current = await GetPageByIdAsync(pageId);
if (current == null || current.Version == null)
{
throw new InvalidOperationException("Unable to retrieve current page version.");
}
var payload = new
{
id = pageId,
type = "page",
title,
space = new { key = spaceKey },
ancestors = string.IsNullOrWhiteSpace(parentId) ? null : new[] { new { id = parentId } },
version = new { number = current.Version.Number + 1 },
body = new
{
storage = new
{
value = bodyStorage,
representation = "storage"
}
}
};
var response = await _httpClient.PutAsync($"rest/api/content/{pageId}", SerializeJson(payload));
var body = await response.Content.ReadAsStringAsync();
_logger.Info($"PUT rest/api/content/{pageId} -> {(int)response.StatusCode} {response.ReasonPhrase}");
if (!response.IsSuccessStatusCode)
{
throw new InvalidOperationException($"Failed to update page: {body}");
}
return JsonSerializer.Deserialize<ConfluencePage>(body) ?? throw new InvalidOperationException("Missing update page response.");
}
public async Task UploadAttachmentAsync(string pageId, AttachmentInfo attachment)
{
_logger.Info($"Uploading attachment: {attachment.FileName}");
using var form = new MultipartFormDataContent();
using var fileStream = File.OpenRead(attachment.SourcePath);
var fileContent = new StreamContent(fileStream);
fileContent.Headers.ContentType = new MediaTypeHeaderValue(GetMimeType(attachment.SourcePath));
form.Add(fileContent, "file", attachment.FileName);
var request = new HttpRequestMessage(HttpMethod.Post, $"rest/api/content/{pageId}/child/attachment")
{
Content = form
};
request.Headers.Add("X-Atlassian-Token", "no-check");
var response = await _httpClient.SendAsync(request);
var body = await response.Content.ReadAsStringAsync();
_logger.Info($"POST rest/api/content/{pageId}/child/attachment -> {(int)response.StatusCode} {response.ReasonPhrase}");
if (!response.IsSuccessStatusCode)
{
_logger.Warn(body);
}
}
private async Task<ConfluencePage?> GetPageByIdAsync(string pageId)
{
var url = $"rest/api/content/{pageId}?expand=version";
var response = await _httpClient.GetAsync(url);
var body = await response.Content.ReadAsStringAsync();
_logger.Info($"GET {url} -> {(int)response.StatusCode} {response.ReasonPhrase}");
if (!response.IsSuccessStatusCode)
{
_logger.Warn(body);
return null;
}
return JsonSerializer.Deserialize<ConfluencePage>(body);
}
private static StringContent SerializeJson(object payload)
{
var json = JsonSerializer.Serialize(payload, new JsonSerializerOptions { DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull });
return new StringContent(json, Encoding.UTF8, "application/json");
}
private static string GetMimeType(string path)
{
var extension = Path.GetExtension(path).ToLowerInvariant();
return extension switch
{
".png" => "image/png",
".jpg" => "image/jpeg",
".jpeg" => "image/jpeg",
".gif" => "image/gif",
".svg" => "image/svg+xml",
".bmp" => "image/bmp",
".webp" => "image/webp",
_ => "application/octet-stream"
};
}
public void Dispose()
{
_httpClient.Dispose();
}
}
internal sealed class ConfluenceSearchResult
{
public List<ConfluencePage>? Results { get; set; }
}
internal sealed class ConfluencePage
{
public string Id { get; set; } = string.Empty;
public ConfluenceVersion? Version { get; set; }
}
internal sealed class ConfluenceVersion
{
public int Number { get; set; }
}