프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ 60723dc9

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

    
31
        private StationServiceClient StationServiceClient; 
32

    
33
        /// <summary>
34
        /// 프로세스 초기화
35
        /// </summary>
36
        /// <param name="convertContext"></param>
37
        public ConvertService(ProcessContext convertContext) : base()
38
        {
39
            logger = LogManager.GetLogger(typeof(ConvertService));
40

    
41
            ConvertProcessContext = convertContext;
42
            
43
            BasicHttpBinding myBinding = new BasicHttpBinding();
44
            EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(ConvertProcessContext.ServiceStationUri));
45
            StationServiceClient = new StationServiceClient(myBinding, myEndpoint);
46
           
47
            gMarkusPDF = new MarkusPDF();
48
            gSaveTask = new SaveTask();
49
            gSaveTask.StateChangeEvent += MarkusPdfStateChangeEvent;
50
        }
51

    
52
        public ConvertService()
53
        {
54
        }
55

    
56
        public void Dispose()
57
        {
58
            try
59
            {
60
                gMarkusPDF.Dispose();
61
                gSaveTask.Dispose();
62

    
63
                //if (System.IO.File.Exists(gTempFileName))
64
                //{
65
                //    File.Delete(gTempFileName);
66
                //}
67

    
68
            }
69
            catch (Exception ex)
70
            {
71
                logger.Error("Convert Service Dispose Error", ex);
72
            }
73
            finally
74
            {
75
                GC.Collect(2);
76
                GC.Collect(2);
77
            }
78
        }
79

    
80

    
81
        /// <summary>
82
        ///  markus lib에서 받는 이벤트
83
        /// </summary>
84
        /// <param name="sender"></param>
85
        /// <param name="e"></param>
86
        private void MarkusPdfStateChangeEvent(object sender, Markus.Message.StateEventArgs e)
87
        {
88
            try
89
            {
90
                int currentPage = e.SaveItem.CurrentPage;
91

    
92
                if (e.SaveItem.CurrentPage == 0)    /// 초기 wait status인 경우 0일수 있다. %계산시 오류 방지
93
                {
94
                    currentPage = 1;
95
                }
96

    
97
                StationServiceClient.ConvertProcessStateAsync(e.SaveItem.Id, (int)e.SaveItem.Status, e.SaveItem.CurrentPage, e.SaveItem.TotalPages, e.SaveItem.ErrorMessage);
98
                
99
                switch (e.SaveItem.Status)
100
                {
101
                    case StatusCodeType.None:
102
                        break;
103
                    case StatusCodeType.Wait:
104
                        break;
105
                    case StatusCodeType.PageLoading:
106
                        break;
107
                    case StatusCodeType.Saving:
108
                        break;
109
                    case StatusCodeType.Completed:
110
                        gSaveTask.StateChangeEvent -= MarkusPdfStateChangeEvent;
111
                        gSaveTask.Dispose();
112
                        GC.Collect(2);
113
                        GC.Collect(2);
114
                        break;
115
                    case StatusCodeType.FileError:
116
                        break;
117
                    case StatusCodeType.PageError:
118
                        break;
119
                    case StatusCodeType.NeedsPassword:
120
                        break;
121
                    case StatusCodeType.Error:
122
                        break;
123
                    default:
124
                        break;
125
                }
126
            }
127
            catch (Exception ex)
128
            {
129
                logger.Error($"Status Change Error", ex);
130
            }
131
        }
132

    
133
        [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
134
        public async Task<SaveResult> SetFileAsync()
135
        {
136
            SaveResult result = new SaveResult();
137

    
138
            SaveItem saveitem = new SaveItem
139
            {
140
                Id = ConvertProcessContext.ConvertID,
141
                PdfFilePath = ConvertProcessContext.OriginFilePath,
142
                SavePath = ConvertProcessContext.SaveDirectory,
143
                Status = StatusCodeType.None,
144
                MinimumFontSize = ConvertProcessContext.MinFontSize,
145
                UseResolution = ConvertProcessContext.UseResolution
146
            };
147

    
148
            try
149
            {
150
                StationServiceClient.ConvertProcessState(ConvertProcessContext.ConvertID, (int)StatusCodeType.Wait, 0, 0, "");
151

    
152
                result = await ConvertAsync(saveitem);
153

    
154
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages,result.Message);
155
            }
156
            catch (Exception ex)
157
            {
158
                logger.Error($"File Convert Error",ex);
159
                StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages, $"ConvertService Error    {saveitem.Id}");
160
            }
161

    
162
            return result;
163
        }
164

    
165
        private async Task<SaveResult> ConvertAsync(SaveItem saveitem)
166
        { 
167
            SaveResult result = new SaveResult();
168
         
169
            try
170
            {
171
                DateTime deleteTime = DateTime.Now;
172

    
173
                while (System.IO.Directory.Exists(saveitem.SavePath))
174
                {
175
                    System.IO.Directory.Delete(saveitem.SavePath, true);
176

    
177
                    if ((DateTime.Now - deleteTime) > new TimeSpan(0, 5, 0))
178
                    {
179
                        string msg = $"ConvertService Error {saveitem.SavePath} Delete Error";
180
                        logger.Error(msg);
181
                        result.StatusCode = StatusCodeType.FileError;
182
                        result.Message = msg;
183

    
184
                        return result;
185
                    }
186

    
187
                    System.Threading.Thread.SpinWait(10);
188
                }
189

    
190
                System.IO.Directory.CreateDirectory(saveitem.SavePath);
191

    
192
                //파일 다운로드
193
                if (await DownloadFileAsync(saveitem))
194
                {
195
                    gTempFileName = saveitem.PdfFilePath;
196

    
197
                    gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
198

    
199
                    /// 설정된 MultiThreadMaxPages에 따른 컨버터 분기
200
                    if (gMarkusPDF.PageCount() > ConvertProcessContext.MultiThreadMaxPages)
201
                    {
202
                        /// 큰 사이즈의 파일 컨버팅
203
                        result = ConvertBigFileProcess(saveitem);
204
                    }
205
                    else
206
                    {
207
                        /// 작은 사이즈의 컨버팅
208
                        await Task.Factory.StartNew(new Action(() =>
209
                        {
210
                            result = gSaveTask.SaveFile(saveitem);
211

    
212
                        }), TaskCreationOptions.LongRunning);
213
                    }
214

    
215
                    ///  페이지 정보 저장
216
                    if (result.PageInfoList?.Count() > 0)
217
                    {
218
                        bool docSetResult = false;
219

    
220
                        using (Markus.Service.DataBase.ConvertDatabase database = new Markus.Service.DataBase.ConvertDatabase(ConvertProcessContext.ConnectionString))
221
                        {
222
                            List<EntityModel.DOCPAGE> docPageList = new List<EntityModel.DOCPAGE>();
223

    
224
                            docPageList = result.PageInfoList.Select(f => new EntityModel.DOCPAGE
225
                            {
226
                                ID = GuidExtension.shortGuid(),
227
                                PAGE_WIDTH = f.Width.ToString(),
228
                                PAGE_HEIGHT = f.Height.ToString(),
229
                                PAGE_NUMBER = f.PageNo
230
                            }).ToList();
231

    
232
                            docSetResult = database.SetDocumentInfo(saveitem.Id, result.PageInfoList.Count, docPageList);
233
                        }
234

    
235
                        if (docSetResult)
236
                        {
237
                            result.StatusCode = StatusCodeType.Completed;
238
                        }
239
                        else
240
                        {
241
                            result.StatusCode = StatusCodeType.FileError;
242
                            result.Message =  $"Doc Set Error. {result.Message}";
243
                        }
244
                    }
245
                    else
246
                    {
247
                        result.StatusCode = StatusCodeType.FileError;
248
                        result.Message = $"Page List Get Error. {result.Message} ";
249
                    }
250
                }
251
                else
252
                {
253
                    result.Message  = $"File Download Error  - File path : { saveitem.PdfFilePath}";
254
                    result.StatusCode = StatusCodeType.FileError;
255
                }
256
            }
257
            catch (Exception ex)
258
            {
259
                result.Message = "ConvertService Convert Error" + ex.Message;
260
                result.StatusCode = StatusCodeType.Error;
261
            }
262
            finally
263
            {
264

    
265
            }
266

    
267
            return result;
268
        }
269

    
270
        /// <summary>
271
        /// 파일 다운로드
272
        /// </summary>
273
        /// <param name="saveItem"></param>
274
        /// <returns></returns>
275
        private async Task<bool> DownloadFileAsync(SaveItem saveItem)
276
        {
277
            bool result = false;
278

    
279
            try
280
            {
281
                Uri pdfFileUri = null;
282

    
283
                //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB"))
284
                //{
285
                //    FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
286
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
287
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
288
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
289
                //    DownloadFilePath = ItemPath + "\\" + FileName;
290
                //}
291
                //else
292
                //{
293
                //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
294
                //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
295
                //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
296
                //    FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName");
297
                //    DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName;
298

    
299
                //}
300

    
301
                saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
302

    
303

    
304
                string FileName = "";
305
                string downloadFilePath = "";
306

    
307
                // 드라이브 경로가 포함되었는지 판단.
308
                if (Path.IsPathRooted(saveItem.PdfFilePath))
309
                {
310
                    FileInfo file = new FileInfo(saveItem.PdfFilePath);
311

    
312
                    if (file.Exists)
313
                    {
314
                        FileName = file.Name;
315
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
316
                        file.CopyTo(downloadFilePath, true);
317
                    }
318
                    else
319
                    {
320
                        throw new Exception("File Not Found. Please, check the file path.");
321
                    }
322
                }
323
                else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
324
                {
325
                    try
326
                    {
327
                        FileName = DownloadUri.GetFileName(saveItem.PdfFilePath);
328
                        downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
329

    
330
                        using (System.Net.WebClient webClient = new System.Net.WebClient())
331
                        {
332
                            webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
333

    
334
                            //if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
335
                            //{
336
                            //    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
337
                            //}
338

    
339
                            await webClient.DownloadFileTaskAsync(pdfFileUri, downloadFilePath);
340
                        }
341
                    }
342
                    catch (Exception)
343
                    {
344
                        throw new Exception("File Download Error. Please, check the file path.");
345
                    }
346
                }
347
                else
348
                {
349
                    throw new Exception("Please, check the file path.");
350
                }
351

    
352
                if (File.Exists(downloadFilePath))
353
                {
354
                    var file = File.Open(downloadFilePath, FileMode.Open);
355

    
356
                    if (file.Length == 0)
357
                    {
358
                        throw new Exception("File Size 0. Please, check the file path.");
359
                    }
360

    
361
                    file.Close();
362
                    file.Dispose();
363

    
364
                    saveItem.PdfFilePath = downloadFilePath;
365
                    result = true;
366

    
367
                }
368
            }
369
            catch (Exception)
370
            {
371
                result = false;
372
            }
373

    
374
            return result;
375
        }
376

    
377
        /// <summary>
378
        /// 큰파일 변환
379
        /// </summary>
380
        /// <param name="saveitem"></param>
381
        /// <returns></returns>
382
        private SaveResult ConvertBigFileProcess(SaveItem saveitem)
383
        {
384
            SaveResult result = new SaveResult();
385

    
386
            try
387
            {
388
                saveitem.TotalPages = gMarkusPDF.PageCount();
389

    
390
                for (int currentPageNo = 1; currentPageNo <= saveitem.TotalPages; currentPageNo++)
391
                {
392
                    var saveResult = gMarkusPDF.SavePage(currentPageNo, Path.Combine(saveitem.SavePath, $"{currentPageNo}.png"));
393

    
394
                    saveitem.Status = StatusCodeType.Saving;
395
                    saveitem.CurrentPage = currentPageNo;
396
                    saveitem.ErrorMessage = saveResult.Message;
397

    
398
                    result.PageInfoAdd(saveResult.SavePageInfo);
399

    
400
                    MarkusPdfStateChangeEvent(this, new StateEventArgs(saveitem));
401
                    Console.WriteLine($"CurrentPage : {currentPageNo}");
402

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

    
408
                        gMarkusPDF.Dispose();
409

    
410
                        System.Threading.Thread.SpinWait(5);
411

    
412
                        gMarkusPDF = new MarkusPDF();
413
                        gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution);
414
                    }
415
                    System.Threading.Thread.SpinWait(2);
416
                }
417

    
418
                result.StatusCode = StatusCodeType.Completed;
419
            }
420
            catch (Exception ex)
421
            {
422
                result.StatusCode = StatusCodeType.Error;
423
                result.Message = ex.Message;
424
            }
425

    
426
            return result;
427
        }
428

    
429
        public bool Stop()
430
        {
431
            try
432
            {
433
                gSaveTask.Dispose();
434
            }
435
            catch (Exception ex)
436
            {
437
                System.Diagnostics.Debug.WriteLine(ex.ToString());
438
            }
439

    
440
            return true;
441
        }
442

    
443

    
444
        /// <summary>
445
        /// 사용안함
446
        /// </summary>
447
        /// <param name="param"></param>
448
        /// <returns></returns>
449
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
450
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
451
        //private SaveResult SetFile()
452
        //{
453
        //    var saveitem = new SaveItem
454
        //    {
455
        //        Id = ConvertProcessContext.ConvertID,
456
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
457
        //        SavePath = ConvertProcessContext.SaveDirectory,
458
        //        Status = StatusCodeType.None
459
        //    };
460

    
461
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
462
        //    {
463
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
464
        //    }
465

    
466
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
467

    
468
        //    try
469
        //    {
470
        //        Uri pdfFileUri = null;
471

    
472
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
473
        //        {
474
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
475
        //            {
476
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
477

    
478
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
479
        //                {
480
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
481
        //                }
482

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

    
486
        //                saveitem.PdfFilePath = downloadFilePath;
487
        //            }
488
        //        }
489
        //    }
490
        //    catch (Exception ex)
491
        //    {
492
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
493
        //    }
494

    
495
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
496

    
497
        //    var result = gSaveTask.SaveFile(saveitem);
498

    
499
        //    return result;
500
        //}
501

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