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