public static File GetParams(File file, bool lastVersion, bool checkLink, bool itsNew, bool editPossible, bool rightToEdit, bool tryEdit, out DocumentServiceParams docServiceParams) { if (!TenantExtra.GetTenantQuota().DocsEdition) { throw new Exception(FilesCommonResource.ErrorMassage_PayTariffDocsEdition); } if (!checkLink && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) { rightToEdit = false; } if (file == null) { throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); } if (!checkLink) { rightToEdit = rightToEdit && Global.GetFilesSecurity().CanEdit(file); if (editPossible && !rightToEdit) { editPossible = false; } if (!editPossible && !Global.GetFilesSecurity().CanRead(file)) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } } if (file.RootFolderType == FolderType.TRASH) { throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); } rightToEdit = rightToEdit && !EntryManager.FileLockedForMe(file.ID); if (editPossible && !rightToEdit) { editPossible = false; } rightToEdit = rightToEdit && ((file.FileStatus & FileStatus.IsEditing) != FileStatus.IsEditing || FileUtility.CanCoAuhtoring(file.Title)); if (editPossible && !rightToEdit) { editPossible = false; } rightToEdit = rightToEdit && FileUtility.CanWebEdit(file.Title); if (editPossible && !rightToEdit) { editPossible = false; } if (!editPossible && !FileUtility.CanWebView(file.Title)) { throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat); } var versionForKey = file.Version; if (!FileTracker.FixedVersion(file.ID)) { versionForKey++; } //CreateNewDoc if (itsNew && file.Version == 1 && file.ConvertedType != null && file.CreateOn == file.ModifiedOn) { versionForKey = 1; } var docKey = GetDocKey(file.ID, versionForKey, file.ProviderEntry ? file.ModifiedOn : file.CreateOn); var modeWrite = editPossible && tryEdit; docServiceParams = new DocumentServiceParams { File = file, Key = docKey, CanEdit = rightToEdit && lastVersion, ModeWrite = modeWrite, }; return(file); }
private void PageLoad() { var editPossible = !RequestEmbedded; var isExtenral = false; File file; var fileUri = string.Empty; try { if (string.IsNullOrEmpty(RequestFileUrl)) { _fileNew = (Request["new"] ?? "") == "true"; var app = ThirdPartySelector.GetAppByFileId(RequestFileId); if (app == null) { var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]); file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams); _fileNew = _fileNew && file.Version == 1 && file.ConvertedType != null && file.CreateOn == file.ModifiedOn; } else { isExtenral = true; bool editable; _thirdPartyApp = true; file = app.GetFile(RequestFileId, out editable); file = DocumentServiceHelper.GetParams(file, true, true, true, editable, editable, editable, out _docParams); _docParams.FileUri = app.GetFileStreamUrl(file); _docParams.FolderUrl = string.Empty; } } else { isExtenral = true; fileUri = RequestFileUrl; var fileTitle = Request[FilesLinkUtility.FileTitle]; if (string.IsNullOrEmpty(fileTitle)) { fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? ""; } if (CoreContext.Configuration.Standalone) { try { var webRequest = WebRequest.Create(RequestFileUrl); using (var response = webRequest.GetResponse()) using (var responseStream = new ResponseStream(response)) { var externalFileKey = DocumentServiceConnector.GenerateRevisionId(RequestFileUrl); fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), externalFileKey); } } catch (Exception error) { Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error); } } file = new File { ID = RequestFileUrl, Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle) }; file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, out _docParams); _docParams.CanEdit = editPossible && !CoreContext.Configuration.Standalone; _editByUrl = true; _docParams.FileUri = fileUri; } } catch (Exception ex) { _errorMessage = ex.Message; return; } if (_docParams.ModeWrite && FileConverter.MustConvert(file)) { try { file = FileConverter.ExecDuplicate(file, RequestShareLinkKey); } catch (Exception e) { _docParams = null; _errorMessage = e.Message; return; } var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit); Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment); return; } Title = file.Title; if (string.IsNullOrEmpty(_docParams.FolderUrl)) { _docParams.FolderUrl = Request[FilesLinkUtility.FolderUrl] ?? ""; } if (MobileDetector.IsRequestMatchesMobile(true)) { _docParams.FolderUrl = string.Empty; } if (RequestEmbedded) { _docParams.Type = DocumentServiceParams.EditorType.Embedded; var shareLinkParam = "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey; _docParams.ViewerUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=view" + shareLinkParam); _docParams.DownloadUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FileHandlerPath + "?" + FilesLinkUtility.Action + "=download" + shareLinkParam); _docParams.EmbeddedUrl = CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.FilesBaseAbsolutePath + FilesLinkUtility.EditorPage + "?" + FilesLinkUtility.Action + "=embedded" + shareLinkParam); } else { _docParams.Type = IsMobile ? DocumentServiceParams.EditorType.Mobile : DocumentServiceParams.EditorType.Desktop; if (FileSharing.CanSetAccess(file)) { _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(Share.Location + "?" + FilesLinkUtility.FileId + "=" + file.ID); } } if (!isExtenral) { _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue); FileMarker.RemoveMarkAsNew(file); } if (_docParams.ModeWrite) { _tabId = FileTracker.Add(file.ID, _fileNew); _fixedVersion = FileTracker.FixedVersion(file.ID); _docParams.FileChoiceUrl = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.DocumentTypeParam + "=" + FilterType.SpreadsheetsOnly; } else { _docParams.LinkToEdit = _editByUrl ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title)) : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID)); if (FileConverter.MustConvert(_docParams.File)) { _editByUrl = true; } } }
private void MoveOrCopyFiles(ICollection fileIds, Folder toFolder, bool copy) { if (fileIds.Count == 0) { return; } var toFolderId = toFolder.ID; foreach (var fileId in fileIds) { CancellationToken.ThrowIfCancellationRequested(); var file = FileDao.GetFile(fileId); if (file == null) { Error = FilesCommonResource.ErrorMassage_FileNotFound; } else if (!FilesSecurity.CanRead(file)) { Error = FilesCommonResource.ErrorMassage_SecurityException_ReadFile; } else if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title))) { Error = FilesCommonResource.ErrorMassage_NotSupportedFormat; } else if (file.ContentLength > SetupInfo.AvailableFileSize && file.ProviderId != toFolder.ProviderId) { Error = string.Format(copy ? FilesCommonResource.ErrorMassage_FileSizeCopy : FilesCommonResource.ErrorMassage_FileSizeMove, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)); } else { var parentFolder = FolderDao.GetFolder(file.FolderID); try { var conflict = resolveType == FileConflictResolveType.Duplicate ? null : FileDao.GetFile(toFolderId, file.Title); if (conflict != null && !FilesSecurity.CanEdit(conflict)) { Error = FilesCommonResource.ErrorMassage_SecurityException; } else if (conflict != null && EntryManager.FileLockedForMe(conflict.ID)) { Error = FilesCommonResource.ErrorMassage_LockedFile; } else if (conflict == null) { File newFile = null; if (copy) { try { newFile = FileDao.CopyFile(file.ID, toFolderId); //Stream copy will occur inside dao FilesMessageService.Send(newFile, toFolder, headers, MessageAction.FileCopied, newFile.Title, parentFolder.Title, toFolder.Title); if (Equals(newFile.FolderID.ToString(), this.toFolderId)) { needToMark.Add(newFile); } if (ProcessedFile(fileId)) { Status += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR); } } catch { if (newFile != null) { FileDao.DeleteFile(newFile.ID); } throw; } } else { if (EntryManager.FileLockedForMe(file.ID)) { Error = FilesCommonResource.ErrorMassage_LockedFile; } else if (FileTracker.IsEditing(file.ID)) { Error = FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile; } else if (FilesSecurity.CanDelete(file)) { FileMarker.RemoveMarkAsNewForAll(file); var newFileId = FileDao.MoveFile(file.ID, toFolderId); newFile = FileDao.GetFile(newFileId); FilesMessageService.Send(file.RootFolderType != FolderType.USER ? file : newFile, toFolder, headers, MessageAction.FileMoved, file.Title, parentFolder.Title, toFolder.Title); if (Equals(toFolderId.ToString(), this.toFolderId)) { needToMark.Add(newFile); } if (ProcessedFile(fileId)) { Status += string.Format("file_{0}{1}", newFileId, SPLIT_CHAR); } } else { Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFile; } } } else { if (resolveType == FileConflictResolveType.Overwrite) { if (EntryManager.FileLockedForMe(conflict.ID)) { Error = FilesCommonResource.ErrorMassage_LockedFile; } else if (FileTracker.IsEditing(conflict.ID)) { Error = FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile; } else { var newFile = conflict; newFile.Version++; newFile.ContentLength = file.ContentLength; newFile.PureTitle = file.PureTitle; newFile.ConvertedType = file.ConvertedType; newFile.Comment = FilesCommonResource.CommentOverwrite; using (var stream = FileDao.GetFileStream(file)) { newFile = FileDao.SaveFile(newFile, stream); } needToMark.Add(newFile); if (copy) { FilesMessageService.Send(newFile, toFolder, headers, MessageAction.FileCopiedWithOverwriting, newFile.Title, parentFolder.Title, toFolder.Title); if (ProcessedFile(fileId)) { Status += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR); } } else { if (Equals(file.FolderID.ToString(), toFolderId.ToString())) { if (ProcessedFile(fileId)) { Status += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR); } } else { if (EntryManager.FileLockedForMe(file.ID)) { Error = FilesCommonResource.ErrorMassage_LockedFile; } else if (FileTracker.IsEditing(file.ID)) { Error = FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile; } else if (FilesSecurity.CanDelete(file)) { FileDao.DeleteFile(file.ID); FilesMessageService.Send(file.RootFolderType != FolderType.USER ? file : newFile, toFolder, headers, MessageAction.FileMovedWithOverwriting, file.Title, parentFolder.Title, toFolder.Title); if (ProcessedFile(fileId)) { Status += string.Format("file_{0}{1}", newFile.ID, SPLIT_CHAR); } } else { Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFile; } } } } } else if (resolveType == FileConflictResolveType.Skip) { //nothing } } } catch (Exception ex) { Error = ex.Message; Logger.Error(Error, ex); } } ProgressStep(fileId: FolderDao.CanCalculateSubitems(fileId) ? null : fileId); } }
public static File GetParams(File file, bool lastVersion, FileShare linkRight, bool rightToRename, bool rightToEdit, bool editPossible, bool tryEdit, bool tryCoauth, out Configuration configuration) { if (file == null) { throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); } if (!string.IsNullOrEmpty(file.Error)) { throw new Exception(file.Error); } var rightToReview = rightToEdit; var reviewPossible = editPossible; var rightToFillForms = rightToEdit; var fillFormsPossible = editPossible; var rightToComment = rightToEdit; var commentPossible = editPossible; if (linkRight == FileShare.Restrict && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) { rightToEdit = false; rightToReview = false; rightToFillForms = false; rightToComment = false; } var fileSecurity = Global.GetFilesSecurity(); rightToEdit = rightToEdit && (linkRight == FileShare.ReadWrite || fileSecurity.CanEdit(file)); if (editPossible && !rightToEdit) { editPossible = false; } rightToRename = rightToRename && rightToEdit && fileSecurity.CanEdit(file); rightToReview = rightToReview && (linkRight == FileShare.Review || linkRight == FileShare.ReadWrite || fileSecurity.CanReview(file)); if (reviewPossible && !rightToReview) { reviewPossible = false; } rightToFillForms = rightToFillForms && (linkRight == FileShare.FillForms || linkRight == FileShare.Review || linkRight == FileShare.ReadWrite || fileSecurity.CanFillForms(file)); if (fillFormsPossible && !rightToFillForms) { fillFormsPossible = false; } rightToComment = rightToComment && (linkRight == FileShare.Comment || linkRight == FileShare.Review || linkRight == FileShare.ReadWrite || fileSecurity.CanComment(file)); if (commentPossible && !rightToComment) { commentPossible = false; } if (linkRight == FileShare.Restrict && !(editPossible || reviewPossible || fillFormsPossible || commentPossible) && !fileSecurity.CanRead(file)) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } if (file.RootFolderType == FolderType.TRASH) { throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); } if (file.ContentLength > SetupInfo.AvailableFileSize) { throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeEdit, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize))); } string strError = null; if ((editPossible || reviewPossible || fillFormsPossible || commentPossible) && EntryManager.FileLockedForMe(file.ID)) { if (tryEdit) { strError = FilesCommonResource.ErrorMassage_LockedFile; } rightToRename = false; rightToEdit = editPossible = false; rightToReview = reviewPossible = false; rightToFillForms = fillFormsPossible = false; rightToComment = commentPossible = false; } if (editPossible && !FileUtility.CanWebEdit(file.Title)) { rightToEdit = editPossible = false; } if (!editPossible && !FileUtility.CanWebView(file.Title)) { throw new Exception(string.Format("{0} ({1})", FilesCommonResource.ErrorMassage_NotSupportedFormat, FileUtility.GetFileExtension(file.Title))); } if (reviewPossible && !FileUtility.CanWebReview(file.Title)) { rightToReview = reviewPossible = false; } if (fillFormsPossible && !FileUtility.CanWebRestrictedEditing(file.Title)) { rightToFillForms = fillFormsPossible = false; } if (commentPossible && !FileUtility.CanWebComment(file.Title)) { rightToComment = commentPossible = false; } var rightChangeHistory = rightToEdit; if (FileTracker.IsEditing(file.ID)) { rightChangeHistory = false; bool coauth; if ((editPossible || reviewPossible || fillFormsPossible || commentPossible) && tryCoauth && (!(coauth = FileUtility.CanCoAuhtoring(file.Title)) || FileTracker.IsEditingAlone(file.ID))) { if (tryEdit) { var editingBy = FileTracker.GetEditingBy(file.ID).FirstOrDefault(); strError = string.Format(!coauth ? FilesCommonResource.ErrorMassage_EditingCoauth : FilesCommonResource.ErrorMassage_EditingMobile, Global.GetUserName(editingBy, true)); } rightToEdit = editPossible = reviewPossible = fillFormsPossible = commentPossible = false; } } var docKey = GetDocKey(file); var modeWrite = (editPossible || reviewPossible || fillFormsPossible || commentPossible) && tryEdit; configuration = new Configuration(file) { Document = { Key = docKey, Permissions = { Edit = rightToEdit && lastVersion, Rename = rightToRename && lastVersion && !file.ProviderEntry, Review = rightToReview && lastVersion, FillForms = rightToFillForms && lastVersion, Comment = rightToComment && lastVersion, ChangeHistory = rightChangeHistory, } }, EditorConfig = { ModeWrite = modeWrite, }, ErrorMessage = strError, }; if (!lastVersion) { configuration.Document.Title += string.Format(" ({0})", file.CreateOnString); } return(file); }
public static File GetParams(File file, bool lastVersion, bool checkLink, bool itsNew, bool editPossible, bool rightToEdit, bool rightToReview, bool tryEdit, out DocumentServiceParams docServiceParams) { if (!checkLink && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()) { rightToEdit = false; rightToReview = false; } if (file == null) { throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound); } if (!string.IsNullOrEmpty(file.Error)) { throw new Exception(file.Error); } var fileSecurity = Global.GetFilesSecurity(); var reviewPossible = editPossible; if (!checkLink) { rightToEdit = rightToEdit && fileSecurity.CanEdit(file); if (editPossible && !rightToEdit) { editPossible = false; } rightToReview = rightToReview && fileSecurity.CanReview(file); if (reviewPossible && !rightToReview) { reviewPossible = false; } if (!(editPossible || reviewPossible) && !fileSecurity.CanRead(file)) { throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile); } } if (file.RootFolderType == FolderType.TRASH) { throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem); } if (file.ContentLength > SetupInfo.AvailableFileSize) { throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeEdit, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize))); } if ((editPossible || reviewPossible) && EntryManager.FileLockedForMe(file.ID)) { rightToEdit = editPossible = reviewPossible = false; } if ((editPossible || reviewPossible) && FileTracker.IsEditing(file.ID) && (!FileUtility.CanCoAuhtoring(file.Title) || FileTracker.IsEditingAlone(file.ID))) { rightToEdit = editPossible = reviewPossible = false; } if (editPossible && !FileUtility.CanWebEdit(file.Title)) { rightToEdit = editPossible = false; } if (!editPossible && !FileUtility.CanWebView(file.Title)) { throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat); } rightToReview = rightToReview && reviewPossible && FileUtility.CanWebReview(file.Title); var versionForKey = file.Version; //CreateNewDoc if ((itsNew || FileTracker.FixedVersion(file.ID)) && file.Version == 1 && file.CreateOn == file.ModifiedOn) { versionForKey = 0; } var docKey = GetDocKey(file.ID, versionForKey, file.ProviderEntry ? file.ModifiedOn : file.CreateOn); var modeWrite = (editPossible || reviewPossible) && tryEdit; docServiceParams = new DocumentServiceParams { File = file, Key = docKey, CanEdit = rightToEdit && lastVersion, ModeWrite = modeWrite, CanReview = rightToReview && lastVersion, }; return(file); }
private TrackResponse ProcessSave(string fileId, TrackerData fileData) { var comments = new List <string>(); if (fileData.Status == TrackerStatus.Corrupted || fileData.Status == TrackerStatus.CorruptedForceSave) { comments.Add(FilesCommonResource.ErrorMassage_SaveCorrupted); } var forcesave = fileData.Status == TrackerStatus.ForceSave || fileData.Status == TrackerStatus.CorruptedForceSave; if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out var userId)) { userId = FileTracker.GetEditingBy(fileId).FirstOrDefault(); } var app = ThirdPartySelector.GetAppByFileId(fileId); if (app == null) { File fileStable; fileStable = DaoFactory.FileDao.GetFileStable(fileId); var docKey = DocumentServiceHelper.GetDocKey(fileStable); if (!fileData.Key.Equals(docKey)) { Logger.ErrorFormat("DocService saving file {0} ({1}) with key {2}", fileId, docKey, fileData.Key); StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); return(new TrackResponse { Message = "Expected key " + docKey }); } } UserInfo user = null; try { SecurityContext.AuthenticateMe(userId); user = UserManager.GetUsers(userId); var culture = string.IsNullOrEmpty(user.CultureName) ? TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; } catch (Exception ex) { Logger.Info("DocService save error: anonymous author - " + userId, ex); if (!userId.Equals(ASC.Core.Configuration.Constants.Guest.ID)) { comments.Add(FilesCommonResource.ErrorMassage_SaveAnonymous); } } File file = null; var saveMessage = "Not saved"; if (string.IsNullOrEmpty(fileData.Url)) { try { comments.Add(FilesCommonResource.ErrorMassage_SaveUrlLost); file = EntryManager.CompleteVersionFile(fileId, 0, false, false); DaoFactory.FileDao.UpdateComment(file.ID, file.Version, string.Join("; ", comments)); file = null; Logger.ErrorFormat("DocService save error. Empty url. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key); } catch (Exception ex) { Logger.Error(string.Format("DocService save error. Version update. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key), ex); } } else { if (fileData.Encrypted) { comments.Add(FilesCommonResource.CommentEditEncrypt); } var forcesaveType = ForcesaveType.None; if (forcesave) { switch (fileData.ForceSaveType) { case TrackerData.ForceSaveInitiator.Command: forcesaveType = ForcesaveType.Command; break; case TrackerData.ForceSaveInitiator.Timer: forcesaveType = ForcesaveType.Timer; break; case TrackerData.ForceSaveInitiator.User: forcesaveType = ForcesaveType.User; break; } comments.Add(fileData.ForceSaveType == TrackerData.ForceSaveInitiator.User ? FilesCommonResource.CommentForcesave : FilesCommonResource.CommentAutosave); } try { file = EntryManager.SaveEditing(fileId, null, DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url), null, string.Empty, string.Join("; ", comments), false, fileData.Encrypted, forcesaveType); saveMessage = fileData.Status == TrackerStatus.MustSave || fileData.Status == TrackerStatus.ForceSave ? null : "Status " + fileData.Status; } catch (Exception ex) { Logger.Error(string.Format("DocService save error. File id: '{0}'. UserId: {1}. DocKey '{2}'. DownloadUri: {3}", fileId, userId, fileData.Key, fileData.Url), ex); saveMessage = ex.Message; StoringFileAfterError(fileId, userId.ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); } } if (!forcesave) { FileTracker.Remove(fileId); } if (file != null) { if (user != null) { FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.UserFileUpdated, user.DisplayUserName(false, DisplayUserSettingsHelper), file.Title); } if (!forcesave) { SaveHistory(file, (fileData.History ?? "").ToString(), DocumentServiceConnector.ReplaceDocumentAdress(fileData.ChangesUrl)); } } SocketManager.FilesChangeEditors(fileId, !forcesave); var result = new TrackResponse { Message = saveMessage }; if (string.IsNullOrEmpty(saveMessage) && file != null && file.Encrypted) { result.Addresses = EncryptionAddressHelper.GetAddresses(file.ID.ToString()).ToArray(); } return(result); }
private TrackResponse ProcessMailMerge(string fileId, TrackerData fileData) { if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out var userId)) { userId = FileTracker.GetEditingBy(fileId).FirstOrDefault(); } string saveMessage; try { SecurityContext.AuthenticateMe(userId); var user = UserManager.GetUsers(userId); var culture = string.IsNullOrEmpty(user.CultureName) ? TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; if (string.IsNullOrEmpty(fileData.Url)) { throw new ArgumentException("emptry url"); } if (fileData.MailMerge == null) { throw new ArgumentException("MailMerge is null"); } var message = fileData.MailMerge.Message; Stream attach = null; switch (fileData.MailMerge.Type) { case MailMergeType.AttachDocx: case MailMergeType.AttachPdf: var downloadRequest = (HttpWebRequest)WebRequest.Create(DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } using (var downloadStream = new ResponseStream(downloadRequest.GetResponse())) { const int bufferSize = 2048; var buffer = new byte[bufferSize]; int readed; attach = new MemoryStream(); while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0) { attach.Write(buffer, 0, readed); } attach.Position = 0; } if (string.IsNullOrEmpty(fileData.MailMerge.Title)) { fileData.MailMerge.Title = "Attach"; } var attachExt = fileData.MailMerge.Type == MailMergeType.AttachDocx ? ".docx" : ".pdf"; var curExt = FileUtility.GetFileExtension(fileData.MailMerge.Title); if (curExt != attachExt) { fileData.MailMerge.Title += attachExt; } break; case MailMergeType.Html: var httpWebRequest = (HttpWebRequest)WebRequest.Create(DocumentServiceConnector.ReplaceDocumentAdress(fileData.Url)); // hack. http://ubuntuforums.org/showthread.php?t=1841740 if (WorkContext.IsMono) { ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true; } using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse()) using (var stream = httpWebResponse.GetResponseStream()) if (stream != null) { using (var reader = new StreamReader(stream, Encoding.GetEncoding(Encoding.UTF8.WebName))) { message = reader.ReadToEnd(); } } break; } using (var mailMergeTask = new MailMergeTask { From = fileData.MailMerge.From, Subject = fileData.MailMerge.Subject, To = fileData.MailMerge.To, Message = message, AttachTitle = fileData.MailMerge.Title, Attach = attach }) { var response = MailMergeTaskRunner.Run(mailMergeTask); Logger.InfoFormat("DocService mailMerge {0}/{1} send: {2}", fileData.MailMerge.RecordIndex + 1, fileData.MailMerge.RecordCount, response); } saveMessage = null; } catch (Exception ex) { Logger.Error( string.Format("DocService mailMerge{0} error: userId - {1}, url - {2}", (fileData.MailMerge == null ? "" : " " + fileData.MailMerge.RecordIndex + "/" + fileData.MailMerge.RecordCount), userId, fileData.Url), ex); saveMessage = ex.Message; } if (fileData.MailMerge != null && fileData.MailMerge.RecordIndex == fileData.MailMerge.RecordCount - 1) { var errorCount = fileData.MailMerge.RecordErrorCount; if (!string.IsNullOrEmpty(saveMessage)) { errorCount++; } NotifyClient.SendMailMergeEnd(userId, fileData.MailMerge.RecordCount, errorCount); } return(new TrackResponse { Message = saveMessage }); }
private void ProcessEdit(string fileId, TrackerData fileData) { if (ThirdPartySelector.GetAppByFileId(fileId) != null) { return; } var users = FileTracker.GetEditingBy(fileId); var usersDrop = new List <string>(); string docKey; var app = ThirdPartySelector.GetAppByFileId(fileId); if (app == null) { File fileStable; fileStable = DaoFactory.FileDao.GetFileStable(fileId); docKey = DocumentServiceHelper.GetDocKey(fileStable); } else { docKey = fileData.Key; } if (!fileData.Key.Equals(docKey)) { Logger.InfoFormat("DocService editing file {0} ({1}) with key {2} for {3}", fileId, docKey, fileData.Key, string.Join(", ", fileData.Users)); usersDrop = fileData.Users; } else { foreach (var user in fileData.Users) { if (!Guid.TryParse(user, out var userId)) { Logger.Error("DocService userId is not Guid: " + user); continue; } users.Remove(userId); try { var doc = FileShareLink.CreateKey(fileId); EntryManager.TrackEditing(fileId, userId, userId, doc); } catch (Exception e) { Logger.DebugFormat("Drop command: fileId '{0}' docKey '{1}' for user {2} : {3}", fileId, fileData.Key, user, e.Message); usersDrop.Add(userId.ToString()); } } } if (usersDrop.Any()) { if (!DocumentServiceHelper.DropUser(fileData.Key, usersDrop.ToArray(), fileId)) { Logger.Error("DocService drop failed for users " + string.Join(",", usersDrop)); } } foreach (var removeUserId in users) { FileTracker.Remove(fileId, userId: removeUserId); } SocketManager.FilesChangeEditors(fileId); }
/// <summary> /// Handles the FileOk event of the saveFileDialog control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="CancelEventArgs" /> instance containing the event data.</param> private void saveFileDialog_FileOk(object sender, CancelEventArgs e) { FileTracker.ActiveFile = new FileInfo(saveFileDialog.FileName); FileTracker.SaveFile(getFileContentString()); updateFormText(); }
/// <summary> /// Handles the FileOk event of the saveCombiledFileDialog control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="CancelEventArgs" /> instance containing the event data.</param> private void saveCombiledFileDialog_FileOk(object sender, CancelEventArgs e) { FileTracker.SaveFile(getFileContentString()); Utils.Compiler.Compile(richTextBox.Text, richTextBox1.Text, FileTracker.ActiveCompileFile); }
/// <summary> /// Handles the Click event of the saveToolStripMenuItem control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> private void saveToolStripMenuItem_Click(object sender, EventArgs e) { FileTracker.SaveFile(getFileContentString()); updateFormText(); saveToolStripMenuItem.Enabled = false; }
private static string ProcessSave(string fileId, TrackerData fileData) { Guid userId; var comments = new List <string>(); if (fileData.Status == TrackerStatus.Corrupted) { comments.Add(FilesCommonResource.ErrorMassage_SaveCorrupted); } if (fileData.Users == null || fileData.Users.Count == 0 || !Guid.TryParse(fileData.Users[0], out userId)) { userId = FileTracker.GetEditingBy(fileId).FirstOrDefault(); } try { SecurityContext.AuthenticateMe(userId); } catch (Exception ex) { Global.Logger.Info("DocService save error: anonymous author - " + userId, ex); if (!userId.Equals(ASC.Core.Configuration.Constants.Guest.ID)) { comments.Add(FilesCommonResource.ErrorMassage_SaveAnonymous); } } File file = null; var saved = false; FileTracker.Remove(fileId); if (string.IsNullOrEmpty(fileData.Url)) { try { comments.Add(FilesCommonResource.ErrorMassage_SaveUrlLost); file = EntryManager.CompleteVersionFile(fileId, 0, false, false); using (var fileDao = Global.DaoFactory.GetFileDao()) { fileDao.UpdateComment(file.ID, file.Version, string.Join("; ", comments)); } } catch (Exception ex) { Global.Logger.Error(string.Format("DocService save error. Version update. File id: '{0}'. UserId: {1}. DocKey '{2}'", fileId, userId, fileData.Key), ex); } } else { try { file = EntryManager.SaveEditing(fileId, null, fileData.Url, null, string.Empty, string.Join("; ", comments), false); saved = fileData.Status == TrackerStatus.MustSave; } catch (Exception ex) { Global.Logger.Error(string.Format("DocService save error. File id: '{0}'. UserId: {1}. DocKey '{2}'. DownloadUri: {3}", fileId, userId, fileData.Key, fileData.Url), ex); StoringFileAfterError(fileId, userId.ToString(), fileData.Url); } } if (file != null) { var user = CoreContext.UserManager.GetUsers(userId); if (user != null) { FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.UserFileUpdated, user.DisplayUserName(false), file.Title); } SaveHistory(file, (fileData.History ?? "").ToString(), fileData.ChangesUrl); } Global.SocketManager.FilesChangeEditors(fileId, true); return(saved ? "0" //error:0 - saved : "1"); //error:1 - some error }