AipFileService.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. using Microsoft.InformationProtection.File;
  2. using Microsoft.InformationProtection;
  3. using Aip.Api.Service.Aip.Models;
  4. using Aip.Api.Service.Aip.Exceptions;
  5. using Microsoft.InformationProtection.Policy;
  6. using Microsoft.InformationProtection.Protection;
  7. namespace Aip.Api.Service.Aip.Serivces;
  8. public class AipFileService : IDisposable
  9. {
  10. private readonly Serilog.ILogger _log;
  11. private readonly AipConfig _aipConfig;
  12. private readonly ApplicationInfo _appInfo;
  13. private readonly AuthDelegateImplementation _authDelegate;
  14. public int LastErrNo { get; internal set; }
  15. public string LastErrMsg { get; internal set; }
  16. private MipContext _mipContext;
  17. private IFileProfile _fileProfile;
  18. private IFileEngine _fileEngine;
  19. private IPolicyProfile _policyProfile;
  20. private IPolicyEngine _policyEngine;
  21. private IProtectionProfile _protectionProfile;
  22. private IProtectionEngine _protectionEngine;
  23. private string _engineId = string.Empty;
  24. private bool disposedValue;
  25. public AipFileService(Serilog.Core.Logger logger, AipConfig aipConfig)
  26. {
  27. _log = logger.ForContext<AipFileService>();
  28. _aipConfig = aipConfig;
  29. _appInfo = new ApplicationInfo()
  30. {
  31. ApplicationId = _aipConfig.ClientId,
  32. ApplicationName = _aipConfig.AppName,
  33. ApplicationVersion = _aipConfig.AppVersion
  34. };
  35. //_engineId = _aipConfig.EMail;
  36. _engineId = _aipConfig.ClientId;
  37. LastErrNo = 0;
  38. LastErrMsg = string.Empty;
  39. _authDelegate = new AuthDelegateImplementation(logger, _aipConfig);
  40. try
  41. {
  42. // Initialize SDK DLLs. If DLLs are missing or wrong type, this will throw an exception
  43. MIP.Initialize(MipComponent.File);
  44. //MIP.Initialize(MipComponent.Policy);
  45. //MIP.Initialize(MipComponent.Protection); // Protection
  46. MipConfiguration mipConfiguration = new MipConfiguration(_appInfo, _aipConfig.MipData, Microsoft.InformationProtection.LogLevel.Warning, false);
  47. _mipContext = MIP.CreateMipContext(mipConfiguration);
  48. Microsoft.InformationProtection.Identity identity = new Microsoft.InformationProtection.Identity(_aipConfig.EMail);
  49. _fileProfile = CreateFileProfile();
  50. _fileEngine = CreateFileEngine(identity);
  51. _policyProfile = CreatePolicyProfile();
  52. _policyEngine = CreatePolicyEngine(identity);
  53. _protectionProfile = CreateProtectionProfile();
  54. _protectionEngine = CreateProtectionEngine(identity);
  55. }
  56. catch (Exception ex)
  57. {
  58. SetError(1, "MIP.Initialize Failed.", ex.Message, false);
  59. throw;
  60. }
  61. }
  62. //----------------------------------------------------------------------------------------------------------------
  63. private IFileProfile CreateFileProfile()
  64. {
  65. var profileSettings = new FileProfileSettings(_mipContext,
  66. //CacheStorageType.OnDiskEncrypted,
  67. CacheStorageType.InMemory,
  68. new ConsentDelegateImplementation());
  69. // IFileProfile은 특정 애플리케이션에 대한 모든 SDK 작업의 루트입니다.
  70. return Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
  71. }
  72. private IFileEngine CreateFileEngine(Microsoft.InformationProtection.Identity identity)
  73. {
  74. var engineSettings = new FileEngineSettings(_engineId, _authDelegate, string.Empty, "en-US")
  75. {
  76. Identity = identity,
  77. //ProtectionOnlyEngine = true
  78. };
  79. return Task.Run(async () => await _fileProfile.AddEngineAsync(engineSettings)).Result;
  80. }
  81. //----------------------------------------------------------------------------------------------------------------
  82. public IPolicyProfile CreatePolicyProfile()
  83. {
  84. var profileSettings = new PolicyProfileSettings(_mipContext,
  85. //CacheStorageType.OnDiskEncrypted
  86. CacheStorageType.InMemory
  87. );
  88. return Task.Run(async () => await MIP.LoadPolicyProfileAsync(profileSettings)).Result;
  89. }
  90. public IPolicyEngine CreatePolicyEngine(Microsoft.InformationProtection.Identity identity)
  91. {
  92. var engineSettings = new PolicyEngineSettings(_engineId, _authDelegate, string.Empty, "en-US")
  93. {
  94. // Provide the identity for service discovery.
  95. Identity = identity
  96. };
  97. return Task.Run(async () => await _policyProfile.AddEngineAsync(engineSettings)).Result;
  98. }
  99. //----------------------------------------------------------------------------------------------------------------
  100. public IProtectionProfile CreateProtectionProfile()
  101. {
  102. var profileSettings = new ProtectionProfileSettings(_mipContext,
  103. //CacheStorageType.OnDiskEncrypted,
  104. CacheStorageType.InMemory,
  105. new ConsentDelegateImplementation());
  106. return Task.Run(async () => await MIP.LoadProtectionProfileAsync(profileSettings)).Result;
  107. }
  108. public IProtectionEngine CreateProtectionEngine(Microsoft.InformationProtection.Identity identity)
  109. {
  110. var engineSettings = new ProtectionEngineSettings(_engineId, _authDelegate, string.Empty, "en-US")
  111. {
  112. // Provide the identity for service discovery.
  113. Identity = identity
  114. };
  115. return Task.Run(async () => await _protectionProfile.AddEngineAsync(engineSettings)).Result;
  116. }
  117. //----------------------------------------------------------------------------------------------------------------
  118. //----------------------------------------------------------------------------------------------------------------
  119. public bool IsProtected(Stream inputStream, string filePath)
  120. {
  121. IFileStatus status = FileHandler.GetFileStatus(inputStream, filePath, _mipContext);
  122. bool result = status.IsProtected();
  123. return result;
  124. }
  125. public bool IsLabeledOrProtected(Stream inputStream, string filePath)
  126. {
  127. IFileStatus status = FileHandler.GetFileStatus(inputStream, filePath, _mipContext);
  128. bool isLabeled = status.IsLabeled();
  129. bool isProtected = status.IsProtected();
  130. return (isLabeled || isProtected);
  131. }
  132. //----------------------------------------------------------------------------------------------------------------
  133. public List<AipLabel> SensitivityLabels()
  134. {
  135. var result = new List<AipLabel>();
  136. try
  137. {
  138. var labels = _fileEngine.SensitivityLabels;
  139. foreach (var label in labels)
  140. {
  141. var aipLabel = AipUtils.LabelToAip(label);
  142. if (aipLabel != null)
  143. {
  144. if (label.Children.Count > 0)
  145. {
  146. foreach (var child in label.Children)
  147. {
  148. var aipChildLabel = AipUtils.LabelToAip(child);
  149. if (aipChildLabel != null) aipLabel.Children.Add(aipChildLabel);
  150. }
  151. }
  152. result.Add(aipLabel);
  153. }
  154. }
  155. }
  156. catch (Exception ex)
  157. {
  158. SetError(31, "SensitivityLabels Failed.", ex.Message);
  159. result = new List<AipLabel>();
  160. }
  161. return result;
  162. }
  163. public List<AipLabel> ListSensitivityLabels()
  164. {
  165. var result = new List<AipLabel>();
  166. try
  167. {
  168. var labels = _policyEngine.ListSensitivityLabels();
  169. foreach (var label in labels)
  170. {
  171. var aipLabel = AipUtils.LabelToAip(label);
  172. if (aipLabel != null)
  173. {
  174. if (label.Children.Count > 0)
  175. {
  176. foreach (var child in label.Children)
  177. {
  178. var aipChildLabel = AipUtils.LabelToAip(child);
  179. if (aipChildLabel != null) aipLabel.Children.Add(aipChildLabel);
  180. }
  181. }
  182. result.Add(aipLabel);
  183. }
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. SetError(32, "ListSensitivityLabels Failed.", ex.Message);
  189. result = new List<AipLabel>();
  190. }
  191. return result;
  192. }
  193. public List<AipTemplate> GetTemplates()
  194. {
  195. var result = new List<AipTemplate>();
  196. try
  197. {
  198. var templates = _protectionEngine.GetTemplates();
  199. foreach (var template in templates)
  200. {
  201. var aipTemplate = AipUtils.TemplateToAip(template);
  202. if (aipTemplate != null)
  203. {
  204. result.Add(aipTemplate);
  205. }
  206. }
  207. }
  208. catch (Exception ex)
  209. {
  210. SetError(33, "GetTemplates Failed.", ex.Message);
  211. result = new List<AipTemplate>();
  212. }
  213. return result;
  214. }
  215. //----------------------------------------------------------------------------------------------------------------
  216. private IFileHandler? CreateFileHandler(Stream inputStream, string outputFile)
  217. {
  218. if (inputStream is null)
  219. {
  220. SetError(LastErrNo, "CreateFileHandler Failed.", "요청한 스트림의 정보가 없습니다.");
  221. return null;
  222. }
  223. if (outputFile is null || outputFile.Length == 0)
  224. {
  225. SetError(LastErrNo, "CreateFileHandler Failed.", "요청한 출력 파일 이릅이 존재하지 않습니다.");
  226. return null;
  227. }
  228. try
  229. {
  230. var handler = Task.Run(async () => await _fileEngine.CreateFileHandlerAsync(inputStream, outputFile, false)) .Result;
  231. return handler;
  232. }
  233. catch (Exception ex)
  234. {
  235. SetError(LastErrNo, "CreateFileHandler Failed. Stream: " + outputFile, ex.Message);
  236. }
  237. return null;
  238. }
  239. private IFileHandler? CreateFileHandler(string inputFile, string outputFile)
  240. {
  241. if (!File.Exists(inputFile))
  242. {
  243. SetError(LastErrNo, "CreateFileHandler Failed.", "요청한 파일이 존재하지 않습니다. " + inputFile);
  244. return null;
  245. }
  246. try
  247. {
  248. //Stopwatch sw = new Stopwatch();
  249. //sw.Start();
  250. var handler = _fileEngine.CreateFileHandlerAsync(inputFile, outputFile, false).Result;
  251. //var handler = Task.Run(async () => await _engine.CreateFileHandlerAsync(inputFile, outputFile, true)).Result;
  252. //sw.Stop();
  253. //_log.Information("********: [{0}], CreateFileHandlerAsync: -------- {1,6} ms. inputFile: {2}", Task.CurrentId, sw.ElapsedMilliseconds.ToString("#,##0"), inputFile);
  254. return handler;
  255. }
  256. catch (Exception ex)
  257. {
  258. SetError(LastErrNo, "CreateFileHandler Failed. File: " + inputFile, ex.Message);
  259. }
  260. return null;
  261. }
  262. //----------------------------------------------------------------------------------------------------------------
  263. private AipFileInfo GetFileInfo(IFileHandler handler)
  264. {
  265. AipFileInfo fileInfo = new AipFileInfo
  266. {
  267. Content = null,
  268. Label = null,
  269. Protection = null,
  270. OutputFileName = null,
  271. FileSize = 0,
  272. };
  273. fileInfo.OutputFileName = handler.OutputFileName;
  274. if (handler.Label != null)
  275. {
  276. fileInfo.Content = new AipContentLabel()
  277. {
  278. //Label = Utilities.LabelToAip(handler.Label.Label),
  279. CreationTime = handler.Label.CreationTime,
  280. AssignmentMethod = (AipAssignmentMethod)handler.Label.AssignmentMethod,
  281. IsProtectionAppliedFromLabel = handler.Label.IsProtectionAppliedFromLabel,
  282. };
  283. fileInfo.Label = AipUtils.LabelToAip(handler.Label.Label);
  284. }
  285. if (handler.Protection != null)
  286. {
  287. fileInfo.Protection = new AipProtection()
  288. {
  289. Owner = handler.Protection.Owner,
  290. IssuedTo = handler.Protection.IssuedTo,
  291. IsIssuedToOwner = handler.Protection.IsIssuedToOwner,
  292. ContentId = handler.Protection.ContentId,
  293. AuditedExtractAllowed = handler.Protection.AuditedExtractAllowed,
  294. BlockSize = handler.Protection.BlockSize,
  295. ProtectionDescriptor = null,
  296. };
  297. if (handler.Protection.ProtectionDescriptor != null)
  298. {
  299. fileInfo.Protection.ProtectionDescriptor = new AipProtectionDescriptor()
  300. {
  301. ProtectionType = (AipProtectionType)handler.Protection.ProtectionDescriptor.ProtectionType,
  302. TemplateId = handler.Protection.ProtectionDescriptor.TemplateId,
  303. LabelInformation = new AipLabelInfo(),
  304. LabelId = handler.Protection.ProtectionDescriptor.LabelId,
  305. Owner = handler.Protection.ProtectionDescriptor.Owner,
  306. ContentId = handler.Protection.ProtectionDescriptor.ContentId,
  307. Name = handler.Protection.ProtectionDescriptor.Name,
  308. Description = handler.Protection.ProtectionDescriptor.Description,
  309. AllowOfflineAccess = handler.Protection.ProtectionDescriptor.AllowOfflineAccess,
  310. Referrer = handler.Protection.ProtectionDescriptor.Referrer,
  311. ContentValidUntil = handler.Protection.ProtectionDescriptor.ContentValidUntil,
  312. DoubleKeyUrl = handler.Protection.ProtectionDescriptor.DoubleKeyUrl,
  313. };
  314. if (handler.Protection.ProtectionDescriptor.LabelInformation != null)
  315. {
  316. fileInfo.Protection.ProtectionDescriptor.LabelInformation.LabelId =
  317. handler.Protection.ProtectionDescriptor.LabelInformation.LabelId;
  318. fileInfo.Protection.ProtectionDescriptor.LabelInformation.TenantId =
  319. handler.Protection.ProtectionDescriptor.LabelInformation.TenantId;
  320. }
  321. }
  322. }
  323. return fileInfo;
  324. }
  325. public AipFileInfo? GetFileInfo(string fileName)
  326. {
  327. LastErrNo = 21;
  328. using var handler = CreateFileHandler(fileName, fileName);
  329. if (handler == null)
  330. {
  331. return null;
  332. }
  333. var result = GetFileInfo(handler);
  334. try
  335. {
  336. result.FileSize = GetFileSize(fileName);
  337. }
  338. catch (Exception ex)
  339. {
  340. result.FileSize = 0;
  341. SetError(11, "GetFileInfo Failed. " + fileName, ex.Message);
  342. }
  343. return result;
  344. }
  345. public AipFileInfo? GetFileInfo(Stream fileStream, string outputFileName)
  346. {
  347. LastErrNo = 22;
  348. using var handler = CreateFileHandler(fileStream, outputFileName);
  349. if (handler == null)
  350. {
  351. //File.Delete(outputFileName);
  352. return null;
  353. }
  354. var result = GetFileInfo(handler);
  355. try
  356. {
  357. result.FileSize = fileStream.Length;
  358. //File.Delete(outputFileName);
  359. }
  360. catch (Exception ex)
  361. {
  362. result.FileSize = 0;
  363. SetError(12, "GetFileInfo Failed. " + outputFileName, ex.Message);
  364. }
  365. return result;
  366. }
  367. //----------------------------------------------------------------------------------------------------------------
  368. public Label GetLabelById(string labelId)
  369. {
  370. return _fileEngine.GetLabelById(labelId);
  371. }
  372. //----------------------------------------------------------------------------------------------------------------
  373. private void GetActionFileInfo(string actualFileName, SetFileInfo result)
  374. {
  375. AipFileInfo? info = GetFileInfo(actualFileName);
  376. if (info != null)
  377. {
  378. if (info.Label != null)
  379. {
  380. result.newFileLabelGuid = info.Label.Id;
  381. }
  382. if (info.Protection != null)
  383. {
  384. result.newFileOwner = info.Protection.Owner;
  385. if (info.Protection.ProtectionDescriptor != null)
  386. {
  387. result.newFileTemplateGuid = info.Protection.ProtectionDescriptor.TemplateId;
  388. }
  389. }
  390. }
  391. }
  392. //----------------------------------------------------------------------------------------------------------------
  393. private string GetOrgFileInfo(IFileHandler handler, string email, SetFileInfo result)
  394. {
  395. string ownerEmail = email;
  396. if (handler.Label != null && handler.Label.Label != null)
  397. {
  398. result.labelGuid = handler.Label.Label.Id;
  399. }
  400. if (handler.Protection != null)
  401. {
  402. ownerEmail = handler.Protection.Owner;
  403. result.fileOwner = handler.Protection.Owner;
  404. if (handler.Protection.ProtectionDescriptor != null)
  405. {
  406. result.templateGuid = handler.Protection.ProtectionDescriptor.TemplateId;
  407. }
  408. }
  409. return ownerEmail;
  410. }
  411. //----------------------------------------------------------------------------------------------------------------
  412. private bool CommitAsync(IFileHandler handler, string actualFileName, SetFileInfo result)
  413. {
  414. bool isCommitted = false;
  415. if (handler.IsModified())
  416. {
  417. try
  418. {
  419. //using (var outputStream = new MemoryStream())
  420. {
  421. //Stopwatch sw = new Stopwatch();
  422. //sw.Start();
  423. //_log.Warn($"SetLabel: [{Task.CurrentId}], CommitAsync[2]: actualFileName: {actualFileName}");
  424. //isCommitted = Task.Run(async () => await handler.CommitAsync(actualFileName)).Result;
  425. isCommitted = handler.CommitAsync(actualFileName).Result;
  426. //isCommitted = Task.Run(async () => await handler.CommitAsync(outputStream)).Result;
  427. //sw.Stop();
  428. //_log.Information("********: [{0}], CommitAsync: ------------------- {1,6} ms. actualFileName: {2}", Task.CurrentId, sw.ElapsedMilliseconds.ToString("#,##0"), actualFileName);
  429. }
  430. }
  431. catch (Exception ex)
  432. {
  433. result.errorMsg = "AIP File CommitAsync Failed." + actualFileName + ex.Message;
  434. SetError(55, "FileManager CommitAsync Failed. " + actualFileName, ex.Message);
  435. }
  436. }
  437. return isCommitted;
  438. }
  439. //----------------------------------------------------------------------------------------------------------------
  440. public SetFileInfo SetLabel(IFileHandler? handler, string actualFileName, string email, string labelId, string templateId, string comments, long fileSize)
  441. {
  442. SetFileInfo result = new SetFileInfo()
  443. {
  444. errorNo = 0,
  445. errorMsg = AipConstants.AIP_RESULT_SUCCESS,
  446. };
  447. if (handler == null)
  448. {
  449. result.errorNo = 201;
  450. result.errorMsg = LastErrMsg;
  451. return result;
  452. }
  453. result.fileSize = fileSize;
  454. Label label = GetLabelById(labelId);
  455. if (label == null)
  456. {
  457. result.errorNo = 202;
  458. result.errorMsg = LastErrMsg;
  459. return result;
  460. }
  461. LabelingOptions labelingOptions = new LabelingOptions()
  462. {
  463. AssignmentMethod = AssignmentMethod.Auto,
  464. JustificationMessage = comments,
  465. IsDowngradeJustified = true
  466. };
  467. string ownerEmail = GetOrgFileInfo(handler, email, result);
  468. var protectionSettings = new ProtectionSettings
  469. {
  470. PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
  471. };
  472. if (ownerEmail != "")
  473. {
  474. protectionSettings.DelegatedUserEmail = ownerEmail;
  475. }
  476. try
  477. {
  478. handler.SetLabel(label, labelingOptions, protectionSettings);
  479. if (templateId != "")
  480. {
  481. ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(templateId);
  482. handler.SetProtection(protectionDescriptor, protectionSettings);
  483. }
  484. }
  485. catch (Exception ex)
  486. {
  487. result.errorNo = 203;
  488. result.errorMsg = ex.Message;
  489. SetError(203, "FileManager::SetLabel Failed. " + actualFileName, ex.Message);
  490. return result;
  491. }
  492. //Log.Error("actualFileName EXT: " + Path.GetExtension(actualFileName).ToLower());
  493. //Log.Error("actualFileName DIR: " + Path.GetDirectoryName(actualFileName));
  494. //Log.Error("actualFileName NAME: " + Path.GetFileNameWithoutExtension(actualFileName));
  495. //Log.Error("actualFileName FULL NAME: " + actualFileName);
  496. //Log.Error(" handler.OutputFileName: " + handler.OutputFileName);
  497. //Log.Error(" handler.OutputFileName: " + Path.GetExtension(handler.OutputFileName).ToLower());
  498. //_log.Warn($"SetLabel: [{Task.CurrentId}], CommitAsync[B]: actualFileName: {actualFileName}");
  499. actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName)!, Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
  500. bool isCommitted = CommitAsync(handler, actualFileName, result);
  501. if (isCommitted)
  502. {
  503. //handler.NotifyCommitSuccessful(actualFileName);
  504. result.newFileSize = GetFileSize(actualFileName);
  505. result.newFileLabelGuid = labelId;
  506. result.newFileName = actualFileName;
  507. result.newFileOwner = ownerEmail;
  508. result.newFileTemplateGuid = labelId;
  509. }
  510. else
  511. {
  512. result.errorNo = 204;
  513. result.errorMsg = "AIP File CommitAsync Failed.";
  514. SetError(53, "FileManager::SetLabel Failed.", "Label Id: " + labelId + ", SetLabel Failed. " + actualFileName);
  515. }
  516. //GetActionFileInfo(actualFileName, result);
  517. return result;
  518. }
  519. public SetFileInfo SetLabel(string fileName, string actualFileName, string email, string labelId, string templateId, string comments = "")
  520. {
  521. // 레이블 및 템플릿 정보 가져오기
  522. if (comments == "")
  523. {
  524. comments = "SetLabel";
  525. }
  526. LastErrNo = 31;
  527. using var handler = CreateFileHandler(fileName, actualFileName);
  528. return SetLabel(handler, actualFileName, email, labelId, templateId, comments, GetFileSize(fileName));
  529. }
  530. public SetFileInfo SetLabel(Stream fileStream, string actualFileName, string email, string labelId, string templateId, string comments = "")
  531. {
  532. // 레이블 및 템플릿 정보 가져오기
  533. if (comments == "")
  534. {
  535. comments = "SetLabel by " + email;
  536. }
  537. LastErrNo = 32;
  538. using var handler = CreateFileHandler(fileStream, actualFileName);
  539. return SetLabel(handler, actualFileName, email, labelId, templateId, comments, fileStream.Length);
  540. }
  541. //----------------------------------------------------------------------------------------------------------------
  542. public SetFileInfo DeleteLabel(IFileHandler? handler, string actualFileName, string email, string comments, bool isDelProtection, long fileSize)
  543. {
  544. SetFileInfo result = new SetFileInfo()
  545. {
  546. errorNo = 0,
  547. errorMsg = AipConstants.AIP_RESULT_SUCCESS,
  548. };
  549. if (handler == null)
  550. {
  551. result.errorNo = 201;
  552. result.errorMsg = LastErrMsg;
  553. return result;
  554. }
  555. result.fileSize = fileSize;
  556. LabelingOptions invokeLabelingOptions = new LabelingOptions()
  557. {
  558. AssignmentMethod = AssignmentMethod.Privileged, //because we are removing a high priority label
  559. JustificationMessage = comments,
  560. IsDowngradeJustified = true
  561. };
  562. string ownerEmail = GetOrgFileInfo(handler, email, result);
  563. var protectionSettings = new ProtectionSettings
  564. {
  565. PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
  566. };
  567. if (ownerEmail != "")
  568. {
  569. protectionSettings.DelegatedUserEmail = ownerEmail;
  570. }
  571. try
  572. {
  573. if (isDelProtection && handler.Protection != null)
  574. {
  575. if (handler.Protection.AccessCheck(Rights.Extract) || handler.Protection.AccessCheck(Rights.Owner))
  576. {
  577. handler.RemoveProtection();
  578. }
  579. }
  580. handler.DeleteLabel(invokeLabelingOptions);
  581. }
  582. catch (Exception ex)
  583. {
  584. result.errorNo = 203;
  585. result.errorMsg = ex.Message;
  586. SetError(53, "FileManager::DeleteLabel Failed.", ex.Message);
  587. return result;
  588. }
  589. actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName)!, Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
  590. bool isCommitted = CommitAsync(handler, actualFileName, result);
  591. if (isCommitted)
  592. {
  593. //handler.NotifyCommitSuccessful(fileName);
  594. result.newFileSize = GetFileSize(actualFileName);
  595. result.newFileLabelGuid = "";
  596. result.newFileName = actualFileName;
  597. result.newFileOwner = ownerEmail;
  598. result.newFileTemplateGuid = "";
  599. }
  600. else
  601. {
  602. result.errorNo = 204;
  603. result.errorMsg = "AIP File CommitAsync Failed.";
  604. SetError(54, "FileManager::DeleteLabel Failed.", "DeleteLabel Failed by " + ownerEmail);
  605. }
  606. //GetActionFileInfo(actualFileName, result);
  607. return result;
  608. }
  609. public SetFileInfo DeleteLabel(string fileName, string actualFileName, string email, string comments, bool isDelProtection)
  610. {
  611. if (comments == "")
  612. {
  613. comments = "Delete Label by " + email;
  614. }
  615. var outFileName = actualFileName == string.Empty ? fileName : actualFileName;
  616. LastErrNo = 33;
  617. using var handler = CreateFileHandler(fileName, outFileName);
  618. return DeleteLabel(handler, actualFileName, email, comments, isDelProtection, GetFileSize(fileName));
  619. }
  620. public SetFileInfo DeleteLabel(Stream fileStream, string actualFileName, string email, string comments, bool isDelProtection)
  621. {
  622. if (comments == "")
  623. {
  624. comments = "Delete Label by " + email;
  625. }
  626. LastErrNo = 34;
  627. using var handler = CreateFileHandler(fileStream, actualFileName);
  628. return DeleteLabel(handler, actualFileName, email, comments, isDelProtection, fileStream.Length);
  629. }
  630. //----------------------------------------------------------------------------------------------------------------
  631. public SetFileInfo SetProtection(IFileHandler? handler, string actualFileName, string email, string templateId, string comments, long fileSize)
  632. {
  633. SetFileInfo result = new SetFileInfo()
  634. {
  635. errorNo = 0,
  636. errorMsg = AipConstants.AIP_RESULT_SUCCESS,
  637. };
  638. if (handler == null)
  639. {
  640. result.errorNo = 201;
  641. result.errorMsg = LastErrMsg;
  642. return result;
  643. }
  644. result.fileSize = fileSize;
  645. string ownerEmail = GetOrgFileInfo(handler, email, result);
  646. try
  647. {
  648. ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(templateId);
  649. ProtectionSettings protectionSettings = new ProtectionSettings
  650. {
  651. PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
  652. };
  653. if (ownerEmail != "")
  654. {
  655. protectionSettings.DelegatedUserEmail = ownerEmail;
  656. }
  657. handler.SetProtection(protectionDescriptor, protectionSettings);
  658. }
  659. catch (Exception ex)
  660. {
  661. result.errorNo = 204;
  662. result.errorMsg = ex.Message;
  663. SetError(54, "FileManager::SetProtect Failed.", ex.Message);
  664. return result;
  665. }
  666. actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName)!, Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
  667. bool isCommitted = CommitAsync(handler, actualFileName, result);
  668. if (isCommitted)
  669. {
  670. //handler.NotifyCommitSuccessful(fileName);
  671. result.newFileSize = GetFileSize(actualFileName);
  672. //result.newFileLabelGuid = string.Empty;
  673. result.newFileName = actualFileName;
  674. result.newFileOwner = ownerEmail;
  675. result.newFileTemplateGuid = string.Empty;
  676. }
  677. else
  678. {
  679. result.errorNo = 206;
  680. result.errorMsg = "AIP File CommitAsync Failed.";
  681. SetError(56, "FileManager::SetProtect Failed.", "Template Id: " + templateId + ", SetProtect Failed.");
  682. }
  683. //GetActionFileInfo(actualFileName, result);
  684. return result;
  685. }
  686. public SetFileInfo SetProtection(string fileName, string actualFileName, string email, string templateId, string comments)
  687. {
  688. if (comments == "")
  689. {
  690. comments = "SetProtection by " + email;
  691. }
  692. LastErrNo = 41;
  693. using var handler = CreateFileHandler(fileName, actualFileName);
  694. return SetProtection(handler, actualFileName, email, templateId, comments, GetFileSize(fileName));
  695. }
  696. public SetFileInfo SetProtection(Stream fileStream, string actualFileName, string email, string templateId, string comments)
  697. {
  698. if (comments == "")
  699. {
  700. comments = "SetProtection by " + email;
  701. }
  702. LastErrNo = 42;
  703. using var handler = CreateFileHandler(fileStream, actualFileName);
  704. return SetProtection(handler, actualFileName, email, templateId, comments, fileStream.Length);
  705. }
  706. //----------------------------------------------------------------------------------------------------------------
  707. public SetFileInfo RemoveProtection(IFileHandler? handler, string actualFileName, string email, string comments, long fileSize)
  708. {
  709. SetFileInfo result = new SetFileInfo()
  710. {
  711. errorNo = 0,
  712. errorMsg = AipConstants.AIP_RESULT_SUCCESS,
  713. };
  714. if (handler == null)
  715. {
  716. result.errorNo = 201;
  717. result.errorMsg = LastErrMsg;
  718. return result;
  719. }
  720. result.fileSize = fileSize;
  721. string ownerEmail = GetOrgFileInfo(handler, email, result);
  722. //LabelingOptions invokeLabelingOptions = new LabelingOptions()
  723. //{
  724. // AssignmentMethod = AssignmentMethod.Privileged, //because we are removing a high priority label
  725. // JustificationMessage = comments,
  726. // IsDowngradeJustified = true,
  727. //};
  728. var protectionSettings = new ProtectionSettings
  729. {
  730. PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
  731. };
  732. if (ownerEmail != "")
  733. {
  734. protectionSettings.DelegatedUserEmail = ownerEmail;
  735. }
  736. try
  737. {
  738. if (handler.Protection != null)
  739. {
  740. // 원본 파일 형식이 레이블 지정을 지원하지 않는 경우 보호를 제거하면 레이블이 손실됩니다.
  741. // 기본 형식이 레이블 지정을 지원하는 경우 레이블 메타데이터가 유지됩니다.
  742. if (handler.Protection.AccessCheck(Rights.Extract) || handler.Protection.AccessCheck(Rights.Owner))
  743. {
  744. handler.RemoveProtection();
  745. }
  746. //Use the GetTemporaryDecryptedStream() or GetTemporaryDecryptedFile() API to create a temp decrypted output to render in your application.
  747. }
  748. else
  749. {
  750. result.errorNo = 209;
  751. result.errorMsg = "파일에 암호화 정보가 없습니다.";
  752. return result;
  753. }
  754. }
  755. catch (Exception ex)
  756. {
  757. result.errorNo = 208;
  758. result.errorMsg = "FileManager::RemoveProtection Failed." + ex.Message;
  759. SetError(59, "FileManager::RemoveProtection Failed.", ex.Message);
  760. return result;
  761. }
  762. actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName)!, Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
  763. bool isCommitted = CommitAsync(handler, actualFileName, result);
  764. if (isCommitted)
  765. {
  766. //handler.NotifyCommitSuccessful(fileName);
  767. result.newFileSize = GetFileSize(actualFileName);
  768. result.newFileLabelGuid = string.Empty;
  769. result.newFileName = actualFileName;
  770. result.newFileOwner = ownerEmail;
  771. result.newFileTemplateGuid = string.Empty;
  772. }
  773. else
  774. {
  775. result.errorNo = 204;
  776. result.errorMsg = "AIP File CommitAsync Failed.";
  777. SetError(53, "FileManager::RemoveProtection Failed.", "RemoveProtection Failed by " + ownerEmail);
  778. }
  779. //GetActionFileInfo(actualFileName, result);
  780. return result;
  781. }
  782. public SetFileInfo RemoveProtection(string fileName, string actualFileName, string email, string comments)
  783. {
  784. if (comments == "")
  785. {
  786. comments = "Remove Protection by " + email;
  787. }
  788. LastErrNo = 43;
  789. using var handler = CreateFileHandler(fileName, actualFileName);
  790. return RemoveProtection(handler, actualFileName, email, comments, GetFileSize(fileName));
  791. }
  792. public SetFileInfo RemoveProtection(Stream fileStream, string actualFileName, string email, string comments)
  793. {
  794. if (comments == "")
  795. {
  796. comments = "Remove Protection by " + email;
  797. }
  798. LastErrNo = 44;
  799. using var handler = CreateFileHandler(fileStream, actualFileName);
  800. return RemoveProtection(handler, actualFileName, email, comments, fileStream.Length);
  801. }
  802. //----------------------------------------------------------------------------------------------------------------
  803. public AipFileStatus? GetAipFileStatus(string fileName)
  804. {
  805. try
  806. {
  807. var fileStatus = FileHandler.GetFileStatus(fileName, _mipContext);
  808. AipFileStatus result = new AipFileStatus
  809. {
  810. IsProtected = fileStatus.IsProtected(),
  811. IsLabeled = fileStatus.IsLabeled(),
  812. ContainsProtectedObjects = fileStatus.ContainsProtectedObjects()
  813. };
  814. return result;
  815. }
  816. catch (Exception ex)
  817. {
  818. SetError(81, "AipFileManager::GetAipFileStatus Failed.", ex.Message);
  819. }
  820. return null;
  821. }
  822. //----------------------------------------------------------------------------------------------------------------
  823. private Int64 GetFileSize(string fileName)
  824. {
  825. try
  826. {
  827. return new FileInfo(fileName).Length;
  828. }
  829. catch { return 0; }
  830. }
  831. //----------------------------------------------------------------------------------------------------------------
  832. private void SetError(int errNo, string errMsg1, string errMsg2 = "", bool isThrowEx = true)
  833. {
  834. LastErrNo = errNo;
  835. if (errMsg2 == "")
  836. {
  837. LastErrMsg = errMsg1;
  838. }
  839. else
  840. {
  841. LastErrMsg = errMsg1 + "\r\n" + errMsg2;
  842. }
  843. _log.Error("AipFileService::SetError ==> {0}, {1}, {2}", errNo, errMsg1, errMsg2);
  844. if (isThrowEx && LastErrNo != 0)
  845. {
  846. throw new AipFileException(errNo, LastErrMsg);
  847. }
  848. }
  849. protected virtual void Dispose(bool disposing)
  850. {
  851. if (!disposedValue)
  852. {
  853. if (disposing)
  854. {
  855. // TODO: 관리형 상태(관리형 개체)를 삭제합니다.
  856. }
  857. disposedValue = true;
  858. }
  859. }
  860. public void Dispose()
  861. {
  862. _fileProfile.UnloadEngineAsync(_fileEngine.Settings.EngineId).GetAwaiter().GetResult();
  863. _fileEngine.Dispose();
  864. _fileProfile.Dispose();
  865. _policyProfile.UnloadEngineAsync(_policyEngine.Settings.Id).GetAwaiter().GetResult();
  866. _policyEngine.Dispose();
  867. _policyProfile.Dispose();
  868. //_protectionProfile.Dispose();
  869. _protectionEngine.Dispose();
  870. _protectionProfile.Dispose();
  871. _mipContext.ShutDown();
  872. _mipContext.Dispose();
  873. Dispose(disposing: true);
  874. GC.SuppressFinalize(this);
  875. }
  876. }