public static FileShare Check(string key, IFileDao fileDao, out File file)
        {
            file = null;
            if (string.IsNullOrEmpty(key)) return FileShare.Restrict;
            var fileId = Parse(key);
            file = fileDao.GetFile(fileId);
            if (file == null) return FileShare.Restrict;

            var filesSecurity = Global.GetFilesSecurity();
            if (filesSecurity.CanEdit(file, FileConstant.ShareLinkId)) return FileShare.ReadWrite;
            if (filesSecurity.CanRead(file, FileConstant.ShareLinkId)) return FileShare.Read;
            return FileShare.Restrict;
        }
        public static List<DocServiceParams.RecentDocument> GetRecentEditedDocument(bool forEdit, int count, string crumbsSeporator, IFileDao fileDao)
        {
            var recent = new List<DocServiceParams.RecentDocument>();

            var activity = UserActivityManager.GetUserActivities(TenantProvider.CurrentTenantID, SecurityContext.CurrentAccount.ID,
                                                                 ProductEntryPoint.ID, null, UserActivityConstants.AllActionType,
                                                                 new[] {"OpenEditorFile"}, 0, 100);

            foreach (var entryId in activity.Select(userActivity => userActivity.ContentID.Substring("file_".Length)))
            {
                if (recent.Exists(r => r.ID.Equals(entryId)))
                    continue;

                var fileAct = fileDao.GetFile(entryId);

                if (fileAct.RootFolderType == FolderType.TRASH)
                    continue;

                if (!FileUtility.UsingHtml5(fileAct.Title))
                    continue;

                if (!Global.GetFilesSecurity().CanRead(fileAct))
                    continue;

                string uri;
                if (forEdit && Global.GetFilesSecurity().CanEdit(fileAct))
                    uri = CommonLinkUtility.GetFileWebEditorUrl(fileAct.ID);
                else
                    uri = CommonLinkUtility.GetFileWebViewerUrl(fileAct.ID);

                var fileBreadCrumbs = Global.GetBreadCrumbs(fileAct.FolderID);
                recent.Add(new DocServiceParams.RecentDocument
                               {
                                   ID = entryId,
                                   Title = fileAct.Title,
                                   Uri = CommonLinkUtility.GetFullAbsolutePath(uri),
                                   FolderPath = string.Join(crumbsSeporator, fileBreadCrumbs.Select(folder => folder.Title).ToArray())
                               });

                if (recent.Count == count)
                    break;
            }
            return recent;
        }
        public static bool Check(string key, bool checkRead, IFileDao fileDao, out File file)
        {
            var fileShare = Check(key, fileDao, out file);

            return((!checkRead && fileShare == FileShare.ReadWrite) || (checkRead && fileShare <= FileShare.Read));
        }
Exemple #4
0
        public static IEnumerable <FileEntry> GetEntries(IFolderDao folderDao, IFileDao fileDao, Folder parent, FilterType filter, Guid subjectId, OrderBy orderBy, String searchText, int from, int count, out int total)
        {
            total = 0;

            if (parent == null)
            {
                throw new ArgumentNullException("parent", FilesCommonResource.ErrorMassage_FolderNotFound);
            }

            var fileSecurity = Global.GetFilesSecurity();
            var entries      = Enumerable.Empty <FileEntry>();

            if (parent.FolderType == FolderType.Projects && parent.ID.Equals(Global.FolderProjects))
            {
                var apiServer = new ASC.Api.ApiServer();
                var apiUrl    = string.Format("{0}project/maxlastmodified.json", SetupInfo.WebApiBaseUrl);

                var responseBody = apiServer.GetApiResponse(apiUrl, "GET");
                if (responseBody != null)
                {
                    var responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(responseBody)));

                    var          projectLastModified         = responseApi["response"].Value <String>();
                    const string projectLastModifiedCacheKey = "documents/projectFolders/projectLastModified";
                    if (HttpRuntime.Cache.Get(projectLastModifiedCacheKey) == null || !HttpRuntime.Cache.Get(projectLastModifiedCacheKey).Equals(projectLastModified))
                    {
                        HttpRuntime.Cache.Remove(projectLastModifiedCacheKey);
                        HttpRuntime.Cache.Insert(projectLastModifiedCacheKey, projectLastModified);
                    }
                    var projectListCacheKey = string.Format("documents/projectFolders/{0}", SecurityContext.CurrentAccount.ID);
                    var fromCache           = HttpRuntime.Cache.Get(projectListCacheKey);

                    if (fromCache == null || !string.IsNullOrEmpty(searchText))
                    {
                        apiUrl = string.Format("{0}project/filter.json?sortBy=title&sortOrder=ascending&status=open&fields=id,title,security,projectFolder", SetupInfo.WebApiBaseUrl);

                        responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET"))));

                        var responseData = responseApi["response"];

                        if (!(responseData is JArray))
                        {
                            return(entries.ToList());
                        }

                        var folderIDProjectTitle = new Dictionary <object, KeyValuePair <int, string> >();

                        foreach (JObject projectInfo in responseData.Children())
                        {
                            var projectID    = projectInfo["id"].Value <int>();
                            var projectTitle = Global.ReplaceInvalidCharsAndTruncate(projectInfo["title"].Value <String>());
                            int projectFolderID;

                            JToken projectSecurityJToken;
                            if (projectInfo.TryGetValue("security", out projectSecurityJToken))
                            {
                                var    projectSecurity = projectInfo["security"].Value <JObject>();
                                JToken projectCanFileReadJToken;
                                if (projectSecurity.TryGetValue("canReadFiles", out projectCanFileReadJToken))
                                {
                                    if (!projectSecurity["canReadFiles"].Value <bool>())
                                    {
                                        continue;
                                    }
                                }
                            }

                            JToken projectFolderIDJToken;

                            if (projectInfo.TryGetValue("projectFolder", out projectFolderIDJToken))
                            {
                                projectFolderID = projectInfo["projectFolder"].Value <int>();
                            }
                            else
                            {
                                projectFolderID = (int)FilesIntegration.RegisterBunch("projects", "project", projectID.ToString());
                            }

                            if (!folderIDProjectTitle.ContainsKey(projectFolderID))
                            {
                                folderIDProjectTitle.Add(projectFolderID, new KeyValuePair <int, string>(projectID, projectTitle));
                            }

                            AscCache.Default.Remove("documents/folders/" + projectFolderID.ToString());
                            AscCache.Default.Insert("documents/folders/" + projectFolderID.ToString(), projectTitle, TimeSpan.FromMinutes(30));
                        }

                        var folders = folderDao.GetFolders(folderIDProjectTitle.Keys.ToArray(), searchText, !string.IsNullOrEmpty(searchText), false);
                        folders.ForEach(x =>
                        {
                            x.Title     = folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID].Value : x.Title;
                            x.FolderUrl = PathProvider.GetFolderUrl(x, folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID].Key : 0);
                        });

                        folders = fileSecurity.FilterRead(folders).ToList();

                        entries = entries.Concat(folders);

                        if (!string.IsNullOrEmpty(searchText))
                        {
                            var files = fileDao.GetFiles(folderIDProjectTitle.Keys.ToArray(), searchText, !string.IsNullOrEmpty(searchText)).ToList();
                            files   = fileSecurity.FilterRead(files).ToList();
                            entries = entries.Concat(files);
                        }

                        if (entries.Any() && string.IsNullOrEmpty(searchText))
                        {
                            HttpRuntime.Cache.Remove(projectListCacheKey);
                            HttpRuntime.Cache.Insert(projectListCacheKey, entries, new CacheDependency(null, new[] { projectLastModifiedCacheKey }), Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(15));
                        }
                    }
                    else
                    {
                        entries = entries.Concat((IEnumerable <FileEntry>)fromCache);
                    }
                }

                entries = FilterEntries(entries, filter, subjectId, searchText);

                parent.TotalFiles      = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalFiles : 1));
                parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalSubFolders + 1 : 0));
            }
            else if (parent.FolderType == FolderType.SHARE)
            {
                //share
                var shared = (IEnumerable <FileEntry>)fileSecurity.GetSharesForMe(searchText);

                shared  = FilterEntries(shared, filter, subjectId, searchText);
                entries = entries.Concat(shared);

                parent.TotalFiles      = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalFiles : 1));
                parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f is Folder ? ((Folder)f).TotalSubFolders + 1 : 0));
            }
            else
            {
                var folders = folderDao.GetFolders(parent.ID, orderBy, filter, subjectId, searchText, !string.IsNullOrEmpty(searchText) && parent.FolderType != FolderType.TRASH).Cast <FileEntry>();
                folders = fileSecurity.FilterRead(folders);
                entries = entries.Concat(folders);

                var files = fileDao.GetFiles(parent.ID, orderBy, filter, subjectId, searchText, withSubfolders: !string.IsNullOrEmpty(searchText) && parent.FolderType != FolderType.TRASH).Cast <FileEntry>();
                files   = fileSecurity.FilterRead(files);
                entries = entries.Concat(files);

                if (filter == FilterType.None || filter == FilterType.FoldersOnly)
                {
                    var folderList = GetThirpartyFolders(parent, searchText);

                    var thirdPartyFolder = FilterEntries(folderList, filter, subjectId, searchText);
                    entries = entries.Concat(thirdPartyFolder);
                }
            }

            if (orderBy.SortedBy != SortedByType.New)
            {
                entries = SortEntries(entries, orderBy);

                total = entries.Count();
                if (0 < from)
                {
                    entries = entries.Skip(from);
                }
                if (0 < count)
                {
                    entries = entries.Take(count);
                }
            }

            entries = FileMarker.SetTagsNew(folderDao, parent, entries);

            //sorting after marking
            if (orderBy.SortedBy == SortedByType.New)
            {
                entries = SortEntries(entries, orderBy);

                total = entries.Count();
                if (0 < from)
                {
                    entries = entries.Skip(from);
                }
                if (0 < count)
                {
                    entries = entries.Take(count);
                }
            }

            SetFileStatus(entries.Where(r => r != null && r.ID != null && r is File).Select(r => r as File).ToList());

            return(entries);
        }
Exemple #5
0
        public static void ReassignItems(object parentId, Guid fromUserId, Guid toUserId, IFolderDao folderDao, IFileDao fileDao)
        {
            var files = fileDao.GetFiles(parentId, new OrderBy(SortedByType.AZ, true), FilterType.ByUser, fromUserId, null, withSubfolders: true)
                        .Where(file => file.CreateBy == fromUserId);

            foreach (var file in files)
            {
                file.CreateBy = toUserId;
                fileDao.SaveFile(file, null);
            }

            var folders = folderDao.GetFolders(parentId, new OrderBy(SortedByType.AZ, true), FilterType.ByUser, fromUserId, null, true)
                          .Where(folder => folder.CreateBy == fromUserId);

            foreach (var folder in folders)
            {
                folder.CreateBy = toUserId;
                folderDao.SaveFolder(folder);
            }
        }
Exemple #6
0
        public static void MoveSharedItems(object parentId, object toId, IFolderDao folderDao, IFileDao fileDao)
        {
            var fileSecurity = Global.GetFilesSecurity();

            var folders = folderDao.GetFolders(parentId);

            foreach (var folder in folders)
            {
                var shared = folder.Shared &&
                             fileSecurity.GetShares(folder).Any(record => record.Share != FileShare.Restrict);
                if (shared)
                {
                    folderDao.MoveFolder(folder.ID, toId);
                }
                else
                {
                    MoveSharedItems(folder.ID, toId, folderDao, fileDao);
                }
            }

            var files = fileDao.GetFiles(parentId, null, FilterType.None, Guid.Empty, string.Empty);

            foreach (var file
                     in files.Where(file =>
                                    file.Shared &&
                                    fileSecurity.GetShares(file)
                                    .Any(record =>
                                         record.Subject != FileConstant.ShareLinkId &&
                                         record.Share != FileShare.Restrict)))
            {
                fileDao.MoveFile(file.ID, toId);
            }
        }
Exemple #7
0
        public File <TTo> PerformCrossDaoFileCopy <TFrom, TTo>(
            TFrom fromFileId, IFileDao <TFrom> fromFileDao, Func <TFrom, TFrom> fromConverter,
            TTo toFolderId, IFileDao <TTo> toFileDao, Func <TTo, TTo> toConverter,
            bool deleteSourceFile)
        {
            //Get File from first dao
            var fromFile = fromFileDao.GetFile(fromConverter(fromFileId));

            if (fromFile.ContentLength > SetupInfo.AvailableFileSize)
            {
                throw new Exception(string.Format(deleteSourceFile ? FilesCommonResource.ErrorMassage_FileSizeMove : FilesCommonResource.ErrorMassage_FileSizeCopy,
                                                  FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
            }

            var securityDao = ServiceProvider.GetService <ISecurityDao <TFrom> >();
            var tagDao      = ServiceProvider.GetService <ITagDao <TFrom> >();

            var fromFileShareRecords = securityDao.GetPureShareRecords(fromFile).Where(x => x.EntryType == FileEntryType.File);
            var fromFileNewTags      = tagDao.GetNewTags(Guid.Empty, fromFile).ToList();
            var fromFileLockTag      = tagDao.GetTags(fromFile.ID, FileEntryType.File, TagType.Locked).FirstOrDefault();
            var fromFileFavoriteTag  = tagDao.GetTags(fromFile.ID, FileEntryType.File, TagType.Favorite);
            var fromFileTemplateTag  = tagDao.GetTags(fromFile.ID, FileEntryType.File, TagType.Template);

            var toFile = ServiceProvider.GetService <File <TTo> >();

            toFile.Title     = fromFile.Title;
            toFile.Encrypted = fromFile.Encrypted;
            toFile.FolderID  = toConverter(toFolderId);

            fromFile.ID = fromConverter(fromFile.ID);

            var mustConvert = !string.IsNullOrEmpty(fromFile.ConvertedType);

            using (var fromFileStream = mustConvert
                                            ? FileConverter.Exec(fromFile)
                                            : fromFileDao.GetFileStream(fromFile))
            {
                toFile.ContentLength = fromFileStream.CanSeek ? fromFileStream.Length : fromFile.ContentLength;
                toFile = toFileDao.SaveFile(toFile, fromFileStream);
            }

            if (fromFile.ThumbnailStatus == Thumbnail.Created)
            {
                using (var thumbnail = fromFileDao.GetThumbnail(fromFile))
                {
                    toFileDao.SaveThumbnail(toFile, thumbnail);
                }
                toFile.ThumbnailStatus = Thumbnail.Created;
            }

            if (deleteSourceFile)
            {
                if (fromFileShareRecords.Any())
                {
                    fromFileShareRecords.ToList().ForEach(x =>
                    {
                        x.EntryId = toFile.ID;
                        securityDao.SetShare(x);
                    });
                }

                var fromFileTags = fromFileNewTags;
                if (fromFileLockTag != null)
                {
                    fromFileTags.Add(fromFileLockTag);
                }
                if (fromFileFavoriteTag != null)
                {
                    fromFileTags.AddRange(fromFileFavoriteTag);
                }
                if (fromFileTemplateTag != null)
                {
                    fromFileTags.AddRange(fromFileTemplateTag);
                }

                if (fromFileTags.Any())
                {
                    fromFileTags.ForEach(x => x.EntryId = toFile.ID);

                    tagDao.SaveTags(fromFileTags);
                }

                //Delete source file if needed
                fromFileDao.DeleteFile(fromConverter(fromFileId));
            }
            return(toFile);
        }
Exemple #8
0
        protected override void run()
        {
            try
            {
                MessageTO jobResponse = null;
                if (String.Equals("false", ConfigurationManager.AppSettings[config.AppConfigSettingsConstants.EnforceCallback], StringComparison.CurrentCultureIgnoreCase))
                {
                    jobResponse = _client.sendNewJobRequest("SansCallback", 0);
                }
                else // default if config item doesn't exist or it set to anything but false
                {
                    jobResponse = _client.sendNewJobRequest(_server.SocketContainer.HostName, _server.SocketContainer.ListeningPort);
                }
                _client.disconnect();
                // check job stack isn't empty
                if (jobResponse != null && jobResponse.MessageType == MessageTypeTO.NewJobResponse &&
                    !String.IsNullOrEmpty(jobResponse.Message) && jobResponse.Message.Contains("No more jobs"))
                {
                    _report.addInfo("The Orchestrator service reported there are no more jobs on the work stack. Exiting normally...");
                    return;
                }
                // then check we received a valid response
                if (jobResponse == null || jobResponse.MessageType != MessageTypeTO.NewJobResponse ||
                    jobResponse.Configuration == null || !jobResponse.Configuration.isCompleteConfiguration())
                {
                    throw new DownstreamException(null, null, null, jobResponse, "Invalid new job response!", null);
                }

                _report.addInfo("Successfully connected and registered with orchestrator and received a valid job!");
                _config = jobResponse.Configuration;
                _report.setConfiguration(_config);
                _report.BatchId = jobResponse.Message; // we have the batch ID now - set it on the report for easy tracing
                _extractor      = jobResponse.Extractor;

                // now that we have our config, we can create our file DAO
                _fileDao = new FileDaoFactory().getFileDao();
                _fileDao.setExtractsDirectory(_config.SiteCode, jobResponse.Message); // messsage should contain correct directory name


                // Create the top level query that will drive any subqueries
                _vistaQuery = new VistaQuery(_config, _config.QueryConfigurations.RootNode.Value);

                if (checkSiteForWork())
                {
                    _report.addDebug(_config.SiteCode + " appears to have work! Starting extraction job...");
                    extract();
                }
                else
                {
                    _report.addDebug("Site appears to have no work!");
                }

                // finally, try and notify orchestrator we have finished
                sendUnlockRequest(MessageTypeTO.JobCompletedRequest, _client);
            }
            catch (Exception exc)
            {
                _report.Errored = true;
                _report.addException(exc);
                if (_config != null) // if this was set then we know we received a job
                {
                    sendUnlockRequest(MessageTypeTO.JobErrorRequest, _client);
                }
            }
            finally
            {
                try
                {
                    _client.disconnect();
                    _server.stopListener();
                }
                catch (Exception) { /* nothing we can do if these error */ }
                GC.Collect();
            }
        }
 public static bool Check(string key, bool checkRead, IFileDao fileDao, out File file)
 {
     var fileShare = Check(key, fileDao, out file);
     return (!checkRead && fileShare == FileShare.ReadWrite) || (checkRead && fileShare <= FileShare.Read);
 }
Exemple #10
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 = ReplaceInvalidCharsAndTruncate(fileName),
                            ContentLength = stream.Length,
                            ContentType = MimeMapping.GetMimeMapping(fileName),
                            FolderID = folder,
                        };
         stream.Position = 0;
         try
         {
             fileDao.SaveFile(file, stream);
         }
         catch
         {
         }
     }
 }
Exemple #11
0
        private static void SaveStartDocument(IFolderDao folderDao, IFileDao fileDao, object folderId, string path, IDataStore storeTemp)
        {
            foreach (var file in storeTemp.ListFilesRelative("", path, "*", false))
            {
                SaveFile(fileDao, folderId, path + file, storeTemp);
            }

            foreach (var folderUri in storeTemp.List(path, false))
            {
                var folderName = Path.GetFileName(folderUri.ToString());

                var subFolderid = folderDao.SaveFolder(new Folder
                                                           {
                                                               Title = ReplaceInvalidCharsAndTruncate(folderName),
                                                               ParentFolderID = folderId
                                                           });

                SaveStartDocument(folderDao, fileDao, subFolderid, path + folderName + "/", storeTemp);
            }
        }
Exemple #12
0
 public Handler()
 {
     fileDao = DaoProvider.fileDao;
 }
        private static FileShare CheckShareLink(string key, IFileDao fileDao, out File file)
        {
            file = null;

            var fileId = ParseShareLink(key);
            file = fileDao.GetFile(fileId);
            if (file == null)
            {
                return FileShare.Restrict;
            }

            var filesSecurity = Global.GetFilesSecurity();
            if (filesSecurity.CanEdit(file, FileConstant.ShareLinkId))
            {
                return FileShare.ReadWrite;
            }
            if (filesSecurity.CanRead(file, FileConstant.ShareLinkId))
            {
                return FileShare.Read;
            }
            return FileShare.Restrict;
        }
Exemple #14
0
 public FileLogic(IFileDao fDao)
 {
     _fileDao = fDao;
 }
Exemple #15
0
        public static void ReassignItems(object parentId, Guid fromUserId, Guid toUserId, IFolderDao folderDao, IFileDao fileDao)
        {
            var fileIds = fileDao.GetFiles(parentId, new OrderBy(SortedByType.AZ, true), FilterType.ByUser, fromUserId, null, true)
                          .Where(file => file.CreateBy == fromUserId).Select(file => file.ID);

            fileDao.ReassignFiles(fileIds.ToArray(), toUserId);

            var folderIds = folderDao.GetFolders(parentId, new OrderBy(SortedByType.AZ, true), FilterType.ByUser, fromUserId, null, true)
                            .Where(folder => folder.CreateBy == fromUserId).Select(folder => folder.ID);

            folderDao.ReassignFolders(folderIds.ToArray(), toUserId);
        }
Exemple #16
0
        private static void SaveStartDocument(IFolderDao folderDao, IFileDao fileDao, object folderId, string path, IDataStore storeTemp)
        {
            foreach (var file in storeTemp.ListFilesRelative("", path, "*", false))
            {
                SaveFile(fileDao, folderId, path + file, storeTemp);
            }

            if (storeTemp is S3Storage) return;

            foreach (var folderUri in storeTemp.List(path, false))
            {
                var folderName = Path.GetFileName(folderUri.ToString());

                var subFolder = folderDao.SaveFolder(new Folder
                    {
                        Title = folderName,
                        ParentFolderID = folderId
                    });

                SaveStartDocument(folderDao, fileDao, subFolder.ID, path + folderName + "/", storeTemp);
            }
        }
Exemple #17
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);
                }
            }
        }
Exemple #18
0
        public static bool Check(string doc, bool checkRead, IFileDao fileDao, out File file)
        {
            var fileShare = Check(doc, fileDao, out file);

            return((!checkRead && (fileShare == FileShare.ReadWrite || fileShare == FileShare.Review)) || (checkRead && fileShare != FileShare.Restrict));
        }
Exemple #19
0
        public Folder <TTo> PerformCrossDaoFolderCopy <TFrom, TTo>
            (TFrom fromFolderId, IFolderDao <TFrom> fromFolderDao, IFileDao <TFrom> fromFileDao, Func <TFrom, TFrom> fromConverter,
            TTo toRootFolderId, IFolderDao <TTo> toFolderDao, IFileDao <TTo> toFileDao, Func <TTo, TTo> toConverter,
            bool deleteSourceFolder, CancellationToken?cancellationToken)
        {
            var fromFolder = fromFolderDao.GetFolder(fromConverter(fromFolderId));

            var toFolder1 = ServiceProvider.GetService <Folder <TTo> >();

            toFolder1.Title    = fromFolder.Title;
            toFolder1.FolderID = toConverter(toRootFolderId);

            var toFolder   = toFolderDao.GetFolder(fromFolder.Title, toConverter(toRootFolderId));
            var toFolderId = toFolder != null
                                 ? toFolder.ID
                                 : toFolderDao.SaveFolder(toFolder1);

            var       foldersToCopy = fromFolderDao.GetFolders(fromConverter(fromFolderId));
            var       fileIdsToCopy = fromFileDao.GetFiles(fromConverter(fromFolderId));
            Exception copyException = null;

            //Copy files first
            foreach (var fileId in fileIdsToCopy)
            {
                if (cancellationToken.HasValue)
                {
                    cancellationToken.Value.ThrowIfCancellationRequested();
                }
                try
                {
                    PerformCrossDaoFileCopy(fileId, fromFileDao, fromConverter,
                                            toFolderId, toFileDao, toConverter,
                                            deleteSourceFolder);
                }
                catch (Exception ex)
                {
                    copyException = ex;
                }
            }
            foreach (var folder in foldersToCopy)
            {
                if (cancellationToken.HasValue)
                {
                    cancellationToken.Value.ThrowIfCancellationRequested();
                }
                try
                {
                    PerformCrossDaoFolderCopy(folder.ID, fromFolderDao, fromFileDao, fromConverter,
                                              toFolderId, toFolderDao, toFileDao, toConverter,
                                              deleteSourceFolder, cancellationToken);
                }
                catch (Exception ex)
                {
                    copyException = ex;
                }
            }

            if (deleteSourceFolder)
            {
                var securityDao          = ServiceProvider.GetService <ISecurityDao <TFrom> >();
                var fromFileShareRecords = securityDao.GetPureShareRecords(fromFolder)
                                           .Where(x => x.EntryType == FileEntryType.Folder);

                if (fromFileShareRecords.Any())
                {
                    fromFileShareRecords.ToList().ForEach(x =>
                    {
                        x.EntryId = toFolderId;
                        securityDao.SetShare(x);
                    });
                }

                var tagDao          = ServiceProvider.GetService <ITagDao <TFrom> >();
                var fromFileNewTags = tagDao.GetNewTags(Guid.Empty, fromFolder).ToList();

                if (fromFileNewTags.Any())
                {
                    fromFileNewTags.ForEach(x => x.EntryId = toFolderId);

                    tagDao.SaveTags(fromFileNewTags);
                }

                if (copyException == null)
                {
                    fromFolderDao.DeleteFolder(fromConverter(fromFolderId));
                }
            }

            if (copyException != null)
            {
                throw copyException;
            }

            return(toFolderDao.GetFolder(toConverter(toFolderId)));
        }
 public CommentLogic(ICommentDao commentDao, IFileDao fileDao)
 {
     _commentDao = commentDao;
     _fileDao    = fileDao;
 }