FileManager.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Threading.Tasks;
  5. using Microsoft.InformationProtection;
  6. using Microsoft.InformationProtection.File;
  7. using Microsoft.InformationProtection.Protection;
  8. using System.Diagnostics;
  9. using Serilog;
  10. using Serilog.Core;
  11. namespace AipGateway.AIP
  12. {
  13. public class FileManager : AbstractManager
  14. {
  15. private readonly ILogger _log;
  16. private IFileProfile _profile = null;
  17. private IFileEngine _engine = null;
  18. public FileManager(Logger logger, string clientId) : base(logger, clientId)
  19. {
  20. _log = logger.ForContext<FileManager>();
  21. }
  22. ~FileManager() => this.Dispose(false);
  23. public override void Dispose()
  24. {
  25. this.Dispose(true);
  26. GC.SuppressFinalize((object)this);
  27. }
  28. protected virtual void Dispose(bool disposing)
  29. {
  30. lock (this)
  31. {
  32. if (_profile != null & _engine != null)
  33. {
  34. //_profile.UnloadEngineAsync(_engine.Settings.EngineId).Wait();
  35. }
  36. _engine = null;
  37. _profile = null;
  38. }
  39. }
  40. public override bool CreateProfile(ref MipContext mipContext)
  41. {
  42. try
  43. {
  44. var profileSettings = new FileProfileSettings(mipContext,
  45. //CacheStorageType.OnDiskEncrypted,
  46. CacheStorageType.InMemory,
  47. new ConsentDelegateImplementation());
  48. // IFileProfile은 특정 애플리케이션에 대한 모든 SDK 작업의 루트입니다.
  49. _profile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
  50. }
  51. catch (Exception e)
  52. {
  53. SetError(1, "FileManager::CreateProfile Failed.", e.Message);
  54. return false;
  55. }
  56. return _profile != null;
  57. }
  58. public override bool CreateEngine(ref Identity identity, ref AuthDelegateImplementation authDelegate)
  59. {
  60. try
  61. {
  62. authDelegate.ResetError();
  63. //CultureInfo.CurrentCulture.Name;
  64. // 보호 엔진 설정 개체를 만듭니다. 첫 번째 매개변수인 엔진 ID에 빈 문자열을 전달하면 SDK가 GUID를 생성합니다.
  65. // 이메일 주소나 기타 고유한 값을 전달하면 동일한 사용자에 대해 캐시된 엔진이 매번 로드되도록 하는 데 도움이 됩니다.
  66. // 로캘 설정은 지원되며 특히 클라이언트 응용 프로그램의 경우 컴퓨터 로캘을 기반으로 제공되어야 합니다.
  67. //_log.Information("Engine ClientID: {0}", _clientId);
  68. //_log.Information("Engine UserID: {0}", identity.Email);
  69. var engineSettings = new FileEngineSettings(_clientId, authDelegate, string.Empty, "en-US")
  70. {
  71. // Provide the identity for service discovery.
  72. Identity = identity,
  73. // Set ProtectionOnlyEngine to true for AD RMS as labeling isn't supported
  74. //ProtectionOnlyEngine = true
  75. };
  76. _engine = Task.Run(async () => await _profile.AddEngineAsync(engineSettings)).Result;
  77. }
  78. catch (Exception e)
  79. {
  80. if (authDelegate.LastErrNo != 0)
  81. {
  82. SetError(authDelegate.LastErrNo, "FileManager::CreateEngine Failed.", authDelegate.LastErrMsg);
  83. }
  84. else
  85. {
  86. SetError(2, "FileManager::CreateEngine Failed.", e.Message);
  87. }
  88. return false;
  89. }
  90. return _engine != null;
  91. }
  92. public IEnumerable<Label> SensitivityLabels()
  93. {
  94. return _engine.SensitivityLabels;
  95. }
  96. private IFileHandler CreateFileHandler(Stream inputStream, string outputFile)
  97. {
  98. if (inputStream == null)
  99. {
  100. SetError(91, "FileManager::CreateFileHandler Failed.", "요청한 스트림의 정보가 없습니다.");
  101. return null;
  102. }
  103. if (outputFile == null || outputFile.Length == 0)
  104. {
  105. SetError(91, "FileManager::CreateFileHandler Failed.", "요청한 출력 파일 이릅이 존재하지 않습니다.");
  106. return null;
  107. }
  108. try
  109. {
  110. var handler = Task.Run(async () => await _engine.CreateFileHandlerAsync(inputStream, outputFile, true))
  111. .Result;
  112. return handler;
  113. }
  114. catch (Exception ex)
  115. {
  116. SetError(91, "FileManager::CreateFileHandler Failed.", ex.Message);
  117. }
  118. return null;
  119. }
  120. private Int64 GetFileSize(string fileName)
  121. {
  122. try
  123. {
  124. return new FileInfo(fileName).Length;
  125. }
  126. catch { return 0; }
  127. }
  128. private IFileHandler CreateFileHandler(string inputFile, string outputFile)
  129. {
  130. if (!File.Exists(inputFile))
  131. {
  132. SetError(91, "FileManager::CreateFileHandler Failed.", "요청한 파일이 존재하지 않습니다. " + inputFile);
  133. return null;
  134. }
  135. try
  136. {
  137. //Stopwatch sw = new Stopwatch();
  138. //sw.Start();
  139. var handler = _engine.CreateFileHandlerAsync(inputFile, outputFile, true).Result;
  140. //var handler = Task.Run(async () => await _engine.CreateFileHandlerAsync(inputFile, outputFile, true)).Result;
  141. //sw.Stop();
  142. //_log.Information("********: [{0}], CreateFileHandlerAsync: -------- {1,6} ms. inputFile: {2}", Task.CurrentId, sw.ElapsedMilliseconds.ToString("#,##0"), inputFile);
  143. return handler;
  144. }
  145. catch (Exception ex)
  146. {
  147. SetError(91, "FileManager::CreateFileHandler Failed.", ex.Message);
  148. }
  149. return null;
  150. }
  151. public AipFileInfo GetFileInfo(Stream fileStream, string outputFileName)
  152. {
  153. var handler = CreateFileHandler(fileStream, outputFileName);
  154. if (handler == null)
  155. {
  156. //File.Delete(outputFileName);
  157. return null;
  158. }
  159. var result = GetFileInfo(handler);
  160. try
  161. {
  162. result.FileSize = fileStream.Length;
  163. //File.Delete(outputFileName);
  164. }
  165. catch (Exception ex)
  166. {
  167. result.FileSize = 0;
  168. LastErrMsg = ex.Message;
  169. }
  170. return result;
  171. }
  172. public AipFileInfo GetFileInfo(string fileName)
  173. {
  174. var handler = CreateFileHandler(fileName, fileName);
  175. if (handler == null)
  176. {
  177. return null;
  178. }
  179. var result = GetFileInfo(handler);
  180. try
  181. {
  182. result.FileSize = GetFileSize(fileName);
  183. }
  184. catch(Exception ex)
  185. {
  186. result.FileSize = 0;
  187. LastErrMsg = ex.Message;
  188. }
  189. return result;
  190. }
  191. private AipFileInfo GetFileInfo(IFileHandler handler)
  192. {
  193. if (handler == null)
  194. {
  195. return null;
  196. }
  197. //Stopwatch sw = new Stopwatch();
  198. //sw.Start();
  199. AipFileInfo fileInfo = new AipFileInfo
  200. {
  201. Content = null,
  202. Label = null,
  203. Protection = null,
  204. OutputFileName = null,
  205. FileSize = 0,
  206. };
  207. fileInfo.OutputFileName = handler.OutputFileName;
  208. if (handler.Label != null)
  209. {
  210. fileInfo.Content = new AipContentLabel()
  211. {
  212. //Label = Utilities.LabelToAip(handler.Label.Label),
  213. CreationTime = handler.Label.CreationTime,
  214. AssignmentMethod = (AipAssignmentMethod)handler.Label.AssignmentMethod,
  215. IsProtectionAppliedFromLabel = handler.Label.IsProtectionAppliedFromLabel,
  216. };
  217. fileInfo.Label = Utilities.LabelToAip(handler.Label.Label);
  218. }
  219. if (handler.Protection != null)
  220. {
  221. fileInfo.Protection = new AipProtection()
  222. {
  223. Owner = handler.Protection.Owner,
  224. IssuedTo = handler.Protection.IssuedTo,
  225. IsIssuedToOwner = handler.Protection.IsIssuedToOwner,
  226. ContentId = handler.Protection.ContentId,
  227. AuditedExtractAllowed = handler.Protection.AuditedExtractAllowed,
  228. BlockSize = handler.Protection.BlockSize,
  229. ProtectionDescriptor = null,
  230. };
  231. if (handler.Protection.ProtectionDescriptor != null)
  232. {
  233. fileInfo.Protection.ProtectionDescriptor = new AipProtectionDescriptor()
  234. {
  235. ProtectionType = (AipProtectionType)handler.Protection.ProtectionDescriptor.ProtectionType,
  236. TemplateId = handler.Protection.ProtectionDescriptor.TemplateId,
  237. LabelInformation = new AipLabelInfo(),
  238. LabelId = handler.Protection.ProtectionDescriptor.LabelId,
  239. Owner = handler.Protection.ProtectionDescriptor.Owner,
  240. ContentId = handler.Protection.ProtectionDescriptor.ContentId,
  241. Name = handler.Protection.ProtectionDescriptor.Name,
  242. Description = handler.Protection.ProtectionDescriptor.Description,
  243. AllowOfflineAccess = handler.Protection.ProtectionDescriptor.AllowOfflineAccess,
  244. Referrer = handler.Protection.ProtectionDescriptor.Referrer,
  245. ContentValidUntil = handler.Protection.ProtectionDescriptor.ContentValidUntil,
  246. DoubleKeyUrl = handler.Protection.ProtectionDescriptor.DoubleKeyUrl,
  247. };
  248. if (handler.Protection.ProtectionDescriptor.LabelInformation != null)
  249. {
  250. fileInfo.Protection.ProtectionDescriptor.LabelInformation.LabelId =
  251. handler.Protection.ProtectionDescriptor.LabelInformation.LabelId;
  252. fileInfo.Protection.ProtectionDescriptor.LabelInformation.TenantId =
  253. handler.Protection.ProtectionDescriptor.LabelInformation.TenantId;
  254. }
  255. }
  256. }
  257. //sw.Stop();
  258. //_log.Information("********: [{0}], GetFileInfo: ------------------- {1,6} ms. OutputFileName: {2}", Task.CurrentId, sw.ElapsedMilliseconds.ToString("#,##0"), handler.OutputFileName);
  259. return fileInfo;
  260. }
  261. public Label GetLabelById(string labelId)
  262. {
  263. Label label;
  264. try
  265. {
  266. label = _engine.GetLabelById(labelId);
  267. }
  268. catch (Exception ex)
  269. {
  270. SetError(99, "FileManager::GetLabel Failed. Request Label Id: " + labelId, ex.Message);
  271. return null;
  272. }
  273. return label;
  274. }
  275. public SetFileInfo SetLabel(string fileName, string actualFileName, string email, string labelId, string templateId, string comments)
  276. {
  277. //_log.Warn($"SetLabel: [{Task.CurrentId}], {fileName}, {actualFileName}");
  278. var handler = CreateFileHandler(fileName, actualFileName);
  279. return SetLabel(handler, actualFileName, email, labelId, templateId, comments, GetFileSize(fileName));
  280. }
  281. public SetFileInfo SetLabel(Stream fileStream, string actualFileName, string email, string labelId, string templateId, string comments)
  282. {
  283. var handler = CreateFileHandler(fileStream, actualFileName);
  284. return SetLabel(handler, actualFileName, email, labelId, templateId, comments, fileStream.Length);
  285. }
  286. public SetFileInfo SetLabel(IFileHandler handler, string actualFileName, string email, string labelId, string templateId, string comments, long fileSize)
  287. {
  288. SetFileInfo result = new SetFileInfo()
  289. {
  290. errorNo = 0,
  291. errorMsg = AipConstants.AIP_RESULT_SUCCESS,
  292. };
  293. if (handler == null)
  294. {
  295. result.errorNo = 201;
  296. result.errorMsg = LastErrMsg;
  297. return result;
  298. }
  299. result.fileSize = fileSize;
  300. //_log.Warn($"SetLabel: [{Task.CurrentId}], GetLabelById: actualFileName: {actualFileName}");
  301. Label label = GetLabelById(labelId);
  302. if (label == null)
  303. {
  304. result.errorNo = 202;
  305. result.errorMsg = LastErrMsg;
  306. return result;
  307. }
  308. LabelingOptions labelingOptions = new LabelingOptions()
  309. {
  310. AssignmentMethod = AssignmentMethod.Auto,
  311. JustificationMessage = comments,
  312. IsDowngradeJustified = true
  313. };
  314. string ownerEmail = getOrgFileInfo(handler, email, result);
  315. var protectionSettings = new ProtectionSettings
  316. {
  317. PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
  318. };
  319. if (ownerEmail != "")
  320. {
  321. protectionSettings.DelegatedUserEmail = ownerEmail;
  322. }
  323. try
  324. {
  325. //_log.Warn($"SetLabel: [{Task.CurrentId}], SetLabel: actualFileName: {actualFileName}");
  326. handler.SetLabel(label, labelingOptions, protectionSettings);
  327. if (templateId != "")
  328. {
  329. ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(templateId);
  330. handler.SetProtection(protectionDescriptor, protectionSettings);
  331. }
  332. }
  333. catch (Exception ex)
  334. {
  335. result.errorNo = 203;
  336. result.errorMsg = ex.Message;
  337. SetError(53, "FileManager::SetLabel Failed.", ex.Message);
  338. return result;
  339. }
  340. //Log.Error("actualFileName EXT: " + Path.GetExtension(actualFileName).ToLower());
  341. //Log.Error("actualFileName DIR: " + Path.GetDirectoryName(actualFileName));
  342. //Log.Error("actualFileName NAME: " + Path.GetFileNameWithoutExtension(actualFileName));
  343. //Log.Error("actualFileName FULL NAME: " + actualFileName);
  344. //Log.Error(" handler.OutputFileName: " + handler.OutputFileName);
  345. //Log.Error(" handler.OutputFileName: " + Path.GetExtension(handler.OutputFileName).ToLower());
  346. //_log.Warn($"SetLabel: [{Task.CurrentId}], CommitAsync[B]: actualFileName: {actualFileName}");
  347. actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName), Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
  348. bool isCommitted = CommitAsync(handler, actualFileName, result);
  349. if (isCommitted)
  350. {
  351. //TODO
  352. //handler.NotifyCommitSuccessful(actualFileName);
  353. result.newFileSize = GetFileSize(actualFileName);
  354. result.newFileLabelGuid = labelId;
  355. result.newFileName = actualFileName;
  356. result.newFileOwner = ownerEmail;
  357. result.newFileTemplateGuid = labelId;
  358. }
  359. else
  360. {
  361. result.errorNo = 204;
  362. result.errorMsg = "AIP File CommitAsync Failed.";
  363. SetError(53, "FileManager::SetLabel Failed.", "Label Id: " + labelId + ", SetLabel Failed.");
  364. }
  365. //_log.Warn($"SetLabel: [{Task.CurrentId}], CommitAsync[A]: actualFileName: {actualFileName}");
  366. //Stopwatch sw = new Stopwatch();
  367. //sw.Start();
  368. getActionFileInfo(actualFileName, result);
  369. //sw.Stop();
  370. //_log.Warn($"SetLabel: [{Task.CurrentId}], GetFileInfo: -------- {sw.ElapsedMilliseconds} ms. actualFileName: {actualFileName}");
  371. return result;
  372. }
  373. public SetFileInfo DeleteLabel(string fileName, string actualFileName, string email, string comments, bool isDelProtection)
  374. {
  375. var outFileName = actualFileName == string.Empty ? fileName : actualFileName;
  376. var handler = CreateFileHandler(fileName, outFileName);
  377. return DeleteLabel(handler, actualFileName, email, comments, isDelProtection, GetFileSize(fileName));
  378. }
  379. public SetFileInfo DeleteLabel(Stream fileStream, string actualFileName, string email, string comments, bool isDelProtection)
  380. {
  381. var handler = CreateFileHandler(fileStream, actualFileName);
  382. return DeleteLabel(handler, actualFileName, email, comments, isDelProtection, fileStream.Length);
  383. }
  384. public SetFileInfo DeleteLabel(IFileHandler handler, string actualFileName, string email, string comments, bool isDelProtection, long fileSize)
  385. {
  386. SetFileInfo result = new SetFileInfo()
  387. {
  388. errorNo = 0,
  389. errorMsg = AipConstants.AIP_RESULT_SUCCESS,
  390. };
  391. if (handler == null)
  392. {
  393. result.errorNo = 201;
  394. result.errorMsg = LastErrMsg;
  395. return result;
  396. }
  397. result.fileSize = fileSize;
  398. LabelingOptions invokeLabelingOptions = new LabelingOptions()
  399. {
  400. AssignmentMethod = AssignmentMethod.Privileged, //because we are removing a high priority label
  401. JustificationMessage = comments,
  402. IsDowngradeJustified = true
  403. };
  404. string ownerEmail = getOrgFileInfo(handler, email, result);
  405. var protectionSettings = new ProtectionSettings
  406. {
  407. PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
  408. };
  409. if (ownerEmail != "")
  410. {
  411. protectionSettings.DelegatedUserEmail = ownerEmail;
  412. }
  413. try
  414. {
  415. if (isDelProtection && handler.Protection != null)
  416. {
  417. if (handler.Protection.AccessCheck(Rights.Extract) || handler.Protection.AccessCheck(Rights.Owner))
  418. {
  419. handler.RemoveProtection();
  420. }
  421. }
  422. handler.DeleteLabel(invokeLabelingOptions);
  423. }
  424. catch (Exception ex)
  425. {
  426. result.errorNo = 203;
  427. result.errorMsg = ex.Message;
  428. SetError(53, "FileManager::DeleteLabel Failed.", ex.Message);
  429. return result;
  430. }
  431. actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName), Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
  432. bool isCommitted = CommitAsync(handler, actualFileName, result);
  433. if (isCommitted)
  434. {
  435. //handler.NotifyCommitSuccessful(fileName);
  436. result.newFileSize = GetFileSize(actualFileName);
  437. result.newFileLabelGuid = "";
  438. result.newFileName = actualFileName;
  439. result.newFileOwner = ownerEmail;
  440. result.newFileTemplateGuid = "";
  441. }
  442. else
  443. {
  444. result.errorNo = 204;
  445. result.errorMsg = "AIP File CommitAsync Failed.";
  446. SetError(54, "FileManager::DeleteLabel Failed.", "DeleteLabel Failed by " + ownerEmail);
  447. }
  448. getActionFileInfo(actualFileName, result);
  449. return result;
  450. }
  451. public SetFileInfo SetProtection(string fileName, string actualFileName, string email, string templateId, string comments)
  452. {
  453. var handler = CreateFileHandler(fileName, actualFileName);
  454. return SetProtection(handler, actualFileName, email, templateId, comments, GetFileSize(fileName));
  455. }
  456. public SetFileInfo SetProtection(Stream fileStream, string actualFileName, string email, string templateId, string comments)
  457. {
  458. var handler = CreateFileHandler(fileStream, actualFileName);
  459. return SetProtection(handler, actualFileName, email, templateId, comments, fileStream.Length);
  460. }
  461. public SetFileInfo SetProtection(IFileHandler handler, string actualFileName, string email, string templateId, string comments, long fileSize)
  462. {
  463. SetFileInfo result = new SetFileInfo()
  464. {
  465. errorNo = 0,
  466. errorMsg = AipConstants.AIP_RESULT_SUCCESS,
  467. };
  468. if (handler == null)
  469. {
  470. result.errorNo = 201;
  471. result.errorMsg = LastErrMsg;
  472. return result;
  473. }
  474. result.fileSize = fileSize;
  475. string ownerEmail = getOrgFileInfo(handler, email, result);
  476. try
  477. {
  478. ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(templateId);
  479. ProtectionSettings protectionSettings = new ProtectionSettings
  480. {
  481. PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
  482. };
  483. if (ownerEmail != "")
  484. {
  485. protectionSettings.DelegatedUserEmail = ownerEmail;
  486. }
  487. handler.SetProtection(protectionDescriptor, protectionSettings);
  488. }
  489. catch (Exception ex)
  490. {
  491. result.errorNo = 204;
  492. result.errorMsg = ex.Message;
  493. SetError(54, "FileManager::SetProtect Failed.", ex.Message);
  494. return result;
  495. }
  496. actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName), Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
  497. bool isCommitted = CommitAsync(handler, actualFileName, result);
  498. if (isCommitted)
  499. {
  500. //handler.NotifyCommitSuccessful(fileName);
  501. result.newFileSize = GetFileSize(actualFileName);
  502. //result.newFileLabelGuid = string.Empty;
  503. result.newFileName = actualFileName;
  504. result.newFileOwner = ownerEmail;
  505. result.newFileTemplateGuid = string.Empty;
  506. }
  507. else
  508. {
  509. result.errorNo = 206;
  510. result.errorMsg = "AIP File CommitAsync Failed.";
  511. SetError(56, "FileManager::SetProtect Failed.", "Template Id: " + templateId + ", SetProtect Failed.");
  512. }
  513. getActionFileInfo(actualFileName, result);
  514. return result;
  515. }
  516. public SetFileInfo RemoveProtection(string fileName, string actualFileName, string email, string comments)
  517. {
  518. var handler = CreateFileHandler(fileName, actualFileName);
  519. return RemoveProtection(handler, actualFileName, email, comments, GetFileSize(fileName));
  520. }
  521. public SetFileInfo RemoveProtection(Stream fileStream, string actualFileName, string email, string comments)
  522. {
  523. var handler = CreateFileHandler(fileStream, actualFileName);
  524. return RemoveProtection(handler, actualFileName, email, comments, fileStream.Length);
  525. }
  526. public SetFileInfo RemoveProtection(IFileHandler handler, string actualFileName, string email, string comments, long fileSize)
  527. {
  528. SetFileInfo result = new SetFileInfo()
  529. {
  530. errorNo = 0,
  531. errorMsg = AipConstants.AIP_RESULT_SUCCESS,
  532. };
  533. if (handler == null)
  534. {
  535. result.errorNo = 201;
  536. result.errorMsg = LastErrMsg;
  537. return result;
  538. }
  539. result.fileSize = fileSize;
  540. string ownerEmail = getOrgFileInfo(handler, email, result);
  541. //LabelingOptions invokeLabelingOptions = new LabelingOptions()
  542. //{
  543. // AssignmentMethod = AssignmentMethod.Privileged, //because we are removing a high priority label
  544. // JustificationMessage = comments,
  545. // IsDowngradeJustified = true,
  546. //};
  547. var protectionSettings = new ProtectionSettings
  548. {
  549. PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
  550. };
  551. if (ownerEmail != "")
  552. {
  553. protectionSettings.DelegatedUserEmail = ownerEmail;
  554. }
  555. try
  556. {
  557. if (handler.Protection != null)
  558. {
  559. // 원본 파일 형식이 레이블 지정을 지원하지 않는 경우 보호를 제거하면 레이블이 손실됩니다.
  560. // 기본 형식이 레이블 지정을 지원하는 경우 레이블 메타데이터가 유지됩니다.
  561. if (handler.Protection.AccessCheck(Rights.Extract) || handler.Protection.AccessCheck(Rights.Owner))
  562. {
  563. handler.RemoveProtection();
  564. }
  565. //Use the GetTemporaryDecryptedStream() or GetTemporaryDecryptedFile() API to create a temp decrypted output to render in your application.
  566. }
  567. else
  568. {
  569. result.errorNo = 209;
  570. result.errorMsg = "파일에 암호화 정보가 없습니다.";
  571. return result;
  572. }
  573. }
  574. catch (Exception ex)
  575. {
  576. result.errorNo = 208;
  577. result.errorMsg = "FileManager::RemoveProtection Failed." + ex.Message;
  578. SetError(59, "FileManager::RemoveProtection Failed.", ex.Message);
  579. return result;
  580. }
  581. actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName), Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
  582. bool isCommitted = CommitAsync(handler, actualFileName, result);
  583. if (isCommitted)
  584. {
  585. //handler.NotifyCommitSuccessful(fileName);
  586. result.newFileSize = GetFileSize(actualFileName);
  587. result.newFileLabelGuid = string.Empty;
  588. result.newFileName = actualFileName;
  589. result.newFileOwner = ownerEmail;
  590. result.newFileTemplateGuid = string.Empty;
  591. }
  592. else
  593. {
  594. result.errorNo = 204;
  595. result.errorMsg = "AIP File CommitAsync Failed.";
  596. SetError(53, "FileManager::RemoveProtection Failed.", "RemoveProtection Failed by " + ownerEmail);
  597. }
  598. getActionFileInfo(actualFileName, result);
  599. return result;
  600. }
  601. private String getOrgFileInfo(IFileHandler handler, String email, SetFileInfo result)
  602. {
  603. String ownerEmail = email;
  604. if (handler.Label != null && handler.Label.Label != null)
  605. {
  606. result.labelGuid = handler.Label.Label.Id;
  607. }
  608. if (handler.Protection != null)
  609. {
  610. ownerEmail = handler.Protection.Owner;
  611. result.fileOwner = handler.Protection.Owner;
  612. if (handler.Protection.ProtectionDescriptor != null)
  613. {
  614. result.templateGuid = handler.Protection.ProtectionDescriptor.TemplateId;
  615. }
  616. }
  617. return ownerEmail;
  618. }
  619. private void getActionFileInfo(String actualFileName, SetFileInfo result)
  620. {
  621. AipFileInfo info = GetFileInfo(actualFileName);
  622. if (info != null)
  623. {
  624. if (info.Label != null)
  625. {
  626. result.newFileLabelGuid = info.Label.Id;
  627. }
  628. if (info.Protection != null)
  629. {
  630. result.newFileOwner = info.Protection.Owner;
  631. if (info.Protection.ProtectionDescriptor != null)
  632. {
  633. result.newFileTemplateGuid = info.Protection.ProtectionDescriptor.TemplateId;
  634. }
  635. }
  636. }
  637. }
  638. private bool CommitAsync(IFileHandler handler, string actualFileName, SetFileInfo result)
  639. {
  640. bool isCommitted = false;
  641. if (handler.IsModified())
  642. {
  643. try
  644. {
  645. //using (var outputStream = new MemoryStream())
  646. {
  647. //Stopwatch sw = new Stopwatch();
  648. //sw.Start();
  649. //_log.Warn($"SetLabel: [{Task.CurrentId}], CommitAsync[2]: actualFileName: {actualFileName}");
  650. isCommitted = Task.Run(async () => await handler.CommitAsync(actualFileName)).Result;
  651. //isCommitted = handler.CommitAsync(actualFileName).Result;
  652. //isCommitted = Task.Run(async () => await handler.CommitAsync(outputStream)).Result;
  653. //sw.Stop();
  654. //_log.Information("********: [{0}], CommitAsync: ------------------- {1,6} ms. actualFileName: {2}", Task.CurrentId, sw.ElapsedMilliseconds.ToString("#,##0"), actualFileName);
  655. }
  656. }
  657. catch (Exception ex)
  658. {
  659. // TODO: Exception catch 해야함.......... 여기서 캣치하면 정확한 오류 메시지를 확인 할 수 없음.
  660. result.errorNo = 55;
  661. result.errorMsg = "AIP File CommitAsync Failed." + ex.Message;
  662. SetError(55, "FileManager CommitAsync Failed.", ex.Message);
  663. }
  664. }
  665. return isCommitted;
  666. }
  667. public async Task<Stream> GetDecryptedStreamAsync(Stream inputStream, string filename)
  668. {
  669. var handler = CreateFileHandler(inputStream, filename);
  670. return await handler.GetDecryptedTemporaryStreamAsync();
  671. }
  672. // Protect the input bytes.
  673. public byte[] Protect(IProtectionHandler handler, byte[] data)
  674. {
  675. long buffersize = handler.GetProtectedContentLength(data.Length, true);
  676. byte[] outputBuffer = new byte[buffersize];
  677. handler.EncryptBuffer(0, data, outputBuffer, true);
  678. return outputBuffer;
  679. }
  680. public byte[] Unprotect(IProtectionHandler handler, byte[] data)
  681. {
  682. long buffersize = data.Length;
  683. byte[] clearBuffer = new byte[buffersize];
  684. var bytesDecrypted = handler.DecryptBuffer(0, data, clearBuffer, true);
  685. byte[] outputBuffer = new byte[bytesDecrypted];
  686. for (int i = 0; i < bytesDecrypted; i++)
  687. {
  688. outputBuffer[i] = clearBuffer[i];
  689. }
  690. return outputBuffer;
  691. }
  692. }
  693. }