Пример #1
0
        private Document CreateDocument <T>(T fileId, string documentName, string folderId, out File <T> file)
        {
            var fileDao = DaoFactory.GetFileDao <T>();

            file = fileDao.GetFile(fileId);
            if (file == null)
            {
                throw new Exception(FilesCommonResource.ErrorMassage_FileNotFound);
            }
            if (!FileSecurity.CanRead(file))
            {
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
            }
            if (!SupportedFormats.Contains(FileUtility.GetFileExtension(file.Title)))
            {
                throw new ArgumentException(FilesCommonResource.ErrorMassage_NotSupportedFormat);
            }
            if (file.ContentLength > MaxFileSize)
            {
                throw new Exception(FileSizeComment.GetFileSizeExceptionString(MaxFileSize));
            }

            byte[] fileBytes;
            using (var stream = fileDao.GetFileStream(file))
            {
                var buffer = new byte[16 * 1024];
                using var ms = new MemoryStream();
                int read;
                while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                fileBytes = ms.ToArray();
            }

            if (string.IsNullOrEmpty(documentName))
            {
                documentName = file.Title;
            }

            var document = new Document
            {
                DocumentBase64 = Convert.ToBase64String(fileBytes),
                DocumentFields = new List <NameValue>
                {
                    new NameValue {
                        Name = FilesLinkUtility.FolderId, Value = folderId
                    },
                    new NameValue {
                        Name = FilesLinkUtility.FileTitle, Value = file.Title
                    },
                },
                DocumentId    = "1", //file.ID.ToString(),
                FileExtension = FileUtility.GetFileExtension(file.Title),
                Name          = documentName,
            };

            return(document);
        }
Пример #2
0
        private void PrintResultBySave(SaveResult result, string pageName)
        {
            var infoType = InfoType.Info;
            if (!result.Equals(SaveResult.Ok) && !result.Equals(SaveResult.NoChanges))
            {
                infoType = InfoType.Alert;
            }

            switch (result)
            {
                case SaveResult.SectionUpdate:
                    Response.RedirectLC(ActionHelper.GetViewPagePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
                    break;
                case SaveResult.OkPageRename:
                case SaveResult.Ok:
                    PrintInfoMessage(WikiResource.msgSaveSucess, infoType);
                    if (Action.Equals(ActionOnPage.AddNew) || Action.Equals(ActionOnPage.Edit))
                    {
                        Response.RedirectLC(ActionHelper.GetViewPagePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
                    }
                    else if (Action.Equals(ActionOnPage.AddNewFile))
                    {
                        Response.RedirectLC(ActionHelper.GetEditFilePath(this.ResolveUrlLC("Default.aspx"), pageName), this);
                    }
                    break;
                case SaveResult.FileEmpty:
                    PrintInfoMessage(WikiResource.msgFileEmpty, infoType);
                    break;
                case SaveResult.FileSizeExceeded:
                    PrintInfoMessage(FileSizeComment.GetFileSizeExceptionString(FileUploader.MaxUploadSize), infoType);
                    break;
                case SaveResult.NoChanges:
                    PrintInfoMessage(WikiResource.msgNoChanges, infoType);
                    break;
                case SaveResult.PageNameIsEmpty:
                    PrintInfoMessage(WikiResource.msgPageNameEmpty, infoType);
                    break;
                case SaveResult.PageNameIsIncorrect:
                    PrintInfoMessage(WikiResource.msgPageNameIncorrect, infoType);
                    break;
                case SaveResult.SamePageExists:
                    PrintInfoMessage(WikiResource.msgSamePageExists, infoType);
                    break;
                case SaveResult.UserIdIsEmpty:
                    PrintInfoMessage(WikiResource.msgInternalError, infoType);
                    break;
                case SaveResult.OldVersion:
                    PrintInfoMessage(WikiResource.msgOldVersion, infoType);
                    break;
                case SaveResult.Error:
                    PrintInfoMessage(WikiResource.msgMarkupError, InfoType.Alert);
                    break;
                case SaveResult.PageTextIsEmpty:
                    PrintInfoMessage(WikiResource.msgPageTextEmpty, infoType);
                    break;
            }
        }
Пример #3
0
 private void DemandSize()
 {
     if (BackupHelper.ExceedsMaxAvailableSize(TenantManager.GetCurrentTenant().TenantId))
     {
         throw new InvalidOperationException(string.Format(UserControlsCommonResource.BackupSpaceExceed,
                                                           FileSizeComment.FilesSizeToString(BackupHelper.AvailableZipSize),
                                                           "",
                                                           ""));
     }
 }
Пример #4
0
        public static string GetTariffNotify()
        {
            var tariff = GetCurrentTariff();

            if (tariff.State == TariffState.Trial)
            {
                var count = tariff.DueDate.Subtract(DateTime.Today.Date).Days;
                if (count <= 0)
                {
                    return(Resource.TrialPeriodExpired);
                }

                string end;
                var    num = count % 100;

                if (num >= 11 && num <= 19)
                {
                    end = Resource.DaysTwo;
                }
                else
                {
                    var i = count % 10;
                    switch (i)
                    {
                    case (1):
                        end = Resource.Day;
                        break;

                    case (2):
                    case (3):
                    case (4):
                        end = Resource.DaysOne;
                        break;

                    default:
                        end = Resource.DaysTwo;
                        break;
                    }
                }
                return(string.Format(Resource.TrialPeriod, count, end));
            }

            if (tariff.State == TariffState.Paid)
            {
                var  quota = GetTenantQuota();
                long notifySize;
                long.TryParse(ConfigurationManager.AppSettings["web.tariff-notify.storage"] ?? "314572800", out notifySize); //300 MB
                if (notifySize > 0 && quota.MaxTotalSize - TenantStatisticsProvider.GetUsedSize() < notifySize)
                {
                    return(string.Format(Resource.TariffExceedLimit, FileSizeComment.FilesSizeToString(quota.MaxTotalSize)));
                }
            }

            return(string.Empty);
        }
Пример #5
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            var fileUploadResult = new FileUploadResult();

            if (!ProgressFileUploader.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new ProgressFileUploader.FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException("Invalid file.");
            }

            if (0 < SetupInfo.MaxImageUploadSize && SetupInfo.MaxImageUploadSize < file.ContentLength)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = FileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode();
                return(fileUploadResult);
            }

            if (FileUtility.GetFileTypeByFileName(file.FileName) != FileType.Image)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode();
                return(fileUploadResult);
            }


            var contactId  = Convert.ToInt32(context.Request["contactID"]);
            var uploadOnly = Convert.ToBoolean(context.Request["uploadOnly"]);
            var tmpDirName = Convert.ToString(context.Request["tmpDirName"]);
            var photoUri   = "";

            if (contactId != 0)
            {
                photoUri = ContactPhotoManager.UploadPhoto(file.InputStream, contactId, uploadOnly);
            }
            else
            {
                if (String.IsNullOrEmpty(tmpDirName))
                {
                    tmpDirName = Guid.NewGuid().ToString();
                }
                photoUri = ContactPhotoManager.UploadPhoto(file.InputStream, tmpDirName);
            }
            fileUploadResult.Success = true;
            fileUploadResult.Data    = photoUri;

            return(fileUploadResult);
        }
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            if (!CRMSecurity.IsAdmin)
            {
                throw CRMSecurity.CreateSecurityException();
            }

            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < SetupInfo.MaxImageUploadSize && SetupInfo.MaxImageUploadSize < file.ContentLength)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = FileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode();
                return(fileUploadResult);
            }

            if (FileUtility.GetFileTypeByFileName(file.FileName) != FileType.Image)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode();
                return(fileUploadResult);
            }

            try
            {
                var imageData   = Global.ToByteArray(file.InputStream);
                var imageFormat = ContactPhotoManager.CheckImgFormat(imageData);
                var photoUri    = OrganisationLogoManager.UploadLogo(imageData, imageFormat);

                fileUploadResult.Success = true;
                fileUploadResult.Data    = photoUri;
                return(fileUploadResult);
            }
            catch (Exception exception)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = exception.Message.HtmlEncode();
                return(fileUploadResult);
            }
        }
Пример #7
0
 public string GetSpaceUsage()
 {
     try
     {
         var spaceUsage = TalkSpaceUsageStatManager.GetSpaceUsage();
         return(spaceUsage > 0 ? FileSizeComment.FilesSizeToString(spaceUsage) : String.Empty);
     }
     catch (Exception ex)
     {
         LogManager.GetLogger("ASC.Talk").Error(ex);
         return(String.Empty);
     }
 }
Пример #8
0
        public async Task InvokeAsync(HttpContext context,
                                      SetupInfo setupInfo,
                                      DaoFactory daoFactory,
                                      FileSizeComment fileSizeComment,
                                      IServiceProvider serviceProvider,
                                      TenantExtra tenantExtra,
                                      TenantStatisticsProvider tenantStatisticsProvider)
        {
            context.Request.EnableBuffering();

            var fileUploadResult = new FileUploadResult();

            if (context.Request.Form.Files.Count == 0)
            {
                await context.Response.WriteAsync(JsonSerializer.Serialize(fileUploadResult));
            }

            var fileName      = context.Request.Form.Files[0].FileName;
            var contentLength = context.Request.Form.Files[0].Length;

            if (String.IsNullOrEmpty(fileName) || contentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < setupInfo.MaxUploadSize(tenantExtra, tenantStatisticsProvider) && setupInfo.MaxUploadSize(tenantExtra, tenantStatisticsProvider) < contentLength)
            {
                throw fileSizeComment.FileSizeException;
            }

            fileName = fileName.LastIndexOf('\\') != -1
               ? fileName.Substring(fileName.LastIndexOf('\\') + 1)
               : fileName;

            var document = serviceProvider.GetService <File <int> >();

            document.Title         = fileName;
            document.FolderID      = daoFactory.GetFileDao().GetRoot();
            document.ContentLength = contentLength;

            document = daoFactory.GetFileDao().SaveFile(document, context.Request.Form.Files[0].OpenReadStream());

            fileUploadResult.Data     = document.ID;
            fileUploadResult.FileName = document.Title;
            fileUploadResult.FileURL  = document.DownloadUrl;
            fileUploadResult.Success  = true;

            await context.Response.WriteAsync(JsonSerializer.Serialize(fileUploadResult));
        }
Пример #9
0
        public static File VerifyChunkedUpload(string folderId, string fileName, long fileSize, bool updateIfExists, string relativePath = null)
        {
            var maxUploadSize = GetMaxFileSize(folderId, true);

            if (fileSize > maxUploadSize)
            {
                throw FileSizeComment.GetFileSizeException(maxUploadSize);
            }

            var file = VerifyFileUpload(folderId, fileName, updateIfExists, relativePath);

            file.ContentLength = fileSize;

            return(file);
        }
Пример #10
0
        public override SearchResultItem[] Search(string text)
        {
            using (var folderDao = Global.DaoFactory.GetFolderDao())
            {
                var result = SearchFiles(text)
                             .Select(r =>
                {
                    var folders = EntryManager.GetBreadCrumbs(r.FolderID, folderDao);
                    return(new SearchResultItem
                    {
                        Name = r.Title ?? string.Empty,
                        Description = string.Empty,
                        URL = FilesLinkUtility.GetFileWebPreviewUrl(r.Title, r.ID),
                        Date = r.ModifiedOn,
                        Additional = new Dictionary <string, object>
                        {
                            { "Author", r.CreateByString.HtmlEncode() },
                            { "Path", FolderPathBuilder(folders) },
                            { "FullPath", FolderFullPathBuilder(folders) },
                            { "FolderUrl", PathProvider.GetFolderUrl(r.FolderID) },
                            { "Size", FileSizeComment.FilesSizeToString(r.ContentLength) }
                        }
                    });
                });

                var resultFolder = SearchFolders(text)
                                   .Select(f =>
                {
                    var folders = EntryManager.GetBreadCrumbs(f.ID, folderDao);
                    return(new SearchResultItem
                    {
                        Name = f.Title ?? string.Empty,
                        Description = String.Empty,
                        URL = PathProvider.GetFolderUrl(f),
                        Date = f.ModifiedOn,
                        Additional = new Dictionary <string, object>
                        {
                            { "Author", f.CreateByString.HtmlEncode() },
                            { "Path", FolderPathBuilder(folders) },
                            { "FullPath", FolderFullPathBuilder(folders) },
                            { "IsFolder", true }
                        }
                    });
                });

                return(result.Concat(resultFolder).ToArray());
            }
        }
 public void SendMsgRemoveUserDataCompleted(Guid recipientId, Guid fromUserId, string fromUserName, long docsSpace, long crmSpace, long mailSpace, long talkSpace)
 {
     client.SendNoticeToAsync(
         CoreContext.Configuration.CustomMode ? Actions.RemoveUserDataCompletedCustomMode : Actions.RemoveUserDataCompleted,
         null,
         new[] { StudioNotifyHelper.ToRecipient(recipientId) },
         new[] { EMailSenderName },
         null,
         new TagValue(Tags.UserName, DisplayUserSettings.GetFullUserName(recipientId)),
         new TagValue(Tags.FromUserName, fromUserName.HtmlEncode()),
         new TagValue(Tags.FromUserLink, GetUserProfileLink(fromUserId)),
         new TagValue("DocsSpace", FileSizeComment.FilesSizeToString(docsSpace)),
         new TagValue("CrmSpace", FileSizeComment.FilesSizeToString(crmSpace)),
         new TagValue("MailSpace", FileSizeComment.FilesSizeToString(mailSpace)),
         new TagValue("TalkSpace", FileSizeComment.FilesSizeToString(talkSpace)));
 }
Пример #12
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.ChunkUploadSize)
            {
                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)
            {
                using (var linkDao = Global.GetLinkDao())
                {
                    linkDao.DeleteAllLink(uploadSession.File.ID);
                }

                FileMarker.MarkAsNew(uploadSession.File);
                ChunkedUploadSessionHolder.RemoveSession(uploadSession);
            }
            else
            {
                ChunkedUploadSessionHolder.StoreSession(uploadSession);
            }

            return(uploadSession);
        }
Пример #13
0
        public SearchResultItem[] Search(string text)
        {
            var folderDao = DaoFactory.GetFolderDao <int>();
            var files     = SearchFiles(text);
            List <SearchResultItem> list = new List <SearchResultItem>();

            foreach (var file in files)
            {
                var searchResultItem = new SearchResultItem
                {
                    Name        = file.Title ?? string.Empty,
                    Description = string.Empty,
                    URL         = FilesLinkUtility.GetFileWebPreviewUrl(FileUtility, file.Title, file.ID),
                    Date        = file.ModifiedOn,
                    Additional  = new Dictionary <string, object>
                    {
                        { "Author", file.CreateByString.HtmlEncode() },
                        { "Path", FolderPathBuilder <int>(EntryManager.GetBreadCrumbs(file.FolderID, folderDao)) },
                        { "Size", FileSizeComment.FilesSizeToString(file.ContentLength) }
                    }
                };
                list.Add(searchResultItem);
            }

            var folders = SearchFolders(text);

            foreach (var folder in folders)
            {
                var searchResultItem = new SearchResultItem
                {
                    Name        = folder.Title ?? string.Empty,
                    Description = string.Empty,
                    URL         = PathProvider.GetFolderUrl(folder),
                    Date        = folder.ModifiedOn,
                    Additional  = new Dictionary <string, object>
                    {
                        { "Author", folder.CreateByString.HtmlEncode() },
                        { "Path", FolderPathBuilder <int>(EntryManager.GetBreadCrumbs(folder.ID, folderDao)) },
                        { "IsFolder", true }
                    }
                };
                list.Add(searchResultItem);
            }

            return(list.ToArray());
        }
Пример #14
0
        private void ContentSearch()
        {
            var security = Global.GetFilesSecurity();

            using (var folderDao = Global.DaoFactory.GetFolderDao())
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    var files = fileDao.Search(SearchText, FolderType.USER | FolderType.COMMON)
                                .Where(security.CanRead)
                                .Select(r => new SearchItem
                    {
                        ID             = r.ID,
                        FileTitle      = r.Title ?? string.Empty,
                        Owner          = CoreContext.UserManager.GetUsers(r.CreateBy).DisplayUserName() ?? string.Empty,
                        Uploaded       = r.ModifiedOn.ToString(DateTimeExtension.ShortDatePattern),
                        Size           = FileSizeComment.FilesSizeToString(r.ContentLength),
                        FolderPathPart = FolderPathBuilder(folderDao.GetParentFolders(r.FolderID)),
                        ItemUrl        = FileUtility.ExtsWebPreviewed.Contains(FileUtility.GetFileExtension(r.Title), StringComparer.CurrentCultureIgnoreCase) ? CommonLinkUtility.GetFileWebViewerUrl(r.ID) : r.ViewUrl,
                        IsFolder       = false
                    });

                    var folders = folderDao.Search(SearchText, FolderType.USER | FolderType.COMMON)
                                  .Where(security.CanRead)
                                  .Select(f => new SearchItem
                    {
                        ID             = f.ID,
                        FileTitle      = f.Title ?? string.Empty,
                        Body           = string.Empty,
                        Owner          = CoreContext.UserManager.GetUsers(f.CreateBy).DisplayUserName() ?? string.Empty,
                        Uploaded       = f.ModifiedOn.ToString(DateTimeExtension.ShortDatePattern),
                        FolderPathPart = FolderPathBuilder(folderDao.GetParentFolders(f.ID)),
                        ItemUrl        = PathProvider.GetFolderUrl(f),
                        IsFolder       = true
                    });

                    NumberOfFileFound   = files.Count();
                    NumberOfFolderFound = folders.Count();

                    var result = folders.Concat(files).ToList();
                    if (result.Count != 0)
                    {
                        ContentSearchRepeater.DataSource = result;
                        ContentSearchRepeater.DataBind();
                    }
                }
        }
Пример #15
0
        public override SearchResultItem[] Search(string text)
        {
            var security = Global.GetFilesSecurity();

            using (var folderDao = Global.DaoFactory.GetFolderDao())
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    var files = fileDao.Search(text, FolderType.USER | FolderType.COMMON)
                                .Where(security.CanRead)
                                .Select(r => new SearchResultItem
                    {
                        Name        = r.Title ?? string.Empty,
                        Description = string.Empty,
                        URL         = FileUtility.ExtsWebPreviewed.Contains(FileUtility.GetFileExtension(r.Title), StringComparer.CurrentCultureIgnoreCase)
                                                   ? CommonLinkUtility.GetFileWebViewerUrl(r.ID)
                                                   : r.ViewUrl,
                        Date       = r.ModifiedOn,
                        Additional = new Dictionary <string, object>
                        {
                            { "Author", r.CreateByString.HtmlEncode() },
                            { "Container", folderDao.GetParentFolders(r.FolderID) },
                            { "IsFolder", false },
                            { "Size", FileSizeComment.FilesSizeToString(r.ContentLength) }
                        }
                    });

                    var folders = folderDao.Search(text, FolderType.USER | FolderType.COMMON)
                                  .Where(security.CanRead)
                                  .Select(f => new SearchResultItem
                    {
                        Name        = f.Title ?? string.Empty,
                        Description = String.Empty,
                        URL         = PathProvider.GetFolderUrl(f),
                        Date        = f.ModifiedOn,
                        Additional  = new Dictionary <string, object>
                        {
                            { "Author", f.CreateByString.HtmlEncode() },
                            { "Container", folderDao.GetParentFolders(f.ID) },
                            { "IsFolder", true }
                        }
                    });

                    return(folders.Concat(files).ToArray());
                }
        }
Пример #16
0
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            try
            {
                if (context.Request.Files.Count == 0)
                {
                    throw new Exception("there is no file");
                }

                var file = context.Request.Files[0];

                if (file.ContentLength > SetupInfo.MaxImageUploadSize)
                {
                    throw FileSizeComment.FileImageSizeException;
                }

                var UserId   = context.Request["ownjid"];
                var FileName = file.FileName.Replace("~", "-");
                var FileURL  = String.Empty;
                var FileSize = file.InputStream.Length;
                //if (String.IsNullOrEmpty(UserId))
                //{
                //    throw new Exception("there is no userId");
                //}
                var FilePath = StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(), "talk").Save(Path.Combine(MD5Hash(UserId), FileName), file.InputStream);
                FileURL  = FilePath.ToString();
                FileName = FileURL.Substring(FileURL.LastIndexOf("/") + 1);
                return(new FileUploadResult
                {
                    FileName = FileName,
                    Data = FileSizeComment.FilesSizeToString(FileSize),
                    FileURL = CommonLinkUtility.GetFullAbsolutePath(FileURL),
                    Success = true
                });
            }
            catch (Exception ex)
            {
                return(new FileUploadResult()
                {
                    Success = false,
                    Message = ex.Message
                });
            }
        }
Пример #17
0
        public static File VerifyFileUpload(string folderId, string fileName, long fileSize, bool updateIfExists)
        {
            if (fileSize <= 0)
            {
                throw new Exception(FilesCommonResource.ErrorMassage_EmptyFile);
            }

            var maxUploadSize = GetMaxFileSize(folderId);

            if (fileSize > maxUploadSize)
            {
                throw FileSizeComment.GetFileSizeException(maxUploadSize);
            }

            var file = VerifyFileUpload(folderId, fileName, updateIfExists);

            file.ContentLength = fileSize;
            return(file);
        }
Пример #18
0
        public override SearchResultItem[] Search(string text)
        {
            var security = Global.GetFilesSecurity();

            using (var folderDao = Global.DaoFactory.GetFolderDao())
                using (var fileDao = Global.DaoFactory.GetFileDao())
                {
                    var files = fileDao.Search(text, FolderType.USER | FolderType.COMMON)
                                .Where(security.CanRead)
                                .Select(r => new SearchResultItem
                    {
                        Name        = r.Title ?? string.Empty,
                        Description = string.Empty,
                        URL         = CommonLinkUtility.GetFileWebPreviewUrl(r.Title, r.ID),
                        Date        = r.ModifiedOn,
                        Additional  = new Dictionary <string, object>
                        {
                            { "Author", r.CreateByString.HtmlEncode() },
                            { "Path", FolderPathBuilder(EntryManager.GetBreadCrumbs(r.FolderID, folderDao)) },
                            { "Size", FileSizeComment.FilesSizeToString(r.ContentLength) }
                        }
                    });

                    var folders = folderDao.Search(text, FolderType.USER | FolderType.COMMON)
                                  .Where(security.CanRead)
                                  .Select(f => new SearchResultItem
                    {
                        Name        = f.Title ?? string.Empty,
                        Description = String.Empty,
                        URL         = PathProvider.GetFolderUrl(f),
                        Date        = f.ModifiedOn,
                        Additional  = new Dictionary <string, object>
                        {
                            { "Author", f.CreateByString.HtmlEncode() },
                            { "Path", FolderPathBuilder(EntryManager.GetBreadCrumbs(f.ID, folderDao)) },
                            { "IsFolder", true }
                        }
                    });

                    return(folders.Concat(files).ToArray());
                }
        }
Пример #19
0
        public static File VerifyChunkedUpload(string folderId, string fileName, long fileSize, bool updateIfExists)
        {
            long maxUploadSize;

            using (var folderDao = Global.DaoFactory.GetFolderDao())
            {
                maxUploadSize = folderDao.GetMaxUploadSize(folderId, true);
            }

            if (fileSize > maxUploadSize)
            {
                throw FileSizeComment.GetFileSizeException(maxUploadSize);
            }

            File file = VerifyFileUpload(folderId, fileName, updateIfExists);

            file.ContentLength = fileSize;

            return(file);
        }
Пример #20
0
        private Tuple <string, string> GetPersonalTariffNotify()
        {
            var maxTotalSize = CoreContext.Configuration.PersonalMaxSpace;

            var webItem           = WebItemManager.Instance[WebItemManager.DocumentsProductID];
            var spaceUsageManager = webItem.Context.SpaceUsageStatManager as IUserSpaceUsage;

            if (spaceUsageManager == null)
            {
                return(null);
            }

            var usedSize = spaceUsageManager.GetUserSpaceUsage(SecurityContext.CurrentAccount.ID);

            long notifySize;

            long.TryParse(ConfigurationManagerExtension.AppSettings["web.tariff-notify.storage"] ?? "104857600", out notifySize); //100 MB

            if (notifySize > 0 && maxTotalSize - usedSize < notifySize)
            {
                var head = string.Format(Resource.PersonalTariffExceedLimit, FileSizeComment.FilesSizeToString(maxTotalSize));

                string text;

                if (CoreContext.Configuration.CustomMode)
                {
                    text = string.Format(Resource.PersonalTariffExceedLimitInfoText, string.Empty, string.Empty, "</br>");
                }
                else
                {
                    var settings    = MailWhiteLabelSettings.Instance;
                    var supportLink = string.Format("<a target=\"_blank\" href=\"{0}\">", settings.SupportUrl);
                    text = string.Format(Resource.PersonalTariffExceedLimitInfoText, supportLink, "</a>", "</br>");
                }

                return(new Tuple <string, string>(head, text));
            }

            return(null);
        }
Пример #21
0
        public ChunkedUploadSession <T> UploadChunk <T>(string uploadId, Stream stream, long chunkLength)
        {
            var uploadSession = ChunkedUploadSessionHolder.GetSession <T>(uploadId);

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

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

            if (chunkLength > SetupInfo.ChunkUploadSize)
            {
                throw FileSizeComment.GetFileSizeException(SetupInfo.MaxUploadSize(TenantExtra, TenantStatisticsProvider));
            }

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

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

            var dao = DaoFactory.GetFileDao <T>();

            dao.UploadChunk(uploadSession, stream, chunkLength);

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

            return(uploadSession);
        }
        public override FileUploadResult ProcessUpload(HttpContext context)
        {
            try
            {
                if (context.Request.Files.Count == 0)
                {
                    throw new Exception("there is no file");
                }

                var file = context.Request.Files[0];

                if (file.ContentLength > SetupInfo.MaxImageUploadSize)
                {
                    throw FileSizeComment.FileImageSizeException;
                }

                var fileName = file.FileName.Replace("~", "-");
                var storage  = StorageFactory.GetStorage(TenantProvider.CurrentTenantID.ToString(CultureInfo.InvariantCulture), "talk");
                var md5Hash  = TalkSpaceUsageStatManager.GetUserMd5Hash(SecurityContext.CurrentAccount.ID);
                var fileUrl  = storage.Save(Path.Combine(md5Hash, GenerateRandomString(), fileName), file.InputStream).ToString();
                fileName = Path.GetFileName(fileUrl);

                return(new FileUploadResult
                {
                    FileName = fileName,
                    Data = FileSizeComment.FilesSizeToString(file.InputStream.Length),
                    FileURL = CommonLinkUtility.GetFullAbsolutePath(fileUrl),
                    Success = true
                });
            }
            catch (Exception ex)
            {
                return(new FileUploadResult
                {
                    Success = false,
                    Message = ex.Message
                });
            }
        }
Пример #23
0
        protected void cmdFileUpload_Click(object sender, EventArgs e)
        {
            if (fuFile.HasFile)
            {
                var result = EditFile.DirectFileSave(SecurityContext.CurrentAccount.ID, fuFile, MapPath("~"), WikiSection.Section, ConfigLocation, TenantId, HttpContext.Current);

                switch (result)
                {
                case SaveResult.Ok:
                    Response.Redirect(Request.GetUrlRewriter().ToString(), true);
                    return;

                case SaveResult.FileEmpty:
                    WikiMaster.PrintInfoMessage(WikiResource.msgFileEmpty, InfoType.Alert);
                    break;

                case SaveResult.FileSizeExceeded:
                    WikiMaster.PrintInfoMessage(FileSizeComment.GetFileSizeExceptionString(FileUploader.MaxUploadSize), InfoType.Alert);
                    break;
                }
            }

            BindRepeater();
        }
Пример #24
0
        public File CreateOrUpdateFile(File file, Stream stream)
        {
            if (file.FileSize > FileUploader.MaxUploadSize)
            {
                throw FileSizeComment.GetFileSizeException(FileUploader.MaxUploadSize);
            }
            if (String.IsNullOrEmpty(file.FileName))
            {
                throw new ArgumentException(@"name of file cannot be empty", "file");
            }

            file.UserID = SecurityContext.CurrentAccount.ID;
            file.Date   = DateTime.UtcNow;
            file.Version++;
            file.FileLocation = GetFileLocation(file.FileName);

            if (stream != null)
            {
                var store = StorageFactory.GetStorage(CoreContext.TenantManager.GetCurrentTenant().TenantId.ToString(), "wiki");
                store.Save(string.Empty, file.FileLocation, stream, file.FileName);
            }

            return(SaveFile(file));
        }
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < SetupInfo.MaxImageUploadSize && SetupInfo.MaxImageUploadSize < file.ContentLength)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = FileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode();
                return(fileUploadResult);
            }

            if (FileUtility.GetFileTypeByFileName(file.FileName) != FileType.Image)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode();
                return(fileUploadResult);
            }

            var photoUri = OrganisationLogoManager.UploadLogo(file.InputStream, true);

            fileUploadResult.Success = true;
            fileUploadResult.Data    = photoUri;
            return(fileUploadResult);
        }
Пример #26
0
        public FileUploadResult ProcessUpload(HttpContext context)
        {
            if (!WebItemSecurity.IsAvailableForUser(ProductEntryPoint.ID.ToString(), SecurityContext.CurrentAccount.ID))
            {
                throw CRMSecurity.CreateSecurityException();
            }

            var     contactId = Convert.ToInt32(context.Request["contactID"]);
            Contact contact   = null;

            if (contactId != 0)
            {
                contact = Global.DaoFactory.GetContactDao().GetByID(contactId);
                if (!CRMSecurity.CanAccessTo(contact))
                {
                    throw CRMSecurity.CreateSecurityException();
                }
            }

            var fileUploadResult = new FileUploadResult();

            if (!FileToUpload.HasFilesToUpload(context))
            {
                return(fileUploadResult);
            }

            var file = new FileToUpload(context);

            if (String.IsNullOrEmpty(file.FileName) || file.ContentLength == 0)
            {
                throw new InvalidOperationException(CRMErrorsResource.InvalidFile);
            }

            if (0 < SetupInfo.MaxImageUploadSize && SetupInfo.MaxImageUploadSize < file.ContentLength)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = FileSizeComment.GetFileImageSizeNote(CRMCommonResource.ErrorMessage_UploadFileSize, false).HtmlEncode();
                return(fileUploadResult);
            }

            if (FileUtility.GetFileTypeByFileName(file.FileName) != FileType.Image)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = CRMJSResource.ErrorMessage_NotImageSupportFormat.HtmlEncode();
                return(fileUploadResult);
            }

            var uploadOnly = Convert.ToBoolean(context.Request["uploadOnly"]);
            var tmpDirName = Convert.ToString(context.Request["tmpDirName"]);

            try
            {
                string photoUri;
                if (contactId != 0)
                {
                    photoUri = ContactPhotoManager.UploadPhoto(file.InputStream, contactId, uploadOnly);
                }
                else
                {
                    if (String.IsNullOrEmpty(tmpDirName))
                    {
                        tmpDirName = Guid.NewGuid().ToString();
                    }
                    photoUri = ContactPhotoManager.UploadPhoto(file.InputStream, tmpDirName);
                }

                fileUploadResult.Success = true;
                fileUploadResult.Data    = photoUri;
            }
            catch (Exception e)
            {
                fileUploadResult.Success = false;
                fileUploadResult.Message = e.Message.HtmlEncode();
                return(fileUploadResult);
            }

            if (contact != null)
            {
                var messageAction = contact is Company ? MessageAction.CompanyUpdatedPhoto : MessageAction.PersonUpdatedPhoto;
                MessageService.Send(context.Request, messageAction, MessageTarget.Create(contact.ID), contact.GetTitle());
            }

            return(fileUploadResult);
        }
Пример #27
0
        private Stream CompressToZip(ItemNameValueCollection entriesPathId)
        {
            var stream = TempStream.Create();

            using (var zip = new ionic::Ionic.Zip.ZipOutputStream(stream, true))
            {
                zip.CompressionLevel       = ionic::Ionic.Zlib.CompressionLevel.Level3;
                zip.AlternateEncodingUsage = ionic::Ionic.Zip.ZipOption.AsNecessary;
                zip.AlternateEncoding      = Encoding.GetEncoding(Thread.CurrentThread.CurrentCulture.TextInfo.OEMCodePage);

                foreach (var path in entriesPathId.AllKeys)
                {
                    if (Canceled)
                    {
                        zip.Dispose();
                        stream.Dispose();
                        return(null);
                    }

                    var counter = 0;
                    foreach (var entryId in entriesPathId[path])
                    {
                        var newtitle = path;

                        File file         = null;
                        var  convertToExt = string.Empty;

                        if (!string.IsNullOrEmpty(entryId))
                        {
                            file = FileDao.GetFile(entryId);

                            if (file.ContentLength > SetupInfo.AvailableFileSize)
                            {
                                Error = string.Format(FilesCommonResource.ErrorMassage_FileSizeZip, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize));
                                continue;
                            }

                            if (_files.ContainsKey(file.ID.ToString()))
                            {
                                if (_quotaDocsEdition)
                                {
                                    convertToExt = _files[file.ID.ToString()];
                                }

                                if (!string.IsNullOrEmpty(convertToExt))
                                {
                                    newtitle = FileUtility.ReplaceFileExtension(path, convertToExt);
                                }
                            }
                        }

                        if (0 < counter)
                        {
                            var suffix = " (" + counter + ")";

                            if (!string.IsNullOrEmpty(entryId))
                            {
                                newtitle = 0 < newtitle.IndexOf('.')
                                               ? newtitle.Insert(newtitle.LastIndexOf('.'), suffix)
                                               : newtitle + suffix;
                            }
                            else
                            {
                                break;
                            }
                        }

                        zip.PutNextEntry(newtitle);

                        if (!string.IsNullOrEmpty(entryId) && file != null)
                        {
                            if (file.ConvertedType != null || !string.IsNullOrEmpty(convertToExt))
                            {
                                //Take from converter
                                try
                                {
                                    using (var readStream = !string.IsNullOrEmpty(convertToExt)
                                                                ? FileConverter.Exec(file, convertToExt)
                                                                : FileConverter.Exec(file))
                                    {
                                        if (readStream != null)
                                        {
                                            readStream.StreamCopyTo(zip);
                                            if (!string.IsNullOrEmpty(convertToExt))
                                            {
                                                FilesMessageService.Send(file, httpRequestHeaders, MessageAction.FileDownloadedAs, file.Title, convertToExt);
                                            }
                                            else
                                            {
                                                FilesMessageService.Send(file, httpRequestHeaders, MessageAction.FileDownloaded, file.Title);
                                            }
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Error = ex.Message;

                                    Logger.Error(Error, ex);
                                }
                            }
                            else
                            {
                                using (var readStream = FileDao.GetFileStream(file))
                                {
                                    readStream.StreamCopyTo(zip);
                                    FilesMessageService.Send(file, httpRequestHeaders, MessageAction.FileDownloaded, file.Title);
                                }
                            }
                        }
                        counter++;
                    }

                    ProgressStep();
                }
                return(stream);
            }
        }
Пример #28
0
        public File <T> GetParams <T>(File <T> file, bool lastVersion, FileShare linkRight, bool rightToRename, bool rightToEdit, bool editPossible, bool tryEdit, bool tryCoauth, out Configuration <T> configuration)
        {
            if (file == null)
            {
                throw new FileNotFoundException(FilesCommonResource.ErrorMassage_FileNotFound);
            }
            if (!string.IsNullOrEmpty(file.Error))
            {
                throw new Exception(file.Error);
            }

            var rightToReview  = rightToEdit;
            var reviewPossible = editPossible;

            var rightToFillForms  = rightToEdit;
            var fillFormsPossible = editPossible;

            var rightToComment  = rightToEdit;
            var commentPossible = editPossible;

            var rightModifyFilter = rightToEdit;

            if (linkRight == FileShare.Restrict && UserManager.GetUsers(AuthContext.CurrentAccount.ID).IsVisitor(UserManager))
            {
                rightToEdit      = false;
                rightToReview    = false;
                rightToFillForms = false;
                rightToComment   = false;
            }

            var fileSecurity = FileSecurity;

            rightToEdit = rightToEdit &&
                          (linkRight == FileShare.ReadWrite || linkRight == FileShare.CustomFilter ||
                           fileSecurity.CanEdit(file) || fileSecurity.CanCustomFilterEdit(file));
            if (editPossible && !rightToEdit)
            {
                editPossible = false;
            }

            rightModifyFilter = rightModifyFilter &&
                                (linkRight == FileShare.ReadWrite ||
                                 fileSecurity.CanEdit(file));

            rightToRename = rightToRename && rightToEdit && fileSecurity.CanEdit(file);

            rightToReview = rightToReview &&
                            (linkRight == FileShare.Review || linkRight == FileShare.ReadWrite ||
                             fileSecurity.CanReview(file));
            if (reviewPossible && !rightToReview)
            {
                reviewPossible = false;
            }

            rightToFillForms = rightToFillForms &&
                               (linkRight == FileShare.FillForms || linkRight == FileShare.Review || linkRight == FileShare.ReadWrite ||
                                fileSecurity.CanFillForms(file));
            if (fillFormsPossible && !rightToFillForms)
            {
                fillFormsPossible = false;
            }

            rightToComment = rightToComment &&
                             (linkRight == FileShare.Comment || linkRight == FileShare.Review || linkRight == FileShare.ReadWrite ||
                              fileSecurity.CanComment(file));
            if (commentPossible && !rightToComment)
            {
                commentPossible = false;
            }

            if (linkRight == FileShare.Restrict &&
                !(editPossible || reviewPossible || fillFormsPossible || commentPossible) &&
                !fileSecurity.CanRead(file))
            {
                throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException_ReadFile);
            }

            if (file.RootFolderType == FolderType.TRASH)
            {
                throw new Exception(FilesCommonResource.ErrorMassage_ViewTrashItem);
            }

            if (file.ContentLength > SetupInfo.AvailableFileSize)
            {
                throw new Exception(string.Format(FilesCommonResource.ErrorMassage_FileSizeEdit, FileSizeComment.FilesSizeToString(SetupInfo.AvailableFileSize)));
            }

            string strError = null;

            if ((editPossible || reviewPossible || fillFormsPossible || commentPossible) &&
                LockerManager.FileLockedForMe(file.ID))
            {
                if (tryEdit)
                {
                    strError = FilesCommonResource.ErrorMassage_LockedFile;
                }
                rightToRename    = false;
                rightToEdit      = editPossible = false;
                rightToReview    = reviewPossible = false;
                rightToFillForms = fillFormsPossible = false;
                rightToComment   = commentPossible = false;
            }

            if (editPossible &&
                !FileUtility.CanWebEdit(file.Title))
            {
                rightToEdit = editPossible = false;
            }

            if (file.Encrypted &&
                file.RootFolderType != FolderType.Privacy)
            {
                rightToEdit      = editPossible = false;
                rightToReview    = reviewPossible = false;
                rightToFillForms = fillFormsPossible = false;
                rightToComment   = commentPossible = false;
            }


            if (!editPossible && !FileUtility.CanWebView(file.Title))
            {
                throw new Exception(string.Format("{0} ({1})", FilesCommonResource.ErrorMassage_NotSupportedFormat, FileUtility.GetFileExtension(file.Title)));
            }

            if (reviewPossible &&
                !FileUtility.CanWebReview(file.Title))
            {
                rightToReview = reviewPossible = false;
            }

            if (fillFormsPossible &&
                !FileUtility.CanWebRestrictedEditing(file.Title))
            {
                rightToFillForms = fillFormsPossible = false;
            }

            if (commentPossible &&
                !FileUtility.CanWebComment(file.Title))
            {
                rightToComment = commentPossible = false;
            }

            var rightChangeHistory = rightToEdit && !file.Encrypted;

            if (FileTracker.IsEditing(file.ID))
            {
                rightChangeHistory = false;

                bool coauth;
                if ((editPossible || reviewPossible || fillFormsPossible || commentPossible) &&
                    tryCoauth &&
                    (!(coauth = FileUtility.CanCoAuhtoring(file.Title)) || FileTracker.IsEditingAlone(file.ID)))
                {
                    if (tryEdit)
                    {
                        var editingBy = FileTracker.GetEditingBy(file.ID).FirstOrDefault();
                        strError = string.Format(!coauth
                                                     ? FilesCommonResource.ErrorMassage_EditingCoauth
                                                     : FilesCommonResource.ErrorMassage_EditingMobile,
                                                 Global.GetUserName(editingBy, true));
                    }
                    rightToEdit = editPossible = reviewPossible = fillFormsPossible = commentPossible = false;
                }
            }

            var fileStable = file;

            if (lastVersion && file.Forcesave != ForcesaveType.None && tryEdit)
            {
                var fileDao = DaoFactory.GetFileDao <T>();
                fileStable = fileDao.GetFileStable(file.ID, file.Version);
            }

            var docKey    = GetDocKey(fileStable);
            var modeWrite = (editPossible || reviewPossible || fillFormsPossible || commentPossible) && tryEdit;

            configuration = new Configuration <T>(file, ServiceProvider)
            {
                Document =
                {
                    Key         = docKey,
                    Permissions =
                    {
                        Edit          = rightToEdit && lastVersion,
                        Rename        = rightToRename && lastVersion && !file.ProviderEntry,
                        Review        = rightToReview && lastVersion,
                        FillForms     = rightToFillForms && lastVersion,
                        Comment       = rightToComment && lastVersion,
                        ChangeHistory = rightChangeHistory,
                        ModifyFilter  = rightModifyFilter
                    }
                },
                EditorConfig =
                {
                    ModeWrite = modeWrite,
                },
                ErrorMessage = strError,
            };

            if (!lastVersion)
            {
                configuration.Document.Title += string.Format(" ({0})", file.CreateOnString);
            }

            return(file);
        }
Пример #29
0
        private static string CreateConvertedFile(string driveFile, Token token)
        {
            var jsonFile = JObject.Parse(driveFile);
            var fileName = GetCorrectTitle(jsonFile);

            fileName = FileUtility.ReplaceFileExtension(fileName, FileUtility.GetInternalExtension(fileName));

            var folderId = (string)jsonFile.SelectToken("parents[0]");

            Global.Logger.Info("GoogleDriveApp: create copy - " + fileName);

            var ext    = GetCorrectExt(jsonFile);
            var fileId = jsonFile.Value <string>("id");

            if (GoogleLoginProvider.GoogleDriveExt.Contains(ext))
            {
                var fileType         = FileUtility.GetFileTypeByExtention(ext);
                var internalExt      = FileUtility.InternalExtension[fileType];
                var requiredMimeType = MimeMapping.GetMimeMapping(internalExt);

                var downloadUrl = GoogleLoginProvider.GoogleUrlFile
                                  + string.Format("{0}/export?mimeType={1}",
                                                  fileId,
                                                  HttpUtility.UrlEncode(requiredMimeType));

                var request = (HttpWebRequest)WebRequest.Create(downloadUrl);
                request.Method = "GET";
                request.Headers.Add("Authorization", "Bearer " + token);

                Global.Logger.Debug("GoogleDriveApp: download exportLink - " + downloadUrl);
                try
                {
                    using (var response = request.GetResponse())
                        using (var fileStream = new ResponseStream(response))
                        {
                            driveFile = CreateFile(fileStream, fileName, folderId, token);
                        }
                }
                catch (WebException e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error download exportLink", e);
                    request.Abort();
                }
            }
            else
            {
                var downloadUrl = GoogleLoginProvider.GoogleUrlFile + fileId + "?alt=media";

                var convertedUrl = ConvertFile(downloadUrl, ext, token);

                if (string.IsNullOrEmpty(convertedUrl))
                {
                    Global.Logger.ErrorFormat("GoogleDriveApp: Error convertUrl. size {0}", FileSizeComment.FilesSizeToString(jsonFile.Value <int>("size")));
                    throw new Exception(FilesCommonResource.ErrorMassage_DocServiceException + " (convert)");
                }

                driveFile = CreateFile(convertedUrl, fileName, folderId, token);
            }

            jsonFile = JObject.Parse(driveFile);
            return(jsonFile.Value <string>("id"));
        }
Пример #30
0
        public File ReplaceFileVersion(File file, Stream fileStream)
        {
            if (file == null)
            {
                throw new ArgumentNullException("file");
            }
            if (file.ID == null)
            {
                throw new ArgumentException("No file id or folder id toFolderId determine provider");
            }

            if (SetupInfo.MaxChunkedUploadSize < file.ContentLength)
            {
                throw FileSizeComment.GetFileSizeException(SetupInfo.MaxChunkedUploadSize);
            }

            if (CoreContext.Configuration.Personal && SetupInfo.IsVisibleSettings("PersonalMaxSpace"))
            {
                if (CoreContext.Configuration.PersonalMaxSpace - Global.GetUserUsedSpace(file.ID == null ? SecurityContext.CurrentAccount.ID : file.CreateBy) < file.ContentLength)
                {
                    throw FileSizeComment.GetPersonalFreeSpaceException(CoreContext.Configuration.PersonalMaxSpace);
                }
            }

            List <object> parentFoldersIds;

            lock (syncRoot)
            {
                using (var tx = dbManager.BeginTransaction())
                {
                    file.Title = Global.ReplaceInvalidCharsAndTruncate(file.Title);
                    //make lowerCase
                    file.Title = FileUtility.ReplaceFileExtension(file.Title, FileUtility.GetFileExtension(file.Title));

                    file.ModifiedBy = SecurityContext.CurrentAccount.ID;
                    file.ModifiedOn = TenantUtil.DateTimeNow();
                    if (file.CreateBy == default(Guid))
                    {
                        file.CreateBy = SecurityContext.CurrentAccount.ID;
                    }
                    if (file.CreateOn == default(DateTime))
                    {
                        file.CreateOn = TenantUtil.DateTimeNow();
                    }

                    var sql = Update("files_file")
                              .Set("version", file.Version)
                              .Set("version_group", file.VersionGroup)
                              .Set("folder_id", file.FolderID)
                              .Set("title", file.Title)
                              .Set("content_length", file.ContentLength)
                              .Set("category", (int)file.FilterType)
                              .Set("create_by", file.CreateBy.ToString())
                              .Set("create_on", TenantUtil.DateTimeToUtc(file.CreateOn))
                              .Set("modified_by", file.ModifiedBy.ToString())
                              .Set("modified_on", TenantUtil.DateTimeToUtc(file.ModifiedOn))
                              .Set("converted_type", file.ConvertedType)
                              .Set("comment", file.Comment)
                              .Set("encrypted", file.Encrypted)
                              .Set("forcesave", (int)file.Forcesave)
                              .Set("thumb", file.ThumbnailStatus)
                              .Where("id", file.ID)
                              .Where("version", file.Version);
                    dbManager.ExecuteNonQuery(sql);
                    tx.Commit();

                    file.PureTitle = file.Title;

                    parentFoldersIds = dbManager.ExecuteList(
                        new SqlQuery("files_folder_tree")
                        .Select("parent_id")
                        .Where(Exp.Eq("folder_id", file.FolderID))
                        .OrderBy("level", false)
                        ).ConvertAll(row => row[0]);

                    if (parentFoldersIds.Count > 0)
                    {
                        dbManager.ExecuteNonQuery(
                            Update("files_folder")
                            .Set("modified_on", TenantUtil.DateTimeToUtc(file.ModifiedOn))
                            .Set("modified_by", file.ModifiedBy.ToString())
                            .Where(Exp.In("id", parentFoldersIds)));
                    }
                }
            }

            if (fileStream != null)
            {
                try
                {
                    DeleteVersionStream(file);
                    SaveFileStream(file, fileStream);
                }
                catch
                {
                    if (!IsExistOnStorage(file))
                    {
                        DeleteVersion(file);
                    }
                    throw;
                }
            }

            FactoryIndexer <FilesWrapper> .IndexAsync(FilesWrapper.GetFilesWrapper(file, parentFoldersIds));

            return(GetFile(file.ID));
        }