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