프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ 67df8dcd

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

1 53c9637d taeseongkim
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 06f13e11 taeseongkim
using Markus.Service.WcfClient.StationServiceAsync;
14 53c9637d taeseongkim
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 f363a40e taeseongkim
30
        // 컨버터 완료시 파일갯수를 체크 하여 틀리면 reconvert를 1로 하고 다시 컨버팅 하도록 한다.
31
        private int ReConvert;
32
33 53c9637d taeseongkim
34 06f13e11 taeseongkim
        private StationServiceClient StationServiceClient; 
35 53c9637d taeseongkim
36 a53dfe45 taeseongkim
        /// <summary>
37
        /// 프로세스 초기화
38
        /// </summary>
39
        /// <param name="convertContext"></param>
40 53c9637d taeseongkim
        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 06f13e11 taeseongkim
            StationServiceClient = new StationServiceClient(myBinding, myEndpoint);
49 53c9637d taeseongkim
           
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 65fbe3cb taeseongkim
                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 53c9637d taeseongkim
76
                //if (System.IO.File.Exists(gTempFileName))
77
                //{
78
                //    File.Delete(gTempFileName);
79
                //}
80
81
            }
82
            catch (Exception ex)
83
            {
84 65fbe3cb taeseongkim
               logger.Error("Convert Service Dispose Error", ex);
85 53c9637d taeseongkim
            }
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 a0341bef taeseongkim
133
                StationServiceClient.ConvertProcessStateAsync(e.SaveItem.Id, (int)e.SaveItem.Status, e.SaveItem.CurrentPage, e.SaveItem.TotalPages, e.SaveItem.ErrorMessage);
134
                
135 53c9637d taeseongkim
            }
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 2091a7e5 taeseongkim
                MinimumFontSize = ConvertProcessContext.MinFontSize,
154
                UseResolution = ConvertProcessContext.UseResolution
155 53c9637d taeseongkim
            };
156
157
            try
158
            {
159
                StationServiceClient.ConvertProcessState(ConvertProcessContext.ConvertID, (int)StatusCodeType.Wait, 0, 0, "");
160
161
                result = await ConvertAsync(saveitem);
162
163 db0d3db3 taeseongkim
                // 플러그인 실행
164
                PluginService.Run(saveitem.Id);
165
             
166 53c9637d taeseongkim
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages,result.Message);
167
            }
168
            catch (Exception ex)
169
            {
170 db0d3db3 taeseongkim
                result.StatusCode = StatusCodeType.Error;
171 53c9637d taeseongkim
                logger.Error($"File Convert Error",ex);
172 db0d3db3 taeseongkim
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages, $"ConvertService Error    {saveitem.Id} {ex.Message} {ex.InnerException?.ToString()}");
173 53c9637d taeseongkim
            }
174
175
            return result;
176
        }
177
178 65fbe3cb taeseongkim
        [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
179 53c9637d taeseongkim
        private async Task<SaveResult> ConvertAsync(SaveItem saveitem)
180
        { 
181
            SaveResult result = new SaveResult();
182
         
183
            try
184
            {
185
                DateTime deleteTime = DateTime.Now;
186
187
                while (System.IO.Directory.Exists(saveitem.SavePath))
188
                {
189
                    System.IO.Directory.Delete(saveitem.SavePath, true);
190
191
                    if ((DateTime.Now - deleteTime) > new TimeSpan(0, 5, 0))
192
                    {
193
                        string msg = $"ConvertService Error {saveitem.SavePath} Delete Error";
194
                        logger.Error(msg);
195
                        result.StatusCode = StatusCodeType.FileError;
196
                        result.Message = msg;
197
198
                        return result;
199
                    }
200
201 60723dc9 taeseongkim
                    System.Threading.Thread.SpinWait(10);
202 53c9637d taeseongkim
                }
203
204
                System.IO.Directory.CreateDirectory(saveitem.SavePath);
205
206
                //파일 다운로드
207
                if (await DownloadFileAsync(saveitem))
208
                {
209
                    gTempFileName = saveitem.PdfFilePath;
210
211 2091a7e5 taeseongkim
                    gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
212 53c9637d taeseongkim
213
                    /// 설정된 MultiThreadMaxPages에 따른 컨버터 분기
214
                    if (gMarkusPDF.PageCount() > ConvertProcessContext.MultiThreadMaxPages)
215
                    {
216 f363a40e taeseongkim
                        // 큰 사이즈의 파일 컨버팅
217 53c9637d taeseongkim
                        result = ConvertBigFileProcess(saveitem);
218
                    }
219
                    else
220
                    {
221
                        /// 작은 사이즈의 컨버팅
222
                        await Task.Factory.StartNew(new Action(() =>
223
                        {
224
                            result = gSaveTask.SaveFile(saveitem);
225
                        }), TaskCreationOptions.LongRunning);
226
                    }
227
228 f363a40e taeseongkim
                    // 파일 체크 후 갯수가 안맞으면 다시 컨버팅한다.
229
                    if (ReConvert < 1 && (result.PageInfoList.Count() != saveitem.TotalPages
230
                                   || Directory.EnumerateFiles(saveitem.SavePath, "*.png").Count() != saveitem.TotalPages
231
                                       || Directory.EnumerateFiles(saveitem.SavePath, "*.jpg").Count() != saveitem.TotalPages))
232
                    {
233
                        result.StatusCode = StatusCodeType.PageError;
234
                        result.Message = "Page Count Error";
235
                        ReConvert = 1;
236
237
                        result = ConvertBigFileProcess(saveitem);
238
                    }
239
240 53c9637d taeseongkim
                    ///  페이지 정보 저장
241
                    if (result.PageInfoList?.Count() > 0)
242
                    {
243
                        bool docSetResult = false;
244
245
                        using (Markus.Service.DataBase.ConvertDatabase database = new Markus.Service.DataBase.ConvertDatabase(ConvertProcessContext.ConnectionString))
246
                        {
247 ff4b1e6e taeseongkim
                            List<EntityModel.DOCPAGE> docPageList = new List<EntityModel.DOCPAGE>();
248 53c9637d taeseongkim
249 ff4b1e6e taeseongkim
                            docPageList = result.PageInfoList.Select(f => new EntityModel.DOCPAGE
250 53c9637d taeseongkim
                            {
251
                                ID = GuidExtension.shortGuid(),
252
                                PAGE_WIDTH = f.Width.ToString(),
253
                                PAGE_HEIGHT = f.Height.ToString(),
254
                                PAGE_NUMBER = f.PageNo
255
                            }).ToList();
256
257 2091a7e5 taeseongkim
                            docSetResult = database.SetDocumentInfo(saveitem.Id, result.PageInfoList.Count, docPageList);
258 53c9637d taeseongkim
                        }
259
260
                        if (docSetResult)
261
                        {
262
                            result.StatusCode = StatusCodeType.Completed;
263
                        }
264
                        else
265
                        {
266
                            result.StatusCode = StatusCodeType.FileError;
267
                            result.Message =  $"Doc Set Error. {result.Message}";
268
                        }
269
                    }
270
                    else
271
                    {
272
                        result.StatusCode = StatusCodeType.FileError;
273
                        result.Message = $"Page List Get Error. {result.Message} ";
274
                    }
275
                }
276
                else
277
                {
278
                    result.Message  = $"File Download Error  - File path : { saveitem.PdfFilePath}";
279
                    result.StatusCode = StatusCodeType.FileError;
280
                }
281
            }
282
            catch (Exception ex)
283
            {
284
                result.Message = "ConvertService Convert Error" + ex.Message;
285
                result.StatusCode = StatusCodeType.Error;
286
            }
287
            finally
288
            {
289
290
            }
291
292
            return result;
293
        }
294
295
        /// <summary>
296
        /// 파일 다운로드
297
        /// </summary>
298
        /// <param name="saveItem"></param>
299
        /// <returns></returns>
300 af9bffc5 taeseongkim
        public async Task<bool> DownloadFileAsync(SaveItem saveItem)
301 53c9637d taeseongkim
        {
302
            bool result = false;
303
304
            try
305
            {
306
                Uri pdfFileUri = null;
307
308
                //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB"))
309
                //{
310
                //    FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
311
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
312
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
313
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
314
                //    DownloadFilePath = ItemPath + "\\" + FileName;
315
                //}
316
                //else
317
                //{
318
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
319
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
320
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
321
                //    FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName");
322
                //    DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName;
323
324
                //}
325
326
                saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
327
328 60723dc9 taeseongkim
329
                string FileName = "";
330
                string downloadFilePath = "";
331 53c9637d taeseongkim
332
                // 드라이브 경로가 포함되었는지 판단.
333
                if (Path.IsPathRooted(saveItem.PdfFilePath))
334
                {
335 60723dc9 taeseongkim
                    FileInfo file = new FileInfo(saveItem.PdfFilePath);
336
337
                    if (file.Exists)
338 53c9637d taeseongkim
                    {
339 60723dc9 taeseongkim
                        FileName = file.Name;
340
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
341
                        file.CopyTo(downloadFilePath, true);
342 53c9637d taeseongkim
                    }
343
                    else
344
                    {
345
                        throw new Exception("File Not Found. Please, check the file path.");
346
                    }
347
                }
348
                else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
349
                {
350
                    try
351
                    {
352 60723dc9 taeseongkim
                        FileName = DownloadUri.GetFileName(saveItem.PdfFilePath);
353
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
354
355 53c9637d taeseongkim
                        using (System.Net.WebClient webClient = new System.Net.WebClient())
356
                        {
357
                            webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
358
359
                            //if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
360
                            //{
361
                            //    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
362
                            //}
363
364
                            await webClient.DownloadFileTaskAsync(pdfFileUri, downloadFilePath);
365
                        }
366
                    }
367
                    catch (Exception)
368
                    {
369
                        throw new Exception("File Download Error. Please, check the file path.");
370
                    }
371
                }
372
                else
373
                {
374
                    throw new Exception("Please, check the file path.");
375
                }
376
377 3aafb914 taeseongkim
                try
378 53c9637d taeseongkim
                {
379 3aafb914 taeseongkim
                    if (File.Exists(downloadFilePath))
380 53c9637d taeseongkim
                    {
381 3aafb914 taeseongkim
                        var file = File.Open(downloadFilePath, FileMode.Open);
382
383
                        if (file.Length == 0)
384
                        {
385
                            throw new Exception("File Size 0. Please, check the file path.");
386
                        }
387 53c9637d taeseongkim
388 3aafb914 taeseongkim
                        file.Close();
389
                        file.Dispose();
390 53c9637d taeseongkim
391 3aafb914 taeseongkim
                        saveItem.PdfFilePath = downloadFilePath;
392
                        result = true;
393 53c9637d taeseongkim
394 3aafb914 taeseongkim
                    }
395
                }
396
                catch (Exception)
397
                {
398
                    throw new Exception("File Error ." + downloadFilePath);
399
                    throw;
400 53c9637d taeseongkim
                }
401
            }
402 af9bffc5 taeseongkim
            catch (Exception ex)
403 3aafb914 taeseongkim
            {
404
                throw new Exception(ex.ToString());
405 53c9637d taeseongkim
                result = false;
406
            }
407
408
            return result;
409
        }
410
411
        /// <summary>
412
        /// 큰파일 변환
413
        /// </summary>
414
        /// <param name="saveitem"></param>
415
        /// <returns></returns>
416
        private SaveResult ConvertBigFileProcess(SaveItem saveitem)
417
        {
418
            SaveResult result = new SaveResult();
419
420
            try
421
            {
422
                saveitem.TotalPages = gMarkusPDF.PageCount();
423
424
                for (int currentPageNo = 1; currentPageNo <= saveitem.TotalPages; currentPageNo++)
425
                {
426 f363a40e taeseongkim
                    try
427
                    {
428
                        string saveFile = Path.Combine(saveitem.SavePath, $"{currentPageNo}.png");
429 53c9637d taeseongkim
430 f363a40e taeseongkim
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
431
                         {
432 53c9637d taeseongkim
433 f363a40e taeseongkim
                            var saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
434 53c9637d taeseongkim
435 f363a40e taeseongkim
                            saveitem.Status = StatusCodeType.Saving;
436
                            saveitem.CurrentPage = currentPageNo;
437
                            saveitem.ErrorMessage = saveResult.Message;
438 53c9637d taeseongkim
439 f363a40e taeseongkim
                            int pageListCount = 0;
440
441
                            if(result.PageInfoList != null)
442
                            {
443
                                pageListCount = result.PageInfoList.Count(f => f.PageNo == saveResult.SavePageInfo.PageNo);
444
                            }
445
                            
446
                            if (pageListCount == 0)
447
                            {
448
                                result.PageInfoAdd(saveResult.SavePageInfo);
449
                            }
450
451
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(saveitem));
452
                            Console.WriteLine($"CurrentPage : {currentPageNo}");
453
454
                            /// 설정된 최대 페이지이거나 설정된 메모리보다 크면 릴리즈
455
                            if (currentPageNo % ConvertProcessContext.MultiThreadMaxPages == 0 || ConvertProcessContext.ReleaseWorkMemory < Environment.WorkingSet)
456
                            {
457
                                Console.WriteLine($"physical memory : {Environment.WorkingSet}");
458
459
                                gMarkusPDF.Dispose();
460
                                gMarkusPDF = null;
461
                                System.Threading.Thread.SpinWait(5);
462
463
                                gMarkusPDF = new MarkusPDF();
464
                                gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
465
                            }
466
                            System.Threading.Thread.SpinWait(2);
467
                        }
468
                    }
469
                    catch (Exception ex)
470 53c9637d taeseongkim
                    {
471 f363a40e taeseongkim
                        result.StatusCode = StatusCodeType.PageError;
472
                        result.Message = "Save Error - " + ex.Message;
473 53c9637d taeseongkim
474 f363a40e taeseongkim
                        if (gMarkusPDF != null)
475
                        {
476
                            gMarkusPDF.Dispose();
477
                            gMarkusPDF = null;
478
                        }
479 53c9637d taeseongkim
480
                        gMarkusPDF = new MarkusPDF();
481 2091a7e5 taeseongkim
                        gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
482 f363a40e taeseongkim
483
                        currentPageNo = currentPageNo - 1;
484
                    }
485
                    finally
486
                    {
487
                     
488 53c9637d taeseongkim
                    }
489
                }
490
491
                result.StatusCode = StatusCodeType.Completed;
492
            }
493
            catch (Exception ex)
494
            {
495
                result.StatusCode = StatusCodeType.Error;
496
                result.Message = ex.Message;
497
            }
498
499
            return result;
500
        }
501
502
        public bool Stop()
503
        {
504
            try
505
            {
506
                gSaveTask.Dispose();
507
            }
508
            catch (Exception ex)
509
            {
510
                System.Diagnostics.Debug.WriteLine(ex.ToString());
511
            }
512
513
            return true;
514
        }
515
516
517
        /// <summary>
518
        /// 사용안함
519
        /// </summary>
520
        /// <param name="param"></param>
521
        /// <returns></returns>
522
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
523
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
524
        //private SaveResult SetFile()
525
        //{
526
        //    var saveitem = new SaveItem
527
        //    {
528
        //        Id = ConvertProcessContext.ConvertID,
529
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
530
        //        SavePath = ConvertProcessContext.SaveDirectory,
531
        //        Status = StatusCodeType.None
532
        //    };
533
534
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
535
        //    {
536
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
537
        //    }
538
539
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
540
541
        //    try
542
        //    {
543
        //        Uri pdfFileUri = null;
544
545
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
546
        //        {
547
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
548
        //            {
549
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
550
551
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
552
        //                {
553
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
554
        //                }
555
556
        //                var downloadFilePath = System.IO.Path.Combine(ConvertProcessContext.TempDirectory, saveitem.Id.Replace("-", "") + ".pdf");
557
        //                webClient.DownloadFile(pdfFileUri, downloadFilePath);
558
559
        //                saveitem.PdfFilePath = downloadFilePath;
560
        //            }
561
        //        }
562
        //    }
563
        //    catch (Exception ex)
564
        //    {
565
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
566
        //    }
567
568
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
569
570
        //    var result = gSaveTask.SaveFile(saveitem);
571
572
        //    return result;
573
        //}
574
575
    }
576
}
클립보드 이미지 추가 (최대 크기: 500 MB)