프로젝트

일반

사용자정보

통계
| 브랜치(Branch): | 개정판:

markus / DownloadManager / Program.cs @ 6a19b48d

이력 | 보기 | 이력해설 | 다운로드 (13.3 KB)

1

2
using log4net;
3
using RestSharp;
4
using System;
5
using System.Diagnostics;
6
using System.IO;
7
using System.Linq;
8
using System.Net.Http;
9
using System.Net.Http.Headers;
10
using System.Threading.Tasks;
11

    
12
namespace DownloadManager
13
{
14
    class Program
15
    {
16
        private static ILog logger = LogManager.GetLogger(typeof(Program));
17

    
18
        private static string TEMP_FOLDER = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "MARKUS");
19

    
20
        static IIpc.WcfClient wcfClient;
21
        static bool IsDownload;
22
        static bool IsDebug;
23
        static int TotalPages = 0;
24

    
25
        //private const string SECTION_DOWNLOAD_FILE = "DOWNLOAD_FILE";
26

    
27
        //private const string SECTION_DOWNLOAD_DIR = "DOWNLOAD_DIR";
28

    
29
        //private const string KEY_VALUES = "VALUE";
30

    
31

    
32
        //private static string DOWNLOAD_LOG_FILE = System.IO.Path.Combine(TEMP_FOLDER, "Download.log");
33

    
34
        //private static ConfigParser DOWNLOAD_LOG = new ConfigParser(DOWNLOAD_LOG_FILE,
35
        //                                            new ConfigParserSettings
36
        //                                            {
37
        //                                                MultiLineValues = MultiLineValues.Simple | MultiLineValues.AllowValuelessKeys | MultiLineValues.QuoteDelimitedValues,
38
        //                                                Culture = new CultureInfo("en-US")
39
        //                                            });
40

    
41
        private static void ChangeLogFileName(string name)
42
        {
43
            log4net.Repository.ILoggerRepository RootRep;
44
            RootRep = logger.Logger.Repository;// LogManager.GetRepository(Assembly.GetCallingAssembly());
45

    
46
            if (RootRep?.GetAppenders().Count() > 0)
47
            {
48
                (RootRep.GetAppenders().First() as log4net.Appender.RollingFileAppender).File = string.Format((RootRep.GetAppenders().First() as log4net.Appender.RollingFileAppender).File, name);
49
                (RootRep.GetAppenders().First() as log4net.Appender.RollingFileAppender).ActivateOptions();
50
            }
51
        }
52

    
53
        static void Main(string[] args)
54
        {
55
            try
56
            {
57
                ChangeLogFileName($"{DateTime.Now.ToString("yyMMddssmm")}_{args[0]}");
58

    
59
                logger.Info($"param : {string.Join(",", args)}");
60

    
61
                if (args.Length > 0)
62
                {
63
                    for (int i = 0; i < args.Length; i++)
64
                    {
65
                        ConsoleWrite(args[i]);
66
                    }
67

    
68
                    //if (args[0] == IIpc.ProcessTypeDefine.DEFINE_DELETE)
69
                    //{
70
                    //    IsDebug = bool.Parse(args[1]);
71

    
72
                    //    DeleteFiles();
73
                    //}
74
                    if (args[0] == IIpc.ProcessTypeDefine.DEFINE_MONITOR)
75
                    {
76
                        IsDebug = bool.Parse(args[1]);
77
                        int processId = int.Parse(args[2]); /// kcom process id
78
                        int thumbnamilPID = int.Parse(args[3]);
79
                        int filePID = int.Parse(args[4]);
80

    
81
                        string folder1 = args[5];              // folder
82
                        string folder2 = args[6];              // folder
83
                        string file = args[7];              // file
84

    
85
                        string baseUri = args[8];              // uri
86

    
87
                        CheckAutoUpdate.Validation(baseUri);
88

    
89
                        try
90
                        {
91
                            Process process = FindProcess(processId);
92

    
93
                            while (process != null)
94
                            {
95
                                process = FindProcess(processId);
96

    
97
                                ConsoleWrite("Process Check");
98

    
99
                                System.Threading.Thread.Sleep(10000);
100
                            }
101

    
102
                            var p1 = FindProcess(thumbnamilPID);
103

    
104
                            if (p1 != null)
105
                            {
106
                                p1.Kill();
107
                            }
108

    
109

    
110
                            var p2 = FindProcess(filePID);
111

    
112
                            if (p2 != null)
113
                            {
114
                                p2.Kill();
115
                            }
116
                        }
117
                        catch (Exception ex)
118
                        {
119
                            ConsoleWrite(ex.ToString());
120
                        }
121

    
122
                        DeleteFiles(IIpc.ProcessTypeDefine.DEFINE_THUMBNAIL, folder1);
123
                        DeleteFiles(IIpc.ProcessTypeDefine.DEFINE_THUMBNAIL, folder2);
124
                        DeleteFiles(IIpc.ProcessTypeDefine.DEFINE_FILE, file);
125
                    }
126
                    else
127
                    {
128
                        wcfClient = new IIpc.WcfClient(args[1]);
129
                        IsDebug = bool.Parse(args[2]);
130

    
131
                        if (args[0] == IIpc.ProcessTypeDefine.DEFINE_THUMBNAIL)
132
                        {
133
                            string BaseUri = args[3];
134
                            string localStoragePath = args[4];
135
                            string fileExt = args[5];
136
                            int totalPages = int.Parse(args[6]);
137
                            int takeCount = int.Parse(args[6]);
138

    
139
                            TotalPages = totalPages;
140

    
141
                            KCOM.PageManager.PageStorage pageStorage = new KCOM.PageManager.PageStorage(BaseUri, localStoragePath, fileExt, totalPages, takeCount);
142
                            pageStorage.PageLoadCompleted += PageStorage_PageLoadCompleted;
143
                            pageStorage.DownloadWork(1, totalPages);
144
                        }
145
                        else if (args[0] == IIpc.ProcessTypeDefine.DEFINE_FILE)
146
                        {
147
                            using (System.Net.WebClient client = new System.Net.WebClient())
148
                            {
149
                                client.DownloadFileCompleted += Client_DownloadFileCompleted;
150
                                client.DownloadProgressChanged += Client_DownloadProgressChanged;
151
                                client.UseDefaultCredentials = true;
152
                                System.Net.IWebProxy webProxy = client.Proxy;
153

    
154
                                if (webProxy != null)
155
                                {
156
                                    webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
157
                                }
158

    
159
                                client.DownloadFileAsync(new Uri(System.Web.HttpUtility.UrlDecode(args[3])), args[4]);
160
                            }
161
                        }
162
                        else if (args[0] == IIpc.ProcessTypeDefine.DEFINE_REST_FILE)
163
                        {
164
                            var result = RestDownloadAsync(System.Web.HttpUtility.UrlDecode(args[3]), args[4]).GetAwaiter().GetResult();
165

    
166
                            if (!IsDebug)
167
                                wcfClient.SendFileDownloadReceived(100, true);
168

    
169
                            ConsoleWrite($"Download stream {args[4]} Completed");
170
                            IsDownload = result;
171

    
172
                            //var client = new RestClient(System.Web.HttpUtility.UrlDecode(args[3]));
173
                            //client.Timeout = -1;
174
                            //var request = new RestRequest(Method.GET);
175
                            //IRestResponse response = client.Execute(request);
176

    
177
                            //var fileInfo = new FileInfo(args[4]);
178

    
179
                            //using (var fileStream = fileInfo.OpenWrite())
180
                            //{
181
                            //    int position = 0;
182
                            //    int step = 300000;
183
                            //    int length = 300000;
184

    
185
                            //    while (position < response.RawBytes.Length)
186
                            //    {
187
                            //        if (position + step < response.RawBytes.Length)
188
                            //        {
189
                            //            length = position + step;
190
                            //        }
191
                            //        else
192
                            //        {
193
                            //            length = response.RawBytes.Length - position;
194
                            //        }
195

    
196
                            //        fileStream.Write(response.RawBytes, position, length);
197

    
198
                            //        position = position + step;
199
                            //    }
200

    
201
                            //    if (!IsDebug)
202
                            //        wcfClient.SendFileDownloadReceived(100, true);
203

    
204
                            //    ConsoleWrite($"Download stream {args[4]} Completed");
205
                            //    IsDownload = true;
206
                            //}
207
                        }
208

    
209
                        while (!IsDownload)
210
                        {
211
                            System.Threading.Thread.Sleep(1000);
212
                        }
213

    
214
                    }
215

    
216
                    if (IsDebug)
217
                    {
218
                        Console.ReadLine();
219
                    }
220
                }
221
            }
222
            catch (Exception ex)
223
            {
224
                logger.Error($"param : {string.Join(",", args)}", ex);
225
                System.Diagnostics.Debug.WriteLine(ex);
226
            }
227
        }
228

    
229
        private static async Task<bool> RestDownloadAsync(string uri, string savePath)
230
        {
231
            bool result = false;
232

    
233
            try
234
            {
235
                var client = new RestClient(uri);
236
                client.Timeout = -1;
237
                var request = new RestRequest(Method.GET);
238
                IRestResponse response = await client.ExecuteAsync(request);
239

    
240
                if (response.StatusCode == System.Net.HttpStatusCode.OK)
241
                {
242
                    var fs = File.Create(savePath);
243

    
244
                    await fs.WriteAsync(response.RawBytes, 0, response.RawBytes.Length);
245
                    fs.Close();
246
                    result = true;
247
                }
248
            }
249
            catch (Exception ex)
250
            {
251
                logger.Error($"RestDownloadAsync : {uri} {savePath}", ex);
252
            }
253
            return result;
254
        }
255

    
256
        public static void DeleteFiles(string processType, string path)
257
        {
258
            try
259
            {
260
                logger.Info($"DeleteFiles Info {processType} {path}");
261

    
262
                if (processType == IIpc.ProcessTypeDefine.DEFINE_THUMBNAIL)
263
                {
264
                    var dir = System.IO.Directory.GetDirectories(path, "*.*", System.IO.SearchOption.AllDirectories);
265

    
266
                    for (int i = 0; i < dir.Length; i++)
267
                    {
268
                        System.IO.Directory.Delete(dir[i], true);
269
                    }
270
                }
271
                else
272
                {
273
                    if (System.IO.File.Exists(path))
274
                    {
275
                        System.IO.File.Delete(path);
276
                    }
277
                }
278
            }
279
            catch (Exception ex)
280
            {
281
                logger.Error($"DeleteFiles Error {processType} {path}", ex);
282
                System.Diagnostics.Debug.WriteLine(ex);
283
            }
284
        
285
        }
286

    
287
        private static Process FindProcess(int id)
288
        {
289
            Process result = null;
290

    
291
            try
292
            {
293
                var process = Process.GetProcesses().Where(x=>x.Id == id);
294
                
295
                if(process.Count()> 0)
296
                {
297
                    result = process.First();
298
                }
299
            }
300
            catch (Exception ex)
301
            {
302
                logger.Error($"FindProcess Error {id}", ex);
303
                System.Diagnostics.Debug.WriteLine(ex);
304
            }
305

    
306
            return result;
307
        }
308

    
309

    
310
        private static void ConsoleWrite(string data)
311
        {
312
            logger.Info(data);
313

    
314
            if (IsDebug)
315
            {
316
                Console.WriteLine(data);
317
            }
318
        }
319

    
320

    
321
        private static void Client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
322
        {
323
            try
324
            {
325
                wcfClient.SendFileDownloadReceived(100, true);
326

    
327
                ConsoleWrite($"Download file Completed");
328
                IsDownload = true;
329
            }
330
            catch (Exception ex)
331
            {
332
                ConsoleWrite(ex.ToString());
333
            }
334
        }
335

    
336
        private static void Client_DownloadProgressChanged(object sender, System.Net.DownloadProgressChangedEventArgs e)
337
        {
338
            try
339
            {
340
                wcfClient.SendFileDownloadReceived(e.ProgressPercentage, false);
341

    
342
                ConsoleWrite($"Download file {e.ProgressPercentage}");
343
            }
344
            catch (Exception ex)
345
            {
346
                ConsoleWrite(ex.ToString());
347
            }
348
        }
349

    
350
        private static void PageStorage_PageLoadCompleted(object sender, KCOM.PageManager.PageLoadCompletedEventArgs e)
351
        {
352
            try
353
            {
354
                wcfClient.SendThumbnailReceived(e.PageItem.PageNo, e.PageItem.LocalFilePath,e.IsLast);
355

    
356
                ConsoleWrite($"{e.PageItem.PageNo} {e.PageItem.LocalUri}");
357

    
358
                if (e.PageItem.PageNo == TotalPages)
359
                {
360
                    IsDownload = true;
361
                }
362
            }
363
            catch (Exception ex)
364
            {
365
                ConsoleWrite(ex.ToString());
366
            }
367
            
368
        }
369
    }
370
}
클립보드 이미지 추가 (최대 크기: 500 MB)