프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ 7b095cc3

이력 | 보기 | 이력해설 | 다운로드 (22.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
                    gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
221

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

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

    
246
                        result = ConvertBigFileProcess(saveitem);
247
                    }
248

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

    
254
                        using (Markus.Service.DataBase.ConvertDatabase database = new Markus.Service.DataBase.ConvertDatabase(ConvertProcessContext.ConnectionString))
255
                        {
256
                            List<EntityModel.DOCPAGE> docPageList = new List<EntityModel.DOCPAGE>();
257

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

    
266
                            docSetResult = database.SetDocumentInfo(saveitem.Id, result.PageInfoList.Count, docPageList);
267
                        }
268

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

    
296
                logger.Error(ex);
297
            }
298
            finally
299
            {
300

    
301
            }
302

    
303
            return result;
304
        }
305

    
306
        /// <summary>
307
        /// 파일 다운로드
308
        /// </summary>
309
        /// <param name="saveItem"></param>
310
        /// <returns></returns>
311
        public async Task<bool> DownloadFileAsync(SaveItem saveItem)
312
        {
313
            bool result = false;
314

    
315
            try
316
            {
317
                Uri pdfFileUri = null;
318

    
319
                //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB"))
320
                //{
321
                //    FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
322
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
323
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
324
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
325
                //    DownloadFilePath = ItemPath + "\\" + FileName;
326
                //}
327
                //else
328
                //{
329
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
330
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
331
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
332
                //    FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName");
333
                //    DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName;
334

    
335
                //}
336

    
337
                saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
338

    
339

    
340
                string FileName = "";
341
                string downloadFilePath = "";
342

    
343
                // 드라이브 경로가 포함되었는지 판단.
344
                if (Path.IsPathRooted(saveItem.PdfFilePath))
345
                {
346
                    FileInfo file = new FileInfo(saveItem.PdfFilePath);
347

    
348
                    if (file.Exists)
349
                    {
350
                        FileName = file.Name;
351
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
352
                        file.CopyTo(downloadFilePath, true);
353
                    }
354
                    else
355
                    {
356
                        throw new Exception("File Not Found. Please, check the file path.");
357
                    }
358
                }
359
                else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
360
                {
361
                    try
362
                    {
363
                        FileName = DownloadUri.GetFileName(saveItem.PdfFilePath);
364
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
365

    
366
                        using (System.Net.WebClient webClient = new System.Net.WebClient())
367
                        {
368
                            webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
369
                            webClient.Proxy = null;
370
                            //if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
371
                            //{
372
                            //    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
373
                            //}
374

    
375
                            await webClient.DownloadFileTaskAsync(pdfFileUri, downloadFilePath);
376
                            webClient.Dispose();
377
                        }
378

    
379
                        await Task.Delay(300);
380
                    }
381
                    catch (Exception ex)
382
                    {
383
                        logger.Error(ex);
384
                        throw new Exception("File Download Error. Please, check the file path.");
385
                    }
386
                }
387
                else
388
                {
389
                    throw new Exception("Please, check the file path.");
390
                }
391

    
392
                try
393
                {
394
                    if (File.Exists(downloadFilePath))
395
                    {
396
                        var file = File.Open(downloadFilePath, FileMode.Open);
397

    
398
                        if (file.Length == 0)
399
                        {
400
                            throw new Exception("File Size 0. Please, check the file path.");
401
                        }
402

    
403
                        file.Close();
404
                        file.Dispose();
405

    
406
                        saveItem.PdfFilePath = downloadFilePath;
407
                        result = true;
408

    
409
                    }
410
                }
411
                catch (Exception ex)
412
                {
413
                    logger.Error(ex);
414
                    throw new Exception("File Error ." + downloadFilePath);
415
                }
416
            }
417
            catch (Exception ex)
418
            {
419
                logger.Error(ex);
420
                throw new Exception(ex.ToString());
421
            }
422

    
423
            return result;
424
        }
425

    
426
        /// <summary>
427
        /// 큰파일 변환
428
        /// </summary>
429
        /// <param name="saveitem"></param>
430
        /// <returns></returns>
431
        private SaveResult ConvertBigFileProcess(SaveItem saveitem)
432
        {
433
            SaveResult result = new SaveResult();
434

    
435
            try
436
            {
437
                saveitem.TotalPages = gMarkusPDF.PageCount();
438

    
439
                for (int currentPageNo = 1; currentPageNo <= saveitem.TotalPages; currentPageNo++)
440
                {
441
                    try
442
                    {
443
                        string saveFile = Path.Combine(saveitem.SavePath, $"{currentPageNo}.png");
444

    
445
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
446
                         {
447

    
448
                            var saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
449

    
450
                            saveitem.Status = StatusCodeType.Saving;
451
                            saveitem.CurrentPage = currentPageNo;
452
                            saveitem.ErrorMessage = saveResult.Message;
453

    
454
                            int pageListCount = 0;
455

    
456
                            if(result.PageInfoList != null)
457
                            {
458
                                pageListCount = result.PageInfoList.Count(f => f.PageNo == saveResult.SavePageInfo.PageNo);
459
                            }
460
                            
461
                            if (pageListCount == 0)
462
                            {
463
                                result.PageInfoAdd(saveResult.SavePageInfo);
464
                            }
465

    
466
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(saveitem));
467
                            Console.WriteLine($"CurrentPage : {currentPageNo}");
468

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

    
474
                                gMarkusPDF.Dispose();
475
                                gMarkusPDF = null;
476
                                System.Threading.Thread.SpinWait(5);
477

    
478
                                gMarkusPDF = new MarkusPDF();
479
                                gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
480
                            }
481

    
482
                            System.Threading.Thread.SpinWait(2);
483
                        }
484
                    }
485
                    catch (Exception ex)
486
                    {
487
                        result.StatusCode = StatusCodeType.PageError;
488
                        result.Message =  LogHelper.GetStack() + " " +"Save Error - " + ex.Message;
489

    
490
                        if (gMarkusPDF != null)
491
                        {
492
                            gMarkusPDF.Dispose();
493
                            gMarkusPDF = null;
494
                        }
495

    
496
                        gMarkusPDF = new MarkusPDF();
497
                        gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
498

    
499
                        currentPageNo = currentPageNo - 1;
500
                    }
501
                    finally
502
                    {
503
                     
504
                    }
505
                }
506

    
507
                result.StatusCode = StatusCodeType.Completed;
508
            }
509
            catch (Exception ex)
510
            {
511
                result.StatusCode = StatusCodeType.Error;
512
                result.Message =  LogHelper.GetStack() + " " +ex.Message;
513
            }
514

    
515
            return result;
516
        }
517

    
518
        public bool Stop()
519
        {
520
            try
521
            {
522
                gSaveTask.Dispose();
523
            }
524
            catch (Exception ex)
525
            {
526
                System.Diagnostics.Debug.WriteLine(ex.ToString());
527
            }
528

    
529
            return true;
530
        }
531

    
532

    
533
        /// <summary>
534
        /// 사용안함
535
        /// </summary>
536
        /// <param name="param"></param>
537
        /// <returns></returns>
538
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
539
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
540
        //private SaveResult SetFile()
541
        //{
542
        //    var saveitem = new SaveItem
543
        //    {
544
        //        Id = ConvertProcessContext.ConvertID,
545
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
546
        //        SavePath = ConvertProcessContext.SaveDirectory,
547
        //        Status = StatusCodeType.None
548
        //    };
549

    
550
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
551
        //    {
552
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
553
        //    }
554

    
555
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
556

    
557
        //    try
558
        //    {
559
        //        Uri pdfFileUri = null;
560

    
561
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
562
        //        {
563
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
564
        //            {
565
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
566

    
567
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
568
        //                {
569
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
570
        //                }
571

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

    
575
        //                saveitem.PdfFilePath = downloadFilePath;
576
        //            }
577
        //        }
578
        //    }
579
        //    catch (Exception ex)
580
        //    {
581
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
582
        //    }
583

    
584
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
585

    
586
        //    var result = gSaveTask.SaveFile(saveitem);
587

    
588
        //    return result;
589
        //}
590

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