Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
458 lines (421 loc) · 16.7 KB
/
Copy pathProgram.cs
File metadata and controls
458 lines (421 loc) · 16.7 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
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
class Program
{
enum ConversionMode
{
Markdown,
BBCode,
Both // 新增双修模式
}
static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Console.OutputEncoding = Encoding.UTF8;
string filePath = GetFilePath(args);
if (!File.Exists(filePath))
{
Console.WriteLine("文件不存在,请检查路径是否正确");
return;
}
if (!IsValidHtmlFile(filePath))
{
Console.WriteLine("错误:只支持HTML文件(.html 或 .htm 后缀)");
Console.ReadKey();
return;
}
// 读取文件 (UTF-8)
string html = File.ReadAllText(filePath, Encoding.UTF8);
string fileNameNoExt = Path.GetFileNameWithoutExtension(filePath);
string fileDir = Path.GetDirectoryName(filePath) ?? "";
// 选择模式
ConversionMode mode = GetConversionMode();
try
{
// ---------------------------------------------------------
// 逻辑分支:双修模式 vs 单一模式
// ---------------------------------------------------------
if (mode == ConversionMode.Both)
{
Console.WriteLine("\n--- 开始双重转换 ---");
// 1. 处理 BBCode
string bbcode = ConvertHtmlToBBCode(html);
string bbPath = Path.Combine(fileDir, $"{fileNameNoExt}.bbcode");
File.WriteAllText(bbPath, bbcode, Encoding.UTF8);
Console.WriteLine($"[1/2] 文件已保存: {bbPath}");
// 2. 处理 Markdown
string markdown = ConvertHtmlToMarkdown(html);
string mdPath = Path.Combine(fileDir, $"{fileNameNoExt}.md");
File.WriteAllText(mdPath, markdown, Encoding.UTF8);
Console.WriteLine($"[2/2] 文件已保存: {mdPath}");
// 3. 剪贴板流程控制
Console.WriteLine("\n准备复制到剪贴板...");
// 第一步:复制 BBCode
if (CopyToClipboard(bbcode))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(">>> BBCode 已复制!快去 acg.rip 粘贴吧!");
Console.ResetColor();
}
else
{
Console.WriteLine(">>> BBCode 复制失败。");
}
// 等待用户操作
Console.WriteLine("\n--> 粘贴完成后,请按【任意键】继续复制 Markdown <--");
Console.ReadKey(true); // true 表示不回显按键字符
// 第二步:复制 Markdown
if (CopyToClipboard(markdown))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(">>> Markdown 已复制!");
Console.ResetColor();
}
else
{
Console.WriteLine(">>> Markdown 复制失败。");
}
}
else
{
// 单一模式(保持原有逻辑)
string result;
string extension;
if (mode == ConversionMode.Markdown)
{
result = ConvertHtmlToMarkdown(html);
extension = ".md";
}
else
{
result = ConvertHtmlToBBCode(html);
extension = ".bbcode";
}
string outputPath = Path.Combine(fileDir, $"{fileNameNoExt}{extension}");
File.WriteAllText(outputPath, result, Encoding.UTF8);
Console.WriteLine($"转换完成!输出文件:{outputPath}");
if (AskToCopyToClipboard())
{
if (CopyToClipboard(result)) Console.WriteLine("✓ 内容已复制到剪贴板");
else Console.WriteLine("✗ 复制到剪贴板失败");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"处理出错:{ex.Message}");
}
Console.WriteLine("\n全部完成,按任意键退出...");
Console.ReadKey();
}
// --- 辅助方法 ---
static string GetFilePath(string[] args)
{
if (args.Length > 0 && !string.IsNullOrWhiteSpace(args[0])) return args[0].Trim('"');
string filePath;
do
{
Console.Write("请拖入HTML文件或输入路径:");
filePath = Console.ReadLine()?.Trim().Trim('"') ?? "";
if (string.IsNullOrWhiteSpace(filePath)) Console.WriteLine("路径不能为空,请重新输入。");
} while (string.IsNullOrWhiteSpace(filePath));
return filePath;
}
static bool IsValidHtmlFile(string filePath)
{
string extension = Path.GetExtension(filePath).ToLower();
return extension == ".html" || extension == ".htm";
}
static ConversionMode GetConversionMode()
{
Console.WriteLine("\n请选择转换模式:");
Console.WriteLine("1. Markdown");
Console.WriteLine("2. BBCode");
Console.WriteLine("3. 双修模式 (同时生成,先复制BBCode -> 再复制MD)");
Console.Write("请输入选择 (默认双修):");
string input = Console.ReadLine()?.Trim() ?? "";
// 默认改为双修模式,因为这似乎是你最常用的
if (string.IsNullOrEmpty(input) || input == "3")
{
Console.WriteLine("选择了: 双修模式");
return ConversionMode.Both;
}
else if (input == "1")
{
Console.WriteLine("选择了: Markdown");
return ConversionMode.Markdown;
}
else if (input == "2")
{
Console.WriteLine("选择了: BBCode");
return ConversionMode.BBCode;
}
else
{
Console.WriteLine("无效输入,默认: 双修模式");
return ConversionMode.Both;
}
}
static bool AskToCopyToClipboard()
{
Console.Write("是否复制到剪贴板?(Y/n,默认为是):");
string input = Console.ReadLine()?.Trim().ToLower() ?? "";
return string.IsNullOrEmpty(input) || input == "y" || input == "yes";
}
static bool CopyToClipboard(string text)
{
try
{
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) return CopyToClipboardWindows(text);
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) return CopyToClipboardMacOS(text);
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) return CopyToClipboardLinux(text);
else return false;
}
catch (Exception ex)
{
Console.WriteLine($"复制失败:{ex.Message}");
return false;
}
}
// 保持使用临时文件法,解决乱码问题
static bool CopyToClipboardWindows(string text)
{
string tempFile = Path.GetTempFileName();
try
{
File.WriteAllText(tempFile, text, Encoding.UTF8);
var startInfo = new ProcessStartInfo
{
FileName = "powershell",
Arguments = $"-NoProfile -Command \"Get-Content -Path '{tempFile}' -Raw -Encoding UTF8 | Set-Clipboard\"",
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = Process.Start(startInfo))
{
process?.WaitForExit();
return process?.ExitCode == 0;
}
}
catch
{
return false;
}
finally
{
if (File.Exists(tempFile)) try { File.Delete(tempFile); } catch { }
}
}
static bool CopyToClipboardMacOS(string text)
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = "pbcopy",
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = Process.Start(startInfo))
{
if (process?.StandardInput != null)
{
using (var writer = process.StandardInput) { writer.Write(text); }
process.WaitForExit();
return process.ExitCode == 0;
}
}
return false;
}
catch { return false; }
}
static bool CopyToClipboardLinux(string text)
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = "xclip",
Arguments = "-selection clipboard",
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = Process.Start(startInfo))
{
if (process?.StandardInput != null)
{
using (var writer = process.StandardInput) { writer.Write(text); }
process.WaitForExit();
if (process.ExitCode == 0) return true;
}
}
}
catch { }
try
{
var startInfo = new ProcessStartInfo
{
FileName = "xsel",
Arguments = "--clipboard --input",
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = Process.Start(startInfo))
{
if (process?.StandardInput != null)
{
using (var writer = process.StandardInput) { writer.Write(text); }
process.WaitForExit();
return process.ExitCode == 0;
}
}
return false;
}
catch { return false; }
}
static string ConvertHtmlToMarkdown(string html)
{
var doc = new HtmlDocument();
doc.LoadHtml(html);
string markdown = ProcessNodeForMarkdown(doc.DocumentNode);
string[] lines = markdown.Split(new[] { '\n' }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++) lines[i] = lines[i].TrimStart();
return FormatMarkdownSpacing(string.Join("\n", lines));
}
static string ProcessNodeForMarkdown(HtmlNode node)
{
if (node.NodeType == HtmlNodeType.Document)
{
StringBuilder sbDoc = new StringBuilder();
foreach (var child in node.ChildNodes) sbDoc.Append(ProcessNodeForMarkdown(child));
return sbDoc.ToString();
}
if (node.NodeType == HtmlNodeType.Text)
{
string text = node.InnerText;
text = Regex.Replace(text, @"[ \t]+", " ").Replace("\n", " ");
// 列表转义修复
text = Regex.Replace(text, @"(\d+)\.(?=\s)", "$1\\.");
return text;
}
else if (node.NodeType == HtmlNodeType.Element)
{
StringBuilder sb = new StringBuilder();
foreach (var child in node.ChildNodes) sb.Append(ProcessNodeForMarkdown(child));
string innerContent = sb.ToString();
switch (node.Name.ToLower())
{
case "img": return $"})";
case "a":
string href = node.GetAttributeValue("href", "");
return href.StartsWith("http") ? $"[{innerContent}]({href})" : $"[]({href})";
case "br": return " \n";
case "strong": case "b": return $"**{innerContent}**";
case "em": case "i": return $"*{innerContent}*";
case "p":
string content = innerContent.Trim();
return string.IsNullOrEmpty(content) ? "\n" : content + " \n";
case "hr": return "\n* * *\n";
case "h1": return $"# {innerContent}\n";
case "h2": return $"## {innerContent}\n";
case "h3": return $"### {innerContent}\n";
case "h4": return $"#### {innerContent}\n";
case "h5": return $"##### {innerContent}\n";
case "h6": return $"###### {innerContent}\n";
default: return innerContent;
}
}
return "";
}
static string FormatMarkdownSpacing(string markdown)
{
if (string.IsNullOrWhiteSpace(markdown)) return markdown;
string[] lines = markdown.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
int startIndex = 0;
while (startIndex < lines.Length && string.IsNullOrWhiteSpace(lines[startIndex])) startIndex++;
if (startIndex >= lines.Length) return string.Empty;
int endIndex = lines.Length - 1;
while (endIndex >= 0 && string.IsNullOrWhiteSpace(lines[endIndex])) endIndex--;
var formattedLines = new List<string>();
for (int i = startIndex; i <= endIndex; i++)
{
string line = lines[i];
if (line.Trim() == "* * *")
{
if (formattedLines.Count > 0 && !string.IsNullOrWhiteSpace(formattedLines[formattedLines.Count - 1]))
{ formattedLines.Add(""); formattedLines.Add(""); }
else if (formattedLines.Count > 0 && string.IsNullOrWhiteSpace(formattedLines[formattedLines.Count - 1]))
{ formattedLines.Add(""); }
formattedLines.Add(line);
if (i < endIndex) formattedLines.Add("");
}
else if (line.Contains("_") && line.Contains("Source") && line.Contains("Encode"))
{
formattedLines.Add(line);
if (i < endIndex) formattedLines.Add("");
}
else formattedLines.Add(line);
}
return string.Join("\n", formattedLines);
}
static string ConvertHtmlToBBCode(string html)
{
var doc = new HtmlDocument();
doc.LoadHtml(html);
string bbcode = ProcessNodeForBBCode(doc.DocumentNode);
string[] lines = bbcode.Split(new[] { '\n' }, StringSplitOptions.None);
for (int i = 0; i < lines.Length; i++) lines[i] = lines[i].TrimStart();
return FormatBBCodeSpacing(string.Join("\n", lines));
}
static string ProcessNodeForBBCode(HtmlNode node)
{
if (node.NodeType == HtmlNodeType.Document)
{
StringBuilder sbDoc = new StringBuilder();
foreach (var child in node.ChildNodes) sbDoc.Append(ProcessNodeForBBCode(child));
return sbDoc.ToString();
}
if (node.NodeType == HtmlNodeType.Text)
{
string text = node.InnerText;
return Regex.Replace(text, @"[ \t]+", " ").Replace("\n", " ");
}
else if (node.NodeType == HtmlNodeType.Element)
{
StringBuilder sb = new StringBuilder();
foreach (var child in node.ChildNodes) sb.Append(ProcessNodeForBBCode(child));
string innerContent = sb.ToString();
switch (node.Name.ToLower())
{
case "img": return $"[img]{node.GetAttributeValue("src", "")}[/img]";
case "a": return $"[url={node.GetAttributeValue("href", "")}]{innerContent}[/url]";
case "br": return "\n";
case "strong": return $"[b]{innerContent}[/b]";
case "p": return "\n" + innerContent.Trim() + "\n";
case "hr": return "";
default: return innerContent;
}
}
return "";
}
static string FormatBBCodeSpacing(string bbcode)
{
if (string.IsNullOrWhiteSpace(bbcode)) return bbcode;
string[] lines = bbcode.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.None);
int startIndex = 0;
while (startIndex < lines.Length && string.IsNullOrWhiteSpace(lines[startIndex])) startIndex++;
if (startIndex >= lines.Length) return string.Empty;
int endIndex = lines.Length - 1;
while (endIndex >= 0 && string.IsNullOrWhiteSpace(lines[endIndex])) endIndex--;
var formattedLines = new List<string>();
for (int i = startIndex; i <= endIndex; i++) formattedLines.Add(lines[i]);
formattedLines.Add("");
return string.Join(Environment.NewLine, formattedLines);
}
}