프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ bae83c92

이력 | 보기 | 이력해설 | 다운로드 (23.3 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
                    if(gTempFileName.ToCharArray().Any(x=>x.IsKor()))
221
                    {
222
                        gTempFileName = Path.Combine(Path.GetTempPath(), GuidExtension.shortGuid() + ".pdf");
223

    
224
                        File.Copy(saveitem.PdfFilePath, gTempFileName,true);
225

    
226
                        System.Threading.Thread.Sleep(100);
227
                    }
228

    
229
                    gMarkusPDF.pdfLoad(gTempFileName, saveitem.MinimumFontSize, saveitem.UseResolution);
230

    
231
                    if(gMarkusPDF.PageCount() > 0)
232
                    {
233
                        /// 설정된 MultiThreadMaxPages에 따른 컨버터 분기
234
                        //if (gMarkusPDF.PageCount() > ConvertProcessContext.MultiThreadMaxPages)
235
                        //{
236
                        //    // 큰 사이즈의 파일 컨버팅
237
                          result = ConvertBigFileProcess(saveitem);
238
                        //}
239
                        //else
240
                        //{
241
                        //    /// 작은 사이즈의 컨버팅
242
                        //    await Task.Factory.StartNew(new Action(() =>
243
                        //    {
244
                        //        result = gSaveTask.SaveFile(saveitem);
245
                        //    }), TaskCreationOptions.LongRunning);
246
                        //}
247

    
248
                        // 파일 체크 후 갯수가 안맞으면 다시 컨버팅한다.
249
                        if (ReConvert < 1 && (result.PageInfoList.Count() != saveitem.TotalPages
250
                                       || Directory.EnumerateFiles(saveitem.SavePath, "*.png").Count() != saveitem.TotalPages
251
                                           || Directory.EnumerateFiles(saveitem.SavePath, "*.jpg").Count() != saveitem.TotalPages))
252
                        {
253
                            result.StatusCode = StatusCodeType.PageError;
254
                            result.Message =  LogHelper.GetStack() + " " +"Page Count Error";
255
                            ReConvert = 1;
256

    
257
                            result = ConvertBigFileProcess(saveitem);
258
                        }
259

    
260

    
261
                        ///  페이지 정보 저장
262
                        if (result.PageInfoList?.Count() > 0)
263
                        {
264
                            bool docSetResult = false;
265

    
266
                            using (Markus.Service.DataBase.ConvertDatabase database = new Markus.Service.DataBase.ConvertDatabase(ConvertProcessContext.ConnectionString))
267
                            {
268
                                List<EntityModel.DOCPAGE> docPageList = new List<EntityModel.DOCPAGE>();
269

    
270
                                docPageList = result.PageInfoList.Select(f => new EntityModel.DOCPAGE
271
                                {
272
                                    ID = GuidExtension.shortGuid(),
273
                                    PAGE_WIDTH = f.Width.ToString(),
274
                                    PAGE_HEIGHT = f.Height.ToString(),
275
                                    PAGE_NUMBER = f.PageNo
276
                                }).ToList();
277

    
278
                                docSetResult = database.SetDocumentInfo(saveitem.Id, result.PageInfoList.Count, docPageList);
279
                            }
280

    
281
                            if (docSetResult)
282
                            {
283
                                result.StatusCode = StatusCodeType.Completed;
284
                            }
285
                            else
286
                            {
287
                                result.StatusCode = StatusCodeType.FileError;
288
                                result.Message = LogHelper.GetStack() + " " + $"Doc Set Error. {result.Message}";
289
                            }
290
                        }
291
                        else
292
                        {
293
                            result.StatusCode = StatusCodeType.FileError;
294
                            result.Message = LogHelper.GetStack() + " " + $"Page List Get Error. {result.Message} ";
295
                        }
296
                    }
297
                    else
298
                    {
299
                        result.Message = $"File Error Page Count:0 - File path : { saveitem.PdfFilePath}";
300
                        result.StatusCode = StatusCodeType.FileError;
301
                    }
302

    
303
                }
304
                else
305
                {
306
                    result.Message  = $"File Download Error  - File path : { saveitem.PdfFilePath}";
307
                    result.StatusCode = StatusCodeType.FileError;
308
                }
309
            }
310
            catch (Exception ex)
311
            {
312
                result.Message =  LogHelper.GetStack() + " " +"ConvertService Convert Error" + ex.Message;
313
                result.StatusCode = StatusCodeType.Error;
314

    
315
                logger.Error(ex);
316
            }
317
            finally
318
            {
319

    
320
            }
321

    
322
            return result;
323
        }
324

    
325
        /// <summary>
326
        /// 파일 다운로드
327
        /// </summary>
328
        /// <param name="saveItem"></param>
329
        /// <returns></returns>
330
        public async Task<bool> DownloadFileAsync(SaveItem saveItem)
331
        {
332
            bool result = false;
333

    
334
            try
335
            {
336
                Uri pdfFileUri = null;
337

    
338
                //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB"))
339
                //{
340
                //    FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
341
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
342
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
343
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
344
                //    DownloadFilePath = ItemPath + "\\" + FileName;
345
                //}
346
                //else
347
                //{
348
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
349
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
350
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
351
                //    FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName");
352
                //    DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName;
353

    
354
                //}
355

    
356
                saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
357

    
358

    
359
                string FileName = "";
360
                string downloadFilePath = "";
361

    
362
                // 드라이브 경로가 포함되었는지 판단.
363
                if (Path.IsPathRooted(saveItem.PdfFilePath))
364
                {
365
                    FileInfo file = new FileInfo(saveItem.PdfFilePath);
366

    
367
                    if (file.Exists)
368
                    {
369
                        FileName = file.Name;
370
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
371
                        file.CopyTo(downloadFilePath, true);
372
                    }
373
                    else
374
                    {
375
                        throw new Exception("File Not Found. Please, check the file path.");
376
                    }
377
                }
378
                else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
379
                {
380
                    try
381
                    {
382
                        FileName = DownloadUri.GetFileName(saveItem.PdfFilePath);
383
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
384

    
385
                        using (System.Net.WebClient webClient = new System.Net.WebClient())
386
                        {
387
                            webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
388
                            webClient.Proxy = null;
389
                            //if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
390
                            //{
391
                            //    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
392
                            //}
393

    
394
                            webClient.DownloadFile(pdfFileUri, downloadFilePath);
395
                            webClient.Dispose();
396
                        }
397

    
398
                        await Task.Delay(300);
399
                    }
400
                    catch (Exception ex)
401
                    {
402
                        logger.Error(ex);
403
                        throw new Exception("File Download Error. Please, check the file path.");
404
                    }
405
                }
406
                else
407
                {
408
                    throw new Exception("Please, check the file path.");
409
                }
410

    
411
                try
412
                {
413
                    if (File.Exists(downloadFilePath))
414
                    {
415
                        var file = File.Open(downloadFilePath, FileMode.Open);
416

    
417
                        if (file.Length == 0)
418
                        {
419
                            throw new Exception("File Size 0. Please, check the file path.");
420
                        }
421

    
422
                        file.Close();
423
                        file.Dispose();
424

    
425
                        saveItem.PdfFilePath = downloadFilePath;
426
                        result = true;
427

    
428
                    }
429
                }
430
                catch (Exception ex)
431
                {
432
                    logger.Error(ex);
433
                    throw new Exception("File Error ." + downloadFilePath);
434
                }
435
            }
436
            catch (Exception ex)
437
            {
438
                logger.Error(ex);
439
                throw new Exception(ex.ToString());
440
            }
441

    
442
            return result;
443
        }
444

    
445
        /// <summary>
446
        /// 큰파일 변환
447
        /// </summary>
448
        /// <param name="saveitem"></param>
449
        /// <returns></returns>
450
        private SaveResult ConvertBigFileProcess(SaveItem saveitem)
451
        {
452
            SaveResult result = new SaveResult();
453

    
454
            try
455
            {
456
                saveitem.TotalPages = gMarkusPDF.PageCount();
457

    
458
                for (int currentPageNo = 1; currentPageNo <= saveitem.TotalPages; currentPageNo++)
459
                {
460
                    try
461
                    {
462
                        string saveFile = Path.Combine(saveitem.SavePath, $"{currentPageNo}.png");
463

    
464
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
465
                         {
466

    
467
                            var saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
468

    
469
                            saveitem.Status = StatusCodeType.Saving;
470
                            saveitem.CurrentPage = currentPageNo;
471
                            saveitem.ErrorMessage = saveResult.Message;
472

    
473
                            int pageListCount = 0;
474

    
475
                            if(result.PageInfoList != null)
476
                            {
477
                                pageListCount = result.PageInfoList.Count(f => f.PageNo == saveResult.SavePageInfo.PageNo);
478
                            }
479
                            
480
                            if (pageListCount == 0)
481
                            {
482
                                result.PageInfoAdd(saveResult.SavePageInfo);
483
                            }
484

    
485
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(saveitem));
486
                            Console.WriteLine($"CurrentPage : {currentPageNo}");
487

    
488
                            /// 설정된 최대 페이지이거나 설정된 메모리보다 크면 릴리즈
489
                            if ((currentPageNo % ConvertProcessContext.MultiThreadMaxPages == 0 && ConvertProcessContext.MultiThreadMaxPages  > 0)
490
                                || ConvertProcessContext.ReleaseWorkMemory < Environment.WorkingSet)
491
                            {
492
                                Console.WriteLine($"physical memory : {Environment.WorkingSet}");
493

    
494
                                gMarkusPDF.Dispose();
495
                                gMarkusPDF = null;
496
                                System.Threading.Thread.SpinWait(5);
497

    
498
                                gMarkusPDF = new MarkusPDF();
499
                                gMarkusPDF.pdfLoad(gTempFileName, saveitem.MinimumFontSize, saveitem.UseResolution);
500
                            }
501

    
502
                            System.Threading.Thread.SpinWait(2);
503
                        }
504
                    }
505
                    catch (Exception ex)
506
                    {
507
                        result.StatusCode = StatusCodeType.PageError;
508
                        result.Message =  LogHelper.GetStack() + " " +"Save Error - " + ex.Message;
509

    
510
                        if (gMarkusPDF != null)
511
                        {
512
                            gMarkusPDF.Dispose();
513
                            gMarkusPDF = null;
514
                        }
515

    
516
                        gMarkusPDF = new MarkusPDF();
517
                        gMarkusPDF.pdfLoad(gTempFileName, saveitem.MinimumFontSize, saveitem.UseResolution);
518

    
519
                        currentPageNo = currentPageNo - 1;
520
                    }
521
                    finally
522
                    {
523
                     
524
                    }
525
                }
526

    
527
                result.StatusCode = StatusCodeType.Completed;
528
            }
529
            catch (Exception ex)
530
            {
531
                result.StatusCode = StatusCodeType.Error;
532
                result.Message =  LogHelper.GetStack() + " " +ex.Message;
533
            }
534

    
535
            return result;
536
        }
537

    
538
        public bool Stop()
539
        {
540
            try
541
            {
542
                gSaveTask.Dispose();
543
            }
544
            catch (Exception ex)
545
            {
546
                System.Diagnostics.Debug.WriteLine(ex.ToString());
547
            }
548

    
549
            return true;
550
        }
551

    
552

    
553
        /// <summary>
554
        /// 사용안함
555
        /// </summary>
556
        /// <param name="param"></param>
557
        /// <returns></returns>
558
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
559
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
560
        //private SaveResult SetFile()
561
        //{
562
        //    var saveitem = new SaveItem
563
        //    {
564
        //        Id = ConvertProcessContext.ConvertID,
565
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
566
        //        SavePath = ConvertProcessContext.SaveDirectory,
567
        //        Status = StatusCodeType.None
568
        //    };
569

    
570
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
571
        //    {
572
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
573
        //    }
574

    
575
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
576

    
577
        //    try
578
        //    {
579
        //        Uri pdfFileUri = null;
580

    
581
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
582
        //        {
583
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
584
        //            {
585
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
586

    
587
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
588
        //                {
589
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
590
        //                }
591

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

    
595
        //                saveitem.PdfFilePath = downloadFilePath;
596
        //            }
597
        //        }
598
        //    }
599
        //    catch (Exception ex)
600
        //    {
601
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
602
        //    }
603

    
604
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
605

    
606
        //    var result = gSaveTask.SaveFile(saveitem);
607

    
608
        //    return result;
609
        //}
610

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