프로젝트

일반

사용자정보

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

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

이력 | 보기 | 이력해설 | 다운로드 (21.2 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

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

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

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

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

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

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

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

    
162
                result = await ConvertAsync(saveitem);
163

    
164
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages,result.Message);
165
            }
166
            catch (Exception ex)
167
            {
168
                logger.Error($"File Convert Error",ex);
169
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages, $"ConvertService Error    {saveitem.Id}");
170
            }
171

    
172
            return result;
173
        }
174

    
175
        [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
176
        private async Task<SaveResult> ConvertAsync(SaveItem saveitem)
177
        { 
178
            SaveResult result = new SaveResult();
179
         
180
            try
181
            {
182
                DateTime deleteTime = DateTime.Now;
183

    
184
                while (System.IO.Directory.Exists(saveitem.SavePath))
185
                {
186
                    System.IO.Directory.Delete(saveitem.SavePath, true);
187

    
188
                    if ((DateTime.Now - deleteTime) > new TimeSpan(0, 5, 0))
189
                    {
190
                        string msg = $"ConvertService Error {saveitem.SavePath} Delete Error";
191
                        logger.Error(msg);
192
                        result.StatusCode = StatusCodeType.FileError;
193
                        result.Message = msg;
194

    
195
                        return result;
196
                    }
197

    
198
                    System.Threading.Thread.SpinWait(10);
199
                }
200

    
201
                System.IO.Directory.CreateDirectory(saveitem.SavePath);
202

    
203
                //파일 다운로드
204
                if (await DownloadFileAsync(saveitem))
205
                {
206
                    gTempFileName = saveitem.PdfFilePath;
207

    
208
                    gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
209

    
210
                    /// 설정된 MultiThreadMaxPages에 따른 컨버터 분기
211
                    if (gMarkusPDF.PageCount() > ConvertProcessContext.MultiThreadMaxPages)
212
                    {
213
                        // 큰 사이즈의 파일 컨버팅
214
                        result = ConvertBigFileProcess(saveitem);
215
                    }
216
                    else
217
                    {
218
                        /// 작은 사이즈의 컨버팅
219
                        await Task.Factory.StartNew(new Action(() =>
220
                        {
221
                            result = gSaveTask.SaveFile(saveitem);
222
                        }), TaskCreationOptions.LongRunning);
223
                    }
224

    
225
                    // 파일 체크 후 갯수가 안맞으면 다시 컨버팅한다.
226
                    if (ReConvert < 1 && (result.PageInfoList.Count() != saveitem.TotalPages
227
                                   || Directory.EnumerateFiles(saveitem.SavePath, "*.png").Count() != saveitem.TotalPages
228
                                       || Directory.EnumerateFiles(saveitem.SavePath, "*.jpg").Count() != saveitem.TotalPages))
229
                    {
230
                        result.StatusCode = StatusCodeType.PageError;
231
                        result.Message = "Page Count Error";
232
                        ReConvert = 1;
233

    
234
                        result = ConvertBigFileProcess(saveitem);
235
                    }
236

    
237
                    ///  페이지 정보 저장
238
                    if (result.PageInfoList?.Count() > 0)
239
                    {
240
                        bool docSetResult = false;
241

    
242
                        using (Markus.Service.DataBase.ConvertDatabase database = new Markus.Service.DataBase.ConvertDatabase(ConvertProcessContext.ConnectionString))
243
                        {
244
                            List<EntityModel.DOCPAGE> docPageList = new List<EntityModel.DOCPAGE>();
245

    
246
                            docPageList = result.PageInfoList.Select(f => new EntityModel.DOCPAGE
247
                            {
248
                                ID = GuidExtension.shortGuid(),
249
                                PAGE_WIDTH = f.Width.ToString(),
250
                                PAGE_HEIGHT = f.Height.ToString(),
251
                                PAGE_NUMBER = f.PageNo
252
                            }).ToList();
253

    
254
                            docSetResult = database.SetDocumentInfo(saveitem.Id, result.PageInfoList.Count, docPageList);
255
                        }
256

    
257
                        if (docSetResult)
258
                        {
259
                            result.StatusCode = StatusCodeType.Completed;
260
                        }
261
                        else
262
                        {
263
                            result.StatusCode = StatusCodeType.FileError;
264
                            result.Message =  $"Doc Set Error. {result.Message}";
265
                        }
266
                    }
267
                    else
268
                    {
269
                        result.StatusCode = StatusCodeType.FileError;
270
                        result.Message = $"Page List Get Error. {result.Message} ";
271
                    }
272
                }
273
                else
274
                {
275
                    result.Message  = $"File Download Error  - File path : { saveitem.PdfFilePath}";
276
                    result.StatusCode = StatusCodeType.FileError;
277
                }
278
            }
279
            catch (Exception ex)
280
            {
281
                result.Message = "ConvertService Convert Error" + ex.Message;
282
                result.StatusCode = StatusCodeType.Error;
283
            }
284
            finally
285
            {
286

    
287
            }
288

    
289
            return result;
290
        }
291

    
292
        /// <summary>
293
        /// 파일 다운로드
294
        /// </summary>
295
        /// <param name="saveItem"></param>
296
        /// <returns></returns>
297
        public async Task<bool> DownloadFileAsync(SaveItem saveItem)
298
        {
299
            bool result = false;
300

    
301
            try
302
            {
303
                Uri pdfFileUri = null;
304

    
305
                //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB"))
306
                //{
307
                //    FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
308
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
309
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
310
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
311
                //    DownloadFilePath = ItemPath + "\\" + FileName;
312
                //}
313
                //else
314
                //{
315
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
316
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
317
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
318
                //    FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName");
319
                //    DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName;
320

    
321
                //}
322

    
323
                saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
324

    
325

    
326
                string FileName = "";
327
                string downloadFilePath = "";
328

    
329
                // 드라이브 경로가 포함되었는지 판단.
330
                if (Path.IsPathRooted(saveItem.PdfFilePath))
331
                {
332
                    FileInfo file = new FileInfo(saveItem.PdfFilePath);
333

    
334
                    if (file.Exists)
335
                    {
336
                        FileName = file.Name;
337
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
338
                        file.CopyTo(downloadFilePath, true);
339
                    }
340
                    else
341
                    {
342
                        throw new Exception("File Not Found. Please, check the file path.");
343
                    }
344
                }
345
                else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
346
                {
347
                    try
348
                    {
349
                        FileName = DownloadUri.GetFileName(saveItem.PdfFilePath);
350
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
351

    
352
                        using (System.Net.WebClient webClient = new System.Net.WebClient())
353
                        {
354
                            webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
355

    
356
                            //if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
357
                            //{
358
                            //    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
359
                            //}
360

    
361
                            await webClient.DownloadFileTaskAsync(pdfFileUri, downloadFilePath);
362
                        }
363
                    }
364
                    catch (Exception)
365
                    {
366
                        throw new Exception("File Download Error. Please, check the file path.");
367
                    }
368
                }
369
                else
370
                {
371
                    throw new Exception("Please, check the file path.");
372
                }
373

    
374
                if (File.Exists(downloadFilePath))
375
                {
376
                    var file = File.Open(downloadFilePath, FileMode.Open);
377

    
378
                    if (file.Length == 0)
379
                    {
380
                        throw new Exception("File Size 0. Please, check the file path.");
381
                    }
382

    
383
                    file.Close();
384
                    file.Dispose();
385

    
386
                    saveItem.PdfFilePath = downloadFilePath;
387
                    result = true;
388

    
389
                }
390
            }
391
            catch (Exception ex)
392
            {                                                                                      
393
                result = false;
394
            }
395

    
396
            return result;
397
        }
398

    
399
        /// <summary>
400
        /// 큰파일 변환
401
        /// </summary>
402
        /// <param name="saveitem"></param>
403
        /// <returns></returns>
404
        private SaveResult ConvertBigFileProcess(SaveItem saveitem)
405
        {
406
            SaveResult result = new SaveResult();
407

    
408
            try
409
            {
410
                saveitem.TotalPages = gMarkusPDF.PageCount();
411

    
412
                for (int currentPageNo = 1; currentPageNo <= saveitem.TotalPages; currentPageNo++)
413
                {
414
                    try
415
                    {
416
                        string saveFile = Path.Combine(saveitem.SavePath, $"{currentPageNo}.png");
417

    
418
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
419
                         {
420

    
421
                            var saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
422

    
423
                            saveitem.Status = StatusCodeType.Saving;
424
                            saveitem.CurrentPage = currentPageNo;
425
                            saveitem.ErrorMessage = saveResult.Message;
426

    
427
                            int pageListCount = 0;
428

    
429
                            if(result.PageInfoList != null)
430
                            {
431
                                pageListCount = result.PageInfoList.Count(f => f.PageNo == saveResult.SavePageInfo.PageNo);
432
                            }
433
                            
434
                            if (pageListCount == 0)
435
                            {
436
                                result.PageInfoAdd(saveResult.SavePageInfo);
437
                            }
438

    
439
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(saveitem));
440
                            Console.WriteLine($"CurrentPage : {currentPageNo}");
441

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

    
447
                                gMarkusPDF.Dispose();
448
                                gMarkusPDF = null;
449
                                System.Threading.Thread.SpinWait(5);
450

    
451
                                gMarkusPDF = new MarkusPDF();
452
                                gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
453
                            }
454
                            System.Threading.Thread.SpinWait(2);
455
                        }
456
                    }
457
                    catch (Exception ex)
458
                    {
459
                        result.StatusCode = StatusCodeType.PageError;
460
                        result.Message = "Save Error - " + ex.Message;
461

    
462
                        if (gMarkusPDF != null)
463
                        {
464
                            gMarkusPDF.Dispose();
465
                            gMarkusPDF = null;
466
                        }
467

    
468
                        gMarkusPDF = new MarkusPDF();
469
                        gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
470

    
471
                        currentPageNo = currentPageNo - 1;
472
                    }
473
                    finally
474
                    {
475
                     
476
                    }
477
                }
478

    
479
                result.StatusCode = StatusCodeType.Completed;
480
            }
481
            catch (Exception ex)
482
            {
483
                result.StatusCode = StatusCodeType.Error;
484
                result.Message = ex.Message;
485
            }
486

    
487
            return result;
488
        }
489

    
490
        public bool Stop()
491
        {
492
            try
493
            {
494
                gSaveTask.Dispose();
495
            }
496
            catch (Exception ex)
497
            {
498
                System.Diagnostics.Debug.WriteLine(ex.ToString());
499
            }
500

    
501
            return true;
502
        }
503

    
504

    
505
        /// <summary>
506
        /// 사용안함
507
        /// </summary>
508
        /// <param name="param"></param>
509
        /// <returns></returns>
510
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
511
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
512
        //private SaveResult SetFile()
513
        //{
514
        //    var saveitem = new SaveItem
515
        //    {
516
        //        Id = ConvertProcessContext.ConvertID,
517
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
518
        //        SavePath = ConvertProcessContext.SaveDirectory,
519
        //        Status = StatusCodeType.None
520
        //    };
521

    
522
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
523
        //    {
524
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
525
        //    }
526

    
527
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
528

    
529
        //    try
530
        //    {
531
        //        Uri pdfFileUri = null;
532

    
533
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
534
        //        {
535
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
536
        //            {
537
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
538

    
539
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
540
        //                {
541
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
542
        //                }
543

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

    
547
        //                saveitem.PdfFilePath = downloadFilePath;
548
        //            }
549
        //        }
550
        //    }
551
        //    catch (Exception ex)
552
        //    {
553
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
554
        //    }
555

    
556
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
557

    
558
        //    var result = gSaveTask.SaveFile(saveitem);
559

    
560
        //    return result;
561
        //}
562

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