프로젝트

일반

사용자정보

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

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

이력 | 보기 | 이력해설 | 다운로드 (22.1 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
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages,result.Message);
167
            }
168
            catch (Exception ex)
169
            {
170
                result.StatusCode = StatusCodeType.Error;
171
                logger.Error($"File Convert Error",ex);
172
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages, $"ConvertService Error    {saveitem.Id} {ex.Message} {ex.InnerException?.ToString()}");
173
            }
174

    
175
            return result;
176
        }
177

    
178
        [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
179
        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 =  LogHelper.GetStack() + " " +LogHelper.GetStack() + " " + msg;
197

    
198
                        return result;
199
                    }
200

    
201
                    System.Threading.Thread.SpinWait(10);
202
                }
203

    
204
                System.IO.Directory.CreateDirectory(saveitem.SavePath);
205

    
206
                //파일 다운로드
207
                if (await DownloadFileAsync(saveitem))
208
                {
209
                    gTempFileName = saveitem.PdfFilePath;
210

    
211
                    gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
212

    
213
                    /// 설정된 MultiThreadMaxPages에 따른 컨버터 분기
214
                    if (gMarkusPDF.PageCount() > ConvertProcessContext.MultiThreadMaxPages)
215
                    {
216
                        // 큰 사이즈의 파일 컨버팅
217
                        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
                    // 파일 체크 후 갯수가 안맞으면 다시 컨버팅한다.
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 =  LogHelper.GetStack() + " " +"Page Count Error";
235
                        ReConvert = 1;
236

    
237
                        result = ConvertBigFileProcess(saveitem);
238
                    }
239

    
240
                    ///  페이지 정보 저장
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
                            List<EntityModel.DOCPAGE> docPageList = new List<EntityModel.DOCPAGE>();
248

    
249
                            docPageList = result.PageInfoList.Select(f => new EntityModel.DOCPAGE
250
                            {
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
                            docSetResult = database.SetDocumentInfo(saveitem.Id, result.PageInfoList.Count, docPageList);
258
                        }
259

    
260
                        if (docSetResult)
261
                        {
262
                            result.StatusCode = StatusCodeType.Completed;
263
                        }
264
                        else
265
                        {
266
                            result.StatusCode = StatusCodeType.FileError;
267
                            result.Message =  LogHelper.GetStack() + " " + $"Doc Set Error. {result.Message}";
268
                        }
269
                    }
270
                    else
271
                    {
272
                        result.StatusCode = StatusCodeType.FileError;
273
                        result.Message =  LogHelper.GetStack() + " " +$"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 =  LogHelper.GetStack() + " " +"ConvertService Convert Error" + ex.Message;
285
                result.StatusCode = StatusCodeType.Error;
286

    
287
                logger.Error(ex);
288
            }
289
            finally
290
            {
291

    
292
            }
293

    
294
            return result;
295
        }
296

    
297
        /// <summary>
298
        /// 파일 다운로드
299
        /// </summary>
300
        /// <param name="saveItem"></param>
301
        /// <returns></returns>
302
        public async Task<bool> DownloadFileAsync(SaveItem saveItem)
303
        {
304
            bool result = false;
305

    
306
            try
307
            {
308
                Uri pdfFileUri = null;
309

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

    
326
                //}
327

    
328
                saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
329

    
330

    
331
                string FileName = "";
332
                string downloadFilePath = "";
333

    
334
                // 드라이브 경로가 포함되었는지 판단.
335
                if (Path.IsPathRooted(saveItem.PdfFilePath))
336
                {
337
                    FileInfo file = new FileInfo(saveItem.PdfFilePath);
338

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

    
357
                        using (System.Net.WebClient webClient = new System.Net.WebClient())
358
                        {
359
                            webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
360
                            webClient.Proxy = null;
361
                            //if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
362
                            //{
363
                            //    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
364
                            //}
365

    
366
                            await webClient.DownloadFileTaskAsync(pdfFileUri, downloadFilePath);
367
                            webClient.Dispose();
368
                        }
369

    
370
                        await Task.Delay(300);
371
                    }
372
                    catch (Exception ex)
373
                    {
374
                        logger.Error(ex);
375
                        throw new Exception("File Download Error. Please, check the file path.");
376
                    }
377
                }
378
                else
379
                {
380
                    throw new Exception("Please, check the file path.");
381
                }
382

    
383
                try
384
                {
385
                    if (File.Exists(downloadFilePath))
386
                    {
387
                        var file = File.Open(downloadFilePath, FileMode.Open);
388

    
389
                        if (file.Length == 0)
390
                        {
391
                            throw new Exception("File Size 0. Please, check the file path.");
392
                        }
393

    
394
                        file.Close();
395
                        file.Dispose();
396

    
397
                        saveItem.PdfFilePath = downloadFilePath;
398
                        result = true;
399

    
400
                    }
401
                }
402
                catch (Exception ex)
403
                {
404
                    logger.Error(ex);
405
                    throw new Exception("File Error ." + downloadFilePath);
406
                }
407
            }
408
            catch (Exception ex)
409
            {
410
                logger.Error(ex);
411
                throw new Exception(ex.ToString());
412
            }
413

    
414
            return result;
415
        }
416

    
417
        /// <summary>
418
        /// 큰파일 변환
419
        /// </summary>
420
        /// <param name="saveitem"></param>
421
        /// <returns></returns>
422
        private SaveResult ConvertBigFileProcess(SaveItem saveitem)
423
        {
424
            SaveResult result = new SaveResult();
425

    
426
            try
427
            {
428
                saveitem.TotalPages = gMarkusPDF.PageCount();
429

    
430
                for (int currentPageNo = 1; currentPageNo <= saveitem.TotalPages; currentPageNo++)
431
                {
432
                    try
433
                    {
434
                        string saveFile = Path.Combine(saveitem.SavePath, $"{currentPageNo}.png");
435

    
436
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
437
                         {
438

    
439
                            var saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
440

    
441
                            saveitem.Status = StatusCodeType.Saving;
442
                            saveitem.CurrentPage = currentPageNo;
443
                            saveitem.ErrorMessage = saveResult.Message;
444

    
445
                            int pageListCount = 0;
446

    
447
                            if(result.PageInfoList != null)
448
                            {
449
                                pageListCount = result.PageInfoList.Count(f => f.PageNo == saveResult.SavePageInfo.PageNo);
450
                            }
451
                            
452
                            if (pageListCount == 0)
453
                            {
454
                                result.PageInfoAdd(saveResult.SavePageInfo);
455
                            }
456

    
457
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(saveitem));
458
                            Console.WriteLine($"CurrentPage : {currentPageNo}");
459

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

    
465
                                gMarkusPDF.Dispose();
466
                                gMarkusPDF = null;
467
                                System.Threading.Thread.SpinWait(5);
468

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

    
473
                            System.Threading.Thread.SpinWait(2);
474
                        }
475
                    }
476
                    catch (Exception ex)
477
                    {
478
                        result.StatusCode = StatusCodeType.PageError;
479
                        result.Message =  LogHelper.GetStack() + " " +"Save Error - " + ex.Message;
480

    
481
                        if (gMarkusPDF != null)
482
                        {
483
                            gMarkusPDF.Dispose();
484
                            gMarkusPDF = null;
485
                        }
486

    
487
                        gMarkusPDF = new MarkusPDF();
488
                        gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
489

    
490
                        currentPageNo = currentPageNo - 1;
491
                    }
492
                    finally
493
                    {
494
                     
495
                    }
496
                }
497

    
498
                result.StatusCode = StatusCodeType.Completed;
499
            }
500
            catch (Exception ex)
501
            {
502
                result.StatusCode = StatusCodeType.Error;
503
                result.Message =  LogHelper.GetStack() + " " +ex.Message;
504
            }
505

    
506
            return result;
507
        }
508

    
509
        public bool Stop()
510
        {
511
            try
512
            {
513
                gSaveTask.Dispose();
514
            }
515
            catch (Exception ex)
516
            {
517
                System.Diagnostics.Debug.WriteLine(ex.ToString());
518
            }
519

    
520
            return true;
521
        }
522

    
523

    
524
        /// <summary>
525
        /// 사용안함
526
        /// </summary>
527
        /// <param name="param"></param>
528
        /// <returns></returns>
529
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
530
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
531
        //private SaveResult SetFile()
532
        //{
533
        //    var saveitem = new SaveItem
534
        //    {
535
        //        Id = ConvertProcessContext.ConvertID,
536
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
537
        //        SavePath = ConvertProcessContext.SaveDirectory,
538
        //        Status = StatusCodeType.None
539
        //    };
540

    
541
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
542
        //    {
543
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
544
        //    }
545

    
546
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
547

    
548
        //    try
549
        //    {
550
        //        Uri pdfFileUri = null;
551

    
552
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
553
        //        {
554
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
555
        //            {
556
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
557

    
558
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
559
        //                {
560
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
561
        //                }
562

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

    
566
        //                saveitem.PdfFilePath = downloadFilePath;
567
        //            }
568
        //        }
569
        //    }
570
        //    catch (Exception ex)
571
        //    {
572
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
573
        //    }
574

    
575
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
576

    
577
        //    var result = gSaveTask.SaveFile(saveitem);
578

    
579
        //    return result;
580
        //}
581

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