프로젝트

일반

사용자정보

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

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

이력 | 보기 | 이력해설 | 다운로드 (21.9 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 = 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 = "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 =  $"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
                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
                    catch (Exception ex)
371
                    {
372
                        logger.Error(ex);
373
                        throw new Exception("File Download Error. Please, check the file path.");
374
                    }
375
                }
376
                else
377
                {
378
                    throw new Exception("Please, check the file path.");
379
                }
380

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

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

    
392
                        file.Close();
393
                        file.Dispose();
394

    
395
                        saveItem.PdfFilePath = downloadFilePath;
396
                        result = true;
397

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

    
412
            return result;
413
        }
414

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

    
424
            try
425
            {
426
                saveitem.TotalPages = gMarkusPDF.PageCount();
427

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

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

    
437
                            var saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
438

    
439
                            saveitem.Status = StatusCodeType.Saving;
440
                            saveitem.CurrentPage = currentPageNo;
441
                            saveitem.ErrorMessage = saveResult.Message;
442

    
443
                            int pageListCount = 0;
444

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

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

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

    
463
                                gMarkusPDF.Dispose();
464
                                gMarkusPDF = null;
465
                                System.Threading.Thread.SpinWait(5);
466

    
467
                                gMarkusPDF = new MarkusPDF();
468
                                gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
469
                            }
470
                            System.Threading.Thread.SpinWait(2);
471
                        }
472
                    }
473
                    catch (Exception ex)
474
                    {
475
                        result.StatusCode = StatusCodeType.PageError;
476
                        result.Message = "Save Error - " + ex.Message;
477

    
478
                        if (gMarkusPDF != null)
479
                        {
480
                            gMarkusPDF.Dispose();
481
                            gMarkusPDF = null;
482
                        }
483

    
484
                        gMarkusPDF = new MarkusPDF();
485
                        gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
486

    
487
                        currentPageNo = currentPageNo - 1;
488
                    }
489
                    finally
490
                    {
491
                     
492
                    }
493
                }
494

    
495
                result.StatusCode = StatusCodeType.Completed;
496
            }
497
            catch (Exception ex)
498
            {
499
                result.StatusCode = StatusCodeType.Error;
500
                result.Message = ex.Message;
501
            }
502

    
503
            return result;
504
        }
505

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

    
517
            return true;
518
        }
519

    
520

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

    
538
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
539
        //    {
540
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
541
        //    }
542

    
543
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
544

    
545
        //    try
546
        //    {
547
        //        Uri pdfFileUri = null;
548

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

    
555
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
556
        //                {
557
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
558
        //                }
559

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

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

    
572
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
573

    
574
        //    var result = gSaveTask.SaveFile(saveitem);
575

    
576
        //    return result;
577
        //}
578

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