public static Stream Exec(File file, string toExtension) { if (file.ContentLength > SetupInfo.AvailableFileSize) { throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize))); } var fileExtension = file.ConvertedExtension; var requiredFormat = fileExtension.Trim('.').Equals(toExtension.Trim('.'), StringComparison.OrdinalIgnoreCase); if (!EnableConvert(file, toExtension) || requiredFormat) { using (var fileDao = Global.DaoFactory.GetFileDao()) { return(fileDao.GetFileStream(file)); } } var fileUri = PathProvider.GetFileStreamUrl(file); var docKey = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn); string convertUri; DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri); return(new ResponseStream(WebRequest.Create(convertUri).GetResponse())); }
public static Stream Exec(File file, string toExtension) { if (!EnableConvert(file, toExtension)) { using (var fileDao = Global.DaoFactory.GetFileDao()) { return(fileDao.GetFileStream(file)); } } if (file.ContentLength > SetupInfo.AvailableFileSize) { throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize))); } var fileUri = PathProvider.GetFileStreamUrl(file); var docKey = DocumentServiceHelper.GetDocKey(file); string convertUri; fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri); DocumentServiceConnector.GetConvertedUri(fileUri, file.ConvertedExtension, toExtension, docKey, false, out convertUri); if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null) { ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740 } return(new ResponseStream(((HttpWebRequest)WebRequest.Create(convertUri)).GetResponse())); }
public static File ExecSync(File file, string doc) { using (var fileDao = Global.DaoFactory.GetFileDao()) { var fileSecurity = Global.GetFilesSecurity(); if (!fileSecurity.CanRead(file)) { var readLink = FileShareLink.Check(doc, true, fileDao, out file); if (file == null) { throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); } if (!readLink) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } } } var fileUri = PathProvider.GetFileStreamUrl(file); var fileExtension = file.ConvertedExtension; var toExtension = FileUtility.GetInternalExtension(file.Title); var docKey = DocumentServiceHelper.GetDocKey(file); string convertUri; fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri); DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, null, false, out convertUri); return(SaveConvertedFile(file, convertUri)); }
private string GetUrlToFile(Stream docxStream) { var externalUri = _filesPathProvider.GetTempUrl(docxStream, FormatDocx); externalUri = _documentServiceConnector.ReplaceCommunityAdress(externalUri); _logger.DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri); var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString()); string urlToFile; _documentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, null, null, null, false, out urlToFile); _logger.DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile); return(urlToFile); }
private static string GetUrlToFile(Stream docxStream) { var externalUri = Files.Classes.PathProvider.GetTempUrl(docxStream, FormatDocx); externalUri = DocumentServiceConnector.ReplaceCommunityAdress(externalUri); log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri); var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString()); string urlToFile; DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, false, out urlToFile); log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile); return(urlToFile); }
private static string GetUrlToFile(Stream docxStream) { var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString()); var externalUri = DocumentServiceConnector.GetExternalUri(docxStream, "text/plain", revisionId); log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri); string urlToFile; DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, false, out urlToFile); log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile); return(urlToFile); }
private static string ConvertFile(string downloadUrl, string fromExt, Token token) { Global.Logger.Debug("GoogleDriveApp: convert file"); if (string.IsNullOrEmpty(downloadUrl)) { Global.Logger.Error("GoogleDriveApp: downloadUrl is null"); throw new Exception("downloadUrl is null"); } var request = (HttpWebRequest)WebRequest.Create(downloadUrl); request.Method = "GET"; request.Headers.Add("Authorization", "Bearer " + token); try { using (var response = request.GetResponse()) using (var fileStream = new ResponseStream(response)) { Global.Logger.Debug("GoogleDriveApp: GetExternalUri - " + downloadUrl); var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl); downloadUrl = DocumentServiceConnector.GetExternalUri(fileStream, response.ContentType, key); } } catch (WebException e) { Global.Logger.Error("GoogleDriveApp: Error GetExternalUri", e); request.Abort(); } var toExt = FileUtility.GetInternalExtension(fromExt); try { Global.Logger.Debug("GoogleDriveApp: GetConvertedUri- " + downloadUrl); var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl); DocumentServiceConnector.GetConvertedUri(downloadUrl, fromExt, toExt, key, false, out downloadUrl); } catch (Exception e) { Global.Logger.Error("GoogleDriveApp: Error GetConvertedUri", e); } return(downloadUrl); }
private bool GetThumbnailUrl(File file, string toExtension, out string url) { var fileUri = PathProvider.GetFileStreamUrl(file); fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri); var fileExtension = file.ConvertedExtension; var docKey = DocumentServiceHelper.GetDocKey(file); var thumbnailAspect = config.ThumbnailAspect; var thumbnail = GetThumbnailData(thumbnailAspect); var spreadsheetLayout = GetSpreadsheetLayout(thumbnailAspect); var operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, null, null, thumbnail, spreadsheetLayout, false, out url); operationResultProgress = Math.Min(operationResultProgress, 100); return(operationResultProgress == 100); }
public static ConverterData StartCreationFileAsync(Invoice data) { using (var docxStream = GetStreamDocx(data)) { var externalUri = Files.Classes.PathProvider.GetTempUrl(docxStream, FormatDocx); externalUri = DocumentServiceConnector.ReplaceCommunityAdress(externalUri); var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString()); string urlToFile; DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, true, out urlToFile); return(new ConverterData { StorageUrl = externalUri, RevisionId = revisionId, InvoiceId = data.ID, }); } }
public static ConverterData StartCreationFileAsync(Invoice data) { using (var docxStream = GetStreamDocx(data)) { var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString()); var externalUri = DocumentServiceConnector.GetExternalUri(docxStream, MimeMapping.GetMimeMapping(FormatDocx), revisionId); string urlToFile; DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, true, out urlToFile); return(new ConverterData { StorageUrl = externalUri, RevisionId = revisionId, InvoiceId = data.ID, }); } }
public static File GetConvertedFile(ConverterData data, DaoFactory daoFactory) { if (string.IsNullOrEmpty(data.StorageUrl) || string.IsNullOrEmpty(data.RevisionId)) { return(null); } string urlToFile; DocumentServiceConnector.GetConvertedUri(data.StorageUrl, FormatDocx, FormatPdf, data.RevisionId, true, out urlToFile); if (string.IsNullOrEmpty(urlToFile)) { return(null); } var invoice = daoFactory.InvoiceDao.GetByID(data.InvoiceId); return(SaveFile(invoice, urlToFile, daoFactory)); }
private bool GetThumbnailUrl(File <T> file, string toExtension, out string url) { var fileUri = PathProvider.GetFileStreamUrl(file); fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri); var fileExtension = file.ConvertedExtension; var docKey = DocumentServiceHelper.GetDocKey(file); var thumbnail = new DocumentService.ThumbnailData { Aspect = 2, First = true, //Height = config.ThumbnaillHeight, //Width = config.ThumbnaillWidth }; var spreadsheetLayout = new DocumentService.SpreadsheetLayout { IgnorePrintArea = true, //Orientation = "landscape", // "297mm" x "210mm" FitToHeight = 0, FitToWidth = 1, Headings = false, GridLines = false, Margins = new DocumentService.SpreadsheetLayout.LayoutMargins { Top = "0mm", Right = "0mm", Bottom = "0mm", Left = "0mm" }, PageSize = new DocumentService.SpreadsheetLayout.LayoutPageSize { Width = (config.ThumbnaillWidth * 1.5) + "mm", // 192 * 1.5 = "288mm", Height = (config.ThumbnaillHeight * 1.5) + "mm" // 128 * 1.5 = "192mm" } }; var operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, null, thumbnail, spreadsheetLayout, false, out url); operationResultProgress = Math.Min(operationResultProgress, 100); return(operationResultProgress == 100); }
private static string ConvertFile(string fileId, string fromExt) { Global.Logger.Debug("GoogleDriveApp: convert file"); var downloadUrl = GetFileStreamUrl(fileId); var toExt = FileUtility.GetInternalExtension(fromExt); try { Global.Logger.Debug("GoogleDriveApp: GetConvertedUri- " + downloadUrl); var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl); DocumentServiceConnector.GetConvertedUri(downloadUrl, fromExt, toExt, key, false, out downloadUrl); } catch (Exception e) { Global.Logger.Error("GoogleDriveApp: Error GetConvertedUri", e); } return(downloadUrl); }
public static Stream Exec(File file, string toExtension) { if (file.ContentLength > SetupInfo.AvailableFileSize) { throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize))); } var fileExtension = file.ConvertedExtension; var requiredFormat = fileExtension.Trim('.').Equals(toExtension.Trim('.'), StringComparison.OrdinalIgnoreCase); if (!EnableConvert(file, toExtension) || requiredFormat) { using (var fileDao = Global.DaoFactory.GetFileDao()) { return(fileDao.GetFileStream(file)); } } var fileUri = PathProvider.GetFileStreamUrl(file); var docKey = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn); string convertUri; DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri); // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } return(new ResponseStream(WebRequest.Create(convertUri).GetResponse())); }
public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream) { Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId + (stream == null ? " from - " + downloadUrl : " from stream")); fileId = ThirdPartySelector.GetFileId(fileId); var token = Token.GetToken(AppAttr); var driveFile = GetDriveFile(fileId, token); if (driveFile == null) { Global.Logger.Error("GoogleDriveApp: file is null"); throw new Exception("File not found"); } var jsonFile = JObject.Parse(driveFile); var currentType = GetCorrectExt(jsonFile); if (!fileType.Equals(currentType)) { try { var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl ?? Guid.NewGuid().ToString()); if (stream != null) { using (var tmpStream = new MemoryStream()) { stream.CopyTo(tmpStream); Global.Logger.Debug("GoogleDriveApp: GetExternalUri format: " + fileType); downloadUrl = DocumentServiceConnector.GetExternalUri(tmpStream, fileType, key); } } Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl); DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, false, out downloadUrl); stream = null; } catch (Exception e) { Global.Logger.Error("GoogleDriveApp: Error convert", e); } } var request = (HttpWebRequest)WebRequest.Create(GoogleLoginProvider.GoogleUrlFileUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId)); request.Method = "PATCH"; request.Headers.Add("Authorization", "Bearer " + token); request.ContentType = MimeMapping.GetMimeMapping(currentType); if (stream != null) { request.ContentLength = stream.Length; const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; while ((readed = stream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } } else { var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl); using (var downloadStream = new ResponseStream(downloadRequest.GetResponse())) { request.ContentLength = downloadStream.Length; const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } } } try { using (var response = request.GetResponse()) using (var responseStream = response.GetResponseStream()) { string result = null; if (responseStream != null) { using (var readStream = new StreamReader(responseStream)) { result = readStream.ReadToEnd(); } } Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result); } } catch (WebException e) { Global.Logger.Error("GoogleDriveApp: Error save file stream", e); request.Abort(); var httpResponse = (HttpWebResponse)e.Response; if (httpResponse.StatusCode == HttpStatusCode.Forbidden) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e); } throw; } }
public static File SaveEditing(String fileId, int version, Guid tabId, string downloadUri, bool asNew, String shareLinkKey, string comment = null, bool checkRight = true) { var app = ThirdPartySelector.GetAppByFileId(fileId); if (app != null) { app.SaveFile(fileId, downloadUri); return(null); } File file; using (var fileDao = Global.DaoFactory.GetFileDao()) { var editLink = FileShareLink.Check(shareLinkKey, false, fileDao, out file); if (file == null) { file = fileDao.GetFile(fileId); } if (file == null) { throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); } if (checkRight && !editLink && (!Global.GetFilesSecurity().CanEdit(file) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile); } if (checkRight && FileLockedForMe(file.ID)) { throw new Exception(FilesCommonResource.ErrorMassage_LockedFile); } if (file.RootFolderType == FolderType.TRASH) { throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); } var currentType = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title); var newType = FileUtility.GetFileExtension(downloadUri); var updateVersion = file.Version > 1 || file.ConvertedType == null || !asNew; if ((file.Version <= version || currentType != newType || version == -1) && updateVersion && !FileTracker.FixedVersion(file.ID)) { file.Version++; } file.ConvertedType = newType; if (file.ProviderEntry && !newType.Equals(currentType)) { var key = DocumentServiceConnector.GenerateRevisionId(downloadUri); DocumentServiceConnector.GetConvertedUri(downloadUri, newType, currentType, key, false, out downloadUri); file.ConvertedType = currentType; } var req = (HttpWebRequest)WebRequest.Create(downloadUri); using (var editedFileStream = new ResponseStream(req.GetResponse())) { file.ContentLength = editedFileStream.Length; file.Comment = string.IsNullOrEmpty(comment) ? string.Empty : comment; file = fileDao.SaveFile(file, editedFileStream); } } checkRight = FileTracker.ProlongEditing(file.ID, tabId, true, SecurityContext.CurrentAccount.ID); if (checkRight) { FileTracker.ChangeRight(file.ID, SecurityContext.CurrentAccount.ID, false); } FileMarker.MarkAsNew(file); FileMarker.RemoveMarkAsNew(file); return(file); }
private static void CheckConvertFilesStatus(object _) { if (Monitor.TryEnter(singleThread)) { try { List <File> filesIsConverting; lock (locker) { timer.Change(Timeout.Infinite, Timeout.Infinite); conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) && (x.Value.Progress == 100 && DateTime.Now - x.Value.StopDateTime > TimeSpan.FromMinutes(1) || DateTime.Now - x.Value.StopDateTime > TimeSpan.FromMinutes(30))) .ToList() .ForEach(x => { conversionQueue.Remove(x); cache.Remove(GetKey(x.Key)); }); Global.Logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count); if (conversionQueue.Count == 0) { return; } filesIsConverting = conversionQueue .Where(x => String.IsNullOrEmpty(x.Value.Processed)) .Select(x => x.Key) .ToList(); } foreach (var file in filesIsConverting) { var fileUri = file.ID.ToString(); string convertedFileUrl; int operationResultProgress; object folderId; var currentFolder = false; try { int tenantId; IAccount account; lock (locker) { if (!conversionQueue.Keys.Contains(file)) { continue; } var operationResult = conversionQueue[file]; if (!string.IsNullOrEmpty(operationResult.Processed)) { continue; } operationResult.Processed = "1"; tenantId = operationResult.TenantId; account = operationResult.Account; cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30)); } CoreContext.TenantManager.SetCurrentTenant(tenantId); SecurityContext.AuthenticateMe(account); var user = CoreContext.UserManager.GetUsers(account.ID); var culture = string.IsNullOrEmpty(user.CultureName) ? CoreContext.TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; var fileSecurity = Global.GetFilesSecurity(); if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH) { //No rights in CRM after upload before attach throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } if (file.ContentLength > SetupInfo.AvailableFileSize) { throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize))); } folderId = Global.FolderMy; using (var folderDao = Global.DaoFactory.GetFolderDao()) { var parent = folderDao.GetFolder(file.FolderID); if (parent != null && fileSecurity.CanCreate(parent)) { folderId = parent.ID; currentFolder = true; } } if (Equals(folderId, 0)) { throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound); } fileUri = PathProvider.GetFileStreamUrl(file); var toExtension = FileUtility.GetInternalExtension(file.Title); var fileExtension = file.ConvertedExtension; var docKey = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn); operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convertedFileUrl); operationResultProgress = Math.Min(operationResultProgress, 100); } catch (Exception exception) { Global.Logger.ErrorFormat("Error convert {0} with url {1}: {2}", file.ID, fileUri, exception); lock (locker) { if (conversionQueue.Keys.Contains(file)) { var operationResult = conversionQueue[file]; if (operationResult.Delete) { conversionQueue.Remove(file); cache.Remove(GetKey(file)); } else { operationResult.Result = FileJsonSerializer(file); operationResult.Progress = 100; operationResult.StopDateTime = DateTime.Now; operationResult.Error = exception.Message; cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30)); } } } continue; } if (operationResultProgress < 100) { lock (locker) { if (conversionQueue.Keys.Contains(file)) { var operationResult = conversionQueue[file]; operationResult.Processed = ""; operationResult.Progress = operationResultProgress; cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30)); } } continue; } using (var fileDao = Global.DaoFactory.GetFileDao()) using (var folderDao = Global.DaoFactory.GetFolderDao()) { var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title)); File newFile = null; if (FilesSettings.UpdateIfExist && (!currentFolder || !file.ProviderEntry)) { newFile = fileDao.GetFile(folderId, newFileTitle); if (newFile != null && Global.GetFilesSecurity().CanEdit(newFile) && !EntryManager.FileLockedForMe(newFile.ID) && !FileTracker.IsEditing(newFile.ID)) { newFile.Version++; } else { newFile = null; } } if (newFile == null) { newFile = new File { FolderID = folderId }; } newFile.Title = newFileTitle; newFile.ConvertedType = null; newFile.Comment = string.Format(FilesCommonResource.CommentConvert, file.Title); var operationResultError = string.Empty; try { var req = (HttpWebRequest)WebRequest.Create(convertedFileUrl); if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null) { ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740 } using (var convertedFileStream = new ResponseStream(req.GetResponse())) { newFile.ContentLength = convertedFileStream.Length; newFile = fileDao.SaveFile(newFile, convertedFileStream); } FilesMessageService.Send(newFile, MessageInitiator.DocsService, MessageAction.FileConverted, newFile.Title); FileMarker.MarkAsNew(newFile); using (var tagDao = Global.DaoFactory.GetTagDao()) { var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList(); if (tags.Any()) { tags.ForEach(r => r.EntryId = newFile.ID); tagDao.SaveTags(tags.ToArray()); } } operationResultProgress = 100; } catch (WebException e) { using (var response = e.Response) { var httpResponse = (HttpWebResponse)response; var errorString = String.Format("Error code: {0}", httpResponse.StatusCode); if (httpResponse.StatusCode != HttpStatusCode.NotFound) { using (var data = response.GetResponseStream()) { var text = new StreamReader(data).ReadToEnd(); errorString += String.Format(" Error message: {0}", text); } } operationResultProgress = 100; operationResultError = errorString; Global.Logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", errorString, convertedFileUrl, fileUri, e); throw new Exception(errorString); } } finally { var fileSecurity = Global.GetFilesSecurity(); var removeOriginal = !FilesSettings.StoreOriginalFiles && fileSecurity.CanDelete(file) && currentFolder && !EntryManager.FileLockedForMe(file.ID); var folderTitle = folderDao.GetFolder(newFile.FolderID).Title; lock (locker) { if (conversionQueue.Keys.Contains(file)) { var operationResult = conversionQueue[file]; if (operationResult.Delete) { conversionQueue.Remove(file); cache.Remove(GetKey(file)); } else { operationResult.Result = FileJsonSerializer(newFile, removeOriginal, folderTitle); operationResult.StopDateTime = DateTime.Now; operationResult.Processed = "1"; operationResult.Progress = operationResultProgress; if (!string.IsNullOrEmpty(operationResultError)) { operationResult.Error = operationResultError; } cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30)); } } } if (removeOriginal) { FileMarker.RemoveMarkAsNewForAll(file); fileDao.DeleteFile(file.ID); } } } } lock (locker) { timer.Change(TIMER_PERIOD, TIMER_PERIOD); } } catch (Exception exception) { Global.Logger.Error(exception.Message, exception); lock (locker) { timer.Change(Timeout.Infinite, Timeout.Infinite); } } finally { Monitor.Exit(singleThread); } } }
private static void SaveFile(HttpContext context) { try { var shareLinkKey = context.Request[CommonLinkUtility.DocShareKey] ?? ""; var fileID = context.Request[CommonLinkUtility.FileId]; if (string.IsNullOrEmpty(fileID)) { throw new ArgumentNullException(fileID); } var downloadUri = context.Request[CommonLinkUtility.FileUri]; if (string.IsNullOrEmpty(downloadUri)) { throw new ArgumentNullException(downloadUri); } using (var fileDao = Global.DaoFactory.GetFileDao()) { File file; var checkLink = FileShareLink.Check(shareLinkKey, false, fileDao, out file); if (!checkLink && file == null) { file = fileDao.GetFile(fileID); } if (file == null) { throw new HttpException((int)HttpStatusCode.NotFound, FilesCommonResource.ErrorMassage_FileNotFound); } if (!checkLink && (!Global.GetFilesSecurity().CanEdit(file) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile); } if (file.RootFolderType == FolderType.TRASH) { throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_ViewTrashItem); } var versionEdit = context.Request[CommonLinkUtility.Version]; var currentType = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title); var newType = FileUtility.GetFileExtension(downloadUri); var updateVersion = file.Version > 1 || file.ConvertedType == null || string.IsNullOrEmpty(context.Request[UrlConstant.New]); if ((string.IsNullOrEmpty(versionEdit) || file.Version <= Convert.ToInt32(versionEdit) || currentType != newType) && updateVersion && !FileLocker.LockVersion(file.ID)) { file.Version++; } file.ConvertedType = newType; if (file.ProviderEntry && !newType.Equals(currentType)) { var key = DocumentServiceConnector.GenerateRevisionId(downloadUri); DocumentServiceConnector.GetConvertedUri(downloadUri, newType, currentType, key, false, out downloadUri); } var req = (HttpWebRequest)WebRequest.Create(downloadUri); using (var editedFileStream = new ResponseStream(req.GetResponse())) { file.ContentLength = editedFileStream.Length; file = fileDao.SaveFile(file, editedFileStream); } bool checkRight; var tabId = new Guid(context.Request["tabId"]); FileLocker.ProlongLock(file.ID, tabId, true, out checkRight); if (checkRight) { FileLocker.ChangeRight(file.ID, SecurityContext.CurrentAccount.ID, false); } FileMarker.MarkAsNew(file); FileMarker.RemoveMarkAsNew(file); } } catch (Exception ex) { Global.Logger.Error(ex.Message, ex); context.Response.Write("{ \"error\": \"true\", \"message\": \"" + ex.Message + "\" }"); } }
private static void CheckConvertFilesStatus(Object obj) { lock (LockerTimer) { _timer.Change(Timeout.Infinite, Timeout.Infinite); } try { List <File> filesIsConverting; lock (LockerStatus) { ConversionFileStatus.Where(x => ((!String.IsNullOrEmpty(x.Value.Processed) && DateTime.Now.Subtract(x.Value.StopDateTime) > TimeSpan.FromMinutes(30)))) .ToList().ForEach(x => ConversionFileStatus.Remove(x)); filesIsConverting = ConversionFileStatus.Where(x => String.IsNullOrEmpty(x.Value.Processed)).Select(x => x.Key).ToList(); } if (filesIsConverting.Count == 0) { lock (LockerTimer) { _timer.Dispose(); _timer = null; } return; } foreach (var file in filesIsConverting) { var fileUri = file.ID.ToString(); string convetedFileUrl; int operationResultProgress; object folderId; var currentFolder = false; try { int tenantId; IAccount account; lock (LockerStatus) { var operationResult = ConversionFileStatus[file]; if (operationResult == null) { continue; } tenantId = operationResult.TenantId; account = operationResult.Account; } CoreContext.TenantManager.SetCurrentTenant(tenantId); SecurityContext.AuthenticateMe(account); var user = CoreContext.UserManager.GetUsers(account.ID); var culture = string.IsNullOrEmpty(user.CultureName) ? CoreContext.TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; var fileSecurity = Global.GetFilesSecurity(); if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH) //No rights in CRM after upload before attach { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } if (file.ContentLength > SetupInfo.AvailableFileSize) { throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize))); } folderId = Global.FolderMy; using (var folderDao = Global.DaoFactory.GetFolderDao()) { var parent = folderDao.GetFolder(file.FolderID); if (parent != null && fileSecurity.CanCreate(parent)) { folderId = parent.ID; currentFolder = true; } } if (Equals(folderId, 0)) { throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound); } fileUri = PathProvider.GetFileStreamUrl(file); var toExtension = FileUtility.GetInternalExtension(file.Title); var fileExtension = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title); var docKey = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn); operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convetedFileUrl); } catch (Exception exception) { lock (LockerStatus) { var operationResult = ConversionFileStatus[file]; if (operationResult != null) { if (operationResult.Delete) { ConversionFileStatus.Remove(file); } else { operationResult.Result = FileJsonSerializer(file); operationResult.Processed = "1"; operationResult.StopDateTime = DateTime.Now; operationResult.Error = exception.Message; } } } var strExc = exception.Message + " in file " + fileUri; Global.Logger.Error(strExc, exception); continue; } if (operationResultProgress < 100) { lock (LockerStatus) { var operationResult = ConversionFileStatus[file]; if (operationResult != null) { operationResult.Progress = operationResultProgress; } } continue; } using (var fileDao = Global.DaoFactory.GetFileDao()) using (var folderDao = Global.DaoFactory.GetFolderDao()) { var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title)); File newFile = null; if (FilesSettings.UpdateIfExist && (!currentFolder || !file.ProviderEntry)) { newFile = fileDao.GetFile(folderId, newFileTitle); if (newFile != null && Global.GetFilesSecurity().CanEdit(newFile) && !EntryManager.FileLockedForMe(newFile.ID) && !FileTracker.IsEditing(newFile.ID)) { newFile.Version++; } else { newFile = null; } } if (newFile == null) { newFile = new File { FolderID = folderId } } ; newFile.Title = newFileTitle; newFile.ConvertedType = FileUtility.GetInternalExtension(file.Title); var operationResultError = string.Empty; try { var req = (HttpWebRequest)WebRequest.Create(convetedFileUrl); using (var convertedFileStream = new ResponseStream(req.GetResponse())) { newFile.ContentLength = convertedFileStream.Length; newFile.Comment = string.Empty; newFile = fileDao.SaveFile(newFile, convertedFileStream); } FileMarker.MarkAsNew(newFile); using (var tagDao = Global.DaoFactory.GetTagDao()) { var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList(); if (tags.Any()) { tags.ForEach(r => r.EntryId = newFile.ID); tagDao.SaveTags(tags.ToArray()); } } operationResultProgress = 100; } catch (WebException e) { using (var response = e.Response) { var httpResponse = (HttpWebResponse)response; var errorString = String.Format("Error code: {0}", httpResponse.StatusCode); if (httpResponse.StatusCode != HttpStatusCode.NotFound) { using (var data = response.GetResponseStream()) { var text = new StreamReader(data).ReadToEnd(); errorString += String.Format(" Error message: {0}", text); } } operationResultError = errorString; Global.Logger.Error(errorString + " ConvertUrl : " + convetedFileUrl + " fromUrl : " + fileUri, e); throw new Exception(errorString); } } finally { var fileSecurity = Global.GetFilesSecurity(); var removeOriginal = !FilesSettings.StoreOriginalFiles && fileSecurity.CanDelete(file) && currentFolder && !EntryManager.FileLockedForMe(file.ID); var folderTitle = folderDao.GetFolder(newFile.FolderID).Title; lock (LockerStatus) { var operationResult = ConversionFileStatus[file]; if (operationResult.Delete) { ConversionFileStatus.Remove(file); } else { operationResult.Result = FileJsonSerializer(newFile, removeOriginal, folderTitle); operationResult.Processed = "1"; operationResult.StopDateTime = DateTime.Now; operationResult.Progress = operationResultProgress; if (!string.IsNullOrEmpty(operationResultError)) { operationResult.Error = operationResultError; } } } if (removeOriginal) { FileMarker.RemoveMarkAsNewForAll(file); fileDao.DeleteFile(file.ID); } } } } lock (LockerTimer) { _timer.Change(0, TimerConvertPeriod); } } catch (Exception exception) { Global.Logger.Error(exception.Message, exception); lock (LockerTimer) { _timer.Dispose(); _timer = null; } } }
private void CheckConvertFilesStatus(object _) { if (Monitor.TryEnter(singleThread)) { using var scope = ServiceProvider.CreateScope(); var logger = scope.ServiceProvider.GetService <IOptionsMonitor <ILog> >().CurrentValue; var tenantManager = scope.ServiceProvider.GetService <TenantManager>(); var userManager = scope.ServiceProvider.GetService <UserManager>(); var securityContext = scope.ServiceProvider.GetService <SecurityContext>(); var daoFactory = scope.ServiceProvider.GetService <IDaoFactory>(); try { List <File> filesIsConverting; lock (locker) { timer.Change(Timeout.Infinite, Timeout.Infinite); conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) && (x.Value.Progress == 100 && DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(1) || DateTime.UtcNow - x.Value.StopDateTime > TimeSpan.FromMinutes(10))) .ToList() .ForEach(x => { conversionQueue.Remove(x); cache.Remove(GetKey(x.Key)); }); logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count); if (conversionQueue.Count == 0) { return; } filesIsConverting = conversionQueue .Where(x => string.IsNullOrEmpty(x.Value.Processed)) .Select(x => x.Key) .ToList(); } var fileSecurity = FileSecurity; foreach (var file in filesIsConverting) { var fileUri = file.ID.ToString(); string convertedFileUrl; int operationResultProgress; try { int tenantId; IAccount account; string password; lock (locker) { if (!conversionQueue.Keys.Contains(file)) { continue; } var operationResult = conversionQueue[file]; if (!string.IsNullOrEmpty(operationResult.Processed)) { continue; } operationResult.Processed = "1"; tenantId = operationResult.TenantId; account = operationResult.Account; password = operationResult.Password; //if (HttpContext.Current == null && !WorkContext.IsMono) //{ // HttpContext.Current = new HttpContext( // new HttpRequest("hack", operationResult.Url, string.Empty), // new HttpResponse(new StringWriter())); //} cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10)); } tenantManager.SetCurrentTenant(tenantId); securityContext.AuthenticateMe(account); var user = userManager.GetUsers(account.ID); var culture = string.IsNullOrEmpty(user.CultureName) ? TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH) { //No rights in CRM after upload before attach throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } if (file.ContentLength > SetupInfo.AvailableFileSize) { throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize))); } fileUri = PathProvider.GetFileStreamUrl(file); var toExtension = FileUtility.GetInternalExtension(file.Title); var fileExtension = file.ConvertedExtension; var docKey = DocumentServiceHelper.GetDocKey(file); fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri); operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, password, true, out convertedFileUrl); } catch (Exception exception) { var password = exception.InnerException != null && (exception.InnerException is DocumentService.DocumentServiceException documentServiceException) && documentServiceException.Code == DocumentService.DocumentServiceException.ErrorCode.ConvertPassword; logger.Error(string.Format("Error convert {0} with url {1}", file.ID, fileUri), exception); lock (locker) { if (conversionQueue.Keys.Contains(file)) { var operationResult = conversionQueue[file]; if (operationResult.Delete) { conversionQueue.Remove(file); cache.Remove(GetKey(file)); } else { operationResult.Progress = 100; operationResult.StopDateTime = DateTime.UtcNow; operationResult.Error = exception.Message; if (password) { operationResult.Result = "password"; } cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10)); } } } continue; } operationResultProgress = Math.Min(operationResultProgress, 100); if (operationResultProgress < 100) { lock (locker) { if (conversionQueue.Keys.Contains(file)) { var operationResult = conversionQueue[file]; if (DateTime.Now - operationResult.StartDateTime > TimeSpan.FromMinutes(10)) { operationResult.StopDateTime = DateTime.UtcNow; operationResult.Error = FilesCommonResource.ErrorMassage_ConvertTimeout; logger.ErrorFormat("CheckConvertFilesStatus timeout: {0} ({1})", file.ID, file.ContentLengthString); } else { operationResult.Processed = ""; } operationResult.Progress = operationResultProgress; cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10)); } } logger.Debug("CheckConvertFilesStatus iteration continue"); continue; } File newFile = null; var operationResultError = string.Empty; try { newFile = SaveConvertedFile(file, convertedFileUrl); } catch (Exception e) { operationResultError = e.Message; logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", operationResultError, convertedFileUrl, fileUri, e); continue; } finally { lock (locker) { if (conversionQueue.Keys.Contains(file)) { var operationResult = conversionQueue[file]; if (operationResult.Delete) { conversionQueue.Remove(file); cache.Remove(GetKey(file)); } else { if (newFile != null) { var folderDao = daoFactory.FolderDao; var folder = folderDao.GetFolder(newFile.FolderID); var folderTitle = fileSecurity.CanRead(folder) ? folder.Title : null; operationResult.Result = FileJsonSerializer(newFile, folderTitle); } operationResult.Progress = 100; operationResult.StopDateTime = DateTime.UtcNow; operationResult.Processed = "1"; if (!string.IsNullOrEmpty(operationResultError)) { operationResult.Error = operationResultError; } cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10)); } } } } logger.Debug("CheckConvertFilesStatus iteration end"); } lock (locker) { timer.Change(TIMER_PERIOD, TIMER_PERIOD); } } catch (Exception exception) { logger.Error(exception.Message, exception); lock (locker) { timer.Change(Timeout.Infinite, Timeout.Infinite); } } finally { Monitor.Exit(singleThread); } } }
public static File SaveEditing(String fileId, int version, Guid tabId, string fileExtension, string downloadUri, Stream stream, bool asNew, String shareLinkKey, string comment = null, bool checkRight = true) { var newExtension = string.IsNullOrEmpty(fileExtension) ? FileUtility.GetFileExtension(downloadUri) : fileExtension; var app = ThirdPartySelector.GetAppByFileId(fileId); if (app != null) { app.SaveFile(fileId, newExtension, downloadUri, stream); return(null); } File file; using (var fileDao = Global.DaoFactory.GetFileDao()) { var editLink = FileShareLink.Check(shareLinkKey, false, fileDao, out file); if (file == null) { file = fileDao.GetFile(fileId); } if (file == null) { throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); } var fileSecurity = Global.GetFilesSecurity(); if (checkRight && !editLink && (!(fileSecurity.CanEdit(file) || fileSecurity.CanReview(file)) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile); } if (checkRight && FileLockedForMe(file.ID)) { throw new Exception(FilesCommonResource.ErrorMassage_LockedFile); } if (file.RootFolderType == FolderType.TRASH) { throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); } var currentExt = file.ConvertedExtension; if (string.IsNullOrEmpty(newExtension)) { newExtension = FileUtility.GetInternalExtension(file.Title); } if ((file.Version <= version || !newExtension.Equals(currentExt) || version < 1) && (file.Version > 1 || !asNew) && !FileTracker.FixedVersion(file.ID)) { file.Version++; if (string.IsNullOrEmpty(comment)) { comment = FilesCommonResource.CommentEdit; } } else { if (string.IsNullOrEmpty(comment)) { comment = FilesCommonResource.CommentCreate; } } file.ConvertedType = FileUtility.GetFileExtension(file.Title) != newExtension ? newExtension : null; if (file.ProviderEntry && !newExtension.Equals(currentExt)) { if (FileUtility.ExtsConvertible.Keys.Contains(newExtension) && FileUtility.ExtsConvertible[newExtension].Contains(currentExt)) { var key = DocumentServiceConnector.GenerateRevisionId(downloadUri ?? Guid.NewGuid().ToString()); if (stream != null) { using (var tmpStream = new MemoryStream()) { stream.CopyTo(tmpStream); downloadUri = DocumentServiceConnector.GetExternalUri(tmpStream, newExtension, key); } } DocumentServiceConnector.GetConvertedUri(downloadUri, newExtension, currentExt, key, false, out downloadUri); stream = null; } else { file.ID = null; file.Title = FileUtility.ReplaceFileExtension(file.Title, newExtension); } file.ConvertedType = null; } using (var tmpStream = new MemoryStream()) { if (stream != null) { stream.CopyTo(tmpStream); } else { // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } var req = (HttpWebRequest)WebRequest.Create(downloadUri); using (var editedFileStream = new ResponseStream(req.GetResponse())) { editedFileStream.CopyTo(tmpStream); } } tmpStream.Position = 0; file.ContentLength = tmpStream.Length; file.Comment = string.IsNullOrEmpty(comment) ? null : comment; file = fileDao.SaveFile(file, tmpStream); } } checkRight = FileTracker.ProlongEditing(file.ID, tabId, true, SecurityContext.CurrentAccount.ID); if (checkRight) { FileTracker.ChangeRight(file.ID, SecurityContext.CurrentAccount.ID, false); } FileMarker.MarkAsNew(file); FileMarker.RemoveMarkAsNew(file); return(file); }
public static File ExecDuplicate(File file, string shareLinkKey) { var toFolderId = file.FolderID; using (var fileDao = Global.DaoFactory.GetFileDao()) using (var folderDao = Global.DaoFactory.GetFolderDao()) { if (!Global.GetFilesSecurity().CanRead(file)) { var readLink = FileShareLink.Check(shareLinkKey, true, fileDao, out file); if (file == null) { throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); } if (!readLink) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } toFolderId = Global.FolderMy; } if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title))) { throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat); } var toFolder = folderDao.GetFolder(toFolderId); if (toFolder == null) { throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound); } if (!Global.GetFilesSecurity().CanCreate(toFolder)) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create); } var fileUri = PathProvider.GetFileStreamUrl(file); var fileExtension = file.ConvertedExtension; var toExtension = FileUtility.GetInternalExtension(file.Title); var docKey = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn); string convertUri; DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri); var newFile = new File { FolderID = toFolder.ID, Title = FileUtility.ReplaceFileExtension(file.Title, toExtension) }; var req = (HttpWebRequest)WebRequest.Create(convertUri); using (var editedFileStream = new ResponseStream(req.GetResponse())) { newFile.ContentLength = editedFileStream.Length; newFile = fileDao.SaveFile(newFile, editedFileStream); } FileMarker.MarkAsNew(newFile); return(newFile); } }
public static File SaveEditing(String fileId, string fileExtension, string downloadUri, Stream stream, String doc, string comment = null, bool checkRight = true, bool encrypted = false, ForcesaveType?forcesave = null) { var newExtension = string.IsNullOrEmpty(fileExtension) ? FileUtility.GetFileExtension(downloadUri) : fileExtension; var app = ThirdPartySelector.GetAppByFileId(fileId); if (app != null) { app.SaveFile(fileId, newExtension, downloadUri, stream); return(null); } File file; using (var fileDao = Global.DaoFactory.GetFileDao()) { var editLink = FileShareLink.Check(doc, false, fileDao, out file); if (file == null) { file = fileDao.GetFile(fileId); } if (file == null) { throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); } var fileSecurity = Global.GetFilesSecurity(); if (checkRight && !editLink && (!(fileSecurity.CanEdit(file) || fileSecurity.CanReview(file)) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile); } if (checkRight && FileLockedForMe(file.ID)) { throw new Exception(FilesCommonResource.ErrorMassage_LockedFile); } if (checkRight && FileTracker.IsEditing(file.ID)) { throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile); } if (file.RootFolderType == FolderType.TRASH) { throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); } var currentExt = file.ConvertedExtension; if (string.IsNullOrEmpty(newExtension)) { newExtension = FileUtility.GetInternalExtension(file.Title); } var replaceVersion = false; if (file.Forcesave != ForcesaveType.None) { if (file.Forcesave == ForcesaveType.User && FilesSettings.StoreForcesave) { file.Version++; } else { replaceVersion = true; } } else { if (file.Version != 1) { file.VersionGroup++; } else { var storeTemplate = Global.GetStoreTemplate(); var path = FileConstant.NewDocPath + Thread.CurrentThread.CurrentCulture + "/"; if (!storeTemplate.IsDirectory(path)) { path = FileConstant.NewDocPath + "default/"; } path += "new" + FileUtility.GetInternalExtension(file.Title); //todo: think about the criteria for saving after creation if (file.ContentLength != storeTemplate.GetFileSize("", path)) { file.VersionGroup++; } } file.Version++; } file.Forcesave = forcesave.HasValue ? forcesave.Value : ForcesaveType.None; if (string.IsNullOrEmpty(comment)) { comment = FilesCommonResource.CommentEdit; } file.Encrypted = encrypted; file.ConvertedType = FileUtility.GetFileExtension(file.Title) != newExtension ? newExtension : null; if (file.ProviderEntry && !newExtension.Equals(currentExt)) { if (FileUtility.ExtsConvertible.Keys.Contains(newExtension) && FileUtility.ExtsConvertible[newExtension].Contains(currentExt)) { if (stream != null) { downloadUri = PathProvider.GetTempUrl(stream, newExtension); downloadUri = DocumentServiceConnector.ReplaceCommunityAdress(downloadUri); } var key = DocumentServiceConnector.GenerateRevisionId(downloadUri); DocumentServiceConnector.GetConvertedUri(downloadUri, newExtension, currentExt, key, null, false, out downloadUri); stream = null; } else { file.ID = null; file.Title = FileUtility.ReplaceFileExtension(file.Title, newExtension); } file.ConvertedType = null; } using (var tmpStream = new MemoryStream()) { if (stream != null) { stream.CopyTo(tmpStream); } else { // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } var req = (HttpWebRequest)WebRequest.Create(downloadUri); using (var editedFileStream = new ResponseStream(req.GetResponse())) { editedFileStream.CopyTo(tmpStream); } } tmpStream.Position = 0; file.ContentLength = tmpStream.Length; file.Comment = string.IsNullOrEmpty(comment) ? null : comment; if (replaceVersion) { file = fileDao.ReplaceFileVersion(file, tmpStream); } else { file = fileDao.SaveFile(file, tmpStream); } } } FileMarker.MarkAsNew(file); FileMarker.RemoveMarkAsNew(file); return(file); }
public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream) { Logger.Debug("BoxApp: save file stream " + fileId + (stream == null ? " from - " + downloadUrl : " from stream")); fileId = ThirdPartySelector.GetFileId(fileId.ToString()); var token = TokenHelper.GetToken(AppAttr); var boxFile = GetBoxFile(fileId.ToString(), token); if (boxFile == null) { Logger.Error("BoxApp: file is null"); throw new Exception("File not found"); } var jsonFile = JObject.Parse(boxFile); var title = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value <string>("name")); var currentType = FileUtility.GetFileExtension(title); if (!fileType.Equals(currentType)) { try { if (stream != null) { downloadUrl = PathProvider.GetTempUrl(stream, fileType); downloadUrl = DocumentServiceConnector.ReplaceCommunityAdress(downloadUrl); } Logger.Debug("BoxApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl); var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl); DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, null, null, null, false, out downloadUrl); stream = null; } catch (Exception e) { Logger.Error("BoxApp: Error convert", e); } } var request = (HttpWebRequest)WebRequest.Create(BoxUrlUpload.Replace("{fileId}", fileId)); using (var tmpStream = new MemoryStream()) { var boundary = DateTime.UtcNow.Ticks.ToString("x"); var metadata = string.Format("Content-Disposition: form-data; name=\"filename\"; filename=\"{0}\"\r\nContent-Type: application/octet-stream\r\n\r\n", title); var metadataPart = string.Format("--{0}\r\n{1}", boundary, metadata); var bytes = Encoding.UTF8.GetBytes(metadataPart); tmpStream.Write(bytes, 0, bytes.Length); if (stream != null) { stream.CopyTo(tmpStream); } else { var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl); using var downloadStream = new ResponseStream(downloadRequest.GetResponse()); downloadStream.CopyTo(tmpStream); } var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary); bytes = Encoding.UTF8.GetBytes(mediaPartEnd); tmpStream.Write(bytes, 0, bytes.Length); request.Method = "POST"; request.Headers.Add("Authorization", "Bearer " + token); request.ContentType = "multipart/form-data; boundary=" + boundary; request.ContentLength = tmpStream.Length; Logger.Debug("BoxApp: save file totalSize - " + tmpStream.Length); const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; tmpStream.Seek(0, SeekOrigin.Begin); while ((readed = tmpStream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } } try { using var response = request.GetResponse(); using var responseStream = response.GetResponseStream(); string result = null; if (responseStream != null) { using var readStream = new StreamReader(responseStream); result = readStream.ReadToEnd(); } Logger.Debug("BoxApp: save file response - " + result); } catch (WebException e) { Logger.Error("BoxApp: Error save file", e); request.Abort(); var httpResponse = (HttpWebResponse)e.Response; if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e); } throw; } }
public static File ExecDuplicate(File file, string doc) { var toFolderId = file.FolderID; using (var fileDao = Global.DaoFactory.GetFileDao()) using (var folderDao = Global.DaoFactory.GetFolderDao()) { var fileSecurity = Global.GetFilesSecurity(); if (!fileSecurity.CanRead(file)) { var readLink = FileShareLink.Check(doc, true, fileDao, out file); if (file == null) { throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); } if (!readLink) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } toFolderId = Global.FolderMy; } if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title))) { throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat); } var toFolder = folderDao.GetFolder(toFolderId); if (toFolder == null) { throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound); } if (!fileSecurity.CanCreate(toFolder)) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create); } var fileUri = PathProvider.GetFileStreamUrl(file); var fileExtension = file.ConvertedExtension; var toExtension = FileUtility.GetInternalExtension(file.Title); var docKey = DocumentServiceHelper.GetDocKey(file); string convertUri; fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri); DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri); var newFile = new File { FolderID = toFolder.ID, Title = FileUtility.ReplaceFileExtension(file.Title, toExtension), Comment = string.Format(FilesCommonResource.CommentConvert, file.Title), }; var req = (HttpWebRequest)WebRequest.Create(convertUri); // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } using (var editedFileStream = new ResponseStream(req.GetResponse())) { newFile.ContentLength = editedFileStream.Length; newFile = fileDao.SaveFile(newFile, editedFileStream); } FileMarker.MarkAsNew(newFile); return(newFile); } }
public void SaveFile(string fileId, string downloadUrl) { Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId + " from - " + downloadUrl); fileId = ThirdPartySelector.GetFileId(fileId); var token = Token.GetToken(AppAttr); var driveFile = GetDriveFile(fileId, token); if (driveFile == null) { Global.Logger.Error("GoogleDriveApp: file is null"); throw new Exception("File not found"); } var jsonFile = JObject.Parse(driveFile); var curExt = GetCorrectExt(jsonFile); var newExt = FileUtility.GetFileExtension(downloadUrl); if (curExt != newExt) { try { Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + newExt + " to " + curExt + " - " + downloadUrl); var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl); DocumentServiceConnector.GetConvertedUri(downloadUrl, newExt, curExt, key, false, out downloadUrl); } catch (Exception e) { Global.Logger.Error("GoogleDriveApp: Error convert", e); } } var downloadRequest = WebRequest.Create(downloadUrl); using (var downloadResponse = downloadRequest.GetResponse()) using (var downloadStream = new ResponseStream(downloadResponse)) { var request = (HttpWebRequest)WebRequest.Create(GoogleUrlUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId)); request.Method = "PUT"; request.Headers.Add("Authorization", "Bearer " + token.AccessToken); request.ContentType = downloadResponse.ContentType; request.ContentLength = downloadResponse.ContentLength; const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0) { request.GetRequestStream().Write(buffer, 0, readed); } try { using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) { var result = stream != null ? new StreamReader(stream).ReadToEnd() : null; Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result); } } catch (WebException e) { Global.Logger.Error("GoogleDriveApp: Error save file stream", e); request.Abort(); var httpResponse = (HttpWebResponse)e.Response; if (httpResponse.StatusCode == HttpStatusCode.Forbidden) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e); } throw; } } }
public FileOperationResult ExecSync <T>(File <T> file, string doc) { var fileDao = DaoFactory.GetFileDao <T>(); var fileSecurity = FileSecurity; if (!fileSecurity.CanRead(file)) { var readLink = FileShareLink.Check(doc, true, fileDao, out file); if (file == null) { throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound); } if (!readLink) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } } var fileUri = PathProvider.GetFileStreamUrl(file); var fileExtension = file.ConvertedExtension; var toExtension = FileUtility.GetInternalExtension(file.Title); var docKey = DocumentServiceHelper.GetDocKey(file); fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri); DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, null, null, null, false, out var convertUri); var operationResult = new ConvertFileOperationResult { Source = string.Format("{{\"id\":\"{0}\", \"version\":\"{1}\"}}", file.ID, file.Version), OperationType = FileOperationType.Convert, Error = string.Empty, Progress = 0, Result = string.Empty, Processed = "", Id = string.Empty, TenantId = TenantManager.GetCurrentTenant().TenantId, Account = AuthContext.CurrentAccount, Delete = false, StartDateTime = DateTime.Now, Url = HttpContextAccesor?.HttpContext != null?HttpContextAccesor.HttpContext.Request.GetUrlRewriter().ToString() : null, Password = null, ServerRootPath = BaseCommonLinkUtility.ServerRootPath }; var operationResultError = string.Empty; var newFile = SaveConvertedFile(file, convertUri); if (newFile != null) { var folderDao = DaoFactory.GetFolderDao <T>(); var folder = folderDao.GetFolder(newFile.FolderID); var folderTitle = fileSecurity.CanRead(folder) ? folder.Title : null; operationResult.Result = GetFileConverter <T>().FileJsonSerializer(EntryStatusManager, newFile, folderTitle); } operationResult.Progress = 100; operationResult.StopDateTime = DateTime.UtcNow; operationResult.Processed = "1"; if (!string.IsNullOrEmpty(operationResultError)) { operationResult.Error = operationResultError; } return(operationResult); }