protected override void Do()
        {
            var entries = new List <FileEntry>();

            if (Folders.Any())
            {
                entries.AddRange(FolderDao.GetFolders(Folders));
            }
            if (Files.Any())
            {
                entries.AddRange(FileDao.GetFiles(Files));
            }
            entries.ForEach(entry =>
            {
                CancellationToken.ThrowIfCancellationRequested();

                FileMarker.RemoveMarkAsNew(entry, ((IAccount)Thread.CurrentPrincipal.Identity).ID);

                if (entry.FileEntryType == FileEntryType.File)
                {
                    ProcessedFile(entry.ID.ToString());
                    FilesMessageService.Send(entry, headers, MessageAction.FileMarkedAsRead, entry.Title);
                }
                else
                {
                    ProcessedFolder(entry.ID.ToString());
                    FilesMessageService.Send(entry, headers, MessageAction.FolderMarkedAsRead, entry.Title);
                }
                ProgressStep();
            });

            var newrootfolder = FileMarker
                                .GetRootFoldersIdMarkedAsNew()
                                .Select(item => string.Format("new_{{\"key\"? \"{0}\", \"value\"? \"{1}\"}}", item.Key, item.Value));

            Status += string.Join(SPLIT_CHAR, newrootfolder.ToArray());
        }
Beispiel #2
0
        private ItemNameValueCollection GetEntriesPathId(out List <File> filesForSend, out List <Folder> folderForSend)
        {
            filesForSend  = new List <File>();
            folderForSend = new List <Folder>();

            var entriesPathId = new ItemNameValueCollection();

            if (0 < Files.Count)
            {
                filesForSend = FilesSecurity.FilterDownload(FileDao.GetFiles(Files));
                filesForSend.ForEach(file => entriesPathId.Add(ExecPathFromFile(file, string.Empty)));
            }
            if (0 < Folders.Count)
            {
                folderForSend = FolderDao.GetFolders(Folders);
                folderForSend = FilesSecurity.FilterDownload(folderForSend);
                folderForSend.ForEach(folder => FileMarker.RemoveMarkAsNew(folder));

                var filesInFolder = GetFilesInFolders(folderForSend.Select(x => x.ID), string.Empty);
                entriesPathId.Add(filesInFolder);
            }

            if (Folders.Count == 1 && Files.Count == 0)
            {
                var entriesPathIdWithoutRoot = new ItemNameValueCollection();

                foreach (var path in entriesPathId.AllKeys)
                {
                    entriesPathIdWithoutRoot.Add(path.Remove(0, path.IndexOf('/') + 1), entriesPathId[path]);
                }

                return(entriesPathIdWithoutRoot);
            }

            return(entriesPathId);
        }
Beispiel #3
0
        private static void SaveFile(IFileDao fileDao, object folder, string filePath, IDataStore storeTemp)
        {
            using (var stream = storeTemp.IronReadStream("", filePath, 10))
            {
                var fileName = Path.GetFileName(filePath);
                var file     = new File
                {
                    Title         = fileName,
                    ContentLength = stream.Length,
                    FolderID      = folder,
                };
                stream.Position = 0;
                try
                {
                    file = fileDao.SaveFile(file, stream);

                    FileMarker.MarkAsNew(file);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
            }
        }
        private void DeleteFiles(IEnumerable <object> fileIds, bool isNeedSendActions = false)
        {
            foreach (var fileId in fileIds)
            {
                CancellationToken.ThrowIfCancellationRequested();

                var    file = FileDao.GetFile(fileId);
                string tmpError;
                if (file == null)
                {
                    Error = FilesCommonResource.ErrorMassage_FileNotFound;
                }
                else if (!_ignoreException && WithError(new[] { file }, false, out tmpError))
                {
                    Error = tmpError;
                }
                else
                {
                    FileMarker.RemoveMarkAsNewForAll(file);
                    if (!_immediately && FileDao.UseTrashForRemove(file))
                    {
                        FileDao.MoveFile(file.ID, _trashId);
                        if (isNeedSendActions)
                        {
                            FilesMessageService.Send(file, _headers, MessageAction.FileMovedToTrash, file.Title);
                        }
                        if (file.ThumbnailStatus == Thumbnail.Waiting)
                        {
                            file.ThumbnailStatus = Thumbnail.NotRequired;
                            FileDao.SaveThumbnail(file, null);
                        }
                    }
                    else
                    {
                        try
                        {
                            FileDao.DeleteFile(file.ID);
                            if (_headers != null)
                            {
                                if (isNeedSendActions)
                                {
                                    FilesMessageService.Send(file, _headers, MessageAction.FileDeleted, file.Title);
                                }
                            }
                            else
                            {
                                FilesMessageService.Send(file, MessageInitiator.AutoCleanUp, MessageAction.FileDeleted, file.Title);
                            }
                        }
                        catch (Exception ex)
                        {
                            Error = ex.Message;
                            Logger.Error(Error, ex);
                        }

                        LinkDao.DeleteAllLink(file.ID);
                    }
                    ProcessedFile(fileId);
                }
                ProgressStep(fileId: FolderDao.CanCalculateSubitems(fileId) ? null : fileId);
            }
        }
        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;
                            _configuration.Document.Info.Favorite  = null;

                            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;
                        _configuration.Document.Info.Favorite = null;
                    }
                }
                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;
                    _configuration.Document.Info.Favorite = null;
                }
                ErrorMessage = _configuration.ErrorMessage;
            }
            catch (Exception ex)
            {
                Global.Logger.Warn("DocEditor", ex);
                ErrorMessage = ex.Message;
                return;
            }

            var        userAgent      = Request.UserAgent.ToString().ToLower();
            HttpCookie deeplinkCookie = Request.Cookies.Get("deeplink");
            var        deepLink       = ConfigurationManagerExtension.AppSettings["deeplink.documents.url"];

            if (!_valideShareLink &&
                deepLink != null && MobileDetector.IsMobile &&
                ((!userAgent.Contains("version/") && userAgent.Contains("android")) || !userAgent.Contains("android")) &&       //check webkit
                ((Request[DeepLinking.WithoutDeeplinkRedirect] == null && deeplinkCookie == null) ||
                 Request[DeepLinking.WithoutDeeplinkRedirect] == null && deeplinkCookie != null && deeplinkCookie.Value == "app"))
            {
                var          currentUser  = CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID);
                DeepLinkData deepLinkData = new DeepLinkData
                {
                    Email  = currentUser.Email,
                    Portal = CoreContext.TenantManager.GetCurrentTenant().TenantDomain,
                    File   = new DeepLinkDataFile
                    {
                        Id        = file.ID.ToString(),
                        Title     = file.Title,
                        Extension = file.ConvertedExtension
                    },
                    Folder = new DeepLinkDataFolder
                    {
                        Id             = file.FolderID.ToString(),
                        ParentId       = file.RootFolderId.ToString(),
                        RootFolderType = (int)file.RootFolderType
                    },
                    OriginalUrl = Request.GetUrlRewriter().ToString()
                };

                var    jsonDeeplinkData   = JsonConvert.SerializeObject(deepLinkData);
                string base64DeeplinkData = Convert.ToBase64String(Encoding.UTF8.GetBytes(jsonDeeplinkData));

                Response.Redirect("~/DeepLink.aspx?data=" + HttpUtility.UrlEncode(base64DeeplinkData));
            }


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

            var fileSecurity = Global.GetFilesSecurity();

            if (_configuration.EditorConfig.ModeWrite &&
                FileUtility.CanWebRestrictedEditing(file.Title) &&
                fileSecurity.CanFillForms(file) &&
                !fileSecurity.CanEdit(file))
            {
                if (!file.IsFillFormDraft)
                {
                    FileMarker.RemoveMarkAsNew(file);

                    Folder folderIfNew;
                    try
                    {
                        file = EntryManager.GetFillFormDraft(file, out folderIfNew);
                    }
                    catch (Exception ex)
                    {
                        _configuration = null;
                        Global.Logger.Error("DocEditor", ex);
                        ErrorMessage = ex.Message;
                        return;
                    }

                    var comment = folderIfNew == null
                        ? string.Empty
                        : "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.MessageFillFormDraftCreated, folderIfNew.Title));

                    Response.Redirect(FilesLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                    return;
                }
                else if (!EntryManager.CheckFillFormDraft(file))
                {
                    var comment = "#message/" + HttpUtility.UrlEncode(FilesCommonResource.MessageFillFormDraftDiscard);

                    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 (RequestView)
                {
                    FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.FileReaded, file.Title);
                }
                else
                {
                    FilesMessageService.Send(file, MessageInitiator.DocsService, MessageAction.FileOpenedForChange, file.Title);
                }
            }

            if (SecurityContext.IsAuthenticated)
            {
                var saveAsUrl = SaveAs.GetUrl;
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    var folder = folderDao.GetFolder(file.FolderID);
                    if (folder != null && Global.GetFilesSecurity().CanCreate(folder))
                    {
                        saveAsUrl = SaveAs.GetUrlToFolder(file.FolderID);
                    }
                }

                _configuration.EditorConfig.SaveAsUrl = CommonLinkUtility.GetFullAbsolutePath(saveAsUrl);
            }

            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 MoveOrCopyFolders(ICollection folderIds, Folder toFolder, bool copy)
        {
            if (folderIds.Count == 0)
            {
                return;
            }

            var toFolderId = toFolder.ID;
            var isToFolder = Equals(toFolderId.ToString(), this.toFolderId);

            foreach (var folderId in folderIds)
            {
                CancellationToken.ThrowIfCancellationRequested();

                var folder = FolderDao.GetFolder(folderId);
                if (folder == null)
                {
                    Error = FilesCommonResource.ErrorMassage_FolderNotFound;
                }
                else if (!FilesSecurity.CanRead(folder))
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException_ReadFolder;
                }
                else if (!Equals((folder.ParentFolderID ?? string.Empty).ToString(), toFolderId.ToString()) || resolveType == FileConflictResolveType.Duplicate)
                {
                    try
                    {
                        //if destination folder contains folder with same name then merge folders
                        var conflictFolder = FolderDao.GetFolder(folder.Title, toFolderId);

                        if (copy || conflictFolder != null)
                        {
                            Folder newFolder;
                            if (conflictFolder != null)
                            {
                                newFolder = conflictFolder;

                                if (isToFolder)
                                {
                                    needToMark.Add(conflictFolder);
                                }
                            }
                            else
                            {
                                newFolder = FolderDao.CopyFolder(folder.ID, toFolderId);
                                FilesMessageService.Send(folder, toFolder, headers, MessageAction.FolderCopied, folder.Title, toFolder.Title);

                                if (isToFolder)
                                {
                                    needToMark.Add(newFolder);
                                }

                                if (ProcessedFolder(folderId))
                                {
                                    Status += string.Format("folder_{0}{1}", newFolder.ID, SPLIT_CHAR);
                                }
                            }

                            if (FolderDao.UseRecursiveOperation(folder.ID, toFolderId))
                            {
                                MoveOrCopyFiles(FileDao.GetFiles(folder.ID), newFolder, copy);
                                MoveOrCopyFolders(FolderDao.GetFolders(folder.ID).Select(f => f.ID).ToList(), newFolder, copy);

                                if (!copy)
                                {
                                    if (FolderDao.IsEmpty(folder.ID) && FilesSecurity.CanDelete(folder))
                                    {
                                        FolderDao.DeleteFolder(folder.ID);
                                        if (ProcessedFolder(folderId))
                                        {
                                            Status += string.Format("folder_{0}{1}", newFolder.ID, SPLIT_CHAR);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (conflictFolder != null)
                                {
                                    object newFolderId;
                                    if (copy)
                                    {
                                        newFolder   = FolderDao.CopyFolder(folder.ID, toFolderId);
                                        newFolderId = newFolder.ID;
                                        FilesMessageService.Send(folder, toFolder, headers, MessageAction.FolderCopiedWithOverwriting, folder.Title, toFolder.Title);

                                        if (isToFolder)
                                        {
                                            needToMark.Add(newFolder);
                                        }
                                    }
                                    else
                                    {
                                        newFolderId = FolderDao.MoveFolder(folder.ID, toFolderId);
                                        FilesMessageService.Send(folder, toFolder, headers, MessageAction.FolderMovedWithOverwriting, folder.Title, toFolder.Title);

                                        if (isToFolder)
                                        {
                                            needToMark.Add(FolderDao.GetFolder(newFolderId));
                                        }
                                    }

                                    if (ProcessedFolder(folderId))
                                    {
                                        Status += string.Format("folder_{0}{1}", newFolderId, SPLIT_CHAR);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (FilesSecurity.CanDelete(folder))
                            {
                                FileMarker.RemoveMarkAsNewForAll(folder);

                                var newFolderId = FolderDao.MoveFolder(folder.ID, toFolderId);
                                FilesMessageService.Send(folder, toFolder, headers, MessageAction.FolderMoved, folder.Title, toFolder.Title);

                                if (isToFolder)
                                {
                                    needToMark.Add(FolderDao.GetFolder(newFolderId));
                                }

                                if (ProcessedFolder(folderId))
                                {
                                    Status += string.Format("folder_{0}{1}", newFolderId, SPLIT_CHAR);
                                }
                            }
                            else
                            {
                                Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFolder;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ex.Message;

                        Logger.Error(Error, ex);
                    }
                }
                ProgressStep(FolderDao.CanCalculateSubitems(folderId) ? null : folderId);
            }
        }
        private void DeleteFolders(IEnumerable <object> folderIds)
        {
            foreach (var folderId in folderIds)
            {
                CancellationToken.ThrowIfCancellationRequested();

                var    folder       = FolderDao.GetFolder(folderId);
                object canCalculate = null;
                if (folder == null)
                {
                    Error = FilesCommonResource.ErrorMassage_FolderNotFound;
                }
                else if (folder.FolderType != FolderType.DEFAULT && folder.FolderType != FolderType.BUNCH)
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFolder;
                }
                else if (!_ignoreException && !FilesSecurity.CanDelete(folder))
                {
                    canCalculate = FolderDao.CanCalculateSubitems(folderId) ? null : folderId;

                    Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFolder;
                }
                else
                {
                    canCalculate = FolderDao.CanCalculateSubitems(folderId) ? null : folderId;

                    FileMarker.RemoveMarkAsNewForAll(folder);
                    if (folder.ProviderEntry && folder.ID.Equals(folder.RootFolderId))
                    {
                        if (ProviderDao != null)
                        {
                            ProviderDao.RemoveProviderInfo(folder.ProviderId);
                            FilesMessageService.Send(folder, _headers, MessageAction.ThirdPartyDeleted, folder.ID.ToString(), folder.ProviderKey);
                        }

                        ProcessedFolder(folderId);
                    }
                    else
                    {
                        var immediately = _immediately || !FolderDao.UseTrashForRemove(folder);
                        if (immediately && FolderDao.UseRecursiveOperation(folder.ID, null))
                        {
                            DeleteFiles(FileDao.GetFiles(folder.ID));
                            DeleteFolders(FolderDao.GetFolders(folder.ID).Select(f => f.ID).ToList());

                            if (FolderDao.IsEmpty(folder.ID))
                            {
                                FolderDao.DeleteFolder(folder.ID);
                                FilesMessageService.Send(folder, _headers, MessageAction.FolderDeleted, folder.Title);

                                ProcessedFolder(folderId);
                            }
                        }
                        else
                        {
                            var    files = FileDao.GetFiles(folder.ID, new OrderBy(SortedByType.AZ, true), FilterType.FilesOnly, false, Guid.Empty, string.Empty, false, true);
                            string tmpError;
                            if (!_ignoreException && WithError(files, true, out tmpError))
                            {
                                Error = tmpError;
                            }
                            else
                            {
                                if (immediately)
                                {
                                    FolderDao.DeleteFolder(folder.ID);
                                    FilesMessageService.Send(folder, _headers, MessageAction.FolderDeleted, folder.Title);
                                }
                                else
                                {
                                    FolderDao.MoveFolder(folder.ID, _trashId, CancellationToken);
                                    FilesMessageService.Send(folder, _headers, MessageAction.FolderMovedToTrash, folder.Title);
                                }

                                ProcessedFolder(folderId);
                            }
                        }
                    }
                }
                ProgressStep(canCalculate);
            }
        }
Beispiel #8
0
        private static void DownloadFile(HttpContext context)
        {
            var flushed = false;

            try
            {
                var id  = context.Request[FilesLinkUtility.FileId];
                var doc = context.Request[FilesLinkUtility.DocShareKey] ?? "";

                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    File file;
                    var  readLink = FileShareLink.Check(doc, true, fileDao, out file);
                    if (!readLink && file == null)
                    {
                        fileDao.InvalidateCache(id);

                        int version;
                        file = int.TryParse(context.Request[FilesLinkUtility.Version], out version) && version > 0
                                   ? fileDao.GetFile(id, version)
                                   : fileDao.GetFile(id);
                    }

                    if (file == null)
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                        return;
                    }

                    if (!readLink && !Global.GetFilesSecurity().CanRead(file))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        return;
                    }

                    if (!string.IsNullOrEmpty(file.Error))
                    {
                        throw new Exception(file.Error);
                    }

                    if (!fileDao.IsExistOnStorage(file))
                    {
                        Global.Logger.ErrorFormat("Download file error. File is not exist on storage. File id: {0}.", file.ID);
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                        return;
                    }

                    FileMarker.RemoveMarkAsNew(file);

                    context.Response.Clear();
                    context.Response.ClearHeaders();
                    context.Response.Charset = "utf-8";

                    var title = file.Title.Replace(',', '_');

                    var ext = FileUtility.GetFileExtension(file.Title);

                    var outType = context.Request[FilesLinkUtility.OutType];

                    if (!string.IsNullOrEmpty(outType))
                    {
                        outType = outType.Trim();
                        if (FileUtility.ExtsConvertible[ext].Contains(outType))
                        {
                            ext = outType;

                            title = FileUtility.ReplaceFileExtension(title, ext);
                        }
                    }

                    context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(title));
                    context.Response.ContentType = MimeMapping.GetMimeMapping(title);

                    //// Download file via nginx
                    //if (CoreContext.Configuration.Standalone &&
                    //    WorkContext.IsMono &&
                    //    Global.GetStore() is DiscDataStore &&
                    //    !file.ProviderEntry &&
                    //    !FileConverter.EnableConvert(file, ext)
                    //    )
                    //{
                    //    var diskDataStore = (DiscDataStore)Global.GetStore();

                    //    var pathToFile = diskDataStore.GetPhysicalPath(String.Empty, FileDao.GetUniqFilePath(file));

                    //    context.Response.Headers.Add("X-Accel-Redirect", "/filesData" + pathToFile);

                    //    FilesMessageService.Send(file, context.Request, MessageAction.FileDownloaded, file.Title);

                    //    return;
                    //}

                    if (string.Equals(context.Request.Headers["If-None-Match"], GetEtag(file)))
                    {
                        //Its cached. Reply 304
                        context.Response.StatusCode = (int)HttpStatusCode.NotModified;
                        context.Response.Cache.SetETag(GetEtag(file));
                    }
                    else
                    {
                        context.Response.CacheControl = "public";
                        context.Response.Cache.SetETag(GetEtag(file));
                        context.Response.Cache.SetCacheability(HttpCacheability.Public);

                        Stream fileStream = null;

                        try
                        {
                            if (file.ContentLength <= SetupInfo.AvailableFileSize)
                            {
                                if (!FileConverter.EnableConvert(file, ext))
                                {
                                    if (!readLink && fileDao.IsSupportedPreSignedUri(file))
                                    {
                                        context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true);

                                        return;
                                    }

                                    fileStream = fileDao.GetFileStream(file);
                                    context.Response.AddHeader("Content-Length", file.ContentLength.ToString(CultureInfo.InvariantCulture));
                                }
                                else
                                {
                                    fileStream = FileConverter.Exec(file, ext);
                                    context.Response.AddHeader("Content-Length", fileStream.Length.ToString(CultureInfo.InvariantCulture));
                                }

                                fileStream.StreamCopyTo(context.Response.OutputStream);

                                if (!context.Response.IsClientConnected)
                                {
                                    Global.Logger.Warn(String.Format("Download file error {0} {1} Connection is lost. Too long to buffer the file", file.Title, file.ID));
                                }

                                FilesMessageService.Send(file, context.Request, MessageAction.FileDownloaded, file.Title);

                                context.Response.Flush();
                                flushed = true;
                            }
                            else
                            {
                                context.Response.Buffer = false;

                                context.Response.ContentType = "application/octet-stream";

                                long offset = 0;

                                if (context.Request.Headers["Range"] != null)
                                {
                                    context.Response.StatusCode = 206;
                                    var range = context.Request.Headers["Range"].Split(new[] { '=', '-' });
                                    offset = Convert.ToInt64(range[1]);
                                }

                                if (offset > 0)
                                {
                                    Global.Logger.Info("Starting file download offset is " + offset);
                                }

                                context.Response.AddHeader("Connection", "Keep-Alive");
                                context.Response.AddHeader("Accept-Ranges", "bytes");

                                if (offset > 0)
                                {
                                    context.Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", offset, file.ContentLength - 1, file.ContentLength));
                                }

                                var       dataToRead = file.ContentLength;
                                const int bufferSize = 8 * 1024; // 8KB
                                var       buffer     = new Byte[bufferSize];

                                if (!FileConverter.EnableConvert(file, ext))
                                {
                                    if (!readLink && fileDao.IsSupportedPreSignedUri(file))
                                    {
                                        context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true);

                                        return;
                                    }

                                    fileStream = fileDao.GetFileStream(file, offset);
                                    context.Response.AddHeader("Content-Length", (file.ContentLength - offset).ToString(CultureInfo.InvariantCulture));
                                }
                                else
                                {
                                    fileStream = FileConverter.Exec(file, ext);

                                    if (offset > 0)
                                    {
                                        var startBytes = offset;

                                        while (startBytes > 0)
                                        {
                                            long readCount;

                                            if (bufferSize >= startBytes)
                                            {
                                                readCount = startBytes;
                                            }
                                            else
                                            {
                                                readCount = bufferSize;
                                            }

                                            var length = fileStream.Read(buffer, 0, (int)readCount);

                                            startBytes -= length;
                                        }
                                    }
                                }

                                while (dataToRead > 0)
                                {
                                    int length;

                                    try
                                    {
                                        length = fileStream.Read(buffer, 0, bufferSize);
                                    }
                                    catch (HttpException exception)
                                    {
                                        Global.Logger.Error(
                                            String.Format("Read from stream is error. Download file {0} {1}. Maybe Connection is lost.?? Error is {2} ",
                                                          file.Title,
                                                          file.ID,
                                                          exception
                                                          ));

                                        throw;
                                    }

                                    if (context.Response.IsClientConnected)
                                    {
                                        context.Response.OutputStream.Write(buffer, 0, length);
                                        context.Response.Flush();
                                        flushed    = true;
                                        dataToRead = dataToRead - length;
                                    }
                                    else
                                    {
                                        dataToRead = -1;
                                        Global.Logger.Warn(String.Format("IsClientConnected is false. Why? Download file {0} {1} Connection is lost. ", file.Title, file.ID));
                                    }
                                }
                            }
                        }
                        catch (ThreadAbortException)
                        {
                        }
                        catch (HttpException e)
                        {
                            throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
                        }
                        finally
                        {
                            if (fileStream != null)
                            {
                                fileStream.Close();
                                fileStream.Dispose();
                            }
                        }

                        try
                        {
                            context.Response.End();
                            flushed = true;
                        }
                        catch (HttpException)
                        {
                        }
                    }
                }
            }
            catch (ThreadAbortException)
            {
            }
            catch (Exception ex)
            {
                // Get stack trace for the exception with source file information
                var st = new StackTrace(ex, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();

                Global.Logger.ErrorFormat("Url: {0} {1} IsClientConnected:{2}, line number:{3} frame:{4}", context.Request.Url, ex, context.Response.IsClientConnected, line, frame);
                if (!flushed && context.Response.IsClientConnected)
                {
                    context.Response.StatusCode = 400;
                    context.Response.Write(HttpUtility.HtmlEncode(ex.Message));
                }
            }
        }
        private void MoveOrCopyFiles(ICollection fileIds, Folder toFolder, bool copy, FileConflictResolveType resolveType)
        {
            if (fileIds.Count == 0)
            {
                return;
            }

            var toFolderId = toFolder.ID;

            foreach (var fileId in fileIds)
            {
                if (Canceled)
                {
                    return;
                }

                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 &&
                         !Studio.Utility.FileUtility.ExtsUploadable.Contains(Studio.Utility.FileUtility.GetFileExtension(file.Title)))
                {
                    Error = FilesCommonResource.ErrorMassage_NotSupportedFormat;
                }
                else if (!Equals(file.FolderID.ToString(), toFolderId))
                {
                    try
                    {
                        var conflict = FileDao.GetFile(toFolderId, file.Title);
                        if (conflict != null && !FilesSecurity.CanEdit(conflict))
                        {
                            Error = FilesCommonResource.ErrorMassage_SecurityException;
                        }
                        else if (conflict == null)
                        {
                            if (copy)
                            {
                                File newFile = null;
                                try
                                {
                                    newFile = FileDao.CopyFile(file.ID, toFolderId); //Stream copy will occur inside dao

                                    if (Equals(newFile.FolderID.ToString(), _toFolderId))
                                    {
                                        _needToMarkAsNew.Add(newFile);
                                    }

                                    ProcessedFile(fileId);
                                }
                                catch
                                {
                                    if (newFile != null)
                                    {
                                        FileDao.DeleteFile(newFile.ID);
                                    }
                                    throw;
                                }
                            }
                            else
                            {
                                if ((file.FileStatus & FileStatus.IsEditing) == FileStatus.IsEditing)
                                {
                                    Error = FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile;
                                }
                                else if (FilesSecurity.CanDelete(file))
                                {
                                    FileMarker.RemoveMarkAsNewForAll(file);

                                    var newFileId = FileDao.MoveFile(file.ID, toFolderId);

                                    if (Equals(toFolderId.ToString(), _toFolderId))
                                    {
                                        _needToMarkAsNew.Add(FileDao.GetFile(newFileId));
                                    }

                                    ProcessedFile(fileId);
                                }
                                else
                                {
                                    Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFile;
                                }
                            }
                        }
                        else
                        {
                            if (resolveType == FileConflictResolveType.Overwrite)
                            {
                                conflict.Version++;
                                using (var stream = FileDao.GetFileStream(file))
                                {
                                    conflict.ContentLength = stream.Length;
                                    conflict = FileDao.SaveFile(conflict, stream);

                                    _needToMarkAsNew.Add(conflict);
                                }

                                if (copy)
                                {
                                    ProcessedFile(fileId);
                                }
                                else
                                {
                                    if ((file.FileStatus & FileStatus.IsEditing) == FileStatus.IsEditing)
                                    {
                                        Error = FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile;
                                    }
                                    else if (FilesSecurity.CanDelete(file))
                                    {
                                        FileDao.DeleteFile(file.ID);
                                        FileDao.DeleteFolder(file.ID);
                                        ProcessedFile(fileId);
                                    }
                                    else
                                    {
                                        Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFile;
                                    }
                                }
                            }
                            else if (resolveType == FileConflictResolveType.Skip)
                            {
                                //nothing
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ex.Message;
                        Logger.Error(Error, ex);
                    }
                }
                ProgressStep();
            }
        }
Beispiel #10
0
 public void Deconstruct(out FileMarker fileMarker, out FilesMessageService filesMessageService)
 {
     fileMarker          = FileMarker;
     filesMessageService = FilesMessageService;
 }
Beispiel #11
0
 public FileDeleteOperationScope(FileMarker fileMarker, FilesMessageService filesMessageService)
 {
     FileMarker          = fileMarker;
     FilesMessageService = filesMessageService;
 }
Beispiel #12
0
        private static void SaveFile(HttpContext context)
        {
            try
            {
                var shareLinkKey = context.Request[CommonLinkUtility.DocShareKey] ?? "";

                var fileID = context.Request[CommonLinkUtility.FileId];

                if (string.IsNullOrEmpty(fileID))
                {
                    throw new ArgumentNullException(fileID);
                }

                var downloadUri = context.Request[CommonLinkUtility.FileUri];
                if (string.IsNullOrEmpty(downloadUri))
                {
                    throw new ArgumentNullException(downloadUri);
                }

                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    File file;

                    var checkLink = FileShareLink.Check(shareLinkKey, false, fileDao, out file);
                    if (!checkLink && file == null)
                    {
                        file = fileDao.GetFile(fileID);
                    }

                    if (file == null)
                    {
                        throw new HttpException((int)HttpStatusCode.NotFound, FilesCommonResource.ErrorMassage_FileNotFound);
                    }
                    if (!checkLink && (!Global.GetFilesSecurity().CanEdit(file) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                    }
                    if (file.RootFolderType == FolderType.TRASH)
                    {
                        throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_ViewTrashItem);
                    }

                    var versionEdit   = context.Request[CommonLinkUtility.Version];
                    var currentType   = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title);
                    var newType       = FileUtility.GetFileExtension(downloadUri);
                    var updateVersion = file.Version > 1 || file.ConvertedType == null || string.IsNullOrEmpty(context.Request[UrlConstant.New]);

                    if ((string.IsNullOrEmpty(versionEdit) || file.Version <= Convert.ToInt32(versionEdit) || currentType != newType) &&
                        updateVersion &&
                        !FileLocker.LockVersion(file.ID))
                    {
                        file.Version++;
                    }

                    file.ConvertedType = newType;

                    if (file.ProviderEntry && !newType.Equals(currentType))
                    {
                        var key = DocumentServiceConnector.GenerateRevisionId(downloadUri);

                        DocumentServiceConnector.GetConvertedUri(downloadUri, newType, currentType, key, false, out downloadUri);
                    }

                    var req = (HttpWebRequest)WebRequest.Create(downloadUri);

                    using (var editedFileStream = new ResponseStream(req.GetResponse()))
                    {
                        file.ContentLength = editedFileStream.Length;

                        file = fileDao.SaveFile(file, editedFileStream);
                    }

                    bool checkRight;
                    var  tabId = new Guid(context.Request["tabId"]);
                    FileLocker.ProlongLock(file.ID, tabId, true, out checkRight);
                    if (checkRight)
                    {
                        FileLocker.ChangeRight(file.ID, SecurityContext.CurrentAccount.ID, false);
                    }

                    FileMarker.MarkAsNew(file);
                    FileMarker.RemoveMarkAsNew(file);
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error(ex.Message, ex);
                context.Response.Write("{ \"error\": \"true\", \"message\": \"" + ex.Message + "\" }");
            }
        }
Beispiel #13
0
        private static void DownloadFile(HttpContext context, bool inline)
        {
            if (!string.IsNullOrEmpty(context.Request[CommonLinkUtility.TryParam]))
            {
                DownloadTry(context);
                return;
            }

            try
            {
                var id           = context.Request[CommonLinkUtility.FileId];
                var shareLinkKey = context.Request[CommonLinkUtility.DocShareKey] ?? "";

                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    File file;
                    var  checkLink = FileShareLink.Check(shareLinkKey, true, fileDao, out file);
                    if (!checkLink && file == null)
                    {
                        int version;
                        file = int.TryParse(context.Request[CommonLinkUtility.Version], out version) && version > 0
                                   ? fileDao.GetFile(id, version)
                                   : fileDao.GetFile(id);
                    }

                    if (file == null)
                    {
                        context.Response.Redirect("~/404.htm");

                        return;
                    }

                    if (!checkLink && !Global.GetFilesSecurity().CanRead(file))
                    {
                        context.Response.Redirect((context.Request.UrlReferrer != null
                                                       ? context.Request.UrlReferrer.ToString()
                                                       : PathProvider.StartURL)
                                                  + "#" + UrlConstant.Error + "/" +
                                                  HttpUtility.UrlEncode(FilesCommonResource.ErrorMassage_SecurityException_ReadFile));
                        return;
                    }

                    if (!fileDao.IsExistOnStorage(file))
                    {
                        Global.Logger.ErrorFormat("Download file error. File is not exist on storage. File id: {0}.", file.ID);
                        context.Response.Redirect("~/404.htm");

                        return;
                    }

                    FileMarker.RemoveMarkAsNew(file);

                    context.Response.Clear();
                    context.Response.ContentType = MimeMapping.GetMimeMapping(file.Title);
                    context.Response.Charset     = "utf-8";

                    var browser = context.Request.Browser.Browser;
                    var title   = file.Title.Replace(',', '_');

                    var ext = FileUtility.GetFileExtension(file.Title);

                    var outType  = string.Empty;
                    var curQuota = TenantExtra.GetTenantQuota();
                    if (curQuota.DocsEdition || FileUtility.InternalExtension.Values.Contains(ext))
                    {
                        outType = context.Request[CommonLinkUtility.OutType];
                    }

                    if (!string.IsNullOrEmpty(outType) && !inline)
                    {
                        outType = outType.Trim();
                        if (FileUtility.ExtsConvertible[ext].Contains(outType))
                        {
                            ext = outType;

                            title = FileUtility.ReplaceFileExtension(title, ext);
                        }
                    }

                    context.Response.AddHeader("Content-Disposition", ContentDispositionUtil.GetHeaderValue(title, inline));

                    if (inline && string.Equals(context.Request.Headers["If-None-Match"], GetEtag(file)))
                    {
                        //Its cached. Reply 304
                        context.Response.StatusCode = (int)HttpStatusCode.NotModified;
                        context.Response.Cache.SetETag(GetEtag(file));
                    }
                    else
                    {
                        context.Response.CacheControl = "public";
                        context.Response.Cache.SetETag(GetEtag(file));
                        context.Response.Cache.SetCacheability(HttpCacheability.Public);

                        Stream fileStream = null;

                        try
                        {
                            if (file.ContentLength <= SetupInfo.AvailableFileSize)
                            {
                                if (file.ConvertedType == null && (string.IsNullOrEmpty(outType) || inline))
                                {
                                    context.Response.AddHeader("Content-Length", file.ContentLength.ToString(CultureInfo.InvariantCulture));

                                    if (fileDao.IsSupportedPreSignedUri(file))
                                    {
                                        context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true);

                                        return;
                                    }

                                    fileStream = fileDao.GetFileStream(file);
                                }
                                else
                                {
                                    fileStream = FileConverter.Exec(file, ext);
                                }

                                fileStream.StreamCopyTo(context.Response.OutputStream);

                                if (!context.Response.IsClientConnected)
                                {
                                    Global.Logger.Error(String.Format("Download file error {0} {1} Connection is lost. Too long to buffer the file", file.Title, file.ID));
                                }

                                context.Response.Flush();
                            }
                            else
                            {
                                long offset = 0;

                                if (context.Request.Headers["Range"] != null)
                                {
                                    context.Response.StatusCode = 206;
                                    var range = context.Request.Headers["Range"].Split(new[] { '=', '-' });
                                    offset = Convert.ToInt64(range[1]);
                                }

                                if (offset > 0)
                                {
                                    Global.Logger.Info("Starting file download offset is " + offset);
                                }

                                context.Response.AddHeader("Connection", "Keep-Alive");
                                context.Response.AddHeader("Accept-Ranges", "bytes");

                                if (offset > 0)
                                {
                                    context.Response.AddHeader("Content-Range", String.Format(" bytes {0}-{1}/{2}", offset, file.ContentLength - 1, file.ContentLength));
                                }

                                var       dataToRead = file.ContentLength;
                                const int bufferSize = 1024;
                                var       buffer     = new Byte[bufferSize];

                                if (file.ConvertedType == null && (string.IsNullOrEmpty(outType) || inline))
                                {
                                    if (fileDao.IsSupportedPreSignedUri(file))
                                    {
                                        context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true);

                                        return;
                                    }

                                    fileStream = fileDao.GetFileStream(file, offset);
                                    context.Response.AddHeader("Content-Length", (file.ContentLength - offset).ToString(CultureInfo.InvariantCulture));
                                }
                                else
                                {
                                    fileStream = FileConverter.Exec(file, ext);

                                    if (offset > 0)
                                    {
                                        var startBytes = offset;

                                        while (startBytes > 0)
                                        {
                                            long readCount;

                                            if (bufferSize >= startBytes)
                                            {
                                                readCount = startBytes;
                                            }
                                            else
                                            {
                                                readCount = bufferSize;
                                            }

                                            var length = fileStream.Read(buffer, 0, (int)readCount);

                                            startBytes -= length;
                                        }
                                    }
                                }

                                while (dataToRead > 0)
                                {
                                    int length;

                                    try
                                    {
                                        length = fileStream.Read(buffer, 0, bufferSize);
                                    }
                                    catch (HttpException exception)
                                    {
                                        Global.Logger.Error(
                                            String.Format("Read from stream is error. Download file {0} {1}. Maybe Connection is lost.?? Error is {2} ",
                                                          file.Title,
                                                          file.ID,
                                                          exception
                                                          ));

                                        throw;
                                    }

                                    if (context.Response.IsClientConnected)
                                    {
                                        context.Response.OutputStream.Write(buffer, 0, length);
                                        dataToRead = dataToRead - length;
                                    }
                                    else
                                    {
                                        dataToRead = -1;
                                        Global.Logger.Error(String.Format("IsClientConnected is false. Why? Download file {0} {1} Connection is lost. ", file.Title, file.ID));
                                    }
                                }
                            }
                        }
                        catch (HttpException e)
                        {
                            throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
                        }
                        finally
                        {
                            if (fileStream != null)
                            {
                                fileStream.Flush();
                                fileStream.Close();
                                fileStream.Dispose();
                            }
                        }

                        try
                        {
                            context.Response.End();
                        }
                        catch (HttpException)
                        {
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                // Get stack trace for the exception with source file information
                var st = new StackTrace(ex, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();

                Global.Logger.ErrorFormat("Url: {0} {1} IsClientConnected:{2}, line number:{3} frame:{4}", context.Request.Url, ex, context.Response.IsClientConnected, line, frame);
                context.Response.StatusCode = 400;
                context.Response.Write(HttpUtility.HtmlEncode(ex.Message));
            }
        }
        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;
                }
            }
        }
        protected override void Do()
        {
            if (_files.Count == 0)
            {
                return;
            }

            var parent = FolderDao.GetFolder(_parentId);

            if (parent == null)
            {
                throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
            }
            if (!FilesSecurity.CanCreate(parent))
            {
                throw new System.Security.SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
            }
            if (parent.RootFolderType == FolderType.TRASH)
            {
                throw new Exception(FilesCommonResource.ErrorMassage_ImportToTrash);
            }
            if (parent.ProviderEntry)
            {
                throw new System.Security.SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
            }

            var to =
                FolderDao.GetFolder(_folderName, _parentId)
                ?? FolderDao.SaveFolder(
                    new Folder
            {
                FolderType     = FolderType.DEFAULT,
                ParentFolderID = _parentId,
                Title          = _folderName
            });

            foreach (var f in _files)
            {
                if (Canceled)
                {
                    return;
                }
                try
                {
                    long size;
                    using (var stream = _docProvider.GetDocumentStream(f.ContentLink, out size))
                    {
                        if (stream == null)
                        {
                            throw new Exception("Can not import document " + f.ContentLink + ". Empty stream.");
                        }

                        if (SetupInfo.MaxUploadSize < size)
                        {
                            throw FileSizeComment.FileSizeException;
                        }

                        var folderId = to.ID;
                        var pos      = f.Title.LastIndexOf('/');
                        if (0 < pos)
                        {
                            folderId = GetOrCreateHierarchy(f.Title.Substring(0, pos), to);
                            f.Title  = f.Title.Substring(pos + 1);
                        }

                        f.Title = Global.ReplaceInvalidCharsAndTruncate(f.Title);
                        var file = new File
                        {
                            Title         = f.Title,
                            FolderID      = folderId,
                            ContentLength = size,
                        };

                        var conflict = FileDao.GetFile(file.FolderID, file.Title);
                        if (conflict != null)
                        {
                            if (_overwrite)
                            {
                                if (!FilesSecurity.CanEdit(conflict))
                                {
                                    throw new Exception(FilesCommonResource.ErrorMassage_SecurityException);
                                }
                                if ((conflict.FileStatus & FileStatus.IsEditing) == FileStatus.IsEditing)
                                {
                                    throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile);
                                }
                                if (EntryManager.FileLockedForMe(conflict))
                                {
                                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                                }

                                file.ID      = conflict.ID;
                                file.Version = conflict.Version + 1;
                            }
                            else
                            {
                                continue;
                            }
                        }

                        if (size <= 0L)
                        {
                            using (var buffered = stream.GetBuffered())
                            {
                                size = buffered.Length;

                                if (SetupInfo.MaxUploadSize < size)
                                {
                                    throw FileSizeComment.FileSizeException;
                                }

                                file.ContentLength = size;
                                try
                                {
                                    file = FileDao.SaveFile(file, buffered);
                                }
                                catch (Exception error)
                                {
                                    FileDao.DeleteFile(file.ID);
                                    throw error;
                                }
                            }
                        }
                        else
                        {
                            try
                            {
                                file = FileDao.SaveFile(file, stream);
                                FilesMessageService.Send(file, httpRequestHeaders, MessageAction.FileImported, parent.Title, file.Title, _docProvider.Name);
                            }
                            catch (Exception error)
                            {
                                FileDao.DeleteFile(file.ID);
                                throw error;
                            }
                        }

                        FileMarker.MarkAsNew(file, _markAsNewRecipientIDs);
                    }
                }
                catch (Exception ex)
                {
                    Error = ex.Message;
                    Logger.Error(Error, ex);
                }
                finally
                {
                    ProgressStep();
                }
            }
        }
        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)) ?? "";
                    }

                    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, 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 + "=" + file.ID);
                }
            }

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

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_configuration.EditorConfig.ModeWrite)
            {
                _tabId = FileTracker.Add(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;
                }
            }
        }
        private void MoveOrCopyFolders(ICollection folderIds, Folder toFolder, bool copy)
        {
            if (folderIds.Count == 0)
            {
                return;
            }

            var toFolderId = toFolder.ID;
            var isToFolder = Equals(toFolderId.ToString(), _toFolderId);

            foreach (var folderId in folderIds)
            {
                if (Canceled)
                {
                    return;
                }

                var folder = FolderDao.GetFolder(folderId);
                if (folder == null)
                {
                    Error = FilesCommonResource.ErrorMassage_FolderNotFound;
                }
                else if (!FilesSecurity.CanRead(folder))
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException_ReadFolder;
                }
                else if (!Equals((folder.ParentFolderID ?? string.Empty).ToString(), toFolderId.ToString()))
                {
                    try
                    {
                        //if destination folder contains folder with same name then merge folders
                        var conflictFolder = FolderDao.GetFolder(folder.Title, toFolderId);

                        if (copy || conflictFolder != null)
                        {
                            Folder newFolder;
                            if (conflictFolder != null)
                            {
                                newFolder = conflictFolder;

                                if (isToFolder)
                                {
                                    _needToMarkAsNew.Add(conflictFolder);
                                }
                            }
                            else
                            {
                                newFolder = FolderDao.CopyFolder(folder.ID, toFolderId);

                                if (isToFolder)
                                {
                                    _needToMarkAsNew.Add(newFolder);
                                }

                                ProcessedFolder(folderId);
                            }

                            if (FolderDao.UseRecursiveOperation(folder.ID, toFolderId))
                            {
                                MoveOrCopyFiles(FolderDao.GetFiles(folder.ID, false), newFolder, copy, _resolveType);
                                MoveOrCopyFolders(FolderDao.GetFolders(folder.ID).Select(f => f.ID).ToList(), newFolder, copy);

                                if (!copy)
                                {
                                    if (FolderDao.GetItemsCount(folder.ID, true) == 0 && FilesSecurity.CanDelete(folder))
                                    {
                                        FolderDao.DeleteFolder(folder.ID);
                                        ProcessedFolder(folderId);
                                    }
                                }
                            }
                            else
                            {
                                if (conflictFolder != null)
                                {
                                    if (copy)
                                    {
                                        newFolder = FolderDao.CopyFolder(folder.ID, toFolderId);

                                        if (isToFolder)
                                        {
                                            _needToMarkAsNew.Add(newFolder);
                                        }
                                    }
                                    else
                                    {
                                        FolderDao.MoveFolder(folder.ID, toFolderId);

                                        if (isToFolder)
                                        {
                                            _needToMarkAsNew.Add(FolderDao.GetFolder(folder.ID));
                                        }
                                    }

                                    ProcessedFolder(folderId);
                                }
                            }
                        }
                        else
                        {
                            if (FilesSecurity.CanDelete(folder))
                            {
                                FileMarker.RemoveMarkAsNewForAll(folder);

                                FolderDao.MoveFolder(folder.ID, toFolderId);

                                if (isToFolder)
                                {
                                    _needToMarkAsNew.Add(FolderDao.GetFolder(folder.ID));
                                }

                                ProcessedFolder(folderId);
                            }
                            else
                            {
                                Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFolder;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ex.Message;

                        Logger.Error(Error, ex);
                    }
                }
                ProgressStep();
            }
        }
        private static void DownloadFile(HttpContext context)
        {
            var flushed = false;

            try
            {
                var id  = context.Request[FilesLinkUtility.FileId];
                var doc = context.Request[FilesLinkUtility.DocShareKey] ?? "";

                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    File file;
                    var  readLink = FileShareLink.Check(doc, true, fileDao, out file);
                    if (!readLink && file == null)
                    {
                        fileDao.InvalidateCache(id);

                        int version;
                        file = int.TryParse(context.Request[FilesLinkUtility.Version], out version) && version > 0
                                   ? fileDao.GetFile(id, version)
                                   : fileDao.GetFile(id);
                    }

                    if (file == null)
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                        return;
                    }

                    if (!readLink && !Global.GetFilesSecurity().CanRead(file))
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        return;
                    }

                    if (!string.IsNullOrEmpty(file.Error))
                    {
                        throw new Exception(file.Error);
                    }

                    if (!fileDao.IsExistOnStorage(file))
                    {
                        Global.Logger.ErrorFormat("Download file error. File is not exist on storage. File id: {0}.", file.ID);
                        context.Response.StatusCode = (int)HttpStatusCode.NotFound;

                        return;
                    }

                    FileMarker.RemoveMarkAsNew(file);

                    context.Response.Clear();
                    context.Response.ClearHeaders();
                    context.Response.Charset = "utf-8";

                    FilesMessageService.Send(file, context.Request, MessageAction.FileDownloaded, file.Title);

                    if (string.Equals(context.Request.Headers["If-None-Match"], GetEtag(file)))
                    {
                        //Its cached. Reply 304
                        context.Response.StatusCode = (int)HttpStatusCode.NotModified;
                        context.Response.Cache.SetETag(GetEtag(file));
                    }
                    else
                    {
                        context.Response.CacheControl = "public";
                        context.Response.Cache.SetETag(GetEtag(file));
                        context.Response.Cache.SetCacheability(HttpCacheability.Public);

                        Stream fileStream = null;
                        try
                        {
                            var title = file.Title;

                            if (file.ContentLength <= SetupInfo.AvailableFileSize)
                            {
                                var ext = FileUtility.GetFileExtension(file.Title);

                                var outType = (context.Request[FilesLinkUtility.OutType] ?? "").Trim();
                                if (!string.IsNullOrEmpty(outType) &&
                                    FileUtility.ExtsConvertible.Keys.Contains(ext) &&
                                    FileUtility.ExtsConvertible[ext].Contains(outType))
                                {
                                    ext = outType;
                                }

                                long offset = 0;
                                long length;
                                if (!file.ProviderEntry &&
                                    string.Equals(context.Request["convpreview"], "true", StringComparison.InvariantCultureIgnoreCase) &&
                                    FFmpegService.IsConvertable(ext))
                                {
                                    const string mp4Name = "content.mp4";
                                    var          mp4Path = FileDao.GetUniqFilePath(file, mp4Name);
                                    var          store   = Global.GetStore();
                                    if (!store.IsFile(mp4Path))
                                    {
                                        fileStream = fileDao.GetFileStream(file);

                                        Global.Logger.InfoFormat("Converting {0} (fileId: {1}) to mp4", file.Title, file.ID);
                                        var stream = FFmpegService.Convert(fileStream, ext);
                                        store.Save(string.Empty, mp4Path, stream, mp4Name);
                                    }

                                    var fullLength = store.GetFileSize(string.Empty, mp4Path);

                                    length     = ProcessRangeHeader(context, fullLength, ref offset);
                                    fileStream = store.GetReadStream(string.Empty, mp4Path, (int)offset);

                                    title = FileUtility.ReplaceFileExtension(title, ".mp4");
                                }
                                else
                                {
                                    if (!FileConverter.EnableConvert(file, ext))
                                    {
                                        if (!readLink && fileDao.IsSupportedPreSignedUri(file))
                                        {
                                            context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true);

                                            return;
                                        }

                                        fileStream = fileDao.GetFileStream(file); // getStream to fix file.ContentLength

                                        if (fileStream.CanSeek)
                                        {
                                            var fullLength = file.ContentLength;
                                            length = ProcessRangeHeader(context, fullLength, ref offset);
                                            fileStream.Seek(offset, SeekOrigin.Begin);
                                        }
                                        else
                                        {
                                            length = file.ContentLength;
                                        }
                                    }
                                    else
                                    {
                                        title      = FileUtility.ReplaceFileExtension(title, ext);
                                        fileStream = FileConverter.Exec(file, ext);

                                        length = fileStream.Length;
                                    }
                                }

                                SendStreamByChunks(context, length, title, fileStream, ref flushed);
                            }
                            else
                            {
                                if (!readLink && fileDao.IsSupportedPreSignedUri(file))
                                {
                                    context.Response.Redirect(fileDao.GetPreSignedUri(file, TimeSpan.FromHours(1)).ToString(), true);

                                    return;
                                }

                                fileStream = fileDao.GetFileStream(file); // getStream to fix file.ContentLength

                                long offset = 0;
                                var  length = file.ContentLength;
                                if (fileStream.CanSeek)
                                {
                                    length = ProcessRangeHeader(context, file.ContentLength, ref offset);
                                    fileStream.Seek(offset, SeekOrigin.Begin);
                                }

                                SendStreamByChunks(context, length, title, fileStream, ref flushed);
                            }
                        }
                        catch (ThreadAbortException tae)
                        {
                            Global.Logger.Error("DownloadFile", tae);
                        }
                        catch (HttpException e)
                        {
                            Global.Logger.Error("DownloadFile", e);
                            throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
                        }
                        finally
                        {
                            if (fileStream != null)
                            {
                                fileStream.Close();
                                fileStream.Dispose();
                            }
                        }

                        try
                        {
                            context.Response.Flush();
                            context.Response.SuppressContent = true;
                            context.ApplicationInstance.CompleteRequest();
                            flushed = true;
                        }
                        catch (HttpException ex)
                        {
                            Global.Logger.Error("DownloadFile", ex);
                        }
                    }
                }
            }
            catch (ThreadAbortException tae)
            {
                Global.Logger.Error("DownloadFile", tae);
            }
            catch (Exception ex)
            {
                // Get stack trace for the exception with source file information
                var st = new StackTrace(ex, true);
                // Get the top stack frame
                var frame = st.GetFrame(0);
                // Get the line number from the stack frame
                var line = frame.GetFileLineNumber();

                Global.Logger.ErrorFormat("Url: {0} {1} IsClientConnected:{2}, line number:{3} frame:{4}", context.Request.Url, ex, context.Response.IsClientConnected, line, frame);
                if (!flushed && context.Response.IsClientConnected)
                {
                    context.Response.StatusCode = 400;
                    context.Response.Write(HttpUtility.HtmlEncode(ex.Message));
                }
            }
        }
        public static File SaveDocument(string envelopeId, string documentId, string documentName, object folderId)
        {
            if (string.IsNullOrEmpty(envelopeId))
            {
                throw new ArgumentNullException("envelopeId");
            }
            if (string.IsNullOrEmpty(documentId))
            {
                throw new ArgumentNullException("documentId");
            }

            var token         = DocuSignToken.GetToken();
            var account       = GetDocuSignAccount(token);
            var configuration = GetConfiguration(account, token);

            using (var fileDao = Global.DaoFactory.GetFileDao())
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    if (string.IsNullOrEmpty(documentName))
                    {
                        documentName = "new.pdf";
                    }

                    Folder folder;
                    if (folderId == null ||
                        (folder = folderDao.GetFolder(folderId)) == null ||
                        folder.RootFolderType == FolderType.TRASH ||
                        !Global.GetFilesSecurity().CanCreate(folder))
                    {
                        if (Global.FolderMy != null)
                        {
                            folderId = Global.FolderMy;
                        }
                        else
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
                        }
                    }

                    var file = new File
                    {
                        FolderID = folderId,
                        Comment  = FilesCommonResource.CommentCreateByDocuSign,
                        Title    = FileUtility.ReplaceFileExtension(documentName, ".pdf"),
                    };

                    var envelopesApi = new EnvelopesApi(configuration);
                    Log.Info("DocuSign webhook get stream: " + documentId);
                    using (var stream = envelopesApi.GetDocument(account.AccountId, envelopeId, documentId))
                    {
                        file.ContentLength = stream.Length;
                        file = fileDao.SaveFile(file, stream);
                    }

                    FilesMessageService.Send(file, MessageInitiator.ThirdPartyProvider, MessageAction.DocumentSignComplete, "DocuSign", file.Title);

                    FileMarker.MarkAsNew(file);

                    return(file);
                }
        }
Beispiel #20
0
        /// <summary>
        /// DISTRIBUTES THE FILES AMONGST THE REMOTE STORAGE LOCATIONS
        /// </summary>
        /// <param name="folder">FOLDER WHERE FILE IS TO BE STORED</param>
        /// <param name="fileName">FILENAME OF THE FILE BEING STORED</param>
        /// <param name="replicateCount">NUMBERS OF TIMES TO REPLICATE THE FILE NOT INCLUDING THE INITIAL</param>
        /// <param name="tmpFileName">LOCATION OF THE LOCAL FILE TO UPLOAD</param>
        /// <param name="overWrite">DETERMINE IF THE FILE SHOULD BE OVERWRITTEN IF IT EXISTS</param>
        /// <param name="extraInfo">EXTRA INFO TO STORE ABOUT THE FILE, WARNING: THESE PARAMETERS WILL BE STORED IN PLAIN TEXT</param>
        /// <returns>RETURNS TRUE IF THE FILE WAS SUCCESSFULLY STORED OR FALSE IF IT FAILED</returns>
        private bool DistributeFile(string folder, string fileName, int replicateCount, string tmpFileName, bool overWrite, ExtraInfo[] extraInfo)
        {
            List <string> successfulServers = new List <string>();

            //ALL BELOW CHECKS ARE REALLY DONE TO MAKE SURE THE FILE DOES NOT EXISTS IN THE DATABASE ALREADY
            //VERIFY THE FILENAME AND FOLDER ARE VALID
            if (Regex.Match(fileName, @"[\/:*?""<>|]").Success || Regex.Match(folder, @"[:*?""<>|]").Success)
            {
                throw new ArgumentException("Invalid character(s) detected in filename and or folder");
            }

            //CHECK THE FORMAT OF THE FOLDER
            folder = FormatFolder(folder);

            //IF WE ARE NOT SUPPOSED TO OVERWRITE FILES THEN MAKE SURE IT DOES NOT ALREADY EXISTS IN THE FIRST DB IN THE LIST (IN THEORY IF IT DOES NOT HAVE IT NONE OF THEM SHOULD HAVE IT)
            if (!overWrite)
            {
                using (DistributedFileStorageDBDataContext tmpDB = new DistributedFileStorageDBDataContext(ConfigurationManager.ConnectionStrings.Cast <ConnectionStringSettings>().ToArray().Shuffle()[0].ConnectionString))
                {
                    //IF WE FIND A REFERENCE TO THIS FILE THEN WE NEED TO THROW AN ERROR
                    if ((from a in tmpDB.FileMarkers where a.FileName == fileName && a.Folder == folder select a).Count() != 0)
                    {
                        throw new Exception("File already exists");
                    }
                }
            }
            else
            {
                //DELETE THE FILE MARKER FROM ALL THE DATABASE SERVERS IN THE CONNECTION STRING LIST
                bool firstLoop = true;
                foreach (ConnectionStringSettings tmpConnection in ConfigurationManager.ConnectionStrings)
                {
                    //CREATE A NEW INSTANCE OF THE DATABASE ACCESS
                    using (DistributedFileStorageDBDataContext tmpDB = new DistributedFileStorageDBDataContext(tmpConnection.ConnectionString))
                    {
                        //DELETE ALL OF THE FILELOCATIONS FROM THE DATABASE
                        IEnumerable <FileMarker> tmpMarkers = tmpDB.FileMarkers.Where(a => a.Folder == folder && a.FileName == fileName);

                        //ATTEMPT TO DELETE THE REMOTE FILE TO CLEAR DISK SPACE
                        WebClient tmpClient = new WebClient();
                        if (tmpMarkers.Count() != 0 && firstLoop)
                        {
                            foreach (FileLocation tmpLocation in tmpMarkers.First().FileLocations)
                            {
                                try
                                {
                                    tmpClient.DownloadData(string.Format("{0}DeleteFile.aspx?folder={1}&filename={2}", tmpLocation.Location, Server.UrlEncode(tmpLocation.FileMarker.Folder), Server.UrlEncode(tmpLocation.FileMarker.FileName)));
                                }
                                catch
                                {
                                    //DO NOTHING IF WE ARE UNABLE TO DELETE THE FILE FOR ANY REASON
                                }
                            }
                        }

                        foreach (FileMarker tmpMarker in tmpMarkers)
                        {
                            tmpDB.FileLocations.DeleteAllOnSubmit(tmpMarker.FileLocations);
                        }

                        //DELETE ALL OF THE FILEMARKERS FROM THE DATABASE
                        tmpDB.FileMarkers.DeleteAllOnSubmit(tmpMarkers);

                        //SUBMIT THE CHANGES TO THE DATABASE
                        tmpDB.SubmitChanges();

                        //REMEMBER THIS IS NOT THE FIRST LOOP ANYMORE SO WE DO NOT TRY TO DELETE FILES AGAIN IF IN PMR STATE
                        firstLoop = false;
                    }
                }
            }

            //NOW THE FUN PART TRY TO STORE THE FILE ON ANY SERVER WHICH WILL TAKE IT
            try
            {
                //IF THE TEMP FOLDER DOES NOT EXISTS THEN CREATE IT SO WE CAN STORE THE FILE ON DISK AND UPLOAD IT TO THE REMOTE STORAGE LOCATION
                if (!Directory.Exists(serverSettings.TempFolder))
                {
                    Directory.CreateDirectory(serverSettings.TempFolder);
                }

                //USE WEBCLIENT FOR SIMPLE UPLOADS (THIS MAY NEED TO BE LOOKED INTO FOR DIRECT STREAM WRITING ON LARGE FILES)
                WebClient tmpClient = new WebClient();
                foreach (string chosenServer in (from a in serverSettings.RemoteStorage where a.AccessMode.Contains("w") select a.Path).ToArray().Shuffle())
                {
                    try
                    {
                        string result = UploadFile(string.Format("{0}PutFile.aspx?folder={1}&filename={2}", chosenServer, Server.UrlEncode(folder), Server.UrlEncode(fileName)), tmpFileName);

                        //IF THE FILE UPLOAD WAS A SUCCESS THEN TRACK THE SERVER WE PLACED IT ON
                        if (result.ToLower() == "success")
                        {
                            successfulServers.Add(chosenServer);

                            //IF WE HAVE UPLOADED TO ENOUGH SERVERS TO SATISFY THE REPLICATION NEEDS THEN EXIT OUT AND CONTINUE ON
                            if (successfulServers.Count == replicateCount + 1)
                            {
                                break;
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        Logging.WriteEntry(e.Message, e, new StackTrace(true));
                    }
                }
            }
            catch (Exception e)
            {
                //HANDLE ERROR IF TEMP FOLDER DIES
                Logging.WriteEntry(e.Message, e, new StackTrace(true));
            }

            //IF THE FILE WAS SAVED SUCCESSFULLY THEN RETURN TRUE TO THE USER AND SAVE THE MARKER FILE
            if (successfulServers.Count == replicateCount + 1)
            {
                //CREATE A TEMPORARY MARKER TO BE STORED IN THE DATABASE
                FileInfo   tmpFileInfo = new FileInfo(tmpFileName);
                FileMarker tmpMarker   = new FileMarker();
                tmpMarker.FileMarkerID  = Guid.NewGuid().ToString();
                tmpMarker.FileName      = fileName;
                tmpMarker.Folder        = folder;
                tmpMarker.Length        = tmpFileInfo.Length;
                tmpMarker.Hash          = File.Open(tmpFileName, FileMode.Open).ComputeMD5(true);
                tmpMarker.LastWriteTime = DateTime.Now;
                tmpMarker.LastModTime   = DateTime.Now;
                tmpMarker.LastReadTime  = DateTime.Now;
                tmpMarker.ExtraInfo     = extraInfo != null?System.Text.ASCIIEncoding.ASCII.GetBytes(extraInfo.Serialize().Compress()) : new byte[]
                {
                };
                tmpMarker.FileLocations.AddRange(successfulServers.Select(a => new FileLocation()
                {
                    Location = a, LocationID = Guid.NewGuid().ToString()
                }).ToArray());

                //WRITE THE FILE MARKER TO ALL THE DATABASE SERVERS IN THE CONNECTION STRING LIST
                foreach (ConnectionStringSettings tmpConnection in ConfigurationManager.ConnectionStrings)
                {
                    //CREATE A NEW INSTANCE OF THE DATABASE ACCESS
                    using (DistributedFileStorageDBDataContext tmpDB = new DistributedFileStorageDBDataContext(tmpConnection.ConnectionString))
                    {
                        //ADD THE FILE MARKER AND SUBMIT THE CHANGES
                        tmpDB.FileMarkers.InsertOnSubmit(tmpMarker);
                        tmpDB.SubmitChanges();
                    }
                }

                //RETURN THE SUCCESS TO THE CALLING FUNCTION
                return(true);
            }
            else
            {
                //ATTEMPT TO NOW GO BACK AND DELETE ALL THE FILES WHICH DID SUCCESSFULLY UPLOAD
                WebClient tmpClient = new WebClient();
                foreach (string chosenServer in successfulServers)
                {
                    try
                    {
                        string result = System.Text.ASCIIEncoding.ASCII.GetString(tmpClient.DownloadData(string.Format("{0}DeleteFile.aspx?folder={1}&filename={2}", chosenServer, Server.UrlEncode(folder), Server.UrlEncode(fileName))));
                    }
                    catch (Exception e)
                    {
                        Logging.WriteEntry(e.Message, e, new StackTrace(true));
                    }
                }

                //LET THE CALLING FUNCTION KNOW THE STORE FILE FAILED
                return(false);
            }
        }
Beispiel #21
0
        private void DeleteFolders(List <object> folderIds)
        {
            foreach (var folderId in folderIds)
            {
                CancellationToken.ThrowIfCancellationRequested();

                var folder = FolderDao.GetFolder(folderId);
                if (folder == null)
                {
                    Error = FilesCommonResource.ErrorMassage_FolderNotFound;
                }
                else if (!ignoreException && !FilesSecurity.CanDelete(folder))
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFolder;
                }
                else
                {
                    FileMarker.RemoveMarkAsNewForAll(folder);
                    if (FolderDao.UseTrashForRemove(folder))
                    {
                        var files = FileDao.GetFiles(folder.ID, true);
                        if (!ignoreException && files.Exists(FileTracker.IsEditing))
                        {
                            Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteEditingFolder;
                        }
                        else
                        {
                            FolderDao.MoveFolder(folder.ID, trashId);
                            FilesMessageService.Send(folder, headers, MessageAction.FolderMovedToTrash, folder.Title);

                            ProcessedFolder(folderId);
                        }
                    }
                    else
                    {
                        if (FolderDao.UseRecursiveOperation(folder.ID, null))
                        {
                            DeleteFiles(FileDao.GetFiles(folder.ID, false));
                            DeleteFolders(FolderDao.GetFolders(folder.ID).Select(f => f.ID).ToList());

                            if (FolderDao.GetItemsCount(folder.ID, true) == 0)
                            {
                                FolderDao.DeleteFolder(folder.ID);
                                ProcessedFolder(folderId);
                            }
                        }
                        else
                        {
                            if (folder.ProviderEntry && folder.ID.Equals(folder.RootFolderId))
                            {
                                ProviderDao.RemoveProviderInfo(folder.ProviderId);
                            }
                            else
                            {
                                FolderDao.DeleteFolder(folder.ID);
                            }
                            ProcessedFolder(folderId);
                        }
                    }
                }
                ProgressStep();
            }
        }
Beispiel #22
0
        private void MoveOrCopyFolders(ICollection folderIds, Folder toFolder, bool copy)
        {
            if (folderIds.Count == 0)
            {
                return;
            }

            var toFolderId = toFolder.ID;
            var isToFolder = Equals(toFolderId.ToString(), _toFolderId);

            foreach (var folderId in folderIds)
            {
                CancellationToken.ThrowIfCancellationRequested();

                var folder = FolderDao.GetFolder(folderId);
                if (folder == null)
                {
                    Error = FilesCommonResource.ErrorMassage_FolderNotFound;
                }
                else if (!FilesSecurity.CanRead(folder))
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException_ReadFolder;
                }
                else if (!FilesSecurity.CanDownload(folder))
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException;
                }
                else if (folder.RootFolderType == FolderType.Privacy &&
                         (copy || toFolder.RootFolderType != FolderType.Privacy))
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException_MoveFolder;
                }
                else if (!Equals((folder.ParentFolderID ?? string.Empty).ToString(), toFolderId.ToString()) || _resolveType == FileConflictResolveType.Duplicate)
                {
                    try
                    {
                        //if destination folder contains folder with same name then merge folders
                        var conflictFolder = folder.RootFolderType == FolderType.Privacy
                            ? null
                            : FolderDao.GetFolder(folder.Title, toFolderId);
                        Folder newFolder;

                        if (copy || conflictFolder != null)
                        {
                            if (conflictFolder != null)
                            {
                                newFolder = conflictFolder;

                                if (isToFolder)
                                {
                                    _needToMark.Add(conflictFolder);
                                }
                            }
                            else
                            {
                                newFolder = FolderDao.CopyFolder(folder.ID, toFolderId, CancellationToken);
                                FilesMessageService.Send(newFolder, toFolder, _headers, MessageAction.FolderCopied, newFolder.Title, toFolder.Title);

                                if (isToFolder)
                                {
                                    _needToMark.Add(newFolder);
                                }

                                if (ProcessedFolder(folderId))
                                {
                                    Status += string.Format("folder_{0}{1}", newFolder.ID, SPLIT_CHAR);
                                }
                            }

                            if (toFolder.ProviderId == folder.ProviderId && // crossDao operation is always recursive
                                FolderDao.UseRecursiveOperation(folder.ID, toFolderId))
                            {
                                MoveOrCopyFiles(FileDao.GetFiles(folder.ID), newFolder, copy);
                                MoveOrCopyFolders(FolderDao.GetFolders(folder.ID).Select(f => f.ID).ToList(), newFolder, copy);

                                if (!copy)
                                {
                                    if (!FilesSecurity.CanDelete(folder))
                                    {
                                        Error = FilesCommonResource.ErrorMassage_SecurityException_MoveFolder;
                                    }
                                    else if (FolderDao.IsEmpty(folder.ID))
                                    {
                                        FolderDao.DeleteFolder(folder.ID);
                                        if (ProcessedFolder(folderId))
                                        {
                                            Status += string.Format("folder_{0}{1}", newFolder.ID, SPLIT_CHAR);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                if (conflictFolder != null)
                                {
                                    string tmpError;
                                    object newFolderId;
                                    if (copy)
                                    {
                                        newFolder   = FolderDao.CopyFolder(folder.ID, toFolderId, CancellationToken);
                                        newFolderId = newFolder.ID;
                                        FilesMessageService.Send(newFolder, toFolder, _headers, MessageAction.FolderCopiedWithOverwriting, newFolder.Title, toFolder.Title);

                                        if (isToFolder)
                                        {
                                            _needToMark.Add(newFolder);
                                        }

                                        if (ProcessedFolder(folderId))
                                        {
                                            Status += string.Format("folder_{0}{1}", newFolderId, SPLIT_CHAR);
                                        }
                                    }
                                    else if (!FilesSecurity.CanDelete(folder))
                                    {
                                        Error = FilesCommonResource.ErrorMassage_SecurityException_MoveFolder;
                                    }
                                    else if (WithError(FileDao.GetFiles(folder.ID, new OrderBy(SortedByType.AZ, true), FilterType.FilesOnly, false, Guid.Empty, string.Empty, false, true), out tmpError))
                                    {
                                        Error = tmpError;
                                    }
                                    else
                                    {
                                        FileMarker.RemoveMarkAsNewForAll(folder);

                                        newFolderId = FolderDao.MoveFolder(folder.ID, toFolderId, CancellationToken);
                                        newFolder   = FolderDao.GetFolder(newFolderId);
                                        FilesMessageService.Send(folder, toFolder, _headers, MessageAction.FolderMovedWithOverwriting, folder.Title, toFolder.Title);

                                        if (isToFolder)
                                        {
                                            _needToMark.Add(newFolder);
                                        }

                                        if (ProcessedFolder(folderId))
                                        {
                                            Status += string.Format("folder_{0}{1}", newFolderId, SPLIT_CHAR);
                                        }
                                    }
                                }
                            }
                        }
                        else
                        {
                            string tmpError;
                            if (!FilesSecurity.CanDelete(folder))
                            {
                                Error = FilesCommonResource.ErrorMassage_SecurityException_MoveFolder;
                            }
                            else if (WithError(FileDao.GetFiles(folder.ID, new OrderBy(SortedByType.AZ, true), FilterType.FilesOnly, false, Guid.Empty, string.Empty, false, true), out tmpError))
                            {
                                Error = tmpError;
                            }
                            else
                            {
                                FileMarker.RemoveMarkAsNewForAll(folder);
                                var parentFolder = FolderDao.GetFolder(folder.RootFolderId);

                                var newFolderId = FolderDao.MoveFolder(folder.ID, toFolderId, CancellationToken);
                                newFolder = FolderDao.GetFolder(newFolderId);
                                FilesMessageService.Send(folder, toFolder, _headers, MessageAction.FolderMovedFrom, folder.Title, parentFolder.Title, toFolder.Title);

                                if (isToFolder)
                                {
                                    _needToMark.Add(newFolder);
                                }

                                if (ProcessedFolder(folderId))
                                {
                                    Status += string.Format("folder_{0}{1}", newFolderId, SPLIT_CHAR);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ex.Message;

                        Logger.Error(Error, ex);
                    }
                }
                ProgressStep(FolderDao.CanCalculateSubitems(folderId) ? null : folderId);
            }
        }
Beispiel #23
0
        private static void CreateFile(HttpContext context)
        {
            var responseMessage = context.Request["response"] == "message";
            var folderId        = context.Request[FilesLinkUtility.FolderId];

            if (string.IsNullOrEmpty(folderId))
            {
                folderId = Global.FolderMy.ToString();
            }
            Folder folder;

            using (var folderDao = Global.DaoFactory.GetFolderDao())
            {
                folder = folderDao.GetFolder(folderId);
            }
            if (folder == null)
            {
                throw new HttpException((int)HttpStatusCode.NotFound, FilesCommonResource.ErrorMassage_FolderNotFound);
            }
            if (!Global.GetFilesSecurity().CanCreate(folder))
            {
                throw new HttpException((int)HttpStatusCode.Forbidden, FilesCommonResource.ErrorMassage_SecurityException_Create);
            }

            File file;
            var  fileUri   = context.Request[FilesLinkUtility.FileUri];
            var  fileTitle = context.Request[FilesLinkUtility.FileTitle];

            try
            {
                if (!string.IsNullOrEmpty(fileUri))
                {
                    file = CreateFileFromUri(folder, fileUri, fileTitle);
                }
                else
                {
                    var docType = context.Request["doctype"];
                    file = CreateFileFromTemplate(folder, fileTitle, docType);
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error(ex);
                if (responseMessage)
                {
                    context.Response.Write("error: " + ex.Message);
                    return;
                }
                context.Response.Redirect(PathProvider.StartURL + "#error/" + HttpUtility.UrlEncode(ex.Message), true);
                return;
            }

            FileMarker.MarkAsNew(file);

            if (responseMessage)
            {
                return;
            }
            context.Response.Redirect(
                (context.Request["openfolder"] ?? "").Equals("true")
                    ? PathProvider.GetFolderUrl(file.FolderID)
                    : (FilesLinkUtility.GetFileWebEditorUrl(file.ID) + "#message/" + HttpUtility.UrlEncode(string.Format(FilesCommonResource.MessageFileCreated, folder.Title))));
        }
        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 (file.RootFolderType == FolderType.Privacy &&
                         (copy || toFolder.RootFolderType != FolderType.Privacy))
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException_MoveFile;
                }
                else if (Global.EnableUploadFilter &&
                         !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title)))
                {
                    Error = FilesCommonResource.ErrorMassage_NotSupportedFormat;
                }
                else
                {
                    var parentFolder = FolderDao.GetFolder(file.FolderID);
                    try
                    {
                        var conflict = _resolveType == FileConflictResolveType.Duplicate ||
                                       file.RootFolderType == FolderType.Privacy
                                           ? null
                                           : FileDao.GetFile(toFolderId, file.Title);
                        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(), _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
                            {
                                string tmpError;
                                if (WithError(new[] { file }, out tmpError))
                                {
                                    Error = tmpError;
                                }
                                else
                                {
                                    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(), _toFolderId))
                                    {
                                        _needToMark.Add(newFile);
                                    }

                                    if (ProcessedFile(fileId))
                                    {
                                        Status += string.Format("file_{0}{1}", newFileId, SPLIT_CHAR);
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (_resolveType == FileConflictResolveType.Overwrite)
                            {
                                if (!FilesSecurity.CanEdit(conflict))
                                {
                                    Error = FilesCommonResource.ErrorMassage_SecurityException;
                                }
                                else 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.VersionGroup++;
                                    newFile.PureTitle     = file.PureTitle;
                                    newFile.ConvertedType = file.ConvertedType;
                                    newFile.Comment       = FilesCommonResource.CommentOverwrite;
                                    newFile.Encrypted     = file.Encrypted;

                                    using (var stream = FileDao.GetFileStream(file))
                                    {
                                        newFile.ContentLength = stream.CanSeek ? stream.Length : file.ContentLength;

                                        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
                                        {
                                            string tmpError;
                                            if (WithError(new[] { file }, out tmpError))
                                            {
                                                Error = tmpError;
                                            }
                                            else
                                            {
                                                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 if (_resolveType == FileConflictResolveType.Skip)
                            {
                                //nothing
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ex.Message;
                        Logger.Error(Error, ex);
                    }
                }
                ProgressStep(fileId: FolderDao.CanCalculateSubitems(fileId) ? null : fileId);
            }
        }
Beispiel #25
0
        private void MoveOrCopyFiles(ICollection fileIds, Folder toFolder, bool copy)
        {
            if (fileIds.Count == 0)
            {
                return;
            }

            var toFolderId = toFolder.ID;

            foreach (var fileId in fileIds)
            {
                if (Canceled)
                {
                    return;
                }

                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 (!Equals(file.FolderID.ToString(), toFolderId.ToString()) || _resolveType == FileConflictResolveType.Duplicate)
                {
                    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)
                        {
                            if (copy)
                            {
                                File newFile = null;
                                try
                                {
                                    newFile = FileDao.CopyFile(file.ID, toFolderId); //Stream copy will occur inside dao
                                    FilesMessageService.Send(file, toFolder, httpRequestHeaders, MessageAction.FileCopied, file.Title, parentFolder.Title, toFolder.Title);

                                    if (Equals(newFile.FolderID.ToString(), _toFolderId))
                                    {
                                        _needToMarkAsNew.Add(newFile);
                                    }

                                    if (ProcessedFile(fileId))
                                    {
                                        Status += string.Format("file_{0}{1}", newFile.ID, SplitCharacter);
                                        ResultedFile(newFile.ID);
                                    }
                                }
                                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);
                                    FilesMessageService.Send(file, toFolder, httpRequestHeaders, MessageAction.FileMoved, file.Title, parentFolder.Title, toFolder.Title);

                                    if (Equals(toFolderId.ToString(), _toFolderId))
                                    {
                                        _needToMarkAsNew.Add(FileDao.GetFile(newFileId));
                                    }

                                    if (ProcessedFile(fileId))
                                    {
                                        Status += string.Format("file_{0}{1}", newFileId, SplitCharacter);
                                        ResultedFile(newFileId);
                                    }
                                }
                                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
                                {
                                    conflict.Version++;
                                    using (var stream = FileDao.GetFileStream(file))
                                    {
                                        conflict.ContentLength = stream.Length;
                                        conflict.Comment       = string.Empty;
                                        conflict = FileDao.SaveFile(conflict, stream);

                                        _needToMarkAsNew.Add(conflict);
                                    }

                                    if (copy)
                                    {
                                        FilesMessageService.Send(file, toFolder, httpRequestHeaders, MessageAction.FileCopiedWithOverwriting, file.Title, parentFolder.Title, toFolder.Title);
                                        if (ProcessedFile(fileId))
                                        {
                                            Status += string.Format("file_{0}{1}", conflict.ID, SplitCharacter);
                                            ResultedFile(conflict.ID);
                                        }
                                    }
                                    else
                                    {
                                        if (Equals(file.FolderID.ToString(), toFolderId.ToString()))
                                        {
                                            if (ProcessedFile(fileId))
                                            {
                                                Status += string.Format("file_{0}{1}", conflict.ID, SplitCharacter);
                                                ResultedFile(conflict.ID);
                                            }
                                        }
                                        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);
                                                FileDao.DeleteFolder(file.ID);

                                                FilesMessageService.Send(file, toFolder, httpRequestHeaders, MessageAction.FileMovedWithOverwriting, file.Title, parentFolder.Title, toFolder.Title);

                                                if (ProcessedFile(fileId))
                                                {
                                                    Status += string.Format("file_{0}{1}", conflict.ID, SplitCharacter);
                                                    ResultedFile(conflict.ID);
                                                }
                                            }
                                            else
                                            {
                                                Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFile;
                                            }
                                        }
                                    }
                                }
                            }
                            else if (_resolveType == FileConflictResolveType.Skip)
                            {
                                //nothing
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Error = ex.Message;
                        Logger.Error(Error, ex);
                    }
                }
                ProgressStep();
            }
        }
        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;
                    _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;

            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 (!isExtenral)
            {
                _docKeyForTrack = DocumentServiceHelper.GetDocKey(file.ID, -1, DateTime.MinValue);

                FileMarker.RemoveMarkAsNew(file);
            }

            if (SecurityContext.IsAuthenticated)
            {
                _configuration.EditorConfig.SaveAsUrl = _configuration.EditorConfig.MergeFolderUrl = 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 (FileConverter.MustConvert(_configuration.Document.Info.File))
                {
                    _editByUrl = true;
                }
            }

            var actionAnchor = Request[FilesLinkUtility.Anchor];

            if (!string.IsNullOrEmpty(actionAnchor))
            {
                _configuration.EditorConfig.ActionLinkString = actionAnchor;
            }
        }
        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)
                        {
                            if (copy)
                            {
                                File newFile = null;
                                try
                                {
                                    newFile = FileDao.CopyFile(file.ID, toFolderId); //Stream copy will occur inside dao
                                    FilesMessageService.Send(file, toFolder, headers, MessageAction.FileCopied, file.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);
                                    FilesMessageService.Send(file, toFolder, headers, MessageAction.FileMoved, file.Title, parentFolder.Title, toFolder.Title);

                                    if (Equals(toFolderId.ToString(), this.toFolderId))
                                    {
                                        needToMark.Add(FileDao.GetFile(newFileId));
                                    }

                                    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 = conflict.ContentLength;

                                    using (var stream = FileDao.GetFileStream(file))
                                    {
                                        newFile = FileDao.SaveFile(newFile, stream);
                                    }

                                    needToMark.Add(newFile);

                                    if (copy)
                                    {
                                        FilesMessageService.Send(file, toFolder, headers, MessageAction.FileCopiedWithOverwriting, file.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);
                                                FileDao.DeleteFolder(file.ID);

                                                FilesMessageService.Send(file, 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);
            }
        }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded && !IsMobile;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            if (!ItsTry)
            {
                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;
                }
            }
            else
            {
                FileType tryType;
                try
                {
                    tryType = (FileType)Enum.Parse(typeof(FileType), Request[FilesLinkUtility.TryParam]);
                }
                catch
                {
                    tryType = FileType.Document;
                }

                var path = "demo";
                if (!IsMobile)
                {
                    path = FileConstant.NewDocPath + CultureInfo.CurrentUICulture.TwoLetterISOLanguageName + "/";
                    if (!Global.GetStoreTemplate().IsDirectory(path))
                    {
                        path = FileConstant.NewDocPath + "default/";
                    }

                    path += "new";
                }

                path += FileUtility.InternalExtension[tryType];

                var store = Global.GetStoreTemplate();
                fileUri = store.GetUri("", path).ToString();

                var fileTitle = "Demo" + FileUtility.InternalExtension[tryType];
                file = new File
                {
                    ID    = Guid.NewGuid(),
                    Title = Global.ReplaceInvalidCharsAndTruncate(fileTitle)
                };

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

                _docParams.FileUri = CommonLinkUtility.GetFullAbsolutePath(fileUri);
                _editByUrl         = true;
                _docParams.Lang    = CultureInfo.CurrentUICulture.Name;
            }

            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 = HeaderStringHelper.GetPageTitle(file.Title);

            _newScheme = FileUtility.ExtsNewService.Contains(FileUtility.GetFileExtension(file.Title));
            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);

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

            if (_docParams.ModeWrite)
            {
                _tabId        = FileTracker.Add(file.ID, _fileNew);
                _fixedVersion = FileTracker.FixedVersion(file.ID);

                if (ItsTry)
                {
                    AppendAuthControl();
                }
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                            : FileConverter.MustConvert(_docParams.File) || _newScheme
                                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID))
                                                  : string.Empty;
            }

            if (CoreContext.Configuration.Personal && IsMobile)
            {
                _docParams.CanEdit = false;
            }
        }
Beispiel #29
0
 public GlobalFolderHelper(FileMarker fileMarker, IDaoFactory daoFactory, GlobalFolder globalFolder)
 {
     FileMarker   = fileMarker;
     DaoFactory   = daoFactory;
     GlobalFolder = globalFolder;
 }
Beispiel #30
0
        private void DeleteFolders(List <object> folderIds)
        {
            foreach (var folderId in folderIds)
            {
                CancellationToken.ThrowIfCancellationRequested();

                var    folder       = FolderDao.GetFolder(folderId);
                object canCalculate = null;
                if (folder == null)
                {
                    Error = FilesCommonResource.ErrorMassage_FolderNotFound;
                }
                else if (folder.FolderType != FolderType.DEFAULT && folder.FolderType != FolderType.BUNCH)
                {
                    Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFolder;
                }
                else if (!ignoreException && !FilesSecurity.CanDelete(folder))
                {
                    canCalculate = FolderDao.CanCalculateSubitems(folderId) ? null : folderId;

                    Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteFolder;
                }
                else
                {
                    canCalculate = FolderDao.CanCalculateSubitems(folderId) ? null : folderId;

                    FileMarker.RemoveMarkAsNewForAll(folder);
                    if (folder.ProviderEntry && folder.ID.Equals(folder.RootFolderId))
                    {
                        if (ProviderDao != null)
                        {
                            ProviderDao.RemoveProviderInfo(folder.ProviderId);
                            FilesMessageService.Send(folder, headers, MessageAction.ThirdPartyDeleted, folder.ID.ToString(), folder.ProviderKey);
                        }

                        ProcessedFolder(folderId);
                    }
                    else
                    {
                        if (FolderDao.UseTrashForRemove(folder))
                        {
                            var files = FileDao.GetFiles(folder.ID);
                            if (!ignoreException && files.Exists(FileTracker.IsEditing))
                            {
                                Error = FilesCommonResource.ErrorMassage_SecurityException_DeleteEditingFolder;
                            }
                            else
                            {
                                FolderDao.MoveFolder(folder.ID, trashId);
                                FilesMessageService.Send(folder, headers, MessageAction.FolderMovedToTrash, folder.Title);

                                ProcessedFolder(folderId);
                            }
                        }
                        else
                        {
                            if (FolderDao.UseRecursiveOperation(folder.ID, null))
                            {
                                DeleteFiles(FileDao.GetFiles(folder.ID));
                                DeleteFolders(FolderDao.GetFolders(folder.ID).Select(f => f.ID).ToList());

                                if (FolderDao.IsEmpty(folder.ID))
                                {
                                    FolderDao.DeleteFolder(folder.ID);
                                    ProcessedFolder(folderId);
                                }
                            }
                            else
                            {
                                FolderDao.DeleteFolder(folder.ID);
                                ProcessedFolder(folderId);
                            }
                        }
                    }
                }
                ProgressStep(canCalculate);
            }
        }