프로젝트

일반

사용자정보

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

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

이력 | 보기 | 이력해설 | 다운로드 (32 KB)

1 53c9637d taeseongkim
using log4net;
2
using Markus.Message;
3
using Markus.Service.Helper;
4
using System;
5
using System.Collections.Generic;
6
using System.IO;
7
using System.Linq;
8
using System.Net.Http;
9
using System.ServiceModel;
10
using System.Text;
11
using Markus.Service.Extensions;
12 06f13e11 taeseongkim
using Markus.Service.WcfClient.StationServiceAsync;
13 53c9637d taeseongkim
14
using System.Threading.Tasks;
15
using System.Web;
16 1d79913e taeseongkim
using StatusCodeType = Markus.Message.StatusCodeType;
17 a5e5fff6 taeseongkim
using Microsoft.SqlServer.Server;
18
using System.Web.UI;
19
using Markus.Service.DataBase.Entities;
20
using Markus.Service.DataBase.Repositories;
21 53c9637d taeseongkim
22
namespace Markus.Service.Convert
23
{
24
    public class ConvertService : IDisposable
25
    {
26
        // 1GigaBytes
27
        protected ILog logger;
28
29
        readonly ProcessContext ConvertProcessContext;
30
        private Markus.SaveTask gSaveTask;
31
        private Markus.MarkusPDF gMarkusPDF;
32 950e6b84 taeseongkim
        private string gFontsFolder;
33
        private bool gIsApiDownload;
34 f363a40e taeseongkim
35
        // 컨버터 완료시 파일갯수를 체크 하여 틀리면 reconvert를 1로 하고 다시 컨버팅 하도록 한다.
36
        private int ReConvert;
37
38 53c9637d taeseongkim
39 06f13e11 taeseongkim
        private StationServiceClient StationServiceClient; 
40 53c9637d taeseongkim
41 a53dfe45 taeseongkim
        /// <summary>
42
        /// 프로세스 초기화
43
        /// </summary>
44
        /// <param name="convertContext"></param>
45 53c9637d taeseongkim
        public ConvertService(ProcessContext convertContext) : base()
46
        {
47
            logger = LogManager.GetLogger(typeof(ConvertService));
48
49
            ConvertProcessContext = convertContext;
50
            
51 a5e5fff6 taeseongkim
            BasicHttpBinding myBinding = new BasicHttpBinding { TransferMode = TransferMode.Buffered };
52
53
            myBinding.CloseTimeout = new TimeSpan(0, 10, 0);
54
            myBinding.ReceiveTimeout = new TimeSpan(0, 10, 0);
55
            myBinding.SendTimeout = new TimeSpan(0, 10, 0);
56
            myBinding.OpenTimeout = new TimeSpan(0, 10, 0);
57
58 53c9637d taeseongkim
            EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(ConvertProcessContext.ServiceStationUri));
59 06f13e11 taeseongkim
            StationServiceClient = new StationServiceClient(myBinding, myEndpoint);
60 950e6b84 taeseongkim
            gIsApiDownload = ConvertProcessContext.IsApiDownload;
61
62
             gMarkusPDF = new MarkusPDF();
63
            
64 53c9637d taeseongkim
            gSaveTask = new SaveTask();
65 950e6b84 taeseongkim
66
            if (!string.IsNullOrWhiteSpace(ConvertProcessContext.FontsFolder))
67
            {
68
                gFontsFolder = ConvertProcessContext.FontsFolder;
69
                gSaveTask.SetFontsFolder(ConvertProcessContext.FontsFolder);
70
            }
71
72 53c9637d taeseongkim
            gSaveTask.StateChangeEvent += MarkusPdfStateChangeEvent;
73
        }
74
75
        public ConvertService()
76
        {
77
        }
78
79
        public void Dispose()
80
        {
81
            try
82
            {
83 65fbe3cb taeseongkim
                if(gMarkusPDF != null)
84
                {
85
                    gMarkusPDF.Dispose();
86
                    gMarkusPDF = null;
87
                }
88
89
                if (gSaveTask != null)
90
                {
91
                    gSaveTask.StateChangeEvent -= MarkusPdfStateChangeEvent;
92
                    gSaveTask.Dispose();
93
                    gSaveTask = null;
94
                }
95 53c9637d taeseongkim
96
                //if (System.IO.File.Exists(gTempFileName))
97
                //{
98
                //    File.Delete(gTempFileName);
99
                //}
100
101
            }
102
            catch (Exception ex)
103
            {
104 65fbe3cb taeseongkim
               logger.Error("Convert Service Dispose Error", ex);
105 53c9637d taeseongkim
            }
106
            finally
107
            {
108
                GC.Collect(2);
109
                GC.Collect(2);
110
            }
111
        }
112
113
        /// <summary>
114
        ///  markus lib에서 받는 이벤트
115
        /// </summary>
116
        /// <param name="sender"></param>
117
        /// <param name="e"></param>
118
        private void MarkusPdfStateChangeEvent(object sender, Markus.Message.StateEventArgs e)
119
        {
120
            try
121
            {
122
                int currentPage = e.SaveItem.CurrentPage;
123
124
                if (e.SaveItem.CurrentPage == 0)    /// 초기 wait status인 경우 0일수 있다. %계산시 오류 방지
125
                {
126
                    currentPage = 1;
127
                }
128
129
                switch (e.SaveItem.Status)
130
                {
131 1d79913e taeseongkim
                    case Message.StatusCodeType.None:
132 53c9637d taeseongkim
                        break;
133 1d79913e taeseongkim
                    case Message.StatusCodeType.Wait:
134 53c9637d taeseongkim
                        break;
135 1d79913e taeseongkim
                    case Message.StatusCodeType.PageLoading:
136 53c9637d taeseongkim
                        break;
137 1d79913e taeseongkim
                    case Message.StatusCodeType.Saving:
138 53c9637d taeseongkim
                        break;
139 1d79913e taeseongkim
                    case Message.StatusCodeType.Completed:
140 53c9637d taeseongkim
                        break;
141 1d79913e taeseongkim
                    case Message.StatusCodeType.FileError:
142 53c9637d taeseongkim
                        break;
143 1d79913e taeseongkim
                    case Message.StatusCodeType.PageError:
144 53c9637d taeseongkim
                        break;
145 1d79913e taeseongkim
                    case Message.StatusCodeType.FontNotFound:
146 950e6b84 taeseongkim
                        break;
147 1d79913e taeseongkim
                    case Message.StatusCodeType.NeedsPassword:
148 53c9637d taeseongkim
                        break;
149 1d79913e taeseongkim
                    case Message.StatusCodeType.Error:
150 53c9637d taeseongkim
                        break;
151
                    default:
152
                        break;
153
                }
154 d91efe5c taeseongkim
#if PROCESS_TEST
155
                Console.WriteLine($"send wcf service {e.SaveItem.Status}  currentPage : {e.SaveItem.CurrentPage} error message : {(string.IsNullOrWhiteSpace(e.SaveItem.ErrorMessage)?"null":e.SaveItem.ErrorMessage)}");
156
#endif
157 43e1d368 taeseongkim
                StationServiceClient.ConvertProcessState(e.SaveItem.Id, (int)e.SaveItem.Status, e.SaveItem.CurrentPage, e.SaveItem.TotalPages, e.SaveItem.ErrorMessage);
158 d91efe5c taeseongkim
159 53c9637d taeseongkim
            }
160
            catch (Exception ex)
161
            {
162
                logger.Error($"Status Change Error", ex);
163
            }
164
        }
165
166 43e1d368 taeseongkim
        [System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
167 53c9637d taeseongkim
        [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
168 43e1d368 taeseongkim
        public SaveItem SetFile()
169 53c9637d taeseongkim
        {
170
            SaveItem saveitem = new SaveItem
171
            {
172
                Id = ConvertProcessContext.ConvertID,
173
                PdfFilePath = ConvertProcessContext.OriginFilePath,
174
                SavePath = ConvertProcessContext.SaveDirectory,
175
                Status = StatusCodeType.None,
176 2091a7e5 taeseongkim
                MinimumFontSize = ConvertProcessContext.MinFontSize,
177
                UseResolution = ConvertProcessContext.UseResolution
178 53c9637d taeseongkim
            };
179
180
            try
181
            {
182 950e6b84 taeseongkim
#if PROCESS_TEST
183
184
            Console.WriteLine($"ConvertID : {ConvertProcessContext.ConvertID} : {StatusCodeType.Wait.ToString()}");
185 53c9637d taeseongkim
186 950e6b84 taeseongkim
#endif
187 d91efe5c taeseongkim
                StationServiceClient.ConvertProcessState(ConvertProcessContext.ConvertID, (int)StatusCodeType.Wait, 0, 0, "");
188 950e6b84 taeseongkim
189 43e1d368 taeseongkim
                var result = Convert(saveitem);
190 53c9637d taeseongkim
191 d91efe5c taeseongkim
                saveitem.Status = result.StatusCode;
192
                saveitem.ErrorMessage = result.Message;
193 a5e5fff6 taeseongkim
                
194
                if (saveitem.Status < StatusCodeType.Completed)
195 1d79913e taeseongkim
                {
196
                    saveitem.Status = StatusCodeType.Error;
197
                    saveitem.ErrorMessage = "unknown error";
198
                }
199
200
                MarkusPdfStateChangeEvent(this, new StateEventArgs(new SaveItem
201
                {
202
                    ErrorMessage = saveitem.ErrorMessage,
203
                    Id = saveitem.Id,
204
                    CurrentPage = saveitem.CurrentPage,
205
                    TotalPages = saveitem.TotalPages,
206
                    Status = saveitem.Status
207
                }));
208
209 7b095cc3 taeseongkim
210 d91efe5c taeseongkim
                StationServiceClient.ConvertFinish(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
211 53c9637d taeseongkim
            }
212
            catch (Exception ex)
213
            {
214 43e1d368 taeseongkim
                if (saveitem.Status <= StatusCodeType.Completed)
215
                {
216
                    saveitem.Status = StatusCodeType.Error;
217
                }
218
219
                saveitem.ErrorMessage = saveitem.ErrorMessage  + "    Exception : " +  ex.ToString();
220
221
                if( ex.InnerException != null)
222
                {
223
                    saveitem.ErrorMessage = saveitem.ErrorMessage + "  InnerException : " + ex.InnerException.ToString();
224
                }
225
226 950e6b84 taeseongkim
                logger.Error($"File Convert Error", ex);
227
228 a5e5fff6 taeseongkim
                logger.Error($"saveitem.Id : {saveitem.Id} , StatusCode:{(int)saveitem.Status}, CurrentPage : {saveitem.CurrentPage}, TotalPages : {saveitem.TotalPages} , Error : {saveitem.ErrorMessage}");
229
                StationServiceClient.ConvertFinish(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, $"ConvertService Error    {saveitem.Id} {saveitem.ErrorMessage }");
230
            }
231
232
            try
233
            {
234
                // 플러그인 실행
235 950e6b84 taeseongkim
#if PROCESS_TEST
236
237
                Console.WriteLine($"run Plugin : {saveitem.Id}");
238
#endif
239 a5e5fff6 taeseongkim
                PluginService.Run(saveitem.Id);
240 d91efe5c taeseongkim
241 a5e5fff6 taeseongkim
#if PROCESS_TEST
242
243
                Console.WriteLine($"finish!!!");
244
#endif
245
            }
246
            catch (Exception ex)
247
            {
248
249
                throw;
250 950e6b84 taeseongkim
            }
251 d91efe5c taeseongkim
252
            return saveitem;
253 53c9637d taeseongkim
        }
254
255 a5e5fff6 taeseongkim
        private bool MoveOldFiles(string originPath)
256
        {
257
            bool result = false;
258
259
            try
260
            {
261
                DirectoryInfo dir = new DirectoryInfo(originPath);
262
            }
263
            catch (Exception)
264
            {
265
            }
266
267
            return result;
268
        }
269
270 43e1d368 taeseongkim
        private SaveResult Convert(SaveItem saveitem)
271 53c9637d taeseongkim
        { 
272
            SaveResult result = new SaveResult();
273
         
274
            try
275
            {
276
                DateTime deleteTime = DateTime.Now;
277
278
                while (System.IO.Directory.Exists(saveitem.SavePath))
279
                {
280 7b095cc3 taeseongkim
                    try
281
                    {
282
                        System.IO.Directory.Delete(saveitem.SavePath, true);
283
                    }
284 950e6b84 taeseongkim
                    catch (Exception ex)
285 7b095cc3 taeseongkim
                    {
286 950e6b84 taeseongkim
#if PROCESS_TEST
287
                        Console.WriteLine(ex.ToString());
288
#endif
289 7b095cc3 taeseongkim
                    }
290 53c9637d taeseongkim
291
                    if ((DateTime.Now - deleteTime) > new TimeSpan(0, 5, 0))
292
                    {
293
                        string msg = $"ConvertService Error {saveitem.SavePath} Delete Error";
294
                        logger.Error(msg);
295
                        result.StatusCode = StatusCodeType.FileError;
296 c5519c44 taeseongkim
                        result.Message =  LogHelper.GetStack() + " " +LogHelper.GetStack() + " " + msg;
297 950e6b84 taeseongkim
#if PROCESS_TEST
298
                        Console.WriteLine($"{StatusCodeType.FileError.ToString()} : {result.Message} ");
299
#endif
300 53c9637d taeseongkim
                        return result;
301
                    }
302
303 60723dc9 taeseongkim
                    System.Threading.Thread.SpinWait(10);
304 53c9637d taeseongkim
                }
305
306
                System.IO.Directory.CreateDirectory(saveitem.SavePath);
307
308
                //파일 다운로드
309 1d79913e taeseongkim
                var fileDownloadResult = DownloadFile(saveitem);
310
311
                if (fileDownloadResult.IsSuccess)
312 53c9637d taeseongkim
                {
313 1d79913e taeseongkim
                    string downloadFilePath = fileDownloadResult.DownloadFilePath;
314
315 d91efe5c taeseongkim
                    var status =  gMarkusPDF.pdfLoad(downloadFilePath, saveitem.MinimumFontSize, saveitem.UseResolution, gFontsFolder);
316 53c9637d taeseongkim
317 d91efe5c taeseongkim
                    if (gMarkusPDF.PageCount() > 0)
318 53c9637d taeseongkim
                    {
319 1d79913e taeseongkim
                        saveitem.TotalPages = gMarkusPDF.PageCount();
320
321 504c5aa1 taeseongkim
                        /// 설정된 MultiThreadMaxPages에 따른 컨버터 분기
322 43e1d368 taeseongkim
                        if (gMarkusPDF.PageCount() > ConvertProcessContext.MultiThreadMaxPages)
323
                        {
324
                            // 큰 사이즈의 파일 컨버팅
325 1d79913e taeseongkim
                            result = ConvertBigFileProcess(saveitem.TotalPages, saveitem.Id, downloadFilePath,saveitem.SavePath, saveitem.MinimumFontSize,saveitem.UseResolution,gFontsFolder);
326 43e1d368 taeseongkim
                        }
327
                        else
328
                        {
329
                            /// 작은 사이즈의 컨버팅
330 1d79913e taeseongkim
                            result = gSaveTask.SaveFile(new Markus.Message.SaveItem
331 43e1d368 taeseongkim
                            {
332 1d79913e taeseongkim
                                PdfFilePath = downloadFilePath,
333
                                SavePath = saveitem.SavePath,
334
                                MinimumFontSize = saveitem.MinimumFontSize,
335
                                UseResolution = saveitem.UseResolution
336
                            });
337 43e1d368 taeseongkim
                        }
338 1d79913e taeseongkim
                        
339
                        saveitem.Status = result.StatusCode;
340
                        saveitem.ErrorMessage = result.Message;
341 43e1d368 taeseongkim
342
                        if ((int)result.StatusCode <= (int)StatusCodeType.Completed)
343 504c5aa1 taeseongkim
                        {
344 d91efe5c taeseongkim
                            // 파일 체크 후 갯수가 안맞으면 다시 컨버팅한다.
345
                            if (ReConvert < 1 && (result.PageInfoList?.Count() != saveitem.TotalPages
346
                                           || Directory.EnumerateFiles(saveitem.SavePath, "*.png").Count() != saveitem.TotalPages
347
                                               || Directory.EnumerateFiles(saveitem.SavePath, "*.jpg").Count() != saveitem.TotalPages))
348
                            {
349
                            
350
                                ///statuscode가 완료 또는 정상인데 페이지가 맞지 않는 경우 pageError로 처리
351
                                if (result.StatusCode <= StatusCodeType.Completed)
352
                                {
353
                                    result.StatusCode = StatusCodeType.PageError;
354
                                    result.Message = LogHelper.GetStack() + "Page Error : " + result.Message;
355
                                }
356 f363a40e taeseongkim
357 d91efe5c taeseongkim
                                ReConvert = 1;
358 53c9637d taeseongkim
359 1d79913e taeseongkim
                                result = ConvertBigFileProcess(saveitem.TotalPages, saveitem.Id, downloadFilePath, saveitem.SavePath, saveitem.MinimumFontSize, saveitem.UseResolution, gFontsFolder);
360
361
                                saveitem.Status = result.StatusCode;
362
                                saveitem.ErrorMessage = result.Message;
363 d91efe5c taeseongkim
                            }
364 53c9637d taeseongkim
365 d91efe5c taeseongkim
                            ///  페이지 정보 저장
366
                            if (result.PageInfoList?.Count() > 0)
367 53c9637d taeseongkim
                            {
368 d91efe5c taeseongkim
                                bool docSetResult = false;
369 53c9637d taeseongkim
370 d91efe5c taeseongkim
                                try
371 504c5aa1 taeseongkim
                                {
372 a5e5fff6 taeseongkim
                                    using (DOCINFORepository dOCINFORepository = new DOCINFORepository(ConvertProcessContext.ConnectionString))
373 d91efe5c taeseongkim
                                    {
374 a5e5fff6 taeseongkim
                                        var docinfoId = dOCINFORepository.CreateAsync(convertDocID: saveitem.Id, PageCount: result.PageInfoList.Count()).GetAwaiter().GetResult();
375 d91efe5c taeseongkim
376 a5e5fff6 taeseongkim
                                        using (DOCPAGERepository database = new DOCPAGERepository(ConvertProcessContext.ConnectionString))
377 d91efe5c taeseongkim
                                        {
378 a5e5fff6 taeseongkim
                                            var docPageList = result.PageInfoList.Select(f => new DOCPAGE
379
                                            {
380
                                                DOCINFO_ID = docinfoId,
381
                                                PAGE_ANGLE = 0,
382
                                                PAGE_WIDTH = f.Width.ToString(),
383
                                                PAGE_HEIGHT = f.Height.ToString(),
384
                                                PAGE_NUMBER = f.PageNo
385
                                            });
386
387
                                            docSetResult = database.CreateAsync(docPageList).GetAwaiter().GetResult();
388
                                        }
389 d91efe5c taeseongkim
                                    }
390 a5e5fff6 taeseongkim
391
                                    saveitem.CurrentPage = result.PageInfoList.Max(x => x.PageNo);
392
393 d91efe5c taeseongkim
                                }
394
                                catch (Exception ex)
395
                                {
396 a5e5fff6 taeseongkim
                                    result.Message += LogHelper.GetStack() + " " + $"Doc Set Error. {ex.Message}";
397 d91efe5c taeseongkim
                                }
398 504c5aa1 taeseongkim
399 d91efe5c taeseongkim
                                if (docSetResult)
400
                                {
401
                                    result.StatusCode = StatusCodeType.Completed;
402
                                }
403
                                else
404
                                {
405
                                    result.StatusCode = StatusCodeType.FileError;
406
                                    result.Message = LogHelper.GetStack() + " " + $"Doc Set Error. {result.Message}";
407
                                }
408 504c5aa1 taeseongkim
                            }
409
                            else
410
                            {
411
                                result.StatusCode = StatusCodeType.FileError;
412 d91efe5c taeseongkim
                                result.Message = LogHelper.GetStack() + " " + $"Page List Get Error. {result.Message} ";
413 504c5aa1 taeseongkim
                            }
414 53c9637d taeseongkim
                        }
415
                    }
416
                    else
417
                    {
418 d91efe5c taeseongkim
                        result.Message = $"{status.Message}. File path : { saveitem.PdfFilePath}";
419
                        result.StatusCode = status.StatusCode;
420 53c9637d taeseongkim
                    }
421
                }
422
                else
423
                {
424
                    result.Message  = $"File Download Error  - File path : { saveitem.PdfFilePath}";
425
                    result.StatusCode = StatusCodeType.FileError;
426
                }
427
            }
428
            catch (Exception ex)
429
            {
430 d91efe5c taeseongkim
                result.Message =  LogHelper.GetStack() + " " +"ConvertService Convert Error " + ex.Message;
431 53c9637d taeseongkim
                result.StatusCode = StatusCodeType.Error;
432 a2a64028 taeseongkim
433
                logger.Error(ex);
434 53c9637d taeseongkim
            }
435
            finally
436
            {
437 d91efe5c taeseongkim
                if (gMarkusPDF != null)
438
                {
439
                    gMarkusPDF.Dispose();
440
                    gMarkusPDF = null;
441
                }
442 53c9637d taeseongkim
443
            }
444
445
            return result;
446
        }
447
448 1d79913e taeseongkim
        public FileDownloadResult DownloadFile(SaveItem saveItem)
449 d91efe5c taeseongkim
        {
450 1d79913e taeseongkim
            FileDownloadResult result = new FileDownloadResult();
451
452 d91efe5c taeseongkim
            try
453
            {
454 1d79913e taeseongkim
                result = DownloadPluginService.Download(saveItem.PdfFilePath, saveItem.SavePath);
455 d91efe5c taeseongkim
            }
456
            catch (Exception ex)
457
            {
458
                logger.Error(ex);
459 1d79913e taeseongkim
                result.IsSuccess = false;
460
                result.Exception = new Exception(ex.ToString());
461 d91efe5c taeseongkim
            }
462
463
            return result;
464
        }
465
466 43e1d368 taeseongkim
        ///// <summary>
467
        ///// 파일 다운로드
468
        ///// </summary>
469
        ///// <param name="saveItem"></param>
470
        ///// <returns></returns>
471
        //public async Task<bool> DownloadFileAsync(SaveItem saveItem)
472
        //{
473
        //    bool result = false;
474
475
        //    try
476
        //    {
477
        //        Uri pdfFileUri = null;
478
479
        //        //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB"))
480
        //        //{
481
        //        //    FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1);
482
        //        //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
483
        //        //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
484
        //        //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
485
        //        //    DownloadFilePath = ItemPath + "\\" + FileName;
486
        //        //}
487
        //        //else
488
        //        //{
489
        //        //    ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더
490
        //        //    ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString();
491
        //        //    ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID;
492
        //        //    FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName");
493
        //        //    DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName;
494
495
        //        //}
496
497
        //        saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로
498
499
500
        //        string FileName = "";
501
        //        string downloadFilePath = "";
502
503
        //        // 드라이브 경로가 포함되었는지 판단.
504
        //        if (Path.IsPathRooted(saveItem.PdfFilePath))
505
        //        {
506
        //            FileInfo file = new FileInfo(saveItem.PdfFilePath);
507
508
        //            if (file.Exists)
509
        //            {
510
        //                FileName = file.Name;
511
        //                downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
512
        //                file.CopyTo(downloadFilePath, true);
513
        //            }
514
        //            else
515
        //            {
516
        //                throw new Exception("File Not Found. Please, check the file path.");
517
        //            }
518
        //        }
519
        //        else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
520
        //        {
521
        //            try
522
        //            {
523
        //                if (gIsApiDownload)
524
        //                {
525
        //                    ///read api download 
526
        //                    ///벽산
527
        //                    downloadFilePath = await RestDownloadAsync(pdfFileUri, saveItem.SavePath);
528
        //                }
529
        //                else
530
        //                {
531
        //                    FileName = DownloadUri.GetFileName(saveItem.PdfFilePath);
532
        //                    downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName);
533
534
        //                    using (System.Net.WebClient webClient = new System.Net.WebClient())
535
        //                    {
536
        //                        webClient.UseDefaultCredentials = true;
537
        //                        webClient.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
538
        //                        webClient.Proxy = null;
539
        //                        if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
540
        //                        {
541
        //                            System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
542
        //                        }
543
544
        //                        webClient.DownloadFile(pdfFileUri, downloadFilePath);
545
546
        //                        webClient.Dispose();
547
        //                    }
548
        //                }
549
        //                await Task.Delay(300);
550
        //            }
551
        //            catch (Exception ex)
552
        //            {
553
        //                logger.Error(ex);
554
        //                throw new Exception($"File Download Error. Please, check the file path. {pdfFileUri}");
555
        //            }
556
        //        }
557
        //        else
558
        //        {
559
        //            throw new Exception("Please, check the file path.");
560
        //        }
561
562
        //        try
563
        //        {
564
        //            if (File.Exists(downloadFilePath))
565
        //            {
566
        //                var file = File.Open(downloadFilePath, FileMode.Open);
567
568
        //                if (file.Length == 0)
569
        //                {
570
        //                    throw new Exception("File Size 0. Please, check the file path.");
571
        //                }
572
573
        //                file.Close();
574
        //                file.Dispose();
575
576
        //                saveItem.PdfFilePath = downloadFilePath;
577
        //                result = true;
578
579
        //            }
580
        //        }
581
        //        catch (Exception ex)
582
        //        {
583
        //            logger.Error(ex);
584
        //            throw new Exception("File Error ." + downloadFilePath);
585
        //        }
586
        //    }
587
        //    catch (Exception ex)
588
        //    {
589
        //        logger.Error(ex);
590
        //        throw new Exception(ex.ToString());
591
        //    }
592
593
        //    return result;
594
        //}
595
596
        //private  async Task<string> RestDownloadAsync(Uri uri,string savePath)
597
        //{
598
        //    string downloadFilePath = "";
599
600
        //    var client = new RestClient(uri);
601
        //    client.Timeout = -1;
602
        //    var request = new RestRequest(Method.GET);
603
        //    IRestResponse response = await client.ExecuteAsync(request);
604
605
        //    if (response.StatusCode == System.Net.HttpStatusCode.OK)
606
        //    {
607
        //        var fileName = DownloadUri.GetFileNameInDisposition(new System.Net.Mime.ContentDisposition(response.Headers.Where(x => x.Name == "Content-Disposition").First().Value.ToString()));
608
609
        //        downloadFilePath = System.IO.Path.Combine(savePath, fileName);
610
611
        //        var fs = File.Create(downloadFilePath);
612
613
        //        await fs.WriteAsync(response.RawBytes, 0, response.RawBytes.Length);
614
        //        fs.Close();
615
        //    }
616
617
        //    return downloadFilePath;
618
        //}
619 77cdac33 taeseongkim
620 53c9637d taeseongkim
        /// <summary>
621
        /// 큰파일 변환
622
        /// </summary>
623
        /// <param name="saveitem"></param>
624
        /// <returns></returns>
625 1d79913e taeseongkim
        private SaveResult ConvertBigFileProcess(int totalPages,string convertId, string downloadFilePath, string savePath, int minimumFontSize,int useResolution,string fontsFolder)
626 53c9637d taeseongkim
        {
627
            SaveResult result = new SaveResult();
628 a5e5fff6 taeseongkim
            
629 53c9637d taeseongkim
            try
630
            {
631 1d79913e taeseongkim
                for (int currentPageNo = 1; currentPageNo <= totalPages; currentPageNo++)
632 53c9637d taeseongkim
                {
633 f363a40e taeseongkim
                    try
634
                    {
635 1d79913e taeseongkim
                        string saveFile = Path.Combine(savePath, $"{currentPageNo}.png");
636 53c9637d taeseongkim
637 f363a40e taeseongkim
                        if (ReConvert < 1 || (ReConvert == 1 && !File.Exists(saveFile)))
638 d91efe5c taeseongkim
                        {
639 43e1d368 taeseongkim
                            SaveResult saveResult = new SaveResult { StatusCode = StatusCodeType.None };
640 1d79913e taeseongkim
                            StatusCodeType stateCode = StatusCodeType.Saving;
641 43e1d368 taeseongkim
642
                            try
643
                            {
644
                                saveResult = gMarkusPDF.SavePage(currentPageNo, saveFile);
645
                            }
646
                            catch (Exception ex)
647
                            {
648 1d79913e taeseongkim
                                result.Message = LogHelper.GetStack() + " " + ex.ToString() + " " + result.Message;
649 43e1d368 taeseongkim
                            }
650 53c9637d taeseongkim
651 1d79913e taeseongkim
                            result.StatusCode = saveResult.StatusCode;
652 53c9637d taeseongkim
653 1d79913e taeseongkim
                            if (result.StatusCode != StatusCodeType.Completed)
654
                            {
655
                                stateCode = result.StatusCode;
656
                            }
657 d91efe5c taeseongkim
658 1d79913e taeseongkim
                            MarkusPdfStateChangeEvent(this, new StateEventArgs(new SaveItem
659
                            {
660
                                ErrorMessage = result.Message,
661
                                Id = convertId,
662
                                CurrentPage = currentPageNo,
663
                                TotalPages = totalPages,
664
                                Status = stateCode
665
                            }));
666
667
                            if (saveResult.StatusCode == StatusCodeType.Completed)
668
                            {
669
                                result.PageInfoAdd(saveResult.SavePageInfo);
670 f363a40e taeseongkim
671 d91efe5c taeseongkim
                                Console.WriteLine($"CurrentPage : {currentPageNo}");
672 f363a40e taeseongkim
673 d91efe5c taeseongkim
                                /// 설정된 최대 페이지이거나 설정된 메모리보다 크면 릴리즈
674
                                if ((currentPageNo % ConvertProcessContext.MultiThreadMaxPages == 0 && ConvertProcessContext.MultiThreadMaxPages > 0)
675
                                    || ConvertProcessContext.ReleaseWorkMemory < Environment.WorkingSet)
676
                                {
677
                                    Console.WriteLine($"physical memory : {Environment.WorkingSet}");
678 f363a40e taeseongkim
679 d91efe5c taeseongkim
                                    gMarkusPDF.Dispose();
680
                                    gMarkusPDF = null;
681
                                    System.Threading.Thread.SpinWait(5);
682 f363a40e taeseongkim
683 d91efe5c taeseongkim
                                    gMarkusPDF = new MarkusPDF();
684 1d79913e taeseongkim
                                    gMarkusPDF.pdfLoad(downloadFilePath,minimumFontSize,useResolution, fontsFolder);
685 d91efe5c taeseongkim
                                }
686 c5519c44 taeseongkim
687 d91efe5c taeseongkim
                                System.Threading.Thread.SpinWait(2);
688
                            }
689
                            else
690
                            {
691
                                Console.WriteLine($"CurrentPage : {currentPageNo}");
692 1d79913e taeseongkim
                                Console.WriteLine($"convert ID : {convertId}");
693
                                Console.WriteLine($"pdf file Path : {downloadFilePath}");
694
                                Console.WriteLine($"save file path : {savePath}");
695
                                Console.WriteLine($"last status code : {result.StatusCode}");
696
                                Console.WriteLine($"error message : {result.Message}");
697
698 d91efe5c taeseongkim
                                break;
699
                            }
700 f363a40e taeseongkim
                        }
701
                    }
702
                    catch (Exception ex)
703 53c9637d taeseongkim
                    {
704 f363a40e taeseongkim
                        result.StatusCode = StatusCodeType.PageError;
705 c5519c44 taeseongkim
                        result.Message =  LogHelper.GetStack() + " " +"Save Error - " + ex.Message;
706 53c9637d taeseongkim
707 f363a40e taeseongkim
                        if (gMarkusPDF != null)
708
                        {
709
                            gMarkusPDF.Dispose();
710
                            gMarkusPDF = null;
711
                        }
712 53c9637d taeseongkim
713
                        gMarkusPDF = new MarkusPDF();
714 1d79913e taeseongkim
                        gMarkusPDF.pdfLoad(downloadFilePath, minimumFontSize, useResolution, fontsFolder);
715 f363a40e taeseongkim
716
                        currentPageNo = currentPageNo - 1;
717
                    }
718
                    finally
719
                    {
720
                     
721 53c9637d taeseongkim
                    }
722
                }
723
            }
724
            catch (Exception ex)
725
            {
726
                result.StatusCode = StatusCodeType.Error;
727 c5519c44 taeseongkim
                result.Message =  LogHelper.GetStack() + " " +ex.Message;
728 53c9637d taeseongkim
            }
729
730
            return result;
731
        }
732
733
        public bool Stop()
734
        {
735
            try
736
            {
737
                gSaveTask.Dispose();
738
            }
739
            catch (Exception ex)
740
            {
741
                System.Diagnostics.Debug.WriteLine(ex.ToString());
742
            }
743
744
            return true;
745
        }
746
747
748
        /// <summary>
749
        /// 사용안함
750
        /// </summary>
751
        /// <param name="param"></param>
752
        /// <returns></returns>
753
        //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions]
754
        //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)]
755
        //private SaveResult SetFile()
756
        //{
757
        //    var saveitem = new SaveItem
758
        //    {
759
        //        Id = ConvertProcessContext.ConvertID,
760
        //        PdfFilePath = ConvertProcessContext.OriginFilePath,
761
        //        SavePath = ConvertProcessContext.SaveDirectory,
762
        //        Status = StatusCodeType.None
763
        //    };
764
765
        //    if (System.IO.Directory.Exists(saveitem.SavePath))
766
        //    {
767
        //        System.IO.Directory.Delete(saveitem.SavePath, true);
768
        //    }
769
770
        //    System.IO.Directory.CreateDirectory(saveitem.SavePath);
771
772
        //    try
773
        //    {
774
        //        Uri pdfFileUri = null;
775
776
        //        if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri))
777
        //        {
778
        //            using (System.Net.WebClient webClient = new System.Net.WebClient())
779
        //            {
780
        //                webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증
781
782
        //                if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory))
783
        //                {
784
        //                    System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory);
785
        //                }
786
787
        //                var downloadFilePath = System.IO.Path.Combine(ConvertProcessContext.TempDirectory, saveitem.Id.Replace("-", "") + ".pdf");
788
        //                webClient.DownloadFile(pdfFileUri, downloadFilePath);
789
790
        //                saveitem.PdfFilePath = downloadFilePath;
791
        //            }
792
        //        }
793
        //    }
794
        //    catch (Exception ex)
795
        //    {
796
        //        throw new Exception($"File Download Error  - File path : {saveitem.PdfFilePath}");
797
        //    }
798
799
        //    StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage);
800
801
        //    var result = gSaveTask.SaveFile(saveitem);
802
803
        //    return result;
804
        //}
805
806
    }
807
}
클립보드 이미지 추가 (최대 크기: 500 MB)