123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Threading.Tasks;
- using Microsoft.InformationProtection;
- using Microsoft.InformationProtection.File;
- using Microsoft.InformationProtection.Protection;
- using System.Diagnostics;
- using Serilog;
- using Serilog.Core;
- namespace AipGateway.AIP
- {
-
- public class FileManager : AbstractManager
- {
- private readonly ILogger _log;
- private IFileProfile _profile = null;
- private IFileEngine _engine = null;
- public FileManager(Logger logger, string clientId) : base(logger, clientId)
- {
- _log = logger.ForContext<FileManager>();
- }
- ~FileManager() => this.Dispose(false);
- public override void Dispose()
- {
- this.Dispose(true);
- GC.SuppressFinalize((object)this);
-
- }
- protected virtual void Dispose(bool disposing)
- {
- lock (this)
- {
- if (_profile != null & _engine != null)
- {
- //_profile.UnloadEngineAsync(_engine.Settings.EngineId).Wait();
- }
- _engine = null;
- _profile = null;
- }
- }
- public override bool CreateProfile(ref MipContext mipContext)
- {
- try
- {
- var profileSettings = new FileProfileSettings(mipContext,
- //CacheStorageType.OnDiskEncrypted,
- CacheStorageType.InMemory,
- new ConsentDelegateImplementation());
- // IFileProfile은 특정 애플리케이션에 대한 모든 SDK 작업의 루트입니다.
- _profile = Task.Run(async () => await MIP.LoadFileProfileAsync(profileSettings)).Result;
- }
- catch (Exception e)
- {
- SetError(1, "FileManager::CreateProfile Failed.", e.Message);
- return false;
- }
- return _profile != null;
- }
- public override bool CreateEngine(ref Identity identity, ref AuthDelegateImplementation authDelegate)
- {
- try
- {
- authDelegate.ResetError();
- //CultureInfo.CurrentCulture.Name;
- // 보호 엔진 설정 개체를 만듭니다. 첫 번째 매개변수인 엔진 ID에 빈 문자열을 전달하면 SDK가 GUID를 생성합니다.
- // 이메일 주소나 기타 고유한 값을 전달하면 동일한 사용자에 대해 캐시된 엔진이 매번 로드되도록 하는 데 도움이 됩니다.
- // 로캘 설정은 지원되며 특히 클라이언트 응용 프로그램의 경우 컴퓨터 로캘을 기반으로 제공되어야 합니다.
- //_log.Information("Engine ClientID: {0}", _clientId);
- //_log.Information("Engine UserID: {0}", identity.Email);
- var engineSettings = new FileEngineSettings(_clientId, authDelegate, string.Empty, "en-US")
- {
- // Provide the identity for service discovery.
- Identity = identity,
- // Set ProtectionOnlyEngine to true for AD RMS as labeling isn't supported
- //ProtectionOnlyEngine = true
- };
- _engine = Task.Run(async () => await _profile.AddEngineAsync(engineSettings)).Result;
- }
- catch (Exception e)
- {
- if (authDelegate.LastErrNo != 0)
- {
- SetError(authDelegate.LastErrNo, "FileManager::CreateEngine Failed.", authDelegate.LastErrMsg);
- }
- else
- {
- SetError(2, "FileManager::CreateEngine Failed.", e.Message);
- }
- return false;
- }
- return _engine != null;
- }
- public IEnumerable<Label> SensitivityLabels()
- {
- return _engine.SensitivityLabels;
- }
- private IFileHandler CreateFileHandler(Stream inputStream, string outputFile)
- {
- if (inputStream == null)
- {
- SetError(91, "FileManager::CreateFileHandler Failed.", "요청한 스트림의 정보가 없습니다.");
- return null;
- }
- if (outputFile == null || outputFile.Length == 0)
- {
- SetError(91, "FileManager::CreateFileHandler Failed.", "요청한 출력 파일 이릅이 존재하지 않습니다.");
- return null;
- }
- try
- {
- var handler = Task.Run(async () => await _engine.CreateFileHandlerAsync(inputStream, outputFile, true))
- .Result;
- return handler;
- }
- catch (Exception ex)
- {
- SetError(91, "FileManager::CreateFileHandler Failed.", ex.Message);
- }
- return null;
- }
- private Int64 GetFileSize(string fileName)
- {
- try
- {
- return new FileInfo(fileName).Length;
- }
- catch { return 0; }
- }
- private IFileHandler CreateFileHandler(string inputFile, string outputFile)
- {
- if (!File.Exists(inputFile))
- {
- SetError(91, "FileManager::CreateFileHandler Failed.", "요청한 파일이 존재하지 않습니다. " + inputFile);
- return null;
- }
- try
- {
- //Stopwatch sw = new Stopwatch();
- //sw.Start();
- var handler = _engine.CreateFileHandlerAsync(inputFile, outputFile, true).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(91, "FileManager::CreateFileHandler Failed.", ex.Message);
- }
- return null;
- }
-
- public AipFileInfo GetFileInfo(Stream fileStream, string outputFileName)
- {
- 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;
- LastErrMsg = ex.Message;
- }
- return result;
- }
- public AipFileInfo GetFileInfo(string fileName)
- {
- 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;
- LastErrMsg = ex.Message;
- }
- return result;
- }
-
- private AipFileInfo GetFileInfo(IFileHandler handler)
- {
- if (handler == null)
- {
- return null;
- }
- //Stopwatch sw = new Stopwatch();
- //sw.Start();
- 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 = Utilities.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;
- }
- }
- }
- //sw.Stop();
- //_log.Information("********: [{0}], GetFileInfo: ------------------- {1,6} ms. OutputFileName: {2}", Task.CurrentId, sw.ElapsedMilliseconds.ToString("#,##0"), handler.OutputFileName);
- return fileInfo;
- }
- public Label GetLabelById(string labelId)
- {
- Label label;
- try
- {
- label = _engine.GetLabelById(labelId);
- }
- catch (Exception ex)
- {
- SetError(99, "FileManager::GetLabel Failed. Request Label Id: " + labelId, ex.Message);
- return null;
- }
- return label;
- }
- public SetFileInfo SetLabel(string fileName, string actualFileName, string email, string labelId, string templateId, string comments)
- {
- //_log.Warn($"SetLabel: [{Task.CurrentId}], {fileName}, {actualFileName}");
- 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)
- {
- var handler = CreateFileHandler(fileStream, actualFileName);
- return SetLabel(handler, actualFileName, email, labelId, templateId, comments, fileStream.Length);
- }
- 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;
- //_log.Warn($"SetLabel: [{Task.CurrentId}], GetLabelById: actualFileName: {actualFileName}");
- 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
- {
- //_log.Warn($"SetLabel: [{Task.CurrentId}], SetLabel: actualFileName: {actualFileName}");
- 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(53, "FileManager::SetLabel Failed.", 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)
- {
- //TODO
- //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.");
- }
- //_log.Warn($"SetLabel: [{Task.CurrentId}], CommitAsync[A]: actualFileName: {actualFileName}");
- //Stopwatch sw = new Stopwatch();
- //sw.Start();
- getActionFileInfo(actualFileName, result);
- //sw.Stop();
- //_log.Warn($"SetLabel: [{Task.CurrentId}], GetFileInfo: -------- {sw.ElapsedMilliseconds} ms. actualFileName: {actualFileName}");
- return result;
- }
- public SetFileInfo DeleteLabel(string fileName, string actualFileName, string email, string comments, bool isDelProtection)
- {
- var outFileName = actualFileName == string.Empty ? fileName : actualFileName;
- 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)
- {
- var handler = CreateFileHandler(fileStream, actualFileName);
- return DeleteLabel(handler, actualFileName, email, comments, isDelProtection, 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 SetProtection(string fileName, string actualFileName, string email, string templateId, string comments)
- {
- 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)
- {
- var handler = CreateFileHandler(fileStream, actualFileName);
- return SetProtection(handler, actualFileName, email, templateId, comments, 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 RemoveProtection(string fileName, string actualFileName, string email, string comments)
- {
- var handler = CreateFileHandler(fileName, actualFileName);
- return RemoveProtection(handler, actualFileName, email, comments, GetFileSize(fileName));
- }
- public SetFileInfo RemoveProtection(Stream fileStream, string actualFileName, string email, string comments)
- {
- var handler = CreateFileHandler(fileStream, actualFileName);
- return RemoveProtection(handler, actualFileName, email, 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;
- }
- 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 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 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)
- {
- // TODO: Exception catch 해야함.......... 여기서 캣치하면 정확한 오류 메시지를 확인 할 수 없음.
- result.errorNo = 55;
- result.errorMsg = "AIP File CommitAsync Failed." + ex.Message;
- SetError(55, "FileManager CommitAsync Failed.", ex.Message);
- }
- }
- return isCommitted;
- }
- public async Task<Stream> GetDecryptedStreamAsync(Stream inputStream, string filename)
- {
- var handler = CreateFileHandler(inputStream, filename);
- return await handler.GetDecryptedTemporaryStreamAsync();
- }
- // Protect the input bytes.
- public byte[] Protect(IProtectionHandler handler, byte[] data)
- {
- long buffersize = handler.GetProtectedContentLength(data.Length, true);
- byte[] outputBuffer = new byte[buffersize];
- handler.EncryptBuffer(0, data, outputBuffer, true);
- return outputBuffer;
- }
- public byte[] Unprotect(IProtectionHandler handler, byte[] data)
- {
- long buffersize = data.Length;
- byte[] clearBuffer = new byte[buffersize];
- var bytesDecrypted = handler.DecryptBuffer(0, data, clearBuffer, true);
- byte[] outputBuffer = new byte[bytesDecrypted];
- for (int i = 0; i < bytesDecrypted; i++)
- {
- outputBuffer[i] = clearBuffer[i];
- }
- return outputBuffer;
- }
- }
- }
|