Exemple #1
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    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, editPossible, !RequestView, true, out _configuration);
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, editPossible ? FileShare.ReadWrite : FileShare.Read, false, editable, editable, editable, true, out _configuration);

                        _configuration.Document.Url = app.GetFileStreamUrl(file);
                        _configuration.EditorConfig.Customization.GobackUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

                    fileUri = RequestFileUrl;
                    var fileTitle = Request[FilesLinkUtility.FileTitle];
                    if (string.IsNullOrEmpty(fileTitle))
                    {
                        fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                    }

                    file = new File
                    {
                        ID    = RequestFileUrl,
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                    file = DocumentServiceHelper.GetParams(file, true, FileShare.Read, false, false, false, false, false, out _configuration);
                    _configuration.Document.Permissions.Edit          = editPossible && !CoreContext.Configuration.Standalone;
                    _configuration.Document.Permissions.Rename        = false;
                    _configuration.Document.Permissions.Review        = false;
                    _configuration.Document.Permissions.ChangeHistory = false;
                    _editByUrl = true;

                    _configuration.Document.Url = fileUri;
                }
                ErrorMessage = _configuration.ErrorMessage;
            }
            catch (Exception ex)
            {
                Global.Logger.Warn("DocEditor", ex);
                ErrorMessage = ex.Message;
                return;
            }

            if (_configuration.EditorConfig.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception ex)
                {
                    _configuration = null;
                    Global.Logger.Error("DocEditor", ex);
                    ErrorMessage = ex.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.CopyForEdit);

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = file.Title;

            if (_configuration.EditorConfig.Customization.Goback == null || string.IsNullOrEmpty(_configuration.EditorConfig.Customization.Goback.Url))
            {
                _configuration.EditorConfig.Customization.GobackUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }

            _configuration.EditorConfig.Customization.IsRetina = TenantLogoManager.IsRetina(Request);

            if (RequestEmbedded)
            {
                _configuration.Type = Services.DocumentService.Configuration.EditorType.Embedded;

                _configuration.EditorConfig.Embedded.ShareLinkParam = string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
            }
            else
            {
                _configuration.Type = IsMobile ? Services.DocumentService.Configuration.EditorType.Mobile : Services.DocumentService.Configuration.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _configuration.EditorConfig.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(Share.Location + "?" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(file.ID.ToString()));
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_configuration.EditorConfig.ModeWrite)
            {
                _tabId = FileTracker.Add(file.ID);

                Global.SocketManager.FilesChangeEditors(file.ID);

                if (SecurityContext.IsAuthenticated)
                {
                    _configuration.EditorConfig.FileChoiceUrl  = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.ParamFilterExt + "=xlsx&" + FileChoice.MailMergeParam + "=true";
                    _configuration.EditorConfig.MergeFolderUrl = CommonLinkUtility.GetFullAbsolutePath(MailMerge.GetUrl);
                }
            }
            else
            {
                _linkToEdit = _editByUrl
                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                  : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_configuration.Document.Info.File))
                {
                    _editByUrl = true;
                }
            }
        }
Exemple #2
0
        public static bool SetAceObject(List <AceWrapper> aceWrappers, FileEntry entry, bool notify, string message)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest);
            }
            if (!CanSetAccess(entry))
            {
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
            }

            var fileSecurity = Global.GetFilesSecurity();

            var defaultShare = entry.RootFolderType == FolderType.COMMON
                                   ? fileSecurity.DefaultCommonShare
                                   : fileSecurity.DefaultMyShare;

            var entryType  = entry.FileEntryType;
            var recipients = new Dictionary <Guid, FileShare>();
            var changed    = false;

            foreach (var w in aceWrappers.OrderByDescending(ace => ace.SubjectGroup))
            {
                var subjects = fileSecurity.GetUserSubjects(w.SubjectId);

                var ownerId = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator : entry.CreateBy;
                if (entry.RootFolderType == FolderType.COMMON && subjects.Contains(Constants.GroupAdmin.ID) ||
                    ownerId == w.SubjectId)
                {
                    continue;
                }

                var ace = fileSecurity.GetShares(entry)
                          .Where(r => subjects.Contains(r.Subject))
                          .OrderBy(r => subjects.IndexOf(r.Subject))
                          .ThenBy(r => r.Level)
                          .ThenByDescending(r => r.Share)
                          .FirstOrDefault();

                var parentShare = ace != null && !(ace.Subject == w.SubjectId && ace.Share == w.Share) ? ace.Share : defaultShare;
                var share       = parentShare == w.Share ? FileShare.None : w.Share;

                if (w.SubjectId == FileConstant.ShareLinkId)
                {
                    if (w.Share == FileShare.ReadWrite && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
                    }
                    share = w.Share == FileShare.Restrict ? FileShare.None : w.Share;
                }

                fileSecurity.Share(entry.ID, entryType, w.SubjectId, share);
                changed = true;

                if (w.SubjectId == FileConstant.ShareLinkId)
                {
                    continue;
                }

                entry.Access = share;

                var listUsersId = new List <Guid>();

                if (w.SubjectGroup)
                {
                    listUsersId = CoreContext.UserManager.GetUsersByGroup(w.SubjectId).Select(ui => ui.ID).ToList();
                }
                else
                {
                    listUsersId.Add(w.SubjectId);
                }
                listUsersId.Remove(SecurityContext.CurrentAccount.ID);

                if (entryType == FileEntryType.File)
                {
                    listUsersId.ForEach(uid => FileTracker.ChangeRight(entry.ID, uid, true));
                }

                var addRecipient = share == FileShare.Read ||
                                   share == FileShare.ReadWrite ||
                                   share == FileShare.Review ||
                                   share == FileShare.None && entry.RootFolderType == FolderType.COMMON;
                listUsersId.ForEach(id =>
                {
                    recipients.Remove(id);
                    if (addRecipient)
                    {
                        recipients.Add(id, share);
                    }
                });
            }

            if (entryType == FileEntryType.File)
            {
                DocumentServiceHelper.CheckUsersForDrop((File)entry);
            }

            if (recipients.Any())
            {
                if (entryType == FileEntryType.File ||
                    ((Folder)entry).TotalSubFolders + ((Folder)entry).TotalFiles > 0 ||
                    entry.ProviderEntry)
                {
                    FileMarker.MarkAsNew(entry, recipients.Keys.ToList());
                }

                if (entry.RootFolderType == FolderType.USER &&
                    notify)
                {
                    NotifyClient.SendShareNotice(entry, recipients, message);
                }
            }
            return(changed);
        }
        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.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));
                        });

                        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();
                    }

                    var fileSecurity = Global.GetFilesSecurity();
                    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));
                            }

                            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;

                            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, null, null, true, out convertedFileUrl);
                        }
                        catch (Exception exception)
                        {
                            DocumentService.DocumentServiceException documentServiceException;
                            var password = exception.InnerException != null &&
                                           ((documentServiceException = exception.InnerException as DocumentService.DocumentServiceException) != null) &&
                                           documentServiceException.Code == DocumentService.DocumentServiceException.ErrorCode.ConvertPassword;

                            Global.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;
                                        Global.Logger.ErrorFormat("CheckConvertFilesStatus timeout: {0} ({1})", file.ID, file.ContentLengthString);
                                    }
                                    else
                                    {
                                        operationResult.Processed = "";
                                    }
                                    operationResult.Progress = operationResultProgress;
                                    cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                }
                            }

                            Global.Logger.Debug("CheckConvertFilesStatus iteration continue");
                            continue;
                        }

                        File newFile = null;
                        var  operationResultError = string.Empty;

                        try
                        {
                            newFile = SaveConvertedFile(file, convertedFileUrl);
                        }
                        catch (Exception e)
                        {
                            operationResultError = e.Message;

                            Global.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)
                                        {
                                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                                            {
                                                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));
                                    }
                                }
                            }
                        }

                        Global.Logger.Debug("CheckConvertFilesStatus iteration end");
                    }

                    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);
                }
            }
        }
Exemple #4
0
 public List <EditHistory> GetEditHistory(DocumentServiceHelper documentServiceHelper, string fileId, int fileVersion)
 {
     return(null);
 }
Exemple #5
0
        public static bool SetAceObject(List <AceWrapper> aceWrappers, FileEntry entry, bool notify, string message)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest);
            }
            if (!CanSetAccess(entry))
            {
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
            }

            var fileSecurity = Global.GetFilesSecurity();

            var entryType         = entry.FileEntryType;
            var recipients        = new Dictionary <Guid, FileShare>();
            var usersWithoutRight = new List <Guid>();
            var changed           = false;

            foreach (var w in aceWrappers.OrderByDescending(ace => ace.SubjectGroup))
            {
                var subjects = fileSecurity.GetUserSubjects(w.SubjectId);

                var ownerId = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator : entry.CreateBy;
                if (entry.RootFolderType == FolderType.COMMON && subjects.Contains(Constants.GroupAdmin.ID) ||
                    ownerId == w.SubjectId)
                {
                    continue;
                }

                var share = w.Share;

                if (w.SubjectId == FileConstant.ShareLinkId)
                {
                    if (w.Share == FileShare.ReadWrite && CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
                    }

                    // only editable format on personal
                    if (CoreContext.Configuration.Personal && !FileUtility.CanWebView(entry.Title) && w.Share != FileShare.Restrict)
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_BadRequest);
                    }

                    // only editable format on SaaS trial
                    if (w.Share != FileShare.Restrict && !CoreContext.Configuration.Standalone && TenantExtra.GetTenantQuota().Trial&& !FileUtility.CanWebView(entry.Title))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_BadRequest);
                    }

                    share = w.Share == FileShare.Restrict ? FileShare.None : w.Share;
                }

                fileSecurity.Share(entry.ID, entryType, w.SubjectId, share);
                changed = true;

                if (w.SubjectId == FileConstant.ShareLinkId)
                {
                    continue;
                }

                entry.Access = share;

                var listUsersId = new List <Guid>();

                if (w.SubjectGroup)
                {
                    listUsersId = CoreContext.UserManager.GetUsersByGroup(w.SubjectId).Select(ui => ui.ID).ToList();
                }
                else
                {
                    listUsersId.Add(w.SubjectId);
                }
                listUsersId.Remove(SecurityContext.CurrentAccount.ID);

                if (entryType == FileEntryType.File)
                {
                    listUsersId.ForEach(uid => FileTracker.ChangeRight(entry.ID, uid, true));
                }

                var addRecipient = share == FileShare.Read ||
                                   share == FileShare.CustomFilter ||
                                   share == FileShare.ReadWrite ||
                                   share == FileShare.Review ||
                                   share == FileShare.FillForms ||
                                   share == FileShare.Comment ||
                                   share == FileShare.None && entry.RootFolderType == FolderType.COMMON;
                var removeNew = share == FileShare.None && entry.RootFolderType == FolderType.USER ||
                                share == FileShare.Restrict;
                listUsersId.ForEach(id =>
                {
                    recipients.Remove(id);
                    if (addRecipient)
                    {
                        recipients.Add(id, share);
                    }
                    else if (removeNew)
                    {
                        usersWithoutRight.Add(id);
                    }
                });
            }

            if (entryType == FileEntryType.File)
            {
                DocumentServiceHelper.CheckUsersForDrop((File)entry);
            }

            if (recipients.Any())
            {
                if (entryType == FileEntryType.File ||
                    ((Folder)entry).TotalSubFolders + ((Folder)entry).TotalFiles > 0 ||
                    entry.ProviderEntry)
                {
                    FileMarker.MarkAsNew(entry, recipients.Keys.ToList());
                }

                if ((entry.RootFolderType == FolderType.USER ||
                     entry.RootFolderType == FolderType.Privacy) &&
                    notify)
                {
                    NotifyClient.SendShareNotice(entry, recipients, message);
                }
            }

            usersWithoutRight.ForEach(userId => FileMarker.RemoveMarkAsNew(entry, userId));

            return(changed);
        }
Exemple #6
0
        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);
                }
        }
        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.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, 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 = (HttpWebRequest)WebRequest.Create(RequestFileUrl);

                            // hack. http://ubuntuforums.org/showthread.php?t=1841740
                            if (WorkContext.IsMono)
                            {
                                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                            }

                            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, false, out _docParams);
                    _docParams.CanEdit   = editPossible && !CoreContext.Configuration.Standalone;
                    _docParams.CanReview = _docParams.CanEdit;
                    _editByUrl           = true;

                    _docParams.FileUri = fileUri;
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error("DocEditor", ex);
                _errorMessage = ex.Message;
                return;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception ex)
                {
                    _docParams = null;
                    Global.Logger.Error("DocEditor", ex);
                    _errorMessage = ex.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);
                if (SecurityContext.IsAuthenticated)
                {
                    _docParams.FileChoiceUrl  = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.ParamFilterExt + "=xlsx&" + FileChoice.MailMergeParam + "=true";
                    _docParams.MergeFolderUrl = CommonLinkUtility.GetFullAbsolutePath(MailMerge.GetUrl);
                }
            }
            else
            {
                if (!RequestView && FileTracker.IsEditingAlone(file.ID))
                {
                    var editingBy = FileTracker.GetEditingBy(file.ID).FirstOrDefault();
                    _errorMessage = string.Format(FilesCommonResource.ErrorMassage_EditingMobile, Global.GetUserName(editingBy));
                }

                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                            : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_docParams.File))
                {
                    _editByUrl = true;
                }
            }
        }
Exemple #8
0
        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));
                            var isUpdate     = false;

                            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) &&
                                    (newFile.FileStatus & FileStatus.IsEditing) != FileStatus.IsEditing)
                                {
                                    newFile.Version++;
                                    isUpdate = true;
                                }
                                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)
                            {
                                if (!isUpdate)
                                {
                                    fileDao.DeleteFile(newFile.ID);
                                }

                                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;
                }
            }
        }
Exemple #9
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        file = DocumentServiceHelper.GetParams(RequestFileId, RequestVersion, RequestShareLinkKey, editPossible, !RequestView, true, out _configuration);
                        if (_valideShareLink)
                        {
                            _configuration.Document.SharedLinkKey += RequestShareLinkKey;

                            if (CoreContext.Configuration.Personal && !SecurityContext.IsAuthenticated)
                            {
                                var user    = CoreContext.UserManager.GetUsers(file.CreateBy);
                                var culture = CultureInfo.GetCultureInfo(user.CultureName);
                                Thread.CurrentThread.CurrentCulture   = culture;
                                Thread.CurrentThread.CurrentUICulture = culture;
                            }
                        }
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, editPossible ? FileShare.ReadWrite : FileShare.Read, false, editable, editable, editable, true, out _configuration);

                        _configuration.Document.Url = app.GetFileStreamUrl(file);
                        _configuration.EditorConfig.Customization.GobackUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

                    fileUri = RequestFileUrl;
                    var fileTitle = Request[FilesLinkUtility.FileTitle];
                    if (string.IsNullOrEmpty(fileTitle))
                    {
                        fileTitle = Path.GetFileName(HttpUtility.UrlDecode(fileUri)) ?? "";
                    }

                    file = new File
                    {
                        ID    = RequestFileUrl,
                        Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                    };

                    file = DocumentServiceHelper.GetParams(file, true, FileShare.Read, false, false, false, false, false, out _configuration);
                    _configuration.Document.Permissions.Edit          = editPossible && !CoreContext.Configuration.Standalone;
                    _configuration.Document.Permissions.Rename        = false;
                    _configuration.Document.Permissions.Review        = false;
                    _configuration.Document.Permissions.FillForms     = false;
                    _configuration.Document.Permissions.ChangeHistory = false;
                    _configuration.Document.Permissions.ModifyFilter  = false;
                    _editByUrl = true;

                    _configuration.Document.Url = fileUri;
                }
                ErrorMessage = _configuration.ErrorMessage;
            }
            catch (Exception ex)
            {
                Global.Logger.Warn("DocEditor", ex);
                ErrorMessage = ex.Message;
                return;
            }

            if (_configuration.EditorConfig.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecSync(file, RequestShareLinkKey);
                }
                catch (Exception ex)
                {
                    _configuration = null;
                    Global.Logger.Error("DocEditor", ex);
                    ErrorMessage = ex.Message;
                    return;
                }

                var comment = "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.ConvertForEdit, file.Title));

                Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = file.Title + GetPageTitlePostfix();

            if (_configuration.EditorConfig.Customization.Goback == null || string.IsNullOrEmpty(_configuration.EditorConfig.Customization.Goback.Url))
            {
                _configuration.EditorConfig.Customization.GobackUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }

            _configuration.EditorConfig.Customization.IsRetina = TenantLogoManager.IsRetina(Request);

            if (RequestEmbedded)
            {
                _configuration.Type = Services.DocumentService.Configuration.EditorType.Embedded;

                _configuration.EditorConfig.Embedded.ShareLinkParam = string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
            }
            else
            {
                _configuration.Type = IsMobile ? Services.DocumentService.Configuration.EditorType.Mobile : Services.DocumentService.Configuration.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file) &&
                    !(file.Encrypted &&
                      (!Request.DesktopApp() ||
                       CoreContext.Configuration.Personal)))
                {
                    _configuration.EditorConfig.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(
                        Share.Location
                        + "?" + FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(file.ID.ToString())
                        + (Request.DesktopApp() ? "&desktop=true" : string.Empty));
                }

                if (file.RootFolderType == FolderType.Privacy)
                {
                    if (!PrivacyRoomSettings.Enabled)
                    {
                        _configuration = null;
                        ErrorMessage   = FilesCommonResource.ErrorMassage_FileNotFound;
                        return;
                    }
                    else
                    {
                        if (Request.DesktopApp())
                        {
                            var keyPair = EncryptionKeyPair.GetKeyPair();
                            if (keyPair != null)
                            {
                                _configuration.EditorConfig.EncryptionKeys = new Services.DocumentService.Configuration.EditorConfiguration.EncryptionKeysConfig
                                {
                                    PrivateKeyEnc = keyPair.PrivateKeyEnc,
                                    PublicKey     = keyPair.PublicKey,
                                };
                            }
                        }
                    }
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
                if (!file.Encrypted && !file.ProviderEntry)
                {
                    EntryManager.MarkAsRecent(file);
                }
            }

            if (SecurityContext.IsAuthenticated)
            {
                _configuration.EditorConfig.SaveAsUrl = CommonLinkUtility.GetFullAbsolutePath(SaveAs.GetUrl);
            }

            if (_configuration.EditorConfig.ModeWrite)
            {
                _tabId = FileTracker.Add(file.ID);

                Global.SocketManager.FilesChangeEditors(file.ID);

                if (SecurityContext.IsAuthenticated)
                {
                    _configuration.EditorConfig.FileChoiceUrl = CommonLinkUtility.GetFullAbsolutePath(FileChoice.GetUrlForEditor);
                }
            }
            else
            {
                _linkToEdit = _editByUrl
                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                  : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));
                if (Request.DesktopApp())
                {
                    _linkToEdit += "&desktop=true";
                }

                if (FileConverter.MustConvert(_configuration.Document.Info.File))
                {
                    _editByUrl = true;
                }
            }

            var actionAnchor = Request[FilesLinkUtility.Anchor];

            if (!string.IsNullOrEmpty(actionAnchor))
            {
                _configuration.EditorConfig.ActionLinkString = actionAnchor;
            }
        }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File           file;
            var            fileUri = string.Empty;
            IThirdPartyApp app     = null;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    _fileNew = (Request["new"] ?? "") == "true";

                    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;

            _newScheme = FileUtility.ExtsNewService.Contains(FileUtility.GetFileExtension(file.Title)) &&
                         (string.IsNullOrEmpty(RequestShareLinkKey)
                                 ? OnlineEditorsSettings.NewScheme
                                 : OnlineEditorsSettings.NewSchemeFor(file.CreateBy)) &&
                         app == null;
            if (_newScheme)
            {
                DocServiceApiUrl = FilesLinkUtility.DocServiceApiUrlNew;
            }

            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);
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                            : FileConverter.MustConvert(_docParams.File) || _newScheme
                                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID))
                                                  : string.Empty;
            }
        }
Exemple #11
0
        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);
                    }

                    File newFile = null;
                    try
                    {
                        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);

                        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);
                    }
                    catch
                    {
                        if (newFile != null)
                        {
                            fileDao.DeleteFile(newFile.ID);
                        }
                        throw;
                    }
                    return(newFile);
                }
        }
Exemple #12
0
        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);
        }
 /// <summary>
 /// </summary>
 /// <param name="context"></param>
 /// <param name="fileStorageService"></param>
 public FilesControllerHelper(
     ApiContext context,
     FileStorageService <T> fileStorageService,
     GlobalFolderHelper globalFolderHelper,
     FileWrapperHelper fileWrapperHelper,
     FilesSettingsHelper filesSettingsHelper,
     FilesLinkUtility filesLinkUtility,
     FileUploader fileUploader,
     DocumentServiceHelper documentServiceHelper,
     TenantManager tenantManager,
     SecurityContext securityContext,
     FolderWrapperHelper folderWrapperHelper,
     FileOperationWraperHelper fileOperationWraperHelper,
     FileShareWrapperHelper fileShareWrapperHelper,
     FileShareParamsHelper fileShareParamsHelper,
     EntryManager entryManager,
     UserManager userManager,
     WebItemSecurity webItemSecurity,
     CoreBaseSettings coreBaseSettings,
     ThirdpartyConfiguration thirdpartyConfiguration,
     MessageService messageService,
     CommonLinkUtility commonLinkUtility,
     DocumentServiceConnector documentServiceConnector,
     FolderContentWrapperHelper folderContentWrapperHelper,
     WordpressToken wordpressToken,
     WordpressHelper wordpressHelper,
     ConsumerFactory consumerFactory,
     EasyBibHelper easyBibHelper,
     ChunkedUploadSessionHelper chunkedUploadSessionHelper,
     ProductEntryPoint productEntryPoint)
 {
     ApiContext                 = context;
     FileStorageService         = fileStorageService;
     GlobalFolderHelper         = globalFolderHelper;
     FileWrapperHelper          = fileWrapperHelper;
     FilesSettingsHelper        = filesSettingsHelper;
     FilesLinkUtility           = filesLinkUtility;
     FileUploader               = fileUploader;
     DocumentServiceHelper      = documentServiceHelper;
     TenantManager              = tenantManager;
     SecurityContext            = securityContext;
     FolderWrapperHelper        = folderWrapperHelper;
     FileOperationWraperHelper  = fileOperationWraperHelper;
     FileShareWrapperHelper     = fileShareWrapperHelper;
     FileShareParamsHelper      = fileShareParamsHelper;
     EntryManager               = entryManager;
     UserManager                = userManager;
     WebItemSecurity            = webItemSecurity;
     CoreBaseSettings           = coreBaseSettings;
     ThirdpartyConfiguration    = thirdpartyConfiguration;
     ConsumerFactory            = consumerFactory;
     BoxLoginProvider           = ConsumerFactory.Get <BoxLoginProvider>();
     DropboxLoginProvider       = ConsumerFactory.Get <DropboxLoginProvider>();
     GoogleLoginProvider        = ConsumerFactory.Get <GoogleLoginProvider>();
     OneDriveLoginProvider      = ConsumerFactory.Get <OneDriveLoginProvider>();
     MessageService             = messageService;
     CommonLinkUtility          = commonLinkUtility;
     DocumentServiceConnector   = documentServiceConnector;
     FolderContentWrapperHelper = folderContentWrapperHelper;
     WordpressToken             = wordpressToken;
     WordpressHelper            = wordpressHelper;
     EasyBibHelper              = easyBibHelper;
     ChunkedUploadSessionHelper = chunkedUploadSessionHelper;
     ProductEntryPoint          = productEntryPoint;
 }
        private void InitScript()
        {
            var inlineScript = new StringBuilder();

            inlineScript.AppendFormat("\nASC.Files.Constants.URL_WCFSERVICE = \"{0}\";" +
                                      "ASC.Files.Constants.DocsAPIundefined = \"{1}\";",
                                      PathProvider.GetFileServicePath,
                                      FilesCommonResource.DocsAPIundefined);

            if (!CoreContext.Configuration.Personal)
            {
                inlineScript.AppendFormat("\nASC.Files.Constants.URL_MAIL_ACCOUNTS = \"{0}\";",
                                          CommonLinkUtility.GetFullAbsolutePath("~/addons/mail/#accounts"));
            }

            var docServiceParams = new DocumentServiceParams
            {
                DocKeyForTrack     = _docKeyForTrack,
                EditByUrl          = _editByUrl,
                LinkToEdit         = _linkToEdit,
                OpeninigDate       = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture),
                ShareLinkParam     = string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey,
                ServerErrorMessage = ErrorMessage,
                TabId         = _tabId.ToString(),
                ThirdPartyApp = _thirdPartyApp,
            };

            if (_configuration != null)
            {
                docServiceParams.FileId          = _configuration.Document.Info.File.ID.ToString();
                docServiceParams.FileProviderKey = _configuration.Document.Info.File.ProviderKey;
                docServiceParams.FileVersion     = _configuration.Document.Info.File.Version;

                _configuration.Token = DocumentServiceHelper.GetSignature(_configuration);

                if (!string.IsNullOrEmpty(_configuration.Token))
                {
                    _configuration.EditorConfig.CallbackUrl = DocumentServiceTracker.GetCallbackUrl(_configuration.Document.Info.File.ID.ToString());
                }
            }

            inlineScript.AppendFormat("\nASC.Files.Editor.docServiceParams = {0};",
                                      DocumentServiceParams.Serialize(docServiceParams));

            inlineScript.AppendFormat("\nASC.Files.Editor.configurationParams = {0};",
                                      Services.DocumentService.Configuration.Serialize(_configuration));

            if (Request.DesktopApp() && SecurityContext.IsAuthenticated)
            {
                var user = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);

                var displayName = DisplayUserSettings.GetFullUserName(user);
                var email       = user.Email;

                inlineScript.AppendFormat("\nASC.displayName = \"{0}\";" +
                                          "\nASC.email = \"{1}\";",
                                          displayName,
                                          email);
            }

            InlineScripts.Scripts.Add(new Tuple <string, bool>(inlineScript.ToString(), false));
        }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded && !IsMobile;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            if (!ItsTry)
            {
                try
                {
                    if (string.IsNullOrEmpty(RequestFileUrl))
                    {
                        _fileNew = !string.IsNullOrEmpty(Request[UrlConstant.New]) && Request[UrlConstant.New] == "true";

                        var ver = string.IsNullOrEmpty(Request[CommonLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[CommonLinkUtility.Version]);

                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, _fileNew, editPossible, !RequestView, out _docParams);

                        _fileNew = file.Version == 1 && file.ConvertedType != null && _fileNew && file.CreateOn == file.ModifiedOn;
                    }
                    else
                    {
                        isExtenral = true;

                        fileUri = RequestFileUrl;
                        var fileTitle = Request[CommonLinkUtility.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))
                                    {
                                        fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), "new");
                                    }
                            }
                            catch (Exception error)
                            {
                                Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                            }
                        }

                        file = new File
                        {
                            ID    = fileUri.GetHashCode(),
                            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;
                }
            }
            else
            {
                FileType tryType;
                try
                {
                    tryType = (FileType)Enum.Parse(typeof(FileType), Request[CommonLinkUtility.TryParam]);
                }
                catch
                {
                    tryType = FileType.Document;
                }

                var fileTitle = "Demo";
                fileTitle += FileUtility.InternalExtension[tryType];

                var relativeUri = string.Format(CommonLinkUtility.FileHandlerPath + UrlConstant.ParamsDemo, tryType);
                fileUri = new Uri(Request.Url, relativeUri).ToString();

                file = new File
                {
                    ID    = Guid.NewGuid(),
                    Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                };

                file = DocumentServiceHelper.GetParams(file, true, true, true, editPossible, editPossible, true, out _docParams);

                _docParams.FileUri = fileUri;
                _editByUrl         = true;
            }

            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(CommonLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = HeaderStringHelper.GetPageTitle(file.Title);

            if (string.IsNullOrEmpty(_docParams.FolderUrl))
            {
                _docParams.FolderUrl = Request[CommonLinkUtility.FolderUrl] ?? "";
            }
            if (MobileDetector.IsRequestMatchesMobile(Context.Request.UserAgent, true))
            {
                _docParams.FolderUrl = string.Empty;
            }

            if (RequestEmbedded)
            {
                _docParams.Type = DocumentServiceParams.EditorType.Embedded;

                var shareLinkParam = "&" + CommonLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
                _docParams.ViewerUrl   = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + CommonLinkUtility.EditorPage + "?" + CommonLinkUtility.Action + "=view" + shareLinkParam);
                _docParams.DownloadUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FileHandlerPath + "?" + CommonLinkUtility.Action + "=download" + shareLinkParam);
                _docParams.EmbeddedUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + CommonLinkUtility.EditorPage + "?" + CommonLinkUtility.Action + "=embedded" + shareLinkParam);
            }
            else
            {
                _docParams.Type = IsMobile ? DocumentServiceParams.EditorType.Mobile : DocumentServiceParams.EditorType.Desktop;

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + "share.aspx" + "?" + CommonLinkUtility.FileId + "=" + file.ID + "&" + CommonLinkUtility.FileTitle + "=" + HttpUtility.UrlEncode(file.Title));
                }
            }

            if (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                if (!ItsTry)
                {
                    FileMarker.RemoveMarkAsNew(file);
                }
            }

            if (_docParams.ModeWrite)
            {
                _tabId       = FileLocker.Add(file.ID, _fileNew);
                _lockVersion = FileLocker.LockVersion(file.ID);

                if (ItsTry)
                {
                    AppendAuthControl();
                }
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(string.Format(CommonLinkUtility.FileWebEditorExternalUrlString, HttpUtility.UrlEncode(fileUri), file.Title))
                                            : FileConverter.MustConvert(_docParams.File)
                                                  ? CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetFileWebEditorUrl(file.ID))
                                                  : string.Empty;
            }

            if (CoreContext.Configuration.YourDocsDemo && IsMobile)
            {
                _docParams.CanEdit = false;
            }
        }
Exemple #16
0
 public List <EditHistory> GetEditHistory(DocumentServiceHelper documentServiceHelper, string fileId, int fileVersion)
 {
     throw new NotImplementedException();
 }