123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952 |
- using Microsoft.InformationProtection.File;
- using Microsoft.InformationProtection;
- using Aip.Service.Aip.Models;
- using Microsoft.InformationProtection.Policy;
- using Microsoft.InformationProtection.Protection;
- using Aip.Service.Aip.Exceptions;
- using static Dapper.SqlMapper;
- namespace Aip.Service.Aip.Serivces;
- public class AipFileService : IDisposable
- {
- private readonly Serilog.ILogger _log;
- private readonly AipConfig _aipConfig;
- private readonly ApplicationInfo _appInfo;
- private readonly AuthDelegateImplementation _authDelegate;
- public int LastErrNo { get; internal set; }
- public string LastErrMsg { get; internal set; }
-
- private MipContext _mipContext;
- private IFileProfile _fileProfile;
- private IFileEngine _fileEngine;
- private IPolicyProfile _policyProfile;
- private IPolicyEngine _policyEngine;
- private IProtectionProfile _protectionProfile;
- private IProtectionEngine _protectionEngine;
- private string _engineId = string.Empty;
- private bool disposedValue;
- public AipFileService(Serilog.Core.Logger logger, AipConfig aipConfig)
- {
- _log = logger.ForContext<AipFileService>();
- _aipConfig = aipConfig;
- _appInfo = new ApplicationInfo()
- {
- ApplicationId = _aipConfig.ClientId,
- ApplicationName = _aipConfig.AppName,
- ApplicationVersion = _aipConfig.AppVersion
- };
- //_engineId = _aipConfig.EMail;
- _engineId = _aipConfig.ClientId;
- LastErrNo = 0;
- LastErrMsg = string.Empty;
- _authDelegate = new AuthDelegateImplementation(logger, _aipConfig);
- try
- {
- // Initialize SDK DLLs. If DLLs are missing or wrong type, this will throw an exception
- MIP.Initialize(MipComponent.File);
- //MIP.Initialize(MipComponent.Policy);
- //MIP.Initialize(MipComponent.Protection); // Protection
- MipConfiguration mipConfiguration = new MipConfiguration(_appInfo, _aipConfig.MipData, Microsoft.InformationProtection.LogLevel.Warning, false);
- _mipContext = MIP.CreateMipContext(mipConfiguration);
- Microsoft.InformationProtection.Identity identity = new Microsoft.InformationProtection.Identity(_aipConfig.EMail);
- _fileProfile = CreateFileProfile();
- _fileEngine = CreateFileEngine(identity);
- _policyProfile = CreatePolicyProfile();
- _policyEngine = CreatePolicyEngine(identity);
-
- _protectionProfile = CreateProtectionProfile();
- _protectionEngine = CreateProtectionEngine(identity);
- }
- catch (Exception ex)
- {
- SetError(1, "MIP.Initialize Failed.", ex.Message, false);
- throw;
- }
- }
- //----------------------------------------------------------------------------------------------------------------
- private IFileProfile CreateFileProfile()
- {
- var profileSettings = new FileProfileSettings(_mipContext,
- //CacheStorageType.OnDiskEncrypted,
- CacheStorageType.InMemory,
- new ConsentDelegateImplementation());
- // IFileProfile은 특정 애플리케이션에 대한 모든 SDK 작업의 루트입니다.
- return Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
- }
- private IFileEngine CreateFileEngine(Microsoft.InformationProtection.Identity identity)
- {
- var engineSettings = new FileEngineSettings(_engineId, _authDelegate, string.Empty, "en-US")
- {
- Identity = identity,
- //ProtectionOnlyEngine = true
- };
- return Task.Run(async () => await _fileProfile.AddEngineAsync(engineSettings)).Result;
- }
- //----------------------------------------------------------------------------------------------------------------
- public IPolicyProfile CreatePolicyProfile()
- {
- var profileSettings = new PolicyProfileSettings(_mipContext,
- //CacheStorageType.OnDiskEncrypted
- CacheStorageType.InMemory
- );
- return Task.Run(async () => await MIP.LoadPolicyProfileAsync(profileSettings)).Result;
- }
- public IPolicyEngine CreatePolicyEngine(Microsoft.InformationProtection.Identity identity)
- {
- var engineSettings = new PolicyEngineSettings(_engineId, _authDelegate, string.Empty, "en-US")
- {
- // Provide the identity for service discovery.
- Identity = identity
- };
- return Task.Run(async () => await _policyProfile.AddEngineAsync(engineSettings)).Result;
- }
- //----------------------------------------------------------------------------------------------------------------
- public IProtectionProfile CreateProtectionProfile()
- {
- var profileSettings = new ProtectionProfileSettings(_mipContext,
- //CacheStorageType.OnDiskEncrypted,
- CacheStorageType.InMemory,
- new ConsentDelegateImplementation());
- return Task.Run(async () => await MIP.LoadProtectionProfileAsync(profileSettings)).Result;
- }
- public IProtectionEngine CreateProtectionEngine(Microsoft.InformationProtection.Identity identity)
- {
- var engineSettings = new ProtectionEngineSettings(_engineId, _authDelegate, string.Empty, "en-US")
- {
- // Provide the identity for service discovery.
- Identity = identity
- };
- return Task.Run(async () => await _protectionProfile.AddEngineAsync(engineSettings)).Result;
- }
- //----------------------------------------------------------------------------------------------------------------
- //----------------------------------------------------------------------------------------------------------------
- public bool IsProtected(Stream inputStream, string filePath)
- {
- IFileStatus status = FileHandler.GetFileStatus(inputStream, filePath, _mipContext);
- bool result = status.IsProtected();
- return result;
- }
- public bool IsLabeledOrProtected(Stream inputStream, string filePath)
- {
- IFileStatus status = FileHandler.GetFileStatus(inputStream, filePath, _mipContext);
- bool isLabeled = status.IsLabeled();
- bool isProtected = status.IsProtected();
- return (isLabeled || isProtected);
- }
- //----------------------------------------------------------------------------------------------------------------
- public List<AipLabel> SensitivityLabels()
- {
- var result = new List<AipLabel>();
- try
- {
- var labels = _fileEngine.SensitivityLabels;
- foreach (var label in labels)
- {
- var aipLabel = AipUtils.LabelToAip(label);
- if (aipLabel != null)
- {
- if (label.Children.Count > 0)
- {
- foreach (var child in label.Children)
- {
- var aipChildLabel = AipUtils.LabelToAip(child);
- if (aipChildLabel != null) aipLabel.Children.Add(aipChildLabel);
- }
- }
- result.Add(aipLabel);
- }
- }
- }
- catch (Exception ex)
- {
- SetError(31, "SensitivityLabels Failed.", ex.Message);
- result = new List<AipLabel>();
- }
- return result;
- }
- public List<AipLabel> ListSensitivityLabels()
- {
- var result = new List<AipLabel>();
- try
- {
- var labels = _policyEngine.ListSensitivityLabels();
- foreach (var label in labels)
- {
- var aipLabel = AipUtils.LabelToAip(label);
- if (aipLabel != null)
- {
- if (label.Children.Count > 0)
- {
- foreach (var child in label.Children)
- {
- var aipChildLabel = AipUtils.LabelToAip(child);
- if (aipChildLabel != null) aipLabel.Children.Add(aipChildLabel);
- }
- }
- result.Add(aipLabel);
- }
- }
- }
- catch (Exception ex)
- {
- SetError(32, "ListSensitivityLabels Failed.", ex.Message);
- result = new List<AipLabel>();
- }
- return result;
- }
- public List<AipTemplate> GetTemplates()
- {
- var result = new List<AipTemplate>();
- try
- {
- var templates = _protectionEngine.GetTemplates();
- foreach (var template in templates)
- {
- var aipTemplate = AipUtils.TemplateToAip(template);
- if (aipTemplate != null)
- {
- result.Add(aipTemplate);
- }
- }
- }
- catch (Exception ex)
- {
- SetError(33, "GetTemplates Failed.", ex.Message);
- result = new List<AipTemplate>();
- }
- return result;
- }
- //----------------------------------------------------------------------------------------------------------------
- private IFileHandler? CreateFileHandler(Stream inputStream, string outputFile)
- {
- if (inputStream is null)
- {
- SetError(LastErrNo, "CreateFileHandler Failed.", "요청한 스트림의 정보가 없습니다.");
- return null;
- }
- if (outputFile is null || outputFile.Length == 0)
- {
- SetError(LastErrNo, "CreateFileHandler Failed.", "요청한 출력 파일 이릅이 존재하지 않습니다.");
- return null;
- }
- try
- {
- var handler = Task.Run(async () => await _fileEngine.CreateFileHandlerAsync(inputStream, outputFile, false)) .Result;
- return handler;
- }
- catch (Exception ex)
- {
- SetError(LastErrNo, "CreateFileHandler Failed. Stream: " + outputFile, ex.Message);
- }
- return null;
- }
- private IFileHandler? CreateFileHandler(string inputFile, string outputFile)
- {
- if (!File.Exists(inputFile))
- {
- SetError(LastErrNo, "CreateFileHandler Failed.", "요청한 파일이 존재하지 않습니다. " + inputFile);
- return null;
- }
- try
- {
- //Stopwatch sw = new Stopwatch();
- //sw.Start();
- var handler = _fileEngine.CreateFileHandlerAsync(inputFile, outputFile, false).Result;
- //var handler = Task.Run(async () => await _engine.CreateFileHandlerAsync(inputFile, outputFile, true)).Result;
- //sw.Stop();
- //_log.Information("********: [{0}], CreateFileHandlerAsync: -------- {1,6} ms. inputFile: {2}", Task.CurrentId, sw.ElapsedMilliseconds.ToString("#,##0"), inputFile);
- return handler;
- }
- catch (Exception ex)
- {
- SetError(LastErrNo, "CreateFileHandler Failed. File: " + inputFile, ex.Message);
- }
- return null;
- }
- //----------------------------------------------------------------------------------------------------------------
- private AipFileInfo GetFileInfo(IFileHandler handler)
- {
- AipFileInfo fileInfo = new AipFileInfo
- {
- Content = null,
- Label = null,
- Protection = null,
- OutputFileName = null,
- FileSize = 0,
- };
- fileInfo.OutputFileName = handler.OutputFileName;
- if (handler.Label != null)
- {
- fileInfo.Content = new AipContentLabel()
- {
- //Label = Utilities.LabelToAip(handler.Label.Label),
- CreationTime = handler.Label.CreationTime,
- AssignmentMethod = (AipAssignmentMethod)handler.Label.AssignmentMethod,
- IsProtectionAppliedFromLabel = handler.Label.IsProtectionAppliedFromLabel,
- };
- fileInfo.Label = AipUtils.LabelToAip(handler.Label.Label);
- }
- if (handler.Protection != null)
- {
- fileInfo.Protection = new AipProtection()
- {
- Owner = handler.Protection.Owner,
- IssuedTo = handler.Protection.IssuedTo,
- IsIssuedToOwner = handler.Protection.IsIssuedToOwner,
- ContentId = handler.Protection.ContentId,
- AuditedExtractAllowed = handler.Protection.AuditedExtractAllowed,
- BlockSize = handler.Protection.BlockSize,
- ProtectionDescriptor = null,
- };
- if (handler.Protection.ProtectionDescriptor != null)
- {
- fileInfo.Protection.ProtectionDescriptor = new AipProtectionDescriptor()
- {
- ProtectionType = (AipProtectionType)handler.Protection.ProtectionDescriptor.ProtectionType,
- TemplateId = handler.Protection.ProtectionDescriptor.TemplateId,
- LabelInformation = new AipLabelInfo(),
- LabelId = handler.Protection.ProtectionDescriptor.LabelId,
- Owner = handler.Protection.ProtectionDescriptor.Owner,
- ContentId = handler.Protection.ProtectionDescriptor.ContentId,
- Name = handler.Protection.ProtectionDescriptor.Name,
- Description = handler.Protection.ProtectionDescriptor.Description,
- AllowOfflineAccess = handler.Protection.ProtectionDescriptor.AllowOfflineAccess,
- Referrer = handler.Protection.ProtectionDescriptor.Referrer,
- ContentValidUntil = handler.Protection.ProtectionDescriptor.ContentValidUntil,
- DoubleKeyUrl = handler.Protection.ProtectionDescriptor.DoubleKeyUrl,
- };
- if (handler.Protection.ProtectionDescriptor.LabelInformation != null)
- {
- fileInfo.Protection.ProtectionDescriptor.LabelInformation.LabelId =
- handler.Protection.ProtectionDescriptor.LabelInformation.LabelId;
- fileInfo.Protection.ProtectionDescriptor.LabelInformation.TenantId =
- handler.Protection.ProtectionDescriptor.LabelInformation.TenantId;
- }
- }
- }
- return fileInfo;
- }
- public AipFileInfo? GetFileInfo(string fileName)
- {
- LastErrNo = 21;
- using var handler = CreateFileHandler(fileName, fileName);
- if (handler == null)
- {
- return null;
- }
- var result = GetFileInfo(handler);
- try
- {
- result.FileSize = GetFileSize(fileName);
- }
- catch (Exception ex)
- {
- result.FileSize = 0;
- SetError(11, "GetFileInfo Failed. " + fileName, ex.Message);
- }
- return result;
- }
- public AipFileInfo? GetFileInfo(Stream fileStream, string outputFileName)
- {
- LastErrNo = 22;
- using var handler = CreateFileHandler(fileStream, outputFileName);
- if (handler == null)
- {
- //File.Delete(outputFileName);
- return null;
- }
- var result = GetFileInfo(handler);
- try
- {
- result.FileSize = fileStream.Length;
- //File.Delete(outputFileName);
- }
- catch (Exception ex)
- {
- result.FileSize = 0;
- SetError(12, "GetFileInfo Failed. " + outputFileName, ex.Message);
- }
- return result;
- }
- //----------------------------------------------------------------------------------------------------------------
- public Label GetLabelById(string labelId)
- {
- return _fileEngine.GetLabelById(labelId);
- }
- //----------------------------------------------------------------------------------------------------------------
- private void GetActionFileInfo(string actualFileName, SetFileInfo result)
- {
- AipFileInfo? info = GetFileInfo(actualFileName);
- if (info != null)
- {
- if (info.Label != null)
- {
- result.newFileLabelGuid = info.Label.Id;
- }
- if (info.Protection != null)
- {
- result.newFileOwner = info.Protection.Owner;
- if (info.Protection.ProtectionDescriptor != null)
- {
- result.newFileTemplateGuid = info.Protection.ProtectionDescriptor.TemplateId;
- }
- }
- }
- }
- //----------------------------------------------------------------------------------------------------------------
- private string GetOrgFileInfo(IFileHandler handler, string email, SetFileInfo result)
- {
- string ownerEmail = email;
- if (handler.Label != null && handler.Label.Label != null)
- {
- result.labelGuid = handler.Label.Label.Id;
- }
- if (handler.Protection != null)
- {
- ownerEmail = handler.Protection.Owner;
- result.fileOwner = handler.Protection.Owner;
- if (handler.Protection.ProtectionDescriptor != null)
- {
- result.templateGuid = handler.Protection.ProtectionDescriptor.TemplateId;
- }
- }
- return ownerEmail;
- }
- //----------------------------------------------------------------------------------------------------------------
- private bool CommitAsync(IFileHandler handler, string actualFileName, SetFileInfo result)
- {
- bool isCommitted = false;
- if (handler.IsModified())
- {
- try
- {
- //using (var outputStream = new MemoryStream())
- {
- //Stopwatch sw = new Stopwatch();
- //sw.Start();
- //_log.Warn($"SetLabel: [{Task.CurrentId}], CommitAsync[2]: actualFileName: {actualFileName}");
- //isCommitted = Task.Run(async () => await handler.CommitAsync(actualFileName)).Result;
- isCommitted = handler.CommitAsync(actualFileName).Result;
- //isCommitted = Task.Run(async () => await handler.CommitAsync(outputStream)).Result;
- //sw.Stop();
- //_log.Information("********: [{0}], CommitAsync: ------------------- {1,6} ms. actualFileName: {2}", Task.CurrentId, sw.ElapsedMilliseconds.ToString("#,##0"), actualFileName);
- }
- }
- catch (Exception ex)
- {
- result.errorMsg = "AIP File CommitAsync Failed." + actualFileName + ex.Message;
- SetError(55, "FileManager CommitAsync Failed. " + actualFileName, ex.Message);
- }
- }
- return isCommitted;
- }
- //----------------------------------------------------------------------------------------------------------------
- public SetFileInfo SetLabel(IFileHandler? handler, string actualFileName, string email, string labelId, string templateId, string comments, long fileSize)
- {
- SetFileInfo result = new SetFileInfo()
- {
- errorNo = 0,
- errorMsg = AipConstants.AIP_RESULT_SUCCESS,
- };
- if (handler == null)
- {
- result.errorNo = 201;
- result.errorMsg = LastErrMsg;
- return result;
- }
- result.fileSize = fileSize;
- Label label = GetLabelById(labelId);
- if (label == null)
- {
- result.errorNo = 202;
- result.errorMsg = LastErrMsg;
- return result;
- }
- LabelingOptions labelingOptions = new LabelingOptions()
- {
- AssignmentMethod = AssignmentMethod.Auto,
- JustificationMessage = comments,
- IsDowngradeJustified = true
- };
- string ownerEmail = GetOrgFileInfo(handler, email, result);
- var protectionSettings = new ProtectionSettings
- {
- PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
- };
- if (ownerEmail != "")
- {
- protectionSettings.DelegatedUserEmail = ownerEmail;
- }
- try
- {
- handler.SetLabel(label, labelingOptions, protectionSettings);
- if (templateId != "")
- {
- ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(templateId);
- handler.SetProtection(protectionDescriptor, protectionSettings);
- }
- }
- catch (Exception ex)
- {
- result.errorNo = 203;
- result.errorMsg = ex.Message;
- SetError(203, "FileManager::SetLabel Failed. " + actualFileName, ex.Message);
- return result;
- }
- //Log.Error("actualFileName EXT: " + Path.GetExtension(actualFileName).ToLower());
- //Log.Error("actualFileName DIR: " + Path.GetDirectoryName(actualFileName));
- //Log.Error("actualFileName NAME: " + Path.GetFileNameWithoutExtension(actualFileName));
- //Log.Error("actualFileName FULL NAME: " + actualFileName);
- //Log.Error(" handler.OutputFileName: " + handler.OutputFileName);
- //Log.Error(" handler.OutputFileName: " + Path.GetExtension(handler.OutputFileName).ToLower());
- //_log.Warn($"SetLabel: [{Task.CurrentId}], CommitAsync[B]: actualFileName: {actualFileName}");
- actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName)!, Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
- bool isCommitted = CommitAsync(handler, actualFileName, result);
- if (isCommitted)
- {
- //handler.NotifyCommitSuccessful(actualFileName);
- result.newFileSize = GetFileSize(actualFileName);
- result.newFileLabelGuid = labelId;
- result.newFileName = actualFileName;
- result.newFileOwner = ownerEmail;
- result.newFileTemplateGuid = labelId;
- }
- else
- {
- result.errorNo = 204;
- result.errorMsg = "AIP File CommitAsync Failed.";
- SetError(53, "FileManager::SetLabel Failed.", "Label Id: " + labelId + ", SetLabel Failed. " + actualFileName);
- }
- //GetActionFileInfo(actualFileName, result);
- return result;
- }
- public SetFileInfo SetLabel(string fileName, string actualFileName, string email, string labelId, string templateId, string comments = "")
- {
- // 레이블 및 템플릿 정보 가져오기
- if (comments == "")
- {
- comments = "SetLabel";
- }
- LastErrNo = 31;
- using var handler = CreateFileHandler(fileName, actualFileName);
- return SetLabel(handler, actualFileName, email, labelId, templateId, comments, GetFileSize(fileName));
- }
- public SetFileInfo SetLabel(Stream fileStream, string actualFileName, string email, string labelId, string templateId, string comments = "")
- {
- // 레이블 및 템플릿 정보 가져오기
- if (comments == "")
- {
- comments = "SetLabel by " + email;
- }
- LastErrNo = 32;
- using var handler = CreateFileHandler(fileStream, actualFileName);
- return SetLabel(handler, actualFileName, email, labelId, templateId, comments, fileStream.Length);
- }
- //----------------------------------------------------------------------------------------------------------------
- public SetFileInfo DeleteLabel(IFileHandler? handler, string actualFileName, string email, string comments, bool isDelProtection, long fileSize)
- {
- SetFileInfo result = new SetFileInfo()
- {
- errorNo = 0,
- errorMsg = AipConstants.AIP_RESULT_SUCCESS,
- };
- if (handler == null)
- {
- result.errorNo = 201;
- result.errorMsg = LastErrMsg;
- return result;
- }
- result.fileSize = fileSize;
- LabelingOptions invokeLabelingOptions = new LabelingOptions()
- {
- AssignmentMethod = AssignmentMethod.Privileged, //because we are removing a high priority label
- JustificationMessage = comments,
- IsDowngradeJustified = true
- };
- string ownerEmail = GetOrgFileInfo(handler, email, result);
- var protectionSettings = new ProtectionSettings
- {
- PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
- };
- if (ownerEmail != "")
- {
- protectionSettings.DelegatedUserEmail = ownerEmail;
- }
- try
- {
- if (isDelProtection && handler.Protection != null)
- {
- if (handler.Protection.AccessCheck(Rights.Extract) || handler.Protection.AccessCheck(Rights.Owner))
- {
- handler.RemoveProtection();
- }
- }
- handler.DeleteLabel(invokeLabelingOptions);
- }
- catch (Exception ex)
- {
- result.errorNo = 203;
- result.errorMsg = ex.Message;
- SetError(53, "FileManager::DeleteLabel Failed.", ex.Message);
- return result;
- }
- actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName)!, Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
- bool isCommitted = CommitAsync(handler, actualFileName, result);
- if (isCommitted)
- {
- //handler.NotifyCommitSuccessful(fileName);
- result.newFileSize = GetFileSize(actualFileName);
- result.newFileLabelGuid = "";
- result.newFileName = actualFileName;
- result.newFileOwner = ownerEmail;
- result.newFileTemplateGuid = "";
- }
- else
- {
- result.errorNo = 204;
- result.errorMsg = "AIP File CommitAsync Failed.";
- SetError(54, "FileManager::DeleteLabel Failed.", "DeleteLabel Failed by " + ownerEmail);
- }
- //GetActionFileInfo(actualFileName, result);
- return result;
- }
- public SetFileInfo DeleteLabel(string fileName, string actualFileName, string email, string comments, bool isDelProtection)
- {
- if (comments == "")
- {
- comments = "Delete Label by " + email;
- }
- var outFileName = actualFileName == string.Empty ? fileName : actualFileName;
- LastErrNo = 33;
- using var handler = CreateFileHandler(fileName, outFileName);
- return DeleteLabel(handler, actualFileName, email, comments, isDelProtection, GetFileSize(fileName));
- }
- public SetFileInfo DeleteLabel(Stream fileStream, string actualFileName, string email, string comments, bool isDelProtection)
- {
- if (comments == "")
- {
- comments = "Delete Label by " + email;
- }
- LastErrNo = 34;
- using var handler = CreateFileHandler(fileStream, actualFileName);
- return DeleteLabel(handler, actualFileName, email, comments, isDelProtection, fileStream.Length);
- }
- //----------------------------------------------------------------------------------------------------------------
- public SetFileInfo SetProtection(IFileHandler? handler, string actualFileName, string email, string templateId, string comments, long fileSize)
- {
- SetFileInfo result = new SetFileInfo()
- {
- errorNo = 0,
- errorMsg = AipConstants.AIP_RESULT_SUCCESS,
- };
- if (handler == null)
- {
- result.errorNo = 201;
- result.errorMsg = LastErrMsg;
- return result;
- }
- result.fileSize = fileSize;
- string ownerEmail = GetOrgFileInfo(handler, email, result);
- try
- {
- ProtectionDescriptor protectionDescriptor = new ProtectionDescriptor(templateId);
- ProtectionSettings protectionSettings = new ProtectionSettings
- {
- PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
- };
- if (ownerEmail != "")
- {
- protectionSettings.DelegatedUserEmail = ownerEmail;
- }
- handler.SetProtection(protectionDescriptor, protectionSettings);
- }
- catch (Exception ex)
- {
- result.errorNo = 204;
- result.errorMsg = ex.Message;
- SetError(54, "FileManager::SetProtect Failed.", ex.Message);
- return result;
- }
- actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName)!, Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
- bool isCommitted = CommitAsync(handler, actualFileName, result);
- if (isCommitted)
- {
- //handler.NotifyCommitSuccessful(fileName);
- result.newFileSize = GetFileSize(actualFileName);
- //result.newFileLabelGuid = string.Empty;
- result.newFileName = actualFileName;
- result.newFileOwner = ownerEmail;
- result.newFileTemplateGuid = string.Empty;
- }
- else
- {
- result.errorNo = 206;
- result.errorMsg = "AIP File CommitAsync Failed.";
- SetError(56, "FileManager::SetProtect Failed.", "Template Id: " + templateId + ", SetProtect Failed.");
- }
- //GetActionFileInfo(actualFileName, result);
- return result;
- }
- public SetFileInfo SetProtection(string fileName, string actualFileName, string email, string templateId, string comments)
- {
- if (comments == "")
- {
- comments = "SetProtection by " + email;
- }
- LastErrNo = 41;
- using var handler = CreateFileHandler(fileName, actualFileName);
- return SetProtection(handler, actualFileName, email, templateId, comments, GetFileSize(fileName));
- }
- public SetFileInfo SetProtection(Stream fileStream, string actualFileName, string email, string templateId, string comments)
- {
- if (comments == "")
- {
- comments = "SetProtection by " + email;
- }
- LastErrNo = 42;
- using var handler = CreateFileHandler(fileStream, actualFileName);
- return SetProtection(handler, actualFileName, email, templateId, comments, fileStream.Length);
- }
- //----------------------------------------------------------------------------------------------------------------
- public SetFileInfo RemoveProtection(IFileHandler? handler, string actualFileName, string email, string comments, long fileSize)
- {
- SetFileInfo result = new SetFileInfo()
- {
- errorNo = 0,
- errorMsg = AipConstants.AIP_RESULT_SUCCESS,
- };
- if (handler == null)
- {
- result.errorNo = 201;
- result.errorMsg = LastErrMsg;
- return result;
- }
- result.fileSize = fileSize;
- string ownerEmail = GetOrgFileInfo(handler, email, result);
- //LabelingOptions invokeLabelingOptions = new LabelingOptions()
- //{
- // AssignmentMethod = AssignmentMethod.Privileged, //because we are removing a high priority label
- // JustificationMessage = comments,
- // IsDowngradeJustified = true,
- //};
- var protectionSettings = new ProtectionSettings
- {
- PFileExtensionBehavior = PFileExtensionBehavior.PPrefix,//Default,
- };
- if (ownerEmail != "")
- {
- protectionSettings.DelegatedUserEmail = ownerEmail;
- }
- try
- {
- if (handler.Protection != null)
- {
- // 원본 파일 형식이 레이블 지정을 지원하지 않는 경우 보호를 제거하면 레이블이 손실됩니다.
- // 기본 형식이 레이블 지정을 지원하는 경우 레이블 메타데이터가 유지됩니다.
- if (handler.Protection.AccessCheck(Rights.Extract) || handler.Protection.AccessCheck(Rights.Owner))
- {
- handler.RemoveProtection();
- }
- //Use the GetTemporaryDecryptedStream() or GetTemporaryDecryptedFile() API to create a temp decrypted output to render in your application.
- }
- else
- {
- result.errorNo = 209;
- result.errorMsg = "파일에 암호화 정보가 없습니다.";
- return result;
- }
- }
- catch (Exception ex)
- {
- result.errorNo = 208;
- result.errorMsg = "FileManager::RemoveProtection Failed." + ex.Message;
- SetError(59, "FileManager::RemoveProtection Failed.", ex.Message);
- return result;
- }
- actualFileName = Path.Combine(Path.GetDirectoryName(actualFileName)!, Path.GetFileNameWithoutExtension(actualFileName) + Path.GetExtension(handler.OutputFileName).ToLower());
- bool isCommitted = CommitAsync(handler, actualFileName, result);
- if (isCommitted)
- {
- //handler.NotifyCommitSuccessful(fileName);
- result.newFileSize = GetFileSize(actualFileName);
- result.newFileLabelGuid = string.Empty;
- result.newFileName = actualFileName;
- result.newFileOwner = ownerEmail;
- result.newFileTemplateGuid = string.Empty;
- }
- else
- {
- result.errorNo = 204;
- result.errorMsg = "AIP File CommitAsync Failed.";
- SetError(53, "FileManager::RemoveProtection Failed.", "RemoveProtection Failed by " + ownerEmail);
- }
- //GetActionFileInfo(actualFileName, result);
- return result;
- }
- public SetFileInfo RemoveProtection(string fileName, string actualFileName, string email, string comments)
- {
- if (comments == "")
- {
- comments = "Remove Protection by " + email;
- }
- LastErrNo = 43;
- using var handler = CreateFileHandler(fileName, actualFileName);
- return RemoveProtection(handler, actualFileName, email, comments, GetFileSize(fileName));
- }
- public SetFileInfo RemoveProtection(Stream fileStream, string actualFileName, string email, string comments)
- {
- if (comments == "")
- {
- comments = "Remove Protection by " + email;
- }
- LastErrNo = 44;
- using var handler = CreateFileHandler(fileStream, actualFileName);
- return RemoveProtection(handler, actualFileName, email, comments, fileStream.Length);
- }
- //----------------------------------------------------------------------------------------------------------------
- public AipFileStatus? GetAipFileStatus(string fileName)
- {
- try
- {
- var fileStatus = FileHandler.GetFileStatus(fileName, _mipContext);
- AipFileStatus result = new AipFileStatus
- {
- IsProtected = fileStatus.IsProtected(),
- IsLabeled = fileStatus.IsLabeled(),
- ContainsProtectedObjects = fileStatus.ContainsProtectedObjects()
- };
- return result;
- }
- catch (Exception ex)
- {
- SetError(81, "AipFileManager::GetAipFileStatus Failed.", ex.Message);
- }
- return null;
- }
- //----------------------------------------------------------------------------------------------------------------
- private Int64 GetFileSize(string fileName)
- {
- try
- {
- return new FileInfo(fileName).Length;
- }
- catch { return 0; }
- }
- //----------------------------------------------------------------------------------------------------------------
- private void SetError(int errNo, string errMsg1, string errMsg2 = "", bool isThrowEx = true)
- {
- LastErrNo = errNo;
- if (errMsg2 == "")
- {
- LastErrMsg = errMsg1;
- }
- else
- {
- LastErrMsg = errMsg1 + "\r\n" + errMsg2;
- }
- _log.Error("AipFileService::SetError ==> {0}, {1}, {2}", errNo, errMsg1, errMsg2);
- if (isThrowEx && LastErrNo != 0)
- {
- throw new AipFileException(errNo, LastErrMsg);
- }
- }
- protected virtual void Dispose(bool disposing)
- {
- if (!disposedValue)
- {
- if (disposing)
- {
- // TODO: 관리형 상태(관리형 개체)를 삭제합니다.
- }
- disposedValue = true;
- }
- }
- public void Dispose()
- {
- _fileProfile.UnloadEngineAsync(_fileEngine.Settings.EngineId).GetAwaiter().GetResult();
- _fileEngine.Dispose();
- _fileProfile.Dispose();
- _policyProfile.UnloadEngineAsync(_policyEngine.Settings.Id).GetAwaiter().GetResult();
- _policyEngine.Dispose();
- _policyProfile.Dispose();
- //_protectionProfile.Dispose();
- _protectionEngine.Dispose();
- _protectionProfile.Dispose();
- _mipContext.ShutDown();
- _mipContext.Dispose();
- Dispose(disposing: true);
- GC.SuppressFinalize(this);
- }
- }
|