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