프로젝트

일반

사용자정보

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

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

이력 | 보기 | 이력해설 | 다운로드 (21.4 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
                if (File.Exists(downloadFilePath))
378
                {
379
                    var file = File.Open(downloadFilePath, FileMode.Open);
380
381
                    if (file.Length == 0)
382
                    {
383
                        throw new Exception("File Size 0. Please, check the file path.");
384
                    }
385
386
                    file.Close();
387
                    file.Dispose();
388
389
                    saveItem.PdfFilePath = downloadFilePath;
390
                    result = true;
391
392
                }
393
            }
394 af9bffc5 taeseongkim
            catch (Exception ex)
395 f363a40e taeseongkim
            {                                                                                      
396 53c9637d taeseongkim
                result = false;
397
            }
398
399
            return result;
400
        }
401
402
        /// <summary>
403
        /// 큰파일 변환
404
        /// </summary>
405
        /// <param name="saveitem"></param>
406
        /// <returns></returns>
407
        private SaveResult ConvertBigFileProcess(SaveItem saveitem)
408
        {
409
            SaveResult result = new SaveResult();
410
411
            try
412
            {
413
                saveitem.TotalPages = gMarkusPDF.PageCount();
414
415
                for (int currentPageNo = 1; currentPageNo <= saveitem.TotalPages; currentPageNo++)
416
                {
417 f363a40e taeseongkim
                    try
418
                    {
419
                        string saveFile = Path.Combine(saveitem.SavePath, $"{currentPageNo}.png");
420 53c9637d taeseongkim
421 f363a40e taeseongkim
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
422
                         {
423 53c9637d taeseongkim
424 f363a40e taeseongkim
                            var saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
425 53c9637d taeseongkim
426 f363a40e taeseongkim
                            saveitem.Status = StatusCodeType.Saving;
427
                            saveitem.CurrentPage = currentPageNo;
428
                            saveitem.ErrorMessage = saveResult.Message;
429 53c9637d taeseongkim
430 f363a40e taeseongkim
                            int pageListCount = 0;
431
432
                            if(result.PageInfoList != null)
433
                            {
434
                                pageListCount = result.PageInfoList.Count(f => f.PageNo == saveResult.SavePageInfo.PageNo);
435
                            }
436
                            
437
                            if (pageListCount == 0)
438
                            {
439
                                result.PageInfoAdd(saveResult.SavePageInfo);
440
                            }
441
442
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(saveitem));
443
                            Console.WriteLine($"CurrentPage : {currentPageNo}");
444
445
                            /// 설정된 최대 페이지이거나 설정된 메모리보다 크면 릴리즈
446
                            if (currentPageNo % ConvertProcessContext.MultiThreadMaxPages == 0 || ConvertProcessContext.ReleaseWorkMemory < Environment.WorkingSet)
447
                            {
448
                                Console.WriteLine($"physical memory : {Environment.WorkingSet}");
449
450
                                gMarkusPDF.Dispose();
451
                                gMarkusPDF = null;
452
                                System.Threading.Thread.SpinWait(5);
453
454
                                gMarkusPDF = new MarkusPDF();
455
                                gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
456
                            }
457
                            System.Threading.Thread.SpinWait(2);
458
                        }
459
                    }
460
                    catch (Exception ex)
461 53c9637d taeseongkim
                    {
462 f363a40e taeseongkim
                        result.StatusCode = StatusCodeType.PageError;
463
                        result.Message = "Save Error - " + ex.Message;
464 53c9637d taeseongkim
465 f363a40e taeseongkim
                        if (gMarkusPDF != null)
466
                        {
467
                            gMarkusPDF.Dispose();
468
                            gMarkusPDF = null;
469
                        }
470 53c9637d taeseongkim
471
                        gMarkusPDF = new MarkusPDF();
472 2091a7e5 taeseongkim
                        gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
473 f363a40e taeseongkim
474
                        currentPageNo = currentPageNo - 1;
475
                    }
476
                    finally
477
                    {
478
                     
479 53c9637d taeseongkim
                    }
480
                }
481
482
                result.StatusCode = StatusCodeType.Completed;
483
            }
484
            catch (Exception ex)
485
            {
486
                result.StatusCode = StatusCodeType.Error;
487
                result.Message = ex.Message;
488
            }
489
490
            return result;
491
        }
492
493
        public bool Stop()
494
        {
495
            try
496
            {
497
                gSaveTask.Dispose();
498
            }
499
            catch (Exception ex)
500
            {
501
                System.Diagnostics.Debug.WriteLine(ex.ToString());
502
            }
503
504
            return true;
505
        }
506
507
508
        /// <summary>
509
        /// 사용안함
510
        /// </summary>
511
        /// <param name="param"></param>
512
        /// <returns></returns>
513
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
514
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
515
        //private SaveResult SetFile()
516
        //{
517
        //    var saveitem = new SaveItem
518
        //    {
519
        //        Id = ConvertProcessContext.ConvertID,
520
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
521
        //        SavePath = ConvertProcessContext.SaveDirectory,
522
        //        Status = StatusCodeType.None
523
        //    };
524
525
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
526
        //    {
527
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
528
        //    }
529
530
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
531
532
        //    try
533
        //    {
534
        //        Uri pdfFileUri = null;
535
536
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
537
        //        {
538
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
539
        //            {
540
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
541
542
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
543
        //                {
544
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
545
        //                }
546
547
        //                var downloadFilePath = System.IO.Path.Combine(ConvertProcessContext.TempDirectory, saveitem.Id.Replace("-", "") + ".pdf");
548
        //                webClient.DownloadFile(pdfFileUri, downloadFilePath);
549
550
        //                saveitem.PdfFilePath = downloadFilePath;
551
        //            }
552
        //        }
553
        //    }
554
        //    catch (Exception ex)
555
        //    {
556
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
557
        //    }
558
559
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
560
561
        //    var result = gSaveTask.SaveFile(saveitem);
562
563
        //    return result;
564
        //}
565
566
    }
567
}
클립보드 이미지 추가 (최대 크기: 500 MB)