Example #1
0
        public static void RemoveAce(List <FileEntry> entries)
        {
            var fileSecurity = Global.GetFilesSecurity();

            entries.ForEach(
                entry =>
            {
                if (entry.RootFolderType != FolderType.USER || Equals(entry.RootFolderId, Global.FolderMy))
                {
                    return;
                }

                var entryType = entry.FileEntryType;
                fileSecurity.Share(entry.ID, entryType, SecurityContext.CurrentAccount.ID, fileSecurity.DefaultMyShare);

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

                FileMarker.RemoveMarkAsNew(entry);
            });
        }
Example #2
0
        public static File Exec(string folderId, string title, long contentLength, Stream data, bool createNewIfExist, bool deleteConvertStatus = true)
        {
            if (contentLength <= 0)
            {
                throw new Exception(FilesCommonResource.ErrorMassage_EmptyFile);
            }

            var file = VerifyFileUpload(folderId, title, contentLength, !createNewIfExist);

            using (var dao = Global.DaoFactory.GetFileDao())
            {
                file = dao.SaveFile(file, data);
            }

            FileMarker.MarkAsNew(file);

            if (FileConverter.EnableAsUploaded && FileConverter.MustConvert(file))
            {
                FileConverter.ExecAsync(file, deleteConvertStatus);
            }

            return(file);
        }
Example #3
0
 public FileConverter(
     FileUtility fileUtility,
     FilesLinkUtility filesLinkUtility,
     IDaoFactory daoFactory,
     SetupInfo setupInfo,
     PathProvider pathProvider,
     FileSecurity fileSecurity,
     FileMarker fileMarker,
     TenantManager tenantManager,
     AuthContext authContext,
     EntryManager entryManager,
     FilesSettingsHelper filesSettingsHelper,
     GlobalFolderHelper globalFolderHelper,
     FilesMessageService filesMessageService,
     FileShareLink fileShareLink,
     DocumentServiceHelper documentServiceHelper,
     DocumentServiceConnector documentServiceConnector,
     IServiceProvider serviceProvider)
 {
     FileUtility              = fileUtility;
     FilesLinkUtility         = filesLinkUtility;
     DaoFactory               = daoFactory;
     SetupInfo                = setupInfo;
     PathProvider             = pathProvider;
     FileSecurity             = fileSecurity;
     FileMarker               = fileMarker;
     TenantManager            = tenantManager;
     AuthContext              = authContext;
     EntryManager             = entryManager;
     FilesSettingsHelper      = filesSettingsHelper;
     GlobalFolderHelper       = globalFolderHelper;
     FilesMessageService      = filesMessageService;
     FileShareLink            = fileShareLink;
     DocumentServiceHelper    = documentServiceHelper;
     DocumentServiceConnector = documentServiceConnector;
     ServiceProvider          = serviceProvider;
 }
Example #4
0
        public static ChunkedUploadSession UploadChunk(string uploadId, Stream stream, long chunkLength)
        {
            var uploadSession = ChunkedUploadSessionHolder.GetSession(uploadId);

            uploadSession.Expired = DateTime.UtcNow + ChunkedUploadSessionHolder.SlidingExpiration;

            if (chunkLength <= 0)
            {
                throw new Exception(FilesCommonResource.ErrorMassage_EmptyFile);
            }

            if (chunkLength > SetupInfo.MaxUploadSize)
            {
                throw FileSizeComment.GetFileSizeException(SetupInfo.MaxUploadSize);
            }

            var maxUploadSize = GetMaxFileSize(uploadSession.FolderId, uploadSession.BytesTotal > 0);

            if (uploadSession.BytesUploaded + chunkLength > maxUploadSize)
            {
                AbortUpload(uploadSession);
                throw FileSizeComment.GetFileSizeException(maxUploadSize);
            }

            using (var dao = Global.DaoFactory.GetFileDao())
            {
                dao.UploadChunk(uploadSession, stream, chunkLength);
            }

            if (uploadSession.BytesUploaded == uploadSession.BytesTotal)
            {
                FileMarker.MarkAsNew(uploadSession.File);
                ChunkedUploadSessionHolder.RemoveSession(uploadSession);
            }

            return(uploadSession);
        }
        private static void CheckConvertFilesStatus(Object obj)
        {
            lock (LockerTimer)
            {
                _timer.Change(Timeout.Infinite, Timeout.Infinite);
            }
            try
            {
                List <File> filesIsConverting;

                lock (LockerStatus)
                {
                    ConversionFileStatus.Where(x => ((!String.IsNullOrEmpty(x.Value.Processed) &&
                                                      DateTime.Now.Subtract(x.Value.StopDateTime) > TimeSpan.FromMinutes(30))))
                    .ToList().ForEach(x => ConversionFileStatus.Remove(x));

                    filesIsConverting = ConversionFileStatus.Where(x => String.IsNullOrEmpty(x.Value.Processed)).Select(x => x.Key).ToList();
                }

                if (filesIsConverting.Count == 0)
                {
                    lock (LockerTimer)
                    {
                        _timer.Dispose();
                        _timer = null;
                    }
                    return;
                }

                foreach (var file in filesIsConverting)
                {
                    var    fileUri = file.ID.ToString();
                    string convetedFileUrl;
                    int    operationResultProgress;
                    object folderId;
                    var    currentFolder = false;

                    try
                    {
                        int      tenantId;
                        IAccount account;

                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult == null)
                            {
                                continue;
                            }
                            tenantId = operationResult.TenantId;
                            account  = operationResult.Account;
                        }

                        CoreContext.TenantManager.SetCurrentTenant(tenantId);
                        SecurityContext.AuthenticateMe(account);

                        var user    = CoreContext.UserManager.GetUsers(account.ID);
                        var culture = string.IsNullOrEmpty(user.CultureName)
                                          ? CoreContext.TenantManager.GetCurrentTenant().GetCulture()
                                          : CultureInfo.GetCultureInfo(user.CultureName);
                        Thread.CurrentThread.CurrentCulture   = culture;
                        Thread.CurrentThread.CurrentUICulture = culture;

                        var fileSecurity = Global.GetFilesSecurity();
                        if (!fileSecurity.CanRead(file) &&
                            file.RootFolderType != FolderType.BUNCH)    //No rights in CRM after upload before attach
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        if (file.ContentLength > SetupInfo.AvailableFileSize)
                        {
                            throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                        }

                        folderId = Global.FolderMy;
                        using (var folderDao = Global.DaoFactory.GetFolderDao())
                        {
                            var parent = folderDao.GetFolder(file.FolderID);
                            if (parent != null &&
                                fileSecurity.CanCreate(parent))
                            {
                                folderId      = parent.ID;
                                currentFolder = true;
                            }
                        }
                        if (Equals(folderId, 0))
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound);
                        }

                        fileUri = PathProvider.GetFileStreamUrl(file);

                        var toExtension   = FileUtility.GetInternalExtension(file.Title);
                        var fileExtension = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title);
                        var docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

                        operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convetedFileUrl);
                    }
                    catch (Exception exception)
                    {
                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult != null)
                            {
                                if (operationResult.Delete)
                                {
                                    ConversionFileStatus.Remove(file);
                                }
                                else
                                {
                                    operationResult.Result       = FileJsonSerializer(file);
                                    operationResult.Processed    = "1";
                                    operationResult.StopDateTime = DateTime.Now;
                                    operationResult.Error        = exception.Message;
                                }
                            }
                        }

                        var strExc = exception.Message + " in file " + fileUri;
                        Global.Logger.Error(strExc, exception);

                        continue;
                    }

                    if (operationResultProgress < 100)
                    {
                        lock (LockerStatus)
                        {
                            var operationResult = ConversionFileStatus[file];
                            if (operationResult != null)
                            {
                                operationResult.Progress = operationResultProgress;
                            }
                        }
                        continue;
                    }

                    using (var fileDao = Global.DaoFactory.GetFileDao())
                        using (var folderDao = Global.DaoFactory.GetFolderDao())
                        {
                            var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title));

                            File newFile = null;
                            if (FilesSettings.UpdateIfExist && (!currentFolder || !file.ProviderEntry))
                            {
                                newFile = fileDao.GetFile(folderId, newFileTitle);
                                if (newFile != null &&
                                    Global.GetFilesSecurity().CanEdit(newFile) &&
                                    !EntryManager.FileLockedForMe(newFile.ID) &&
                                    !FileTracker.IsEditing(newFile.ID))
                                {
                                    newFile.Version++;
                                }
                                else
                                {
                                    newFile = null;
                                }
                            }

                            if (newFile == null)
                            {
                                newFile = new File {
                                    FolderID = folderId
                                }
                            }
                            ;

                            newFile.Title         = newFileTitle;
                            newFile.ConvertedType = FileUtility.GetInternalExtension(file.Title);

                            var operationResultError = string.Empty;
                            try
                            {
                                var req = (HttpWebRequest)WebRequest.Create(convetedFileUrl);

                                using (var convertedFileStream = new ResponseStream(req.GetResponse()))
                                {
                                    newFile.ContentLength = convertedFileStream.Length;
                                    newFile.Comment       = string.Empty;
                                    newFile = fileDao.SaveFile(newFile, convertedFileStream);
                                }

                                FileMarker.MarkAsNew(newFile);

                                using (var tagDao = Global.DaoFactory.GetTagDao())
                                {
                                    var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList();
                                    if (tags.Any())
                                    {
                                        tags.ForEach(r => r.EntryId = newFile.ID);
                                        tagDao.SaveTags(tags.ToArray());
                                    }
                                }

                                operationResultProgress = 100;
                            }
                            catch (WebException e)
                            {
                                using (var response = e.Response)
                                {
                                    var httpResponse = (HttpWebResponse)response;
                                    var errorString  = String.Format("Error code: {0}", httpResponse.StatusCode);

                                    if (httpResponse.StatusCode != HttpStatusCode.NotFound)
                                    {
                                        using (var data = response.GetResponseStream())
                                        {
                                            var text = new StreamReader(data).ReadToEnd();
                                            errorString += String.Format(" Error message: {0}", text);
                                        }
                                    }

                                    operationResultError = errorString;

                                    Global.Logger.Error(errorString + "  ConvertUrl : " + convetedFileUrl + "    fromUrl : " + fileUri, e);
                                    throw new Exception(errorString);
                                }
                            }
                            finally
                            {
                                var fileSecurity   = Global.GetFilesSecurity();
                                var removeOriginal = !FilesSettings.StoreOriginalFiles &&
                                                     fileSecurity.CanDelete(file) &&
                                                     currentFolder &&
                                                     !EntryManager.FileLockedForMe(file.ID);

                                var folderTitle = folderDao.GetFolder(newFile.FolderID).Title;

                                lock (LockerStatus)
                                {
                                    var operationResult = ConversionFileStatus[file];

                                    if (operationResult.Delete)
                                    {
                                        ConversionFileStatus.Remove(file);
                                    }
                                    else
                                    {
                                        operationResult.Result       = FileJsonSerializer(newFile, removeOriginal, folderTitle);
                                        operationResult.Processed    = "1";
                                        operationResult.StopDateTime = DateTime.Now;
                                        operationResult.Progress     = operationResultProgress;
                                        if (!string.IsNullOrEmpty(operationResultError))
                                        {
                                            operationResult.Error = operationResultError;
                                        }
                                    }
                                }

                                if (removeOriginal)
                                {
                                    FileMarker.RemoveMarkAsNewForAll(file);
                                    fileDao.DeleteFile(file.ID);
                                }
                            }
                        }
                }

                lock (LockerTimer)
                {
                    _timer.Change(0, TimerConvertPeriod);
                }
            }
            catch (Exception exception)
            {
                Global.Logger.Error(exception.Message, exception);
                lock (LockerTimer)
                {
                    _timer.Dispose();
                    _timer = null;
                }
            }
        }
        public static File ExecDuplicate(File file, string shareLinkKey)
        {
            var toFolderId = file.FolderID;

            using (var fileDao = Global.DaoFactory.GetFileDao())
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    if (!Global.GetFilesSecurity().CanRead(file))
                    {
                        var readLink = FileShareLink.Check(shareLinkKey, true, fileDao, out file);

                        if (file == null)
                        {
                            throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
                        }
                        if (!readLink)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        toFolderId = Global.FolderMy;
                    }

                    if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title)))
                    {
                        throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat);
                    }

                    var toFolder = folderDao.GetFolder(toFolderId);
                    if (toFolder == null)
                    {
                        throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
                    }
                    if (!Global.GetFilesSecurity().CanCreate(toFolder))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
                    }

                    var    fileUri       = PathProvider.GetFileStreamUrl(file);
                    var    fileExtension = file.ConvertedExtension;
                    var    toExtension   = FileUtility.GetInternalExtension(file.Title);
                    var    docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);
                    string convertUri;
                    DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri);

                    var newFile = new File
                    {
                        FolderID = toFolder.ID,
                        Title    = FileUtility.ReplaceFileExtension(file.Title, toExtension)
                    };

                    var req = (HttpWebRequest)WebRequest.Create(convertUri);
                    using (var editedFileStream = new ResponseStream(req.GetResponse()))
                    {
                        newFile.ContentLength = editedFileStream.Length;

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

                    FileMarker.MarkAsNew(newFile);
                    return(newFile);
                }
        }
        public static File UpdateToVersionFile(object fileId, int version, String doc = null, bool checkRight = true)
        {
            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                if (version < 1)
                {
                    throw new ArgumentNullException("version");
                }

                File fromFile;
                var  editLink = FileShareLink.Check(doc, false, fileDao, out fromFile);

                if (fromFile == null)
                {
                    fromFile = fileDao.GetFile(fileId);
                }

                if (fromFile == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }

                if (fromFile.Version != version)
                {
                    fromFile = fileDao.GetFile(fromFile.ID, Math.Min(fromFile.Version, version));
                }

                if (fromFile == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                if (checkRight && !editLink && (!Global.GetFilesSecurity().CanEdit(fromFile) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (FileLockedForMe(fromFile.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (checkRight && FileTracker.IsEditing(fromFile.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile);
                }
                if (fromFile.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }
                if (fromFile.ProviderEntry)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_BadRequest);
                }

                var exists = cache.Get <string>(UPDATE_LIST + fileId.ToString()) != null;
                if (exists)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_UpdateEditingFile);
                }
                else
                {
                    cache.Insert(UPDATE_LIST + fileId.ToString(), fileId.ToString(), TimeSpan.FromMinutes(2));
                }

                try
                {
                    var currFile = fileDao.GetFile(fileId);
                    var newFile  = new File
                    {
                        ID            = fromFile.ID,
                        Version       = currFile.Version + 1,
                        VersionGroup  = currFile.VersionGroup,
                        Title         = FileUtility.ReplaceFileExtension(currFile.Title, FileUtility.GetFileExtension(fromFile.Title)),
                        FileStatus    = currFile.FileStatus,
                        FolderID      = currFile.FolderID,
                        CreateBy      = currFile.CreateBy,
                        CreateOn      = currFile.CreateOn,
                        ModifiedBy    = fromFile.ModifiedBy,
                        ModifiedOn    = fromFile.ModifiedOn,
                        ConvertedType = fromFile.ConvertedType,
                        Comment       = string.Format(FilesCommonResource.CommentRevert, fromFile.ModifiedOnString),
                        Encrypted     = fromFile.Encrypted,
                    };

                    using (var stream = fileDao.GetFileStream(fromFile))
                    {
                        newFile.ContentLength = stream.CanSeek ? stream.Length : fromFile.ContentLength;
                        newFile = fileDao.SaveFile(newFile, stream);
                    }

                    FileMarker.MarkAsNew(newFile);

                    SetFileStatus(newFile);

                    return(newFile);
                }
                catch (Exception e)
                {
                    Global.Logger.Error(string.Format("Error on update {0} to version {1}", fileId, version), e);
                    throw new Exception(e.Message, e);
                }
                finally
                {
                    cache.Remove(UPDATE_LIST + fromFile.ID);
                }
            }
        }
        public static File SaveEditing(String fileId, string fileExtension, string downloadUri, Stream stream, String doc, string comment = null, bool checkRight = true, bool encrypted = false, ForcesaveType?forcesave = null)
        {
            var newExtension = string.IsNullOrEmpty(fileExtension)
                              ? FileUtility.GetFileExtension(downloadUri)
                              : fileExtension;

            var app = ThirdPartySelector.GetAppByFileId(fileId);

            if (app != null)
            {
                app.SaveFile(fileId, newExtension, downloadUri, stream);
                return(null);
            }

            File file;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var editLink = FileShareLink.Check(doc, false, fileDao, out file);
                if (file == null)
                {
                    file = fileDao.GetFile(fileId);
                }

                if (file == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                var fileSecurity = Global.GetFilesSecurity();
                if (checkRight && !editLink && (!(fileSecurity.CanEdit(file) || fileSecurity.CanReview(file)) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (checkRight && FileLockedForMe(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (checkRight && FileTracker.IsEditing(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile);
                }
                if (file.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }

                var currentExt = file.ConvertedExtension;
                if (string.IsNullOrEmpty(newExtension))
                {
                    newExtension = FileUtility.GetInternalExtension(file.Title);
                }

                var replaceVersion = false;
                if (file.Forcesave != ForcesaveType.None)
                {
                    if (file.Forcesave == ForcesaveType.User && FilesSettings.StoreForcesave)
                    {
                        file.Version++;
                    }
                    else
                    {
                        replaceVersion = true;
                    }
                }
                else
                {
                    if (file.Version != 1)
                    {
                        file.VersionGroup++;
                    }
                    else
                    {
                        var storeTemplate = Global.GetStoreTemplate();

                        var path = FileConstant.NewDocPath + Thread.CurrentThread.CurrentCulture + "/";
                        if (!storeTemplate.IsDirectory(path))
                        {
                            path = FileConstant.NewDocPath + "default/";
                        }
                        path += "new" + FileUtility.GetInternalExtension(file.Title);

                        //todo: think about the criteria for saving after creation
                        if (file.ContentLength != storeTemplate.GetFileSize("", path))
                        {
                            file.VersionGroup++;
                        }
                    }
                    file.Version++;
                }
                file.Forcesave = forcesave.HasValue ? forcesave.Value : ForcesaveType.None;

                if (string.IsNullOrEmpty(comment))
                {
                    comment = FilesCommonResource.CommentEdit;
                }

                file.Encrypted = encrypted;

                file.ConvertedType = FileUtility.GetFileExtension(file.Title) != newExtension ? newExtension : null;

                if (file.ProviderEntry && !newExtension.Equals(currentExt))
                {
                    if (FileUtility.ExtsConvertible.Keys.Contains(newExtension) &&
                        FileUtility.ExtsConvertible[newExtension].Contains(currentExt))
                    {
                        if (stream != null)
                        {
                            downloadUri = PathProvider.GetTempUrl(stream, newExtension);
                            downloadUri = DocumentServiceConnector.ReplaceCommunityAdress(downloadUri);
                        }

                        var key = DocumentServiceConnector.GenerateRevisionId(downloadUri);
                        DocumentServiceConnector.GetConvertedUri(downloadUri, newExtension, currentExt, key, null, false, out downloadUri);

                        stream = null;
                    }
                    else
                    {
                        file.ID    = null;
                        file.Title = FileUtility.ReplaceFileExtension(file.Title, newExtension);
                    }

                    file.ConvertedType = null;
                }

                using (var tmpStream = new MemoryStream())
                {
                    if (stream != null)
                    {
                        stream.CopyTo(tmpStream);
                    }
                    else
                    {
                        // hack. http://ubuntuforums.org/showthread.php?t=1841740
                        if (WorkContext.IsMono)
                        {
                            ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                        }

                        var req = (HttpWebRequest)WebRequest.Create(downloadUri);
                        using (var editedFileStream = new ResponseStream(req.GetResponse()))
                        {
                            editedFileStream.CopyTo(tmpStream);
                        }
                    }
                    tmpStream.Position = 0;

                    file.ContentLength = tmpStream.Length;
                    file.Comment       = string.IsNullOrEmpty(comment) ? null : comment;
                    if (replaceVersion)
                    {
                        file = fileDao.ReplaceFileVersion(file, tmpStream);
                    }
                    else
                    {
                        file = fileDao.SaveFile(file, tmpStream);
                    }
                }
            }

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }
        public static IEnumerable <FileEntry> GetEntries(IFolderDao folderDao, IFileDao fileDao, Folder parent, int from, int count, FilterType filter, bool subjectGroup, Guid subjectId, String searchText, bool searchInContent, bool withSubfolders, OrderBy orderBy, out int total)
        {
            total = 0;

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

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

            searchInContent = searchInContent && filter != FilterType.ByExtension && !Equals(parent.ID, Global.FolderTrash);

            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 folderIDProjectTitle = (Dictionary <object, KeyValuePair <int, string> >)HttpRuntime.Cache.Get(projectListCacheKey);

                    if (folderIDProjectTitle == null)
                    {
                        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());
                        }

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

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

                            int    projectFolderID;
                            JToken projectFolderIDjToken;
                            if (projectInfo.TryGetValue("projectFolder", out projectFolderIDjToken))
                            {
                                projectFolderID = projectFolderIDjToken.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);
                            AscCache.Default.Insert("documents/folders/" + projectFolderID, projectTitle, TimeSpan.FromMinutes(30));
                        }

                        HttpRuntime.Cache.Remove(projectListCacheKey);
                        HttpRuntime.Cache.Insert(projectListCacheKey, folderIDProjectTitle, new CacheDependency(null, new[] { projectLastModifiedCacheKey }), Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(15));
                    }

                    var rootKeys = folderIDProjectTitle.Keys.ToArray();
                    if (filter == FilterType.None || filter == FilterType.FoldersOnly)
                    {
                        var folders = folderDao.GetFolders(rootKeys, filter, subjectGroup, subjectId, searchText, withSubfolders, false);

                        var emptyFilter = string.IsNullOrEmpty(searchText) && filter == FilterType.None && subjectId == Guid.Empty;
                        if (!emptyFilter)
                        {
                            var projectFolderIds =
                                folderIDProjectTitle
                                .Where(projectFolder => string.IsNullOrEmpty(searchText) ||
                                       (projectFolder.Value.Value ?? "").ToLower().Trim().Contains(searchText.ToLower().Trim()))
                                .Select(projectFolder => projectFolder.Key);

                            folders.RemoveAll(folder => rootKeys.Contains(folder.ID));

                            var projectFolders = folderDao.GetFolders(projectFolderIds.ToArray(), filter, subjectGroup, subjectId, null, false, false);
                            folders.AddRange(projectFolders);
                        }

                        folders.ForEach(x =>
                        {
                            x.Title     = folderIDProjectTitle.ContainsKey(x.ID) ? folderIDProjectTitle[x.ID].Value : x.Title;
                            x.FolderUrl = folderIDProjectTitle.ContainsKey(x.ID) ? PathProvider.GetFolderUrl(x, folderIDProjectTitle[x.ID].Key) : string.Empty;
                        });

                        if (withSubfolders)
                        {
                            folders = fileSecurity.FilterRead(folders).ToList();
                        }

                        entries = entries.Concat(folders);
                    }

                    if (filter != FilterType.FoldersOnly && withSubfolders)
                    {
                        var files = fileDao.GetFiles(rootKeys, filter, subjectGroup, subjectId, searchText, searchInContent).ToList();
                        files   = fileSecurity.FilterRead(files).ToList();
                        entries = entries.Concat(files);
                    }
                }

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

                entries = entries.Concat(shared);

                parent.TotalFiles      = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalFiles : 1));
                parent.TotalSubFolders = entries.Aggregate(0, (a, f) => a + (f.FileEntryType == FileEntryType.Folder ? ((Folder)f).TotalSubFolders + 1 : 0));
            }
            else
            {
                if (parent.FolderType == FolderType.TRASH)
                {
                    withSubfolders = false;
                }

                var folders = folderDao.GetFolders(parent.ID, orderBy, filter, subjectGroup, subjectId, searchText, withSubfolders).Cast <FileEntry>();
                folders = fileSecurity.FilterRead(folders);
                entries = entries.Concat(folders);

                var files = fileDao.GetFiles(parent.ID, orderBy, filter, subjectGroup, subjectId, searchText, searchInContent, withSubfolders).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, subjectGroup, subjectId, searchText, searchInContent);
                    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.FileEntryType == FileEntryType.File).Select(r => r as File).ToList());

            return(entries);
        }
Example #10
0
        public static bool SetAceObject(List <AceWrapper> aceWrappers, FileEntry entry, bool notify, string message)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest);
            }
            if (!CanSetAccess(entry))
            {
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
            }

            var fileSecurity = Global.GetFilesSecurity();

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

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

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

                var share = w.Share;

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

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

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

                entry.Access = share;

                var listUsersId = new List <Guid>();

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

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

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

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

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

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

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

            return(changed);
        }
Example #11
0
        public static File SaveEditing(String fileId, int version, Guid tabId, string fileExtension, string downloadUri, Stream stream, bool asNew, String shareLinkKey, string comment = null, bool checkRight = true)
        {
            var newExtension = string.IsNullOrEmpty(fileExtension)
                              ? FileUtility.GetFileExtension(downloadUri)
                              : fileExtension;

            var app = ThirdPartySelector.GetAppByFileId(fileId);

            if (app != null)
            {
                app.SaveFile(fileId, newExtension, downloadUri, stream);
                return(null);
            }

            File file;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var editLink = FileShareLink.Check(shareLinkKey, false, fileDao, out file);
                if (file == null)
                {
                    file = fileDao.GetFile(fileId);
                }

                if (file == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                var fileSecurity = Global.GetFilesSecurity();
                if (checkRight && !editLink && (!(fileSecurity.CanEdit(file) || fileSecurity.CanReview(file)) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (checkRight && FileLockedForMe(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (file.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }

                var currentExt = file.ConvertedExtension;
                if (string.IsNullOrEmpty(newExtension))
                {
                    newExtension = FileUtility.GetInternalExtension(file.Title);
                }

                if ((file.Version <= version || !newExtension.Equals(currentExt) || version < 1) &&
                    (file.Version > 1 || !asNew) &&
                    !FileTracker.FixedVersion(file.ID))
                {
                    file.Version++;
                    if (string.IsNullOrEmpty(comment))
                    {
                        comment = FilesCommonResource.CommentEdit;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(comment))
                    {
                        comment = FilesCommonResource.CommentCreate;
                    }
                }

                file.ConvertedType = FileUtility.GetFileExtension(file.Title) != newExtension ? newExtension : null;

                if (file.ProviderEntry && !newExtension.Equals(currentExt))
                {
                    if (FileUtility.ExtsConvertible.Keys.Contains(newExtension) &&
                        FileUtility.ExtsConvertible[newExtension].Contains(currentExt))
                    {
                        var key = DocumentServiceConnector.GenerateRevisionId(downloadUri ?? Guid.NewGuid().ToString());
                        if (stream != null)
                        {
                            using (var tmpStream = new MemoryStream())
                            {
                                stream.CopyTo(tmpStream);
                                downloadUri = DocumentServiceConnector.GetExternalUri(tmpStream, newExtension, key);
                            }
                        }

                        DocumentServiceConnector.GetConvertedUri(downloadUri, newExtension, currentExt, key, false, out downloadUri);

                        stream = null;
                    }
                    else
                    {
                        file.ID    = null;
                        file.Title = FileUtility.ReplaceFileExtension(file.Title, newExtension);
                    }

                    file.ConvertedType = null;
                }

                using (var tmpStream = new MemoryStream())
                {
                    if (stream != null)
                    {
                        stream.CopyTo(tmpStream);
                    }
                    else
                    {
                        // hack. http://ubuntuforums.org/showthread.php?t=1841740
                        if (WorkContext.IsMono)
                        {
                            ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
                        }

                        var req = (HttpWebRequest)WebRequest.Create(downloadUri);
                        using (var editedFileStream = new ResponseStream(req.GetResponse()))
                        {
                            editedFileStream.CopyTo(tmpStream);
                        }
                    }
                    tmpStream.Position = 0;

                    file.ContentLength = tmpStream.Length;
                    file.Comment       = string.IsNullOrEmpty(comment) ? null : comment;
                    file = fileDao.SaveFile(file, tmpStream);
                }
            }

            checkRight = FileTracker.ProlongEditing(file.ID, tabId, true, SecurityContext.CurrentAccount.ID);
            if (checkRight)
            {
                FileTracker.ChangeRight(file.ID, SecurityContext.CurrentAccount.ID, false);
            }

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }
Example #12
0
        private static void CheckConvertFilesStatus(object _)
        {
            if (Monitor.TryEnter(singleThread))
            {
                try
                {
                    List <File> filesIsConverting;
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);

                        conversionQueue.Where(x => !string.IsNullOrEmpty(x.Value.Processed) &&
                                              (x.Value.Progress == 100 && DateTime.Now - x.Value.StopDateTime > TimeSpan.FromMinutes(1) ||
                                               DateTime.Now - x.Value.StopDateTime > TimeSpan.FromMinutes(30)))
                        .ToList()
                        .ForEach(x =>
                        {
                            conversionQueue.Remove(x);
                            cache.Remove(GetKey(x.Key));
                        });

                        Global.Logger.DebugFormat("Run CheckConvertFilesStatus: count {0}", conversionQueue.Count);

                        if (conversionQueue.Count == 0)
                        {
                            return;
                        }

                        filesIsConverting = conversionQueue
                                            .Where(x => String.IsNullOrEmpty(x.Value.Processed))
                                            .Select(x => x.Key)
                                            .ToList();
                    }

                    foreach (var file in filesIsConverting)
                    {
                        var    fileUri = file.ID.ToString();
                        string convertedFileUrl;
                        int    operationResultProgress;
                        object folderId;
                        var    currentFolder = false;

                        try
                        {
                            int      tenantId;
                            IAccount account;

                            lock (locker)
                            {
                                if (!conversionQueue.Keys.Contains(file))
                                {
                                    continue;
                                }

                                var operationResult = conversionQueue[file];
                                if (!string.IsNullOrEmpty(operationResult.Processed))
                                {
                                    continue;
                                }

                                operationResult.Processed = "1";
                                tenantId = operationResult.TenantId;
                                account  = operationResult.Account;

                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                            }

                            CoreContext.TenantManager.SetCurrentTenant(tenantId);
                            SecurityContext.AuthenticateMe(account);

                            var user    = CoreContext.UserManager.GetUsers(account.ID);
                            var culture = string.IsNullOrEmpty(user.CultureName) ? CoreContext.TenantManager.GetCurrentTenant().GetCulture() : CultureInfo.GetCultureInfo(user.CultureName);
                            Thread.CurrentThread.CurrentCulture   = culture;
                            Thread.CurrentThread.CurrentUICulture = culture;

                            var fileSecurity = Global.GetFilesSecurity();
                            if (!fileSecurity.CanRead(file) && file.RootFolderType != FolderType.BUNCH)
                            {
                                //No rights in CRM after upload before attach
                                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                            }
                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeConvert, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
                            }

                            folderId = Global.FolderMy;
                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                            {
                                var parent = folderDao.GetFolder(file.FolderID);
                                if (parent != null &&
                                    fileSecurity.CanCreate(parent))
                                {
                                    folderId      = parent.ID;
                                    currentFolder = true;
                                }
                            }
                            if (Equals(folderId, 0))
                            {
                                throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound);
                            }

                            fileUri = PathProvider.GetFileStreamUrl(file);

                            var toExtension   = FileUtility.GetInternalExtension(file.Title);
                            var fileExtension = file.ConvertedExtension;
                            var docKey        = DocumentServiceHelper.GetDocKey(file.ID, file.Version, file.ModifiedOn);

                            operationResultProgress = DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, true, out convertedFileUrl);
                            operationResultProgress = Math.Min(operationResultProgress, 100);
                        }
                        catch (Exception exception)
                        {
                            Global.Logger.ErrorFormat("Error convert {0} with url {1}: {2}", file.ID, fileUri, exception);
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        operationResult.Result       = FileJsonSerializer(file);
                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.Now;
                                        operationResult.Error        = exception.Message;
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                                    }
                                }
                            }
                            continue;
                        }

                        if (operationResultProgress < 100)
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    operationResult.Processed = "";
                                    operationResult.Progress  = operationResultProgress;
                                    cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                                }
                            }
                            continue;
                        }

                        using (var fileDao = Global.DaoFactory.GetFileDao())
                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                            {
                                var newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title));

                                File newFile = null;
                                if (FilesSettings.UpdateIfExist && (!currentFolder || !file.ProviderEntry))
                                {
                                    newFile = fileDao.GetFile(folderId, newFileTitle);
                                    if (newFile != null && Global.GetFilesSecurity().CanEdit(newFile) && !EntryManager.FileLockedForMe(newFile.ID) && !FileTracker.IsEditing(newFile.ID))
                                    {
                                        newFile.Version++;
                                    }
                                    else
                                    {
                                        newFile = null;
                                    }
                                }

                                if (newFile == null)
                                {
                                    newFile = new File {
                                        FolderID = folderId
                                    };
                                }
                                newFile.Title         = newFileTitle;
                                newFile.ConvertedType = null;
                                newFile.Comment       = string.Format(FilesCommonResource.CommentConvert, file.Title);

                                var operationResultError = string.Empty;
                                try
                                {
                                    var req = (HttpWebRequest)WebRequest.Create(convertedFileUrl);

                                    if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null)
                                    {
                                        ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740
                                    }

                                    using (var convertedFileStream = new ResponseStream(req.GetResponse()))
                                    {
                                        newFile.ContentLength = convertedFileStream.Length;
                                        newFile = fileDao.SaveFile(newFile, convertedFileStream);
                                    }

                                    FilesMessageService.Send(newFile, MessageInitiator.DocsService, MessageAction.FileConverted, newFile.Title);
                                    FileMarker.MarkAsNew(newFile);

                                    using (var tagDao = Global.DaoFactory.GetTagDao())
                                    {
                                        var tags = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList();
                                        if (tags.Any())
                                        {
                                            tags.ForEach(r => r.EntryId = newFile.ID);
                                            tagDao.SaveTags(tags.ToArray());
                                        }
                                    }

                                    operationResultProgress = 100;
                                }
                                catch (WebException e)
                                {
                                    using (var response = e.Response)
                                    {
                                        var httpResponse = (HttpWebResponse)response;
                                        var errorString  = String.Format("Error code: {0}", httpResponse.StatusCode);

                                        if (httpResponse.StatusCode != HttpStatusCode.NotFound)
                                        {
                                            using (var data = response.GetResponseStream())
                                            {
                                                var text = new StreamReader(data).ReadToEnd();
                                                errorString += String.Format(" Error message: {0}", text);
                                            }
                                        }

                                        operationResultProgress = 100;
                                        operationResultError    = errorString;

                                        Global.Logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", errorString, convertedFileUrl, fileUri, e);
                                        throw new Exception(errorString);
                                    }
                                }
                                finally
                                {
                                    var fileSecurity   = Global.GetFilesSecurity();
                                    var removeOriginal = !FilesSettings.StoreOriginalFiles && fileSecurity.CanDelete(file) && currentFolder && !EntryManager.FileLockedForMe(file.ID);
                                    var folderTitle    = folderDao.GetFolder(newFile.FolderID).Title;

                                    lock (locker)
                                    {
                                        if (conversionQueue.Keys.Contains(file))
                                        {
                                            var operationResult = conversionQueue[file];
                                            if (operationResult.Delete)
                                            {
                                                conversionQueue.Remove(file);
                                                cache.Remove(GetKey(file));
                                            }
                                            else
                                            {
                                                operationResult.Result       = FileJsonSerializer(newFile, removeOriginal, folderTitle);
                                                operationResult.StopDateTime = DateTime.Now;
                                                operationResult.Processed    = "1";
                                                operationResult.Progress     = operationResultProgress;
                                                if (!string.IsNullOrEmpty(operationResultError))
                                                {
                                                    operationResult.Error = operationResultError;
                                                }
                                                cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(30));
                                            }
                                        }
                                    }

                                    if (removeOriginal)
                                    {
                                        FileMarker.RemoveMarkAsNewForAll(file);
                                        fileDao.DeleteFile(file.ID);
                                    }
                                }
                            }
                    }

                    lock (locker)
                    {
                        timer.Change(TIMER_PERIOD, TIMER_PERIOD);
                    }
                }
                catch (Exception exception)
                {
                    Global.Logger.Error(exception.Message, exception);
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                finally
                {
                    Monitor.Exit(singleThread);
                }
            }
        }
Example #13
0
        public static File UpdateToVersionFile(object fileId, int version, bool checkRight = true)
        {
            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var fromFile = fileDao.GetFile(fileId, version);

                if (fromFile == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                if (checkRight && (!Global.GetFilesSecurity().CanEdit(fromFile) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (FileLockedForMe(fromFile.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (checkRight && FileTracker.IsEditing(fromFile.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_SecurityException_UpdateEditingFile);
                }
                if (fromFile.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }

                lock (Updates)
                {
                    if (Updates.Contains(fromFile.ID))
                    {
                        throw new Exception(FilesCommonResource.ErrorMassage_UpdateEditingFile);
                    }
                    Updates.Add(fromFile.ID);
                }

                try
                {
                    var currFile = fileDao.GetFile(fileId);
                    var newFile  = new File
                    {
                        ID            = fromFile.ID,
                        Version       = currFile.Version + 1,
                        VersionGroup  = currFile.VersionGroup,
                        Title         = fromFile.Title,
                        ContentLength = fromFile.ContentLength,
                        FileStatus    = fromFile.FileStatus,
                        FolderID      = fromFile.FolderID,
                        CreateBy      = fromFile.CreateBy,
                        CreateOn      = fromFile.CreateOn,
                        ModifiedBy    = fromFile.ModifiedBy,
                        ModifiedOn    = fromFile.ModifiedOn,
                        ConvertedType = fromFile.ConvertedType
                    };

                    using (var stream = fileDao.GetFileStream(fromFile))
                    {
                        newFile = fileDao.SaveFile(newFile, stream);
                    }

                    FileMarker.MarkAsNew(newFile);

                    SetFileStatus(newFile);

                    return(newFile);
                }
                catch (Exception e)
                {
                    Global.Logger.Error(string.Format("Error on update {0} to version {1}", fileId, version), e);
                    throw new Exception(e.Message, e);
                }
                finally
                {
                    lock (Updates) Updates.Remove(fromFile.ID);
                }
            }
        }
Example #14
0
        public static IEnumerable <FileEntry> GetEntries(IFolderDao folderDao, 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 responseApi = JObject.Parse(Encoding.UTF8.GetString(Convert.FromBase64String(apiServer.GetApiResponse(apiUrl, "GET"))));

                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.Insert(projectLastModifiedCacheKey, projectLastModified);
                }

                var projectListCacheKey = String.Format("documents/projectFolders/{0}", SecurityContext.CurrentAccount.ID);
                var fromCache           = HttpRuntime.Cache.Get(projectListCacheKey);

                if (fromCache == null)
                {
                    apiUrl = String.Format("{0}project/filter.json?sortBy=title&sortOrder=ascending", 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, String>();

                    foreach (JObject projectInfo in responseData.Children())
                    {
                        var projectID    = projectInfo["id"].Value <String>();
                        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);
                        }

                        if (!folderIDProjectTitle.ContainsKey(projectFolderID))
                        {
                            folderIDProjectTitle.Add(projectFolderID, projectTitle);
                        }

                        HttpRuntime.Cache.Insert("documents/folders/" + projectFolderID.ToString(), projectTitle, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30));
                    }

                    var folders = folderDao.GetFolders(folderIDProjectTitle.Keys.ToArray());
                    folders.ForEach(x =>
                    {
                        x.Title     = folderIDProjectTitle[x.ID];
                        x.Access    = FileShare.ReadWrite;
                        x.FolderUrl = PathProvider.GetFolderUrl(x);
                    });

                    entries = entries.Concat(folders);

                    if (entries.Any())
                    {
                        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();
                shared = FilterEntries(shared, filter, subjectId, searchText)
                         .Where(f => f.CreateBy != SecurityContext.CurrentAccount.ID && // don't show my files
                                f.RootFolderType == FolderType.USER);                   // don't show common files (common files can read)
                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).Cast <FileEntry>();
                folders = fileSecurity.FilterRead(folders);
                entries = entries.Concat(folders);

                var files = folderDao.GetFiles(parent.ID, orderBy, filter, subjectId, searchText).Cast <FileEntry>();
                files   = fileSecurity.FilterRead(files);
                entries = entries.Concat(files);

                if ((parent.ID.Equals(Global.FolderMy) || parent.ID.Equals(Global.FolderCommon)) &&
                    ImportConfiguration.SupportInclusion &&
                    !CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor() &&
                    (Global.IsAdministrator ||
                     CoreContext.Configuration.Personal ||
                     FilesSettings.EnableThirdParty))
                {
                    using (var securityDao = Global.DaoFactory.GetSecurityDao())
                        using (var providerDao = Global.DaoFactory.GetProviderDao())
                        {
                            var providers  = providerDao.GetProvidersInfo(parent.RootFolderType);
                            var folderList = providers
                                             .Select(providerInfo =>
                                                     //Fake folder. Don't send request to third party
                                                     new Folder
                            {
                                ID                = providerInfo.RootFolderId,
                                ParentFolderID    = parent.ID,
                                CreateBy          = providerInfo.Owner,
                                CreateOn          = providerInfo.CreateOn,
                                FolderType        = FolderType.DEFAULT,
                                ModifiedBy        = providerInfo.Owner,
                                ModifiedOn        = providerInfo.CreateOn,
                                ProviderId        = providerInfo.ID,
                                ProviderKey       = providerInfo.ProviderKey,
                                RootFolderCreator = providerInfo.Owner,
                                RootFolderId      = providerInfo.RootFolderId,
                                RootFolderType    = providerInfo.RootFolderType,
                                Shareable         = false,
                                Title             = providerInfo.CustomerTitle,
                                TotalFiles        = 0,
                                TotalSubFolders   = 0
                            }
                                                     )
                                             .Where(fileSecurity.CanRead).ToList();

                            if (folderList.Any())
                            {
                                securityDao.GetPureShareRecords(folderList.Cast <FileEntry>().ToArray())
                                .Where(x => x.Owner == SecurityContext.CurrentAccount.ID)
                                .Select(x => x.EntryId).Distinct().ToList()
                                .ForEach(id =>
                                {
                                    folderList.First(y => y.ID.Equals(id)).SharedByMe = true;
                                });
                            }

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

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

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

            return(entries);
        }
Example #15
0
        public static File SaveEditing(String fileId, int version, Guid tabId, string downloadUri, bool asNew, String shareLinkKey, string comment = null, bool checkRight = true)
        {
            var app = ThirdPartySelector.GetAppByFileId(fileId);

            if (app != null)
            {
                app.SaveFile(fileId, downloadUri);
                return(null);
            }

            File file;

            using (var fileDao = Global.DaoFactory.GetFileDao())
            {
                var editLink = FileShareLink.Check(shareLinkKey, false, fileDao, out file);
                if (file == null)
                {
                    file = fileDao.GetFile(fileId);
                }

                if (file == null)
                {
                    throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
                }
                if (checkRight && !editLink && (!Global.GetFilesSecurity().CanEdit(file) || CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor()))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_EditFile);
                }
                if (checkRight && FileLockedForMe(file.ID))
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_LockedFile);
                }
                if (file.RootFolderType == FolderType.TRASH)
                {
                    throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
                }

                var currentType   = file.ConvertedType ?? FileUtility.GetFileExtension(file.Title);
                var newType       = FileUtility.GetFileExtension(downloadUri);
                var updateVersion = file.Version > 1 || file.ConvertedType == null || !asNew;

                if ((file.Version <= version || currentType != newType || version == -1) &&
                    updateVersion &&
                    !FileTracker.FixedVersion(file.ID))
                {
                    file.Version++;
                }

                file.ConvertedType = newType;

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

                    file.ConvertedType = currentType;
                }

                var req = (HttpWebRequest)WebRequest.Create(downloadUri);
                using (var editedFileStream = new ResponseStream(req.GetResponse()))
                {
                    file.ContentLength = editedFileStream.Length;
                    file.Comment       = string.IsNullOrEmpty(comment) ? string.Empty : comment;
                    file = fileDao.SaveFile(file, editedFileStream);
                }
            }

            checkRight = FileTracker.ProlongEditing(file.ID, tabId, true, SecurityContext.CurrentAccount.ID);
            if (checkRight)
            {
                FileTracker.ChangeRight(file.ID, SecurityContext.CurrentAccount.ID, false);
            }

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }
Example #16
0
        public static bool SetAceObject(List <AceWrapper> aceWrappers, FileEntry entry, bool notify, string message, AceAdvancedSettingsWrapper advancedSettings)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest);
            }
            if (!CanSetAccess(entry))
            {
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
            }

            var fileSecurity      = Global.GetFilesSecurity();
            var ownerId           = entry.RootFolderType == FolderType.USER ? entry.RootFolderCreator : entry.CreateBy;
            var entryType         = entry.FileEntryType;
            var recipients        = new Dictionary <Guid, FileShare>();
            var usersWithoutRight = new List <Guid>();
            var changed           = false;

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

                if (entry.RootFolderType == FolderType.COMMON && subjects.Contains(Constants.GroupAdmin.ID) ||
                    ownerId == w.SubjectId)
                {
                    continue;
                }

                var share = w.Share;

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

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

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

                    share = w.Share == FileShare.Restrict ||
                            !FilesSettings.ExternalShare
                                ? FileShare.None
                                : w.Share;
                }

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

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

                entry.Access = share;

                var listUsersId = new List <Guid>();

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

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

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

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

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

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

            if (advancedSettings != null && entryType == FileEntryType.File && ownerId == SecurityContext.CurrentAccount.ID && FileUtility.CanWebView(entry.Title) && !entry.ProviderEntry)
            {
                fileSecurity.Share(entry.ID, entryType, FileConstant.DenyDownloadId, advancedSettings.DenyDownload ? FileShare.Restrict : FileShare.None);
                fileSecurity.Share(entry.ID, entryType, FileConstant.DenySharingId, advancedSettings.DenySharing ? FileShare.Restrict : FileShare.None);
            }

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

            return(changed);
        }
Example #17
0
        private File SaveConvertedFile(File file, string convertedFileUrl)
        {
            var  fileSecurity = FileSecurity;
            var  fileDao      = DaoFactory.FileDao;
            var  folderDao    = DaoFactory.FolderDao;
            File newFile      = null;
            var  newFileTitle = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetInternalExtension(file.Title));

            if (!FilesSettingsHelper.StoreOriginalFiles && fileSecurity.CanEdit(file))
            {
                newFile = (File)file.Clone();
                newFile.Version++;
            }
            else
            {
                var folderId = GlobalFolderHelper.FolderMy;

                var parent = folderDao.GetFolder(file.FolderID);
                if (parent != null &&
                    fileSecurity.CanCreate(parent))
                {
                    folderId = parent.ID;
                }

                if (Equals(folderId, 0))
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_FolderNotFound);
                }

                if (FilesSettingsHelper.UpdateIfExist && (parent != null && folderId != parent.ID || !file.ProviderEntry))
                {
                    newFile = fileDao.GetFile(folderId, newFileTitle);
                    if (newFile != null && fileSecurity.CanEdit(newFile) && !EntryManager.FileLockedForMe(newFile.ID) && !FileTracker.IsEditing(newFile.ID))
                    {
                        newFile.Version++;
                    }
                    else
                    {
                        newFile = null;
                    }
                }

                if (newFile == null)
                {
                    newFile          = ServiceProvider.GetService <File>();
                    newFile.FolderID = folderId;
                }
            }

            newFile.Title         = newFileTitle;
            newFile.ConvertedType = null;
            newFile.Comment       = string.Format(FilesCommonResource.CommentConvert, file.Title);

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

            if (WorkContext.IsMono && ServicePointManager.ServerCertificateValidationCallback == null)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, c, n, p) => true; //HACK: http://ubuntuforums.org/showthread.php?t=1841740
            }

            try
            {
                using (var convertedFileStream = new ResponseStream(req.GetResponse()))
                {
                    newFile.ContentLength = convertedFileStream.Length;
                    newFile = fileDao.SaveFile(newFile, convertedFileStream);
                }
            }
            catch (WebException e)
            {
                using var response = e.Response;
                var httpResponse = (HttpWebResponse)response;
                var errorString  = string.Format("WebException: {0}", httpResponse.StatusCode);

                if (httpResponse.StatusCode != HttpStatusCode.NotFound)
                {
                    using var responseStream = response.GetResponseStream();
                    if (responseStream != null)
                    {
                        using var readStream = new StreamReader(responseStream);
                        var text = readStream.ReadToEnd();
                        errorString += string.Format(" Error message: {0}", text);
                    }
                }

                throw new Exception(errorString);
            }

            FilesMessageService.Send(newFile, MessageInitiator.DocsService, MessageAction.FileConverted, newFile.Title);
            FileMarker.MarkAsNew(newFile);

            var tagDao = DaoFactory.TagDao;
            var tags   = tagDao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList();

            if (tags.Any())
            {
                tags.ForEach(r => r.EntryId = newFile.ID);
                tagDao.SaveTags(tags);
            }

            return(newFile);
        }
Example #18
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", 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, String>();

                        foreach (JObject projectInfo in responseData.Children())
                        {
                            var projectID    = projectInfo["id"].Value <String>();
                            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);
                            }

                            if (!folderIDProjectTitle.ContainsKey(projectFolderID))
                            {
                                folderIDProjectTitle.Add(projectFolderID, projectTitle);
                            }
                            HttpRuntime.Cache.Remove("documents/folders/" + projectFolderID.ToString());
                            HttpRuntime.Cache.Insert("documents/folders/" + projectFolderID.ToString(), projectTitle, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(30));
                        }

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

                        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, !string.IsNullOrEmpty(searchText));
                if (CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).IsVisitor())
                {
                    shared = shared.Where(r => !r.ProviderEntry);
                }

                shared = FilterEntries(shared, filter, subjectId, searchText)
                         .Where(f => f.CreateBy != SecurityContext.CurrentAccount.ID && // don't show my files
                                f.RootFolderType == FolderType.USER);                   // don't show common files (common files can read)
                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);

                //TODO:Optimize
                var files = fileDao.GetFiles(parent.ID, orderBy, filter, subjectId, searchText, !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.Select(r => r as File).Where(r => r != null && r.ID != null));

            return(entries);
        }
        public static void SetAceObject(List <AceWrapper> aceWrappers, FileEntry entry, bool notify, string message)
        {
            if (entry == null)
            {
                throw new ArgumentNullException(FilesCommonResource.ErrorMassage_BadRequest);
            }
            if (!CanSetAccess(entry))
            {
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException);
            }

            var fileSecurity = Global.GetFilesSecurity();

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

            var entryType  = entry is File ? FileEntryType.File : FileEntryType.Folder;
            var recipients = new Dictionary <Guid, FileShare>();

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

                if (entry.RootFolderType == FolderType.COMMON &&
                    subjects.Contains(Constants.GroupAdmin.ID))
                {
                    continue;
                }

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

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

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

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

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

                entry.Access = share;

                var listUsersId = new List <Guid>();

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

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

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

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

                if (entry.RootFolderType == FolderType.USER &&
                    notify)
                {
                    NotifyClient.SendShareNotice(entry, recipients, message);
                }
            }
        }
        public static File ExecDuplicate(File file, string doc)
        {
            var toFolderId = file.FolderID;

            using (var fileDao = Global.DaoFactory.GetFileDao())
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    var fileSecurity = Global.GetFilesSecurity();
                    if (!fileSecurity.CanRead(file))
                    {
                        var readLink = FileShareLink.Check(doc, true, fileDao, out file);
                        if (file == null)
                        {
                            throw new ArgumentNullException("file", FilesCommonResource.ErrorMassage_FileNotFound);
                        }
                        if (!readLink)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
                        }
                        toFolderId = Global.FolderMy;
                    }
                    if (Global.EnableUploadFilter && !FileUtility.ExtsUploadable.Contains(FileUtility.GetFileExtension(file.Title)))
                    {
                        throw new Exception(FilesCommonResource.ErrorMassage_NotSupportedFormat);
                    }
                    var toFolder = folderDao.GetFolder(toFolderId);
                    if (toFolder == null)
                    {
                        throw new DirectoryNotFoundException(FilesCommonResource.ErrorMassage_FolderNotFound);
                    }
                    if (!fileSecurity.CanCreate(toFolder))
                    {
                        throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_Create);
                    }

                    var fileUri       = PathProvider.GetFileStreamUrl(file);
                    var fileExtension = file.ConvertedExtension;
                    var toExtension   = FileUtility.GetInternalExtension(file.Title);
                    var docKey        = DocumentServiceHelper.GetDocKey(file);

                    string convertUri;
                    fileUri = DocumentServiceConnector.ReplaceCommunityAdress(fileUri);
                    DocumentServiceConnector.GetConvertedUri(fileUri, fileExtension, toExtension, docKey, false, out convertUri);

                    var newFile = new File
                    {
                        FolderID = toFolder.ID,
                        Title    = FileUtility.ReplaceFileExtension(file.Title, toExtension),
                        Comment  = string.Format(FilesCommonResource.CommentConvert, file.Title),
                    };

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

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

                    using (var editedFileStream = new ResponseStream(req.GetResponse()))
                    {
                        newFile.ContentLength = editedFileStream.Length;
                        newFile = fileDao.SaveFile(newFile, editedFileStream);
                    }

                    FileMarker.MarkAsNew(newFile);
                    return(newFile);
                }
        }