markus / ConvertService / ServiceBase / Markus.Service.Convert / ConvertService.cs @ ff4b1e6e
이력 | 보기 | 이력해설 | 다운로드 (18.2 KB)
1 | 53c9637d | taeseongkim | 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 | 06f13e11 | taeseongkim | using Markus.Service.WcfClient.StationServiceAsync; |
14 | 53c9637d | taeseongkim | |
15 | using System.Threading.Tasks; |
||
16 | using System.Web; |
||
17 | |||
18 | namespace Markus.Service.Convert |
||
19 | { |
||
20 | public class ConvertService : IDisposable |
||
21 | { |
||
22 | // 1GigaBytes |
||
23 | protected ILog logger; |
||
24 | |||
25 | readonly ProcessContext ConvertProcessContext; |
||
26 | private string gTempFileName; |
||
27 | private Markus.SaveTask gSaveTask; |
||
28 | private Markus.MarkusPDF gMarkusPDF; |
||
29 | |||
30 | |||
31 | 06f13e11 | taeseongkim | private StationServiceClient StationServiceClient; |
32 | 53c9637d | taeseongkim | |
33 | a53dfe45 | taeseongkim | /// <summary> |
34 | /// 프로세스 초기화 |
||
35 | /// </summary> |
||
36 | /// <param name="convertContext"></param> |
||
37 | 53c9637d | taeseongkim | public ConvertService(ProcessContext convertContext) : base() |
38 | { |
||
39 | logger = LogManager.GetLogger(typeof(ConvertService)); |
||
40 | |||
41 | ConvertProcessContext = convertContext; |
||
42 | |||
43 | BasicHttpBinding myBinding = new BasicHttpBinding(); |
||
44 | EndpointAddress myEndpoint = new EndpointAddress(UriHelper.UriCreate(ConvertProcessContext.ServiceStationUri)); |
||
45 | 06f13e11 | taeseongkim | StationServiceClient = new StationServiceClient(myBinding, myEndpoint); |
46 | 53c9637d | taeseongkim | |
47 | gMarkusPDF = new MarkusPDF(); |
||
48 | gSaveTask = new SaveTask(); |
||
49 | gSaveTask.StateChangeEvent += MarkusPdfStateChangeEvent; |
||
50 | } |
||
51 | |||
52 | public ConvertService() |
||
53 | { |
||
54 | } |
||
55 | |||
56 | public void Dispose() |
||
57 | { |
||
58 | try |
||
59 | { |
||
60 | gMarkusPDF.Dispose(); |
||
61 | gSaveTask.Dispose(); |
||
62 | |||
63 | //if (System.IO.File.Exists(gTempFileName)) |
||
64 | //{ |
||
65 | // File.Delete(gTempFileName); |
||
66 | //} |
||
67 | |||
68 | } |
||
69 | catch (Exception ex) |
||
70 | { |
||
71 | logger.Error("Convert Service Dispose Error", ex); |
||
72 | } |
||
73 | finally |
||
74 | { |
||
75 | GC.Collect(2); |
||
76 | GC.Collect(2); |
||
77 | } |
||
78 | } |
||
79 | |||
80 | |||
81 | /// <summary> |
||
82 | /// markus lib에서 받는 이벤트 |
||
83 | /// </summary> |
||
84 | /// <param name="sender"></param> |
||
85 | /// <param name="e"></param> |
||
86 | private void MarkusPdfStateChangeEvent(object sender, Markus.Message.StateEventArgs e) |
||
87 | { |
||
88 | try |
||
89 | { |
||
90 | int currentPage = e.SaveItem.CurrentPage; |
||
91 | |||
92 | if (e.SaveItem.CurrentPage == 0) /// 초기 wait status인 경우 0일수 있다. %계산시 오류 방지 |
||
93 | { |
||
94 | currentPage = 1; |
||
95 | } |
||
96 | |||
97 | a537d79a | taeseongkim | StationServiceClient.ConvertProcessStateAsync(e.SaveItem.Id, (int)e.SaveItem.Status, e.SaveItem.CurrentPage, e.SaveItem.TotalPages, e.SaveItem.ErrorMessage); |
98 | 53c9637d | taeseongkim | |
99 | switch (e.SaveItem.Status) |
||
100 | { |
||
101 | case StatusCodeType.None: |
||
102 | break; |
||
103 | case StatusCodeType.Wait: |
||
104 | break; |
||
105 | case StatusCodeType.PageLoading: |
||
106 | break; |
||
107 | case StatusCodeType.Saving: |
||
108 | break; |
||
109 | case StatusCodeType.Completed: |
||
110 | gSaveTask.StateChangeEvent -= MarkusPdfStateChangeEvent; |
||
111 | gSaveTask.Dispose(); |
||
112 | GC.Collect(2); |
||
113 | GC.Collect(2); |
||
114 | break; |
||
115 | case StatusCodeType.FileError: |
||
116 | break; |
||
117 | case StatusCodeType.PageError: |
||
118 | break; |
||
119 | case StatusCodeType.NeedsPassword: |
||
120 | break; |
||
121 | case StatusCodeType.Error: |
||
122 | break; |
||
123 | default: |
||
124 | break; |
||
125 | } |
||
126 | } |
||
127 | catch (Exception ex) |
||
128 | { |
||
129 | logger.Error($"Status Change Error", ex); |
||
130 | } |
||
131 | } |
||
132 | |||
133 | [System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)] |
||
134 | public async Task<SaveResult> SetFileAsync() |
||
135 | { |
||
136 | SaveResult result = new SaveResult(); |
||
137 | |||
138 | SaveItem saveitem = new SaveItem |
||
139 | { |
||
140 | Id = ConvertProcessContext.ConvertID, |
||
141 | PdfFilePath = ConvertProcessContext.OriginFilePath, |
||
142 | SavePath = ConvertProcessContext.SaveDirectory, |
||
143 | Status = StatusCodeType.None, |
||
144 | 2091a7e5 | taeseongkim | MinimumFontSize = ConvertProcessContext.MinFontSize, |
145 | UseResolution = ConvertProcessContext.UseResolution |
||
146 | 53c9637d | taeseongkim | }; |
147 | |||
148 | try |
||
149 | { |
||
150 | StationServiceClient.ConvertProcessState(ConvertProcessContext.ConvertID, (int)StatusCodeType.Wait, 0, 0, ""); |
||
151 | |||
152 | result = await ConvertAsync(saveitem); |
||
153 | |||
154 | StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages,result.Message); |
||
155 | } |
||
156 | catch (Exception ex) |
||
157 | { |
||
158 | logger.Error($"File Convert Error",ex); |
||
159 | StationServiceClient.ConvertFinish(saveitem.Id, (int)result.StatusCode, saveitem.CurrentPage, saveitem.TotalPages, $"ConvertService Error {saveitem.Id}"); |
||
160 | } |
||
161 | |||
162 | return result; |
||
163 | } |
||
164 | |||
165 | private async Task<SaveResult> ConvertAsync(SaveItem saveitem) |
||
166 | { |
||
167 | SaveResult result = new SaveResult(); |
||
168 | |||
169 | try |
||
170 | { |
||
171 | DateTime deleteTime = DateTime.Now; |
||
172 | |||
173 | while (System.IO.Directory.Exists(saveitem.SavePath)) |
||
174 | { |
||
175 | System.IO.Directory.Delete(saveitem.SavePath, true); |
||
176 | |||
177 | if ((DateTime.Now - deleteTime) > new TimeSpan(0, 5, 0)) |
||
178 | { |
||
179 | string msg = $"ConvertService Error {saveitem.SavePath} Delete Error"; |
||
180 | logger.Error(msg); |
||
181 | result.StatusCode = StatusCodeType.FileError; |
||
182 | result.Message = msg; |
||
183 | |||
184 | return result; |
||
185 | } |
||
186 | |||
187 | System.Threading.Thread.Sleep(500); |
||
188 | |||
189 | } |
||
190 | |||
191 | System.IO.Directory.CreateDirectory(saveitem.SavePath); |
||
192 | |||
193 | //파일 다운로드 |
||
194 | if (await DownloadFileAsync(saveitem)) |
||
195 | { |
||
196 | gTempFileName = saveitem.PdfFilePath; |
||
197 | |||
198 | 2091a7e5 | taeseongkim | gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution); |
199 | 53c9637d | taeseongkim | |
200 | /// 설정된 MultiThreadMaxPages에 따른 컨버터 분기 |
||
201 | if (gMarkusPDF.PageCount() > ConvertProcessContext.MultiThreadMaxPages) |
||
202 | { |
||
203 | /// 큰 사이즈의 파일 컨버팅 |
||
204 | result = ConvertBigFileProcess(saveitem); |
||
205 | } |
||
206 | else |
||
207 | { |
||
208 | /// 작은 사이즈의 컨버팅 |
||
209 | await Task.Factory.StartNew(new Action(() => |
||
210 | { |
||
211 | result = gSaveTask.SaveFile(saveitem); |
||
212 | 949d5058 | taeseongkim | |
213 | 53c9637d | taeseongkim | }), TaskCreationOptions.LongRunning); |
214 | } |
||
215 | |||
216 | /// 페이지 정보 저장 |
||
217 | if (result.PageInfoList?.Count() > 0) |
||
218 | { |
||
219 | bool docSetResult = false; |
||
220 | |||
221 | using (Markus.Service.DataBase.ConvertDatabase database = new Markus.Service.DataBase.ConvertDatabase(ConvertProcessContext.ConnectionString)) |
||
222 | { |
||
223 | ff4b1e6e | taeseongkim | List<EntityModel.DOCPAGE> docPageList = new List<EntityModel.DOCPAGE>(); |
224 | 53c9637d | taeseongkim | |
225 | ff4b1e6e | taeseongkim | docPageList = result.PageInfoList.Select(f => new EntityModel.DOCPAGE |
226 | 53c9637d | taeseongkim | { |
227 | ID = GuidExtension.shortGuid(), |
||
228 | PAGE_WIDTH = f.Width.ToString(), |
||
229 | PAGE_HEIGHT = f.Height.ToString(), |
||
230 | PAGE_NUMBER = f.PageNo |
||
231 | }).ToList(); |
||
232 | |||
233 | 2091a7e5 | taeseongkim | docSetResult = database.SetDocumentInfo(saveitem.Id, result.PageInfoList.Count, docPageList); |
234 | 53c9637d | taeseongkim | } |
235 | |||
236 | if (docSetResult) |
||
237 | { |
||
238 | result.StatusCode = StatusCodeType.Completed; |
||
239 | } |
||
240 | else |
||
241 | { |
||
242 | result.StatusCode = StatusCodeType.FileError; |
||
243 | result.Message = $"Doc Set Error. {result.Message}"; |
||
244 | } |
||
245 | } |
||
246 | else |
||
247 | { |
||
248 | result.StatusCode = StatusCodeType.FileError; |
||
249 | result.Message = $"Page List Get Error. {result.Message} "; |
||
250 | } |
||
251 | } |
||
252 | else |
||
253 | { |
||
254 | result.Message = $"File Download Error - File path : { saveitem.PdfFilePath}"; |
||
255 | result.StatusCode = StatusCodeType.FileError; |
||
256 | } |
||
257 | } |
||
258 | catch (Exception ex) |
||
259 | { |
||
260 | result.Message = "ConvertService Convert Error" + ex.Message; |
||
261 | result.StatusCode = StatusCodeType.Error; |
||
262 | } |
||
263 | finally |
||
264 | { |
||
265 | |||
266 | } |
||
267 | |||
268 | return result; |
||
269 | } |
||
270 | |||
271 | /// <summary> |
||
272 | /// 파일 다운로드 |
||
273 | /// </summary> |
||
274 | /// <param name="saveItem"></param> |
||
275 | /// <returns></returns> |
||
276 | private async Task<bool> DownloadFileAsync(SaveItem saveItem) |
||
277 | { |
||
278 | bool result = false; |
||
279 | |||
280 | try |
||
281 | { |
||
282 | Uri pdfFileUri = null; |
||
283 | |||
284 | //if (saveItem.PdfFilePath.Contains("VPCS_DOCLIB")) |
||
285 | //{ |
||
286 | // FileName = DocUri.Remove(0, DocUri.LastIndexOf("/") + 1); |
||
287 | // ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더 |
||
288 | // ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString(); |
||
289 | // ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID; |
||
290 | // DownloadFilePath = ItemPath + "\\" + FileName; |
||
291 | //} |
||
292 | //else |
||
293 | //{ |
||
294 | // ProjectFolderPath = DownloadDir_PDF + "\\" + ConverterItem.PROJECT_NO + "_Tile"; //프로젝트 폴더 |
||
295 | // ItemListPath = ProjectFolderPath + "\\" + (System.Convert.ToInt64(ConverterItem.DOCUMENT_ID) / 100).ToString(); |
||
296 | // ItemPath = ItemListPath + "\\" + ConverterItem.DOCUMENT_ID; |
||
297 | // FileName = HttpUtility.ParseQueryString(new Uri(DocUri).Query).Get("fileName"); |
||
298 | // DownloadFilePath = string.IsNullOrWhiteSpace(FileName) ? ItemPath + "\\" + FileName : ItemPath + "\\" + FileName; |
||
299 | |||
300 | //} |
||
301 | |||
302 | saveItem.PdfFilePath = HttpUtility.UrlDecode(saveItem.PdfFilePath); //PDF 전체 경로 |
||
303 | 06f13e11 | taeseongkim | string FileName = DownloadUri.GetFileName(saveItem.PdfFilePath); |
304 | 53c9637d | taeseongkim | |
305 | string downloadFilePath = System.IO.Path.Combine(saveItem.SavePath, FileName); |
||
306 | |||
307 | // 드라이브 경로가 포함되었는지 판단. |
||
308 | if (Path.IsPathRooted(saveItem.PdfFilePath)) |
||
309 | { |
||
310 | if (File.Exists(saveItem.PdfFilePath)) |
||
311 | { |
||
312 | File.Copy(saveItem.PdfFilePath, downloadFilePath, true); |
||
313 | } |
||
314 | else |
||
315 | { |
||
316 | throw new Exception("File Not Found. Please, check the file path."); |
||
317 | } |
||
318 | } |
||
319 | else if (Uri.TryCreate(saveItem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri)) |
||
320 | { |
||
321 | try |
||
322 | { |
||
323 | using (System.Net.WebClient webClient = new System.Net.WebClient()) |
||
324 | { |
||
325 | webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증 |
||
326 | |||
327 | //if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory)) |
||
328 | //{ |
||
329 | // System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory); |
||
330 | //} |
||
331 | |||
332 | await webClient.DownloadFileTaskAsync(pdfFileUri, downloadFilePath); |
||
333 | } |
||
334 | } |
||
335 | catch (Exception) |
||
336 | { |
||
337 | throw new Exception("File Download Error. Please, check the file path."); |
||
338 | } |
||
339 | } |
||
340 | else |
||
341 | { |
||
342 | throw new Exception("Please, check the file path."); |
||
343 | } |
||
344 | |||
345 | if (File.Exists(downloadFilePath)) |
||
346 | { |
||
347 | var file = File.Open(downloadFilePath, FileMode.Open); |
||
348 | |||
349 | if (file.Length == 0) |
||
350 | { |
||
351 | throw new Exception("File Size 0. Please, check the file path."); |
||
352 | } |
||
353 | |||
354 | file.Close(); |
||
355 | file.Dispose(); |
||
356 | |||
357 | saveItem.PdfFilePath = downloadFilePath; |
||
358 | result = true; |
||
359 | |||
360 | } |
||
361 | } |
||
362 | 06f13e11 | taeseongkim | catch (Exception) |
363 | 53c9637d | taeseongkim | { |
364 | result = false; |
||
365 | } |
||
366 | |||
367 | return result; |
||
368 | } |
||
369 | |||
370 | /// <summary> |
||
371 | /// 큰파일 변환 |
||
372 | /// </summary> |
||
373 | /// <param name="saveitem"></param> |
||
374 | /// <returns></returns> |
||
375 | private SaveResult ConvertBigFileProcess(SaveItem saveitem) |
||
376 | { |
||
377 | SaveResult result = new SaveResult(); |
||
378 | |||
379 | try |
||
380 | { |
||
381 | saveitem.TotalPages = gMarkusPDF.PageCount(); |
||
382 | |||
383 | for (int currentPageNo = 1; currentPageNo <= saveitem.TotalPages; currentPageNo++) |
||
384 | { |
||
385 | var saveResult = gMarkusPDF.SavePage(currentPageNo, Path.Combine(saveitem.SavePath, $"{currentPageNo}.png")); |
||
386 | |||
387 | saveitem.Status = StatusCodeType.Saving; |
||
388 | saveitem.CurrentPage = currentPageNo; |
||
389 | saveitem.ErrorMessage = saveResult.Message; |
||
390 | |||
391 | result.PageInfoAdd(saveResult.SavePageInfo); |
||
392 | |||
393 | MarkusPdfStateChangeEvent(this, new StateEventArgs(saveitem)); |
||
394 | Console.WriteLine($"CurrentPage : {currentPageNo}"); |
||
395 | |||
396 | /// 설정된 최대 페이지이거나 설정된 메모리보다 크면 릴리즈 |
||
397 | if (currentPageNo% ConvertProcessContext.MultiThreadMaxPages == 0 || ConvertProcessContext.ReleaseWorkMemory < Environment.WorkingSet) |
||
398 | { |
||
399 | Console.WriteLine($"physical memory : {Environment.WorkingSet}"); |
||
400 | |||
401 | gMarkusPDF.Dispose(); |
||
402 | GC.Collect(); |
||
403 | GC.WaitForPendingFinalizers(); |
||
404 | GC.Collect(); |
||
405 | |||
406 | gMarkusPDF = new MarkusPDF(); |
||
407 | 2091a7e5 | taeseongkim | gMarkusPDF.pdfLoad(saveitem.PdfFilePath, saveitem.MinimumFontSize, saveitem.UseResolution); |
408 | 53c9637d | taeseongkim | } |
409 | } |
||
410 | |||
411 | result.StatusCode = StatusCodeType.Completed; |
||
412 | } |
||
413 | catch (Exception ex) |
||
414 | { |
||
415 | result.StatusCode = StatusCodeType.Error; |
||
416 | result.Message = ex.Message; |
||
417 | } |
||
418 | |||
419 | return result; |
||
420 | } |
||
421 | |||
422 | public bool Stop() |
||
423 | { |
||
424 | try |
||
425 | { |
||
426 | gSaveTask.Dispose(); |
||
427 | } |
||
428 | catch (Exception ex) |
||
429 | { |
||
430 | System.Diagnostics.Debug.WriteLine(ex.ToString()); |
||
431 | } |
||
432 | |||
433 | return true; |
||
434 | } |
||
435 | |||
436 | |||
437 | /// <summary> |
||
438 | /// 사용안함 |
||
439 | /// </summary> |
||
440 | /// <param name="param"></param> |
||
441 | /// <returns></returns> |
||
442 | //[System.Runtime.ExceptionServices.HandleProcessCorruptedStateExceptions] |
||
443 | //[System.Security.Permissions.FileIOPermission(System.Security.Permissions.SecurityAction.LinkDemand)] |
||
444 | //private SaveResult SetFile() |
||
445 | //{ |
||
446 | // var saveitem = new SaveItem |
||
447 | // { |
||
448 | // Id = ConvertProcessContext.ConvertID, |
||
449 | // PdfFilePath = ConvertProcessContext.OriginFilePath, |
||
450 | // SavePath = ConvertProcessContext.SaveDirectory, |
||
451 | // Status = StatusCodeType.None |
||
452 | // }; |
||
453 | |||
454 | // if (System.IO.Directory.Exists(saveitem.SavePath)) |
||
455 | // { |
||
456 | // System.IO.Directory.Delete(saveitem.SavePath, true); |
||
457 | // } |
||
458 | |||
459 | // System.IO.Directory.CreateDirectory(saveitem.SavePath); |
||
460 | |||
461 | // try |
||
462 | // { |
||
463 | // Uri pdfFileUri = null; |
||
464 | |||
465 | // if (Uri.TryCreate(saveitem.PdfFilePath, UriKind.RelativeOrAbsolute, out pdfFileUri)) |
||
466 | // { |
||
467 | // using (System.Net.WebClient webClient = new System.Net.WebClient()) |
||
468 | // { |
||
469 | // webClient.UseDefaultCredentials = true;//.Headers.Add("Authorization: BASIC SGVsbG8="); //가상의 인증 |
||
470 | |||
471 | // if (!System.IO.Directory.Exists(ConvertProcessContext.TempDirectory)) |
||
472 | // { |
||
473 | // System.IO.Directory.CreateDirectory(ConvertProcessContext.TempDirectory); |
||
474 | // } |
||
475 | |||
476 | // var downloadFilePath = System.IO.Path.Combine(ConvertProcessContext.TempDirectory, saveitem.Id.Replace("-", "") + ".pdf"); |
||
477 | // webClient.DownloadFile(pdfFileUri, downloadFilePath); |
||
478 | |||
479 | // saveitem.PdfFilePath = downloadFilePath; |
||
480 | // } |
||
481 | // } |
||
482 | // } |
||
483 | // catch (Exception ex) |
||
484 | // { |
||
485 | // throw new Exception($"File Download Error - File path : {saveitem.PdfFilePath}"); |
||
486 | // } |
||
487 | |||
488 | // StationServiceClient.ConvertProcessStateAsync(saveitem.Id, (int)saveitem.Status, saveitem.CurrentPage, saveitem.TotalPages, saveitem.ErrorMessage); |
||
489 | |||
490 | // var result = gSaveTask.SaveFile(saveitem); |
||
491 | |||
492 | // return result; |
||
493 | //} |
||
494 | |||
495 | } |
||
496 | } |