프로젝트

일반

사용자정보

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

markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ 8ebd5302

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