AipFileService.cs 36 KB

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