1+ using System ;
2+ using System . Collections . Generic ;
3+ using System . ComponentModel . DataAnnotations ;
4+ using System . IO ;
5+ using System . Linq ;
6+ using Dotnetcnblog . TagHandlers ;
7+ using Dotnetcnblog . Utils ;
8+ using McMaster . Extensions . CommandLineUtils ;
9+ using Console = Colorful . Console ;
10+
11+ namespace Dotnetcnblog . Command
12+ {
13+ [ Command ( Name = "proc" , Description = "处理文件" ) ]
14+ public class CommandProcessFile : ICommand
15+ {
16+ private static readonly Dictionary < string , string > ReplaceDic = new Dictionary < string , string > ( ) ;
17+
18+
19+ [ Option ( "-f|--file" , Description = "需要处理的文件路径" ) ]
20+ [ Required ]
21+ public string FilePath { get ; set ; }
22+
23+ public int OnExecute ( CommandLineApplication app )
24+ {
25+ if ( app . Options . Count == 1 && app . Options [ 0 ] . ShortName == "h" )
26+ {
27+ app . ShowHelp ( ) ;
28+ }
29+
30+ Execute ( CommandContextStore . Get ( ) ) ;
31+ return 0 ;
32+ }
33+
34+ public void Execute ( CommandContext context )
35+ {
36+ try
37+ {
38+ if ( ! File . Exists ( FilePath ) )
39+ {
40+ ConsoleHelper . PrintError ( $ "文件不存在:{ FilePath } ") ;
41+ }
42+ else
43+ {
44+ var fileDir = new FileInfo ( FilePath ) . DirectoryName ;
45+ var fileContent = File . ReadAllText ( FilePath ) ;
46+ var imgHandler = new ImageHandler ( ) ;
47+ var imgList = imgHandler . Process ( fileContent ) ;
48+
49+ ConsoleHelper . PrintMsg ( $ "提取图片成功,共 { imgList . Count } 个。") ;
50+
51+ //循环上传图片
52+ foreach ( var img in imgList )
53+ {
54+ if ( img . StartsWith ( "http" ) )
55+ {
56+ ConsoleHelper . PrintMsg ( $ "图片跳过:{ img } ") ;
57+ continue ;
58+ }
59+
60+ try
61+ {
62+ var imgPhyPath = Path . Combine ( fileDir ! , img ) ;
63+ if ( File . Exists ( imgPhyPath ) )
64+ {
65+ var imgUrl = ImageUploadHelper . Upload ( imgPhyPath ) ;
66+ if ( ! ReplaceDic . ContainsKey ( img ) ) ReplaceDic . Add ( img , imgUrl ) ;
67+ ConsoleHelper . PrintMsg ( $ "{ img } 上传成功. { imgUrl } ") ;
68+ }
69+ else
70+ {
71+ ConsoleHelper . PrintMsg ( $ "{ img } 未发现文件.") ;
72+ }
73+ }
74+ catch ( Exception e )
75+ {
76+ Console . WriteLine ( e . Message ) ;
77+ }
78+ }
79+
80+ //替换
81+ fileContent = ReplaceDic . Keys . Aggregate ( fileContent , ( current , key ) => current . Replace ( key , ReplaceDic [ key ] ) ) ;
82+
83+ var newFileName = FilePath . Substring ( 0 , FilePath . LastIndexOf ( '.' ) ) + "-cnblog" + Path . GetExtension ( FilePath ) ;
84+ File . WriteAllText ( newFileName , fileContent , FileEncodingType . GetType ( FilePath ) ) ;
85+
86+ ConsoleHelper . PrintMsg ( $ "处理完成!文件保存在:{ newFileName } ") ;
87+ }
88+ }
89+ catch ( Exception e )
90+ {
91+ ConsoleHelper . PrintError ( e . Message ) ;
92+ }
93+ }
94+ }
95+ }
0 commit comments