프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ 53c9637d

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

    
14
using System.Threading.Tasks;
15
using System.Web;
16

    
17
namespace Markus.Service.Convert
18
{
19
    public class ConvertService : IDisposable
20
    {
21
        // 1GigaBytes
22
        protected ILog logger;
23

    
24
        readonly ProcessContext ConvertProcessContext;
25
        private string gTempFileName;
26
        private Markus.SaveTask gSaveTask;
27
        private Markus.MarkusPDF gMarkusPDF;
28
     
29

    
30
        private StationService.StationServiceClient StationServiceClient; 
31

    
32
        public ConvertService(ProcessContext convertContext) : base()
33
        {
34
            logger = LogManager.GetLogger(typeof(ConvertService));
35

    
36
            ConvertProcessContext = convertContext;
37
            
38
            BasicHttpBinding myBinding = new BasicHttpBinding();
39
            EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(ConvertProcessContext.ServiceStationUri));
40
            StationServiceClient = new StationService.StationServiceClient(myBinding, myEndpoint);
41
           
42
            gMarkusPDF = new MarkusPDF();
43
            gSaveTask = new SaveTask();
44
            gSaveTask.StateChangeEvent += MarkusPdfStateChangeEvent;
45
        }
46

    
47
        public ConvertService()
48
        {
49
        }
50

    
51
        public void Dispose()
52
        {
53
            try
54
            {
55
                gMarkusPDF.Dispose();
56
                gSaveTask.Dispose();
57

    
58
                //if (System.IO.File.Exists(gTempFileName))
59
                //{
60
                //    File.Delete(gTempFileName);
61
                //}
62

    
63
            }
64
            catch (Exception ex)
65
            {
66
                logger.Error("Convert Service Dispose Error", ex);
67
            }
68
            finally
69
            {
70
                GC.Collect(2);
71
                GC.Collect(2);
72
            }
73
        }
74

    
75

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

    
87
                if (e.SaveItem.CurrentPage == 0)    /// 초기 wait status인 경우 0일수 있다. %계산시 오류 방지
88
                {
89
                    currentPage = 1;
90
                }
91

    
92
                if (ConvertProcessContext.SendStatusInterval % currentPage == 0)
93
                {
94
                    StationServiceClient.ConvertProcessStateAsync(e.SaveItem.Id, (int)e.SaveItem.Status, e.SaveItem.CurrentPage, e.SaveItem.TotalPages, e.SaveItem.ErrorMessage);
95
                }
96
                
97

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

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

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

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

    
150
                result = await ConvertAsync(saveitem);
151

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

    
160
            return result;
161
        }
162

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

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

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

    
182
                        return result;
183
                    }
184

    
185
                    System.Threading.Thread.Sleep(500);
186

    
187
                }
188

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

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

    
196
                    gMarkusPDF.pdfLoad(saveitem.PdfFilePath, ConvertProcessContext.MinFontSize);
197

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

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

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

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

    
230
                            docSetResult = database.SetDocumentInfo(ConvertProcessContext.ConvertID, result.PageInfoList.Count, docPageList);
231
                        }
232

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

    
263
            }
264

    
265
            return result;
266
        }
267

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

    
277
            try
278
            {
279
                Uri pdfFileUri = null;
280

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

    
297
                //}
298

    
299
                saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
300
                string FileName = string.Empty;
301

    
302
                if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB") || !saveItem.PdfFilePath.Contains("fileName"))
303
                {
304
                    FileName = saveItem.PdfFilePath.Remove(0, saveItem.PdfFilePath.LastIndexOf("/") + 1);
305
                }
306
                else
307
                {
308
                    FileName = HttpUtility.ParseQueryString(new Uri(saveItem.PdfFilePath).Query).Get("fileName");
309
                }
310
                
311
                string downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
312

    
313
                // 드라이브 경로가 포함되었는지 판단.
314
                if (Path.IsPathRooted(saveItem.PdfFilePath))
315
                {
316
                    if (File.Exists(saveItem.PdfFilePath))
317
                    {
318
                        File.Copy(saveItem.PdfFilePath, downloadFilePath, true);
319
                    }
320
                    else
321
                    {
322
                        throw new Exception("File Not Found. Please, check the file path.");
323
                    }
324
                }
325
                else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
326
                {
327
                    try
328
                    {
329
                        using (System.Net.WebClient webClient = new System.Net.WebClient())
330
                        {
331
                            webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
332

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

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

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

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

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

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

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

    
373
            return result;
374
        }
375

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

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

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

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

    
397
                    result.PageInfoAdd(saveResult.SavePageInfo);
398

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

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

    
407
                        gMarkusPDF.Dispose();
408
                        GC.Collect();
409
                        GC.WaitForPendingFinalizers();
410
                        GC.Collect();
411

    
412
                        gMarkusPDF = new MarkusPDF();
413
                        gMarkusPDF.pdfLoad(saveitem.PdfFilePath, ConvertProcessContext.MinFontSize);
414
                    }
415
                }
416

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

    
425
            return result;
426
        }
427

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

    
439
            return true;
440
        }
441

    
442

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

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

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

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

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

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

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

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

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

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

    
498
        //    return result;
499
        //}
500

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