프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ 504c5aa1

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

1
using log4net;
2
using Markus.Message;
3
using Markus.Service.Helper;
4
using Markus.Service.Interface;
5
using System;
6
using System.Collections.Generic;
7
using System.IO;
8
using System.Linq;
9
using System.Net.Http;
10
using System.ServiceModel;
11
using System.Text;
12
using Markus.Service.Extensions;
13
using Markus.Service.WcfClient.StationServiceAsync;
14

    
15
using System.Threading.Tasks;
16
using System.Web;
17

    
18
namespace Markus.Service.Convert
19
{
20
    public class ConvertService : IDisposable
21
    {
22
        // 1GigaBytes
23
        protected ILog logger;
24

    
25
        readonly ProcessContext ConvertProcessContext;
26
        private string gTempFileName;
27
        private Markus.SaveTask gSaveTask;
28
        private Markus.MarkusPDF gMarkusPDF;
29

    
30
        // 컨버터 완료시 파일갯수를 체크 하여 틀리면 reconvert를 1로 하고 다시 컨버팅 하도록 한다.
31
        private int ReConvert;
32

    
33

    
34
        private StationServiceClient StationServiceClient; 
35

    
36
        /// <summary>
37
        /// 프로세스 초기화
38
        /// </summary>
39
        /// <param name="convertContext"></param>
40
        public ConvertService(ProcessContext convertContext) : base()
41
        {
42
            logger = LogManager.GetLogger(typeof(ConvertService));
43

    
44
            ConvertProcessContext = convertContext;
45
            
46
            BasicHttpBinding myBinding = new BasicHttpBinding();
47
            EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(ConvertProcessContext.ServiceStationUri));
48
            StationServiceClient = new StationServiceClient(myBinding, myEndpoint);
49
           
50
            gMarkusPDF = new MarkusPDF();
51
            gSaveTask = new SaveTask();
52
            gSaveTask.StateChangeEvent += MarkusPdfStateChangeEvent;
53
        }
54

    
55
        public ConvertService()
56
        {
57
        }
58

    
59
        public void Dispose()
60
        {
61
            try
62
            {
63
                if(gMarkusPDF != null)
64
                {
65
                    gMarkusPDF.Dispose();
66
                    gMarkusPDF = null;
67
                }
68

    
69
                if (gSaveTask != null)
70
                {
71
                    gSaveTask.StateChangeEvent -= MarkusPdfStateChangeEvent;
72
                    gSaveTask.Dispose();
73
                    gSaveTask = null;
74
                }
75

    
76
                //if (System.IO.File.Exists(gTempFileName))
77
                //{
78
                //    File.Delete(gTempFileName);
79
                //}
80

    
81
            }
82
            catch (Exception ex)
83
            {
84
               logger.Error("Convert Service Dispose Error", ex);
85
            }
86
            finally
87
            {
88
                GC.Collect(2);
89
                GC.Collect(2);
90
            }
91
        }
92

    
93
        /// <summary>
94
        ///  markus lib에서 받는 이벤트
95
        /// </summary>
96
        /// <param name="sender"></param>
97
        /// <param name="e"></param>
98
        private void MarkusPdfStateChangeEvent(object sender, Markus.Message.StateEventArgs e)
99
        {
100
            try
101
            {
102
                int currentPage = e.SaveItem.CurrentPage;
103

    
104
                if (e.SaveItem.CurrentPage == 0)    /// 초기 wait status인 경우 0일수 있다. %계산시 오류 방지
105
                {
106
                    currentPage = 1;
107
                }
108

    
109
                switch (e.SaveItem.Status)
110
                {
111
                    case StatusCodeType.None:
112
                        break;
113
                    case StatusCodeType.Wait:
114
                        break;
115
                    case StatusCodeType.PageLoading:
116
                        break;
117
                    case StatusCodeType.Saving:
118
                        break;
119
                    case StatusCodeType.Completed:
120
                        break;
121
                    case StatusCodeType.FileError:
122
                        break;
123
                    case StatusCodeType.PageError:
124
                        break;
125
                    case StatusCodeType.NeedsPassword:
126
                        break;
127
                    case StatusCodeType.Error:
128
                        break;
129
                    default:
130
                        break;
131
                }
132

    
133
                StationServiceClient.ConvertProcessStateAsync(e.SaveItem.Id, (int)e.SaveItem.Status, e.SaveItem.CurrentPage, e.SaveItem.TotalPages, e.SaveItem.ErrorMessage);
134
                
135
            }
136
            catch (Exception ex)
137
            {
138
                logger.Error($"Status Change Error", ex);
139
            }
140
        }
141

    
142
        [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
143
        public async Task<SaveResult> SetFileAsync()
144
        {
145
            SaveResult result = new SaveResult();
146

    
147
            SaveItem saveitem = new SaveItem
148
            {
149
                Id = ConvertProcessContext.ConvertID,
150
                PdfFilePath = ConvertProcessContext.OriginFilePath,
151
                SavePath = ConvertProcessContext.SaveDirectory,
152
                Status = StatusCodeType.None,
153
                MinimumFontSize = ConvertProcessContext.MinFontSize,
154
                UseResolution = ConvertProcessContext.UseResolution
155
            };
156

    
157
            try
158
            {
159
                StationServiceClient.ConvertProcessState(ConvertProcessContext.ConvertID, (int)StatusCodeType.Wait, 0, 0, "");
160

    
161
                result = await ConvertAsync(saveitem);
162

    
163
                // 플러그인 실행
164
                PluginService.Run(saveitem.Id);
165

    
166
                this.Dispose();
167

    
168
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages,result.Message);
169
            }
170
            catch (Exception ex)
171
            {
172
                result.StatusCode = StatusCodeType.Error;
173
                logger.Error($"File Convert Error",ex);
174
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages, $"ConvertService Error    {saveitem.Id} {ex.Message} {ex.InnerException?.ToString()}");
175
            }
176

    
177
            return result;
178
        }
179

    
180
        [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
181
        private async Task<SaveResult> ConvertAsync(SaveItem saveitem)
182
        { 
183
            SaveResult result = new SaveResult();
184
         
185
            try
186
            {
187
                DateTime deleteTime = DateTime.Now;
188

    
189
                while (System.IO.Directory.Exists(saveitem.SavePath))
190
                {
191
                    try
192
                    {
193
                        System.IO.Directory.Delete(saveitem.SavePath, true);
194
                    }
195
                    catch (Exception)
196
                    {
197

    
198
                    }
199

    
200
                    if ((DateTime.Now - deleteTime) > new TimeSpan(0, 5, 0))
201
                    {
202
                        string msg = $"ConvertService Error {saveitem.SavePath} Delete Error";
203
                        logger.Error(msg);
204
                        result.StatusCode = StatusCodeType.FileError;
205
                        result.Message =  LogHelper.GetStack() + " " +LogHelper.GetStack() + " " + msg;
206

    
207
                        return result;
208
                    }
209

    
210
                    System.Threading.Thread.SpinWait(10);
211
                }
212

    
213
                System.IO.Directory.CreateDirectory(saveitem.SavePath);
214

    
215
                //파일 다운로드
216
                if (await DownloadFileAsync(saveitem))
217
                {
218
                    gTempFileName = saveitem.PdfFilePath;
219

    
220
                    gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
221

    
222
                    if(gMarkusPDF.PageCount() > 0)
223
                    {
224
                        /// 설정된 MultiThreadMaxPages에 따른 컨버터 분기
225
                        if (gMarkusPDF.PageCount() > ConvertProcessContext.MultiThreadMaxPages)
226
                        {
227
                            // 큰 사이즈의 파일 컨버팅
228
                            result = ConvertBigFileProcess(saveitem);
229
                        }
230
                        else
231
                        {
232
                            /// 작은 사이즈의 컨버팅
233
                            await Task.Factory.StartNew(new Action(() =>
234
                            {
235
                                result = gSaveTask.SaveFile(saveitem);
236
                            }), TaskCreationOptions.LongRunning);
237
                        }
238

    
239
                        // 파일 체크 후 갯수가 안맞으면 다시 컨버팅한다.
240
                        if (ReConvert < 1 && (result.PageInfoList.Count() != saveitem.TotalPages
241
                                       || Directory.EnumerateFiles(saveitem.SavePath, "*.png").Count() != saveitem.TotalPages
242
                                           || Directory.EnumerateFiles(saveitem.SavePath, "*.jpg").Count() != saveitem.TotalPages))
243
                        {
244
                            result.StatusCode = StatusCodeType.PageError;
245
                            result.Message =  LogHelper.GetStack() + " " +"Page Count Error";
246
                            ReConvert = 1;
247

    
248
                            result = ConvertBigFileProcess(saveitem);
249
                        }
250

    
251

    
252
                        ///  페이지 정보 저장
253
                        if (result.PageInfoList?.Count() > 0)
254
                        {
255
                            bool docSetResult = false;
256

    
257
                            using (Markus.Service.DataBase.ConvertDatabase database = new Markus.Service.DataBase.ConvertDatabase(ConvertProcessContext.ConnectionString))
258
                            {
259
                                List<EntityModel.DOCPAGE> docPageList = new List<EntityModel.DOCPAGE>();
260

    
261
                                docPageList = result.PageInfoList.Select(f => new EntityModel.DOCPAGE
262
                                {
263
                                    ID = GuidExtension.shortGuid(),
264
                                    PAGE_WIDTH = f.Width.ToString(),
265
                                    PAGE_HEIGHT = f.Height.ToString(),
266
                                    PAGE_NUMBER = f.PageNo
267
                                }).ToList();
268

    
269
                                docSetResult = database.SetDocumentInfo(saveitem.Id, result.PageInfoList.Count, docPageList);
270
                            }
271

    
272
                            if (docSetResult)
273
                            {
274
                                result.StatusCode = StatusCodeType.Completed;
275
                            }
276
                            else
277
                            {
278
                                result.StatusCode = StatusCodeType.FileError;
279
                                result.Message = LogHelper.GetStack() + " " + $"Doc Set Error. {result.Message}";
280
                            }
281
                        }
282
                        else
283
                        {
284
                            result.StatusCode = StatusCodeType.FileError;
285
                            result.Message = LogHelper.GetStack() + " " + $"Page List Get Error. {result.Message} ";
286
                        }
287
                    }
288
                    else
289
                    {
290
                        result.Message = $"File Error Page Count:0 - File path : { saveitem.PdfFilePath}";
291
                        result.StatusCode = StatusCodeType.FileError;
292
                    }
293

    
294
                }
295
                else
296
                {
297
                    result.Message  = $"File Download Error  - File path : { saveitem.PdfFilePath}";
298
                    result.StatusCode = StatusCodeType.FileError;
299
                }
300
            }
301
            catch (Exception ex)
302
            {
303
                result.Message =  LogHelper.GetStack() + " " +"ConvertService Convert Error" + ex.Message;
304
                result.StatusCode = StatusCodeType.Error;
305

    
306
                logger.Error(ex);
307
            }
308
            finally
309
            {
310

    
311
            }
312

    
313
            return result;
314
        }
315

    
316
        /// <summary>
317
        /// 파일 다운로드
318
        /// </summary>
319
        /// <param name="saveItem"></param>
320
        /// <returns></returns>
321
        public async Task<bool> DownloadFileAsync(SaveItem saveItem)
322
        {
323
            bool result = false;
324

    
325
            try
326
            {
327
                Uri pdfFileUri = null;
328

    
329
                //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB"))
330
                //{
331
                //    FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
332
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
333
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
334
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
335
                //    DownloadFilePath = ItemPath + "\\" + FileName;
336
                //}
337
                //else
338
                //{
339
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
340
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
341
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
342
                //    FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName");
343
                //    DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName;
344

    
345
                //}
346

    
347
                saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
348

    
349

    
350
                string FileName = "";
351
                string downloadFilePath = "";
352

    
353
                // 드라이브 경로가 포함되었는지 판단.
354
                if (Path.IsPathRooted(saveItem.PdfFilePath))
355
                {
356
                    FileInfo file = new FileInfo(saveItem.PdfFilePath);
357

    
358
                    if (file.Exists)
359
                    {
360
                        FileName = file.Name;
361
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
362
                        file.CopyTo(downloadFilePath, true);
363
                    }
364
                    else
365
                    {
366
                        throw new Exception("File Not Found. Please, check the file path.");
367
                    }
368
                }
369
                else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
370
                {
371
                    try
372
                    {
373
                        FileName = DownloadUri.GetFileName(saveItem.PdfFilePath);
374
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
375

    
376
                        using (System.Net.WebClient webClient = new System.Net.WebClient())
377
                        {
378
                            webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
379
                            webClient.Proxy = null;
380
                            //if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
381
                            //{
382
                            //    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
383
                            //}
384

    
385
                            await webClient.DownloadFileTaskAsync(pdfFileUri, downloadFilePath);
386
                            webClient.Dispose();
387
                        }
388

    
389
                        await Task.Delay(300);
390
                    }
391
                    catch (Exception ex)
392
                    {
393
                        logger.Error(ex);
394
                        throw new Exception("File Download Error. Please, check the file path.");
395
                    }
396
                }
397
                else
398
                {
399
                    throw new Exception("Please, check the file path.");
400
                }
401

    
402
                try
403
                {
404
                    if (File.Exists(downloadFilePath))
405
                    {
406
                        var file = File.Open(downloadFilePath, FileMode.Open);
407

    
408
                        if (file.Length == 0)
409
                        {
410
                            throw new Exception("File Size 0. Please, check the file path.");
411
                        }
412

    
413
                        file.Close();
414
                        file.Dispose();
415

    
416
                        saveItem.PdfFilePath = downloadFilePath;
417
                        result = true;
418

    
419
                    }
420
                }
421
                catch (Exception ex)
422
                {
423
                    logger.Error(ex);
424
                    throw new Exception("File Error ." + downloadFilePath);
425
                }
426
            }
427
            catch (Exception ex)
428
            {
429
                logger.Error(ex);
430
                throw new Exception(ex.ToString());
431
            }
432

    
433
            return result;
434
        }
435

    
436
        /// <summary>
437
        /// 큰파일 변환
438
        /// </summary>
439
        /// <param name="saveitem"></param>
440
        /// <returns></returns>
441
        private SaveResult ConvertBigFileProcess(SaveItem saveitem)
442
        {
443
            SaveResult result = new SaveResult();
444

    
445
            try
446
            {
447
                saveitem.TotalPages = gMarkusPDF.PageCount();
448

    
449
                for (int currentPageNo = 1; currentPageNo <= saveitem.TotalPages; currentPageNo++)
450
                {
451
                    try
452
                    {
453
                        string saveFile = Path.Combine(saveitem.SavePath, $"{currentPageNo}.png");
454

    
455
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
456
                         {
457

    
458
                            var saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
459

    
460
                            saveitem.Status = StatusCodeType.Saving;
461
                            saveitem.CurrentPage = currentPageNo;
462
                            saveitem.ErrorMessage = saveResult.Message;
463

    
464
                            int pageListCount = 0;
465

    
466
                            if(result.PageInfoList != null)
467
                            {
468
                                pageListCount = result.PageInfoList.Count(f => f.PageNo == saveResult.SavePageInfo.PageNo);
469
                            }
470
                            
471
                            if (pageListCount == 0)
472
                            {
473
                                result.PageInfoAdd(saveResult.SavePageInfo);
474
                            }
475

    
476
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(saveitem));
477
                            Console.WriteLine($"CurrentPage : {currentPageNo}");
478

    
479
                            /// 설정된 최대 페이지이거나 설정된 메모리보다 크면 릴리즈
480
                            if (currentPageNo % ConvertProcessContext.MultiThreadMaxPages == 0 || ConvertProcessContext.ReleaseWorkMemory < Environment.WorkingSet)
481
                            {
482
                                Console.WriteLine($"physical memory : {Environment.WorkingSet}");
483

    
484
                                gMarkusPDF.Dispose();
485
                                gMarkusPDF = null;
486
                                System.Threading.Thread.SpinWait(5);
487

    
488
                                gMarkusPDF = new MarkusPDF();
489
                                gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
490
                            }
491

    
492
                            System.Threading.Thread.SpinWait(2);
493
                        }
494
                    }
495
                    catch (Exception ex)
496
                    {
497
                        result.StatusCode = StatusCodeType.PageError;
498
                        result.Message =  LogHelper.GetStack() + " " +"Save Error - " + ex.Message;
499

    
500
                        if (gMarkusPDF != null)
501
                        {
502
                            gMarkusPDF.Dispose();
503
                            gMarkusPDF = null;
504
                        }
505

    
506
                        gMarkusPDF = new MarkusPDF();
507
                        gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
508

    
509
                        currentPageNo = currentPageNo - 1;
510
                    }
511
                    finally
512
                    {
513
                     
514
                    }
515
                }
516

    
517
                result.StatusCode = StatusCodeType.Completed;
518
            }
519
            catch (Exception ex)
520
            {
521
                result.StatusCode = StatusCodeType.Error;
522
                result.Message =  LogHelper.GetStack() + " " +ex.Message;
523
            }
524

    
525
            return result;
526
        }
527

    
528
        public bool Stop()
529
        {
530
            try
531
            {
532
                gSaveTask.Dispose();
533
            }
534
            catch (Exception ex)
535
            {
536
                System.Diagnostics.Debug.WriteLine(ex.ToString());
537
            }
538

    
539
            return true;
540
        }
541

    
542

    
543
        /// <summary>
544
        /// 사용안함
545
        /// </summary>
546
        /// <param name="param"></param>
547
        /// <returns></returns>
548
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
549
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
550
        //private SaveResult SetFile()
551
        //{
552
        //    var saveitem = new SaveItem
553
        //    {
554
        //        Id = ConvertProcessContext.ConvertID,
555
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
556
        //        SavePath = ConvertProcessContext.SaveDirectory,
557
        //        Status = StatusCodeType.None
558
        //    };
559

    
560
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
561
        //    {
562
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
563
        //    }
564

    
565
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
566

    
567
        //    try
568
        //    {
569
        //        Uri pdfFileUri = null;
570

    
571
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
572
        //        {
573
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
574
        //            {
575
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
576

    
577
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
578
        //                {
579
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
580
        //                }
581

    
582
        //                var downloadFilePath = System.IO.Path.Combine(ConvertProcessContext.TempDirectory, saveitem.Id.Replace("-", "") + ".pdf");
583
        //                webClient.DownloadFile(pdfFileUri, downloadFilePath);
584

    
585
        //                saveitem.PdfFilePath = downloadFilePath;
586
        //            }
587
        //        }
588
        //    }
589
        //    catch (Exception ex)
590
        //    {
591
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
592
        //    }
593

    
594
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
595

    
596
        //    var result = gSaveTask.SaveFile(saveitem);
597

    
598
        //    return result;
599
        //}
600

    
601
    }
602
}
클립보드 이미지 추가 (최대 크기: 500 MB)