public File SaveFile(File file, Stream stream)
 {
     using (var dao = FilesIntegration.GetFileDao())
     {
         return dao.SaveFile(file, stream);
     }
 }
        /// <summary>
        /// </summary>
        /// <param name="file"></param>
        public FileWrapper(File file)
            : base(file)
        {
            FolderId = file.FolderID;
            if (file.RootFolderType == FolderType.USER
                && !Equals(file.RootFolderCreator, SecurityContext.CurrentAccount.ID))
            {
                RootFolderType = FolderType.SHARE;
                using (var folderDao = Global.DaoFactory.GetFolderDao())
                {
                    var parentFolder = folderDao.GetFolder(file.FolderID);
                    if (!Global.GetFilesSecurity().CanRead(parentFolder))
                        FolderId = Global.FolderShare;
                }
            }

            Version = file.Version;
            ContentLength = file.ContentLengthString;
            FileStatus = file.FileStatus;
            PureContentLength = file.ContentLength;
            try
            {
                ViewUrl = file.ViewUrl;

                WebUrl = CommonLinkUtility.GetFileWebPreviewUrl(file.Title, file.ID);
            }
            catch (Exception)
            {
                //Don't catch anything here because of httpcontext
            }
        }
        public static string GetLink(File file)
        {
            var url = file.ViewUrl;

            if (!FileUtility.CanImageView(file.Title) && TenantExtra.GetTenantQuota().DocsEdition)
                url = FilesLinkUtility.GetFileWebPreviewUrl(file.Title, file.ID);

            var linkParams = CreateKey(file.ID.ToString());
            url += "&" + FilesLinkUtility.DocShareKey + "=" + HttpUtility.UrlEncode(linkParams);

            return CommonLinkUtility.GetFullAbsolutePath(url);
        }
        public Stream GetFileStream(File file, long offset)
        {
            var fileToDownload = ProviderInfo.GetFileById(file.ID);
            if (fileToDownload == null)
                throw new ArgumentNullException("file", Web.Files.Resources.FilesCommonResource.ErrorMassage_FileNotFound);

            var fileStream = ProviderInfo.GetFileStream(fileToDownload.ServerRelativeUrl);

            if (offset > 0)
                fileStream.Seek(offset, SeekOrigin.Begin);

            return fileStream;
        }
        public static string GetLink(File file)
        {
            var url = file.ViewUrl;

            if (FileUtility.CanWebView(file.Title)
                && TenantExtra.GetTenantQuota().DocsEdition)
                url = CommonLinkUtility.GetFileWebEditorUrl(file.ID);

            var linkParams = Signature.Create(file.ID.ToString(), Global.GetDocDbKey());
            url += "&" + CommonLinkUtility.DocShareKey + "=" + HttpUtility.UrlEncode(linkParams);

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

            var filesSecurity = Global.GetFilesSecurity();
            if (filesSecurity.CanEdit(file, FileConstant.ShareLinkId)) return FileShare.ReadWrite;
            if (filesSecurity.CanRead(file, FileConstant.ShareLinkId)) return FileShare.Read;
            return FileShare.Restrict;
        }
        public override 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.MaxUploadSize && SetupInfo.MaxUploadSize < file.ContentLength)
                throw FileSizeComment.FileSizeException;

            if (CallContext.GetData("CURRENT_ACCOUNT") == null)
                CallContext.SetData("CURRENT_ACCOUNT", new Guid(context.Request["UserID"]));


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


            var document = new File
                               {
                                   Title = fileName,
                                   FolderID = Global.DaoFactory.GetFileDao().GetRoot(),
                                   ContentLength = file.ContentLength
                               };

            document.ContentType = MimeMapping.GetMimeMapping(document.Title);

            document = Global.DaoFactory.GetFileDao().SaveFile(document, file.InputStream);

            fileUploadResult.Data = document.ID;
            fileUploadResult.FileName = document.Title;
            fileUploadResult.FileURL = document.FileUri;


            fileUploadResult.Success = true;


            return fileUploadResult;

        }
        public Stream GetFileStream(File file, long offset)
        {
            var driveId = MakeDriveId(file.ID);
            CacheReset(driveId, true);
            var driveFile = GetDriveEntry(file.ID);
            if (driveFile == null) throw new ArgumentNullException("file", Web.Files.Resources.FilesCommonResource.ErrorMassage_FileNotFound);
            if (driveFile is ErrorDriveEntry) throw new Exception(((ErrorDriveEntry)driveFile).Error);

            var fileStream = GoogleDriveProviderInfo.Storage.DownloadStream(driveFile);

            if (fileStream.CanSeek)
                file.ContentLength = fileStream.Length; // hack for google drive

            if (fileStream.CanSeek && offset > 0)
                fileStream.Seek(offset, SeekOrigin.Begin);

            return fileStream;
        }
        public static void SendLinkToEmail(File file, String url, String message, List<String> addressRecipients)
        {
            if (file == null || String.IsNullOrEmpty(url))
                throw new ArgumentException();

            var recipients = addressRecipients
                .ConvertAll(address => (IRecipient) (new DirectRecipient(Guid.NewGuid().ToString(), String.Empty, new[] {address}, false)));

            Instance.SendNoticeToAsync(
                NotifyConstants.Event_LinkToEmail,
                null,
                recipients.ToArray(),
                false,
                new TagValue(NotifyConstants.Tag_DocumentTitle, file.Title),
                new TagValue(NotifyConstants.Tag_DocumentUrl, CommonLinkUtility.GetFullAbsolutePath(url)),
                new TagValue(NotifyConstants.Tag_AccessRights, GetAccessString(file.Access)),
                new TagValue(NotifyConstants.Tag_Message, message.HtmlEncode())
                );
        }
        public static void SendLinkToEmail(File file, String url, String message, List<String> addressRecipients)
        {
            if (file == null || String.IsNullOrEmpty(url))
                throw new ArgumentException();

            var recipients = addressRecipients
                .ConvertAll(address => (IRecipient)(new DirectRecipient(SecurityContext.CurrentAccount.ID.ToString(), String.Empty, new[] { address }, false)));

            Instance.SendNoticeToAsync(
                NotifyConstants.Event_LinkToEmail,
                null,
                recipients.ToArray(),
                new[] { "email.sender" },
                null,
                new TagValue(NotifyConstants.Tag_DocumentTitle, file.Title),
                new TagValue(NotifyConstants.Tag_DocumentUrl, CommonLinkUtility.GetFullAbsolutePath(url)),
                new TagValue(NotifyConstants.Tag_AccessRights, GetAccessString(file.Access, CultureInfo.CurrentUICulture)),
                new TagValue(NotifyConstants.Tag_Message, message.HtmlEncode()),
                new TagValue(NotifyConstants.Tag_UserEmail, CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).Email)
                );
        }
        private ItemNameValueCollection ExecPathFromFile(File file, string path)
        {
            FileMarker.RemoveMarkAsNew(file);

            var title = file.Title;

            if (_files.ContainsKey(file.ID.ToString()))
            {
                var convertToExt = string.Empty;
                if (_quotaDocsEdition || FileUtility.InternalExtension.Values.Contains(convertToExt))
                    convertToExt = _files[file.ID.ToString()];

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

            var entriesPathId = new ItemNameValueCollection();
            entriesPathId.Add(path + title, file.ID.ToString());

            return entriesPathId;
        }
        public Stream GetFileStream(File file, long offset)
        {
            //NOTE: id here is not converted!
            var fileToDownload = GetFileById(file.ID);
            //Check length of the file
            if (fileToDownload == null)
                throw new ArgumentNullException("file", Web.Files.Resources.FilesCommonResource.ErrorMassage_FileNotFound);

            //if (fileToDownload.Length > SetupInfo.AvailableFileSize)
            //{
            //    throw FileSizeComment.FileSizeException;
            //}

            var fileStream = fileToDownload.GetDataTransferAccessor().GetDownloadStream();

            if (fileStream.CanSeek)
                file.ContentLength = fileStream.Length; // hack for google drive

            if (offset > 0)
                fileStream.Seek(offset, SeekOrigin.Begin);

            return fileStream;
        }
Beispiel #13
0
        public static void SendLinkToEmail(File file, String url, String message, List<String> addressRecipients)
        {
            if (file == null || String.IsNullOrEmpty(url))
                throw new ArgumentException();

            foreach (var recipients in addressRecipients
                .Select(addressRecipient => (IRecipient) (new DirectRecipient(SecurityContext.CurrentAccount.ID.ToString(), String.Empty, new[] {addressRecipient}, false))))
            {
                Instance.SendNoticeToAsync(
                    NotifyConstants.Event_LinkToEmail,
                    null,
                    new[] {recipients},
                    new[] {"email.sender"},
                    null,
                    new TagValue(NotifyConstants.Tag_DocumentTitle, file.Title),
                    new TagValue(NotifyConstants.Tag_DocumentUrl, CommonLinkUtility.GetFullAbsolutePath(url)),
                    new TagValue(NotifyConstants.Tag_AccessRights, GetAccessString(file.Access, CultureInfo.CurrentUICulture)),
                    new TagValue(NotifyConstants.Tag_Message, message.HtmlEncode()),
                    new TagValue(NotifyConstants.Tag_UserEmail, CoreContext.UserManager.GetUsers(SecurityContext.CurrentAccount.ID).Email),
                    new TagValue(CommonTags.WithPhoto, CoreContext.Configuration.Personal ? "personal" : ""),
                    new TagValue(CommonTags.IsPromoLetter, CoreContext.Configuration.Personal ? "true" : "false")
                    );
            }
        }
 private static object ToResponseObject(File file)
 {
     return new
         {
             id = file.ID,
             folderId = file.FolderID,
             version = file.Version,
             title = file.Title,
             provider_key = file.ProviderKey
         };
 }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral = false;

            File file;
            var fileUri = string.Empty;

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

                    var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]);

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

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

                        bool editable;
                        _thirdPartyApp = true;
                        file = app.GetFile(RequestFileId, out editable);
                        file = DocumentServiceHelper.GetParams(file, true, true, true, editable, editable, editable, out _docParams);

                        _docParams.FileUri = app.GetFileStreamUrl(file);
                        _docParams.FolderUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

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

                    if (CoreContext.Configuration.Standalone)
                    {
                        try
                        {
                            var webRequest = WebRequest.Create(RequestFileUrl);
                            using (var response = webRequest.GetResponse())
                            using (var responseStream = new ResponseStream(response))
                            {
                                var externalFileKey = DocumentServiceConnector.GenerateRevisionId(RequestFileUrl);
                                fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), externalFileKey);
                            }
                        }
                        catch (Exception error)
                        {
                            Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                        }
                    }

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

                    file = DocumentServiceHelper.GetParams(file, true, true, true, false, false, false, out _docParams);
                    _docParams.CanEdit = editPossible && !CoreContext.Configuration.Standalone;
                    _editByUrl = true;

                    _docParams.FileUri = fileUri;
                }
            }
            catch (Exception ex)
            {
                _errorMessage = ex.Message;
                return;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception e)
                {
                    _docParams = null;
                    _errorMessage = e.Message;
                    return;
                }

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

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

            Title = file.Title;

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

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

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

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(Share.Location + "?" + FilesLinkUtility.FileId + "=" + file.ID);
                }
            }

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

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_docParams.ModeWrite)
            {
                _tabId = FileTracker.Add(file.ID, _fileNew);
                _fixedVersion = FileTracker.FixedVersion(file.ID);
                _docParams.FileChoiceUrl = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.DocumentTypeParam + "=" + FilterType.SpreadsheetsOnly;
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                            : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_docParams.File)) _editByUrl = true;
            }
        }
        public File GetFile(string fileId, out bool editable)
        {
            Global.Logger.Debug("GoogleDriveApp: get file " + fileId);
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);
            var driveFile = GetDriveFile(fileId, token);
            editable = false;

            if (driveFile == null) return null;

            var jsonFile = JObject.Parse(driveFile);

            var file = new File
                {
                    ID = ThirdPartySelector.BuildAppFileId(AppAttr, jsonFile.Value<string>("id")),
                    Title = Global.ReplaceInvalidCharsAndTruncate(GetCorrectTitle(jsonFile)),
                    CreateOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("createdDate")),
                    ModifiedOn = TenantUtil.DateTimeFromUtc(jsonFile.Value<DateTime>("modifiedDate")),
                    ContentLength = Convert.ToInt64(jsonFile.Value<string>("fileSize")),
                    ModifiedByString = jsonFile.Value<string>("lastModifyingUserName"),
                    ProviderKey = "Google"
                };

            var owners = jsonFile.Value<JArray>("ownerNames");
            if (owners != null)
            {
                file.CreateByString = owners.ToObject<List<string>>().FirstOrDefault();
            }

            editable = jsonFile.Value<bool>("editable");
            return file;
        }
        public string GetFileStreamUrl(File file)
        {
            if (file == null) return string.Empty;

            var fileId = ThirdPartySelector.GetFileId(file.ID.ToString());

            Global.Logger.Debug("GoogleDriveApp: get file stream url " + fileId);

            var uriBuilder = new UriBuilder(CommonLinkUtility.GetFullAbsolutePath(ThirdPartyAppHandler.HandlerPath));
            if (uriBuilder.Uri.IsLoopback)
            {
                uriBuilder.Host = Dns.GetHostName();
            }
            var query = uriBuilder.Query;
            query += FilesLinkUtility.Action + "=stream&";
            query += FilesLinkUtility.FileId + "=" + HttpUtility.UrlEncode(fileId) + "&";
            query += CommonLinkUtility.ParamName_UserUserID + "=" + HttpUtility.UrlEncode(SecurityContext.CurrentAccount.ID.ToString()) + "&";
            query += FilesLinkUtility.AuthKey + "=" + EmailValidationKeyProvider.GetEmailKey(fileId + SecurityContext.CurrentAccount.ID) + "&";
            query += ThirdPartySelector.AppAttr + "=" + AppAttr;

            return uriBuilder.Uri + "?" + query;
        }
 public string GetDifferenceUrl(File file)
 {
     var fileId = file.ID;
     var selector = GetSelector(fileId);
     file.ID = selector.ConvertId(fileId);
     var url = selector.GetFileDao(fileId).GetDifferenceUrl(file);
     file.ID = fileId; //Restore
     return url;
 }
Beispiel #19
0
 public static void DemandAccessTo(File file)
 {
     //   if (!CanAccessTo((File)file)) CreateSecurityException();
 }
Beispiel #20
0
 public static void SetAccessTo(File file)
 {
     if (IsAdmin || file.CreateBy == SecurityContext.CurrentAccount.ID || file.ModifiedBy == SecurityContext.CurrentAccount.ID)
         file.Access = FileShare.None;
     else
         file.Access = FileShare.Read;
 }
        private static void CheckConvertFilesStatus(object _)
        {
            if (Monitor.TryEnter(singleThread))
            {
                try
                {
                    List <File> filesIsConverting;
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);

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

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

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

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

                    var fileSecurity = Global.GetFilesSecurity();
                    foreach (var file in filesIsConverting)
                    {
                        var    fileUri = file.ID.ToString();
                        string convertedFileUrl;
                        int    operationResultProgress;

                        try
                        {
                            int      tenantId;
                            IAccount account;

                            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;

                                if (HttpContext.Current == null && !WorkContext.IsMono)
                                {
                                    HttpContext.Current = new HttpContext(
                                        new HttpRequest("hack", operationResult.Url, string.Empty),
                                        new HttpResponse(new StringWriter()));
                                }

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

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

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

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

                            fileUri = PathProvider.GetFileStreamUrl(file);

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

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

                        operationResultProgress = Math.Min(operationResultProgress, 100);
                        if (operationResultProgress < 100)
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];

                                    if (DateTime.Now - operationResult.StartDateTime > TimeSpan.FromMinutes(10))
                                    {
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Error        = FilesCommonResource.ErrorMassage_ConvertTimeout;
                                        Global.Logger.ErrorFormat("CheckConvertFilesStatus timeout: {0} ({1})", file.ID, file.ContentLengthString);
                                    }
                                    else
                                    {
                                        operationResult.Processed = "";
                                    }
                                    operationResult.Progress = operationResultProgress;
                                    cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                }
                            }

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

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

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

                            Global.Logger.ErrorFormat("{0} ConvertUrl: {1} fromUrl: {2}: {3}", operationResultError, convertedFileUrl, fileUri, e);
                            continue;
                        }
                        finally
                        {
                            lock (locker)
                            {
                                if (conversionQueue.Keys.Contains(file))
                                {
                                    var operationResult = conversionQueue[file];
                                    if (operationResult.Delete)
                                    {
                                        conversionQueue.Remove(file);
                                        cache.Remove(GetKey(file));
                                    }
                                    else
                                    {
                                        if (newFile != null)
                                        {
                                            using (var folderDao = Global.DaoFactory.GetFolderDao())
                                            {
                                                var folder      = folderDao.GetFolder(newFile.FolderID);
                                                var folderTitle = fileSecurity.CanRead(folder) ? folder.Title : null;
                                                operationResult.Result = FileJsonSerializer(newFile, folderTitle);
                                            }
                                        }

                                        operationResult.Progress     = 100;
                                        operationResult.StopDateTime = DateTime.UtcNow;
                                        operationResult.Processed    = "1";
                                        if (!string.IsNullOrEmpty(operationResultError))
                                        {
                                            operationResult.Error = operationResultError;
                                        }
                                        cache.Insert(GetKey(file), operationResult, TimeSpan.FromMinutes(10));
                                    }
                                }
                            }
                        }

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

                    lock (locker)
                    {
                        timer.Change(TIMER_PERIOD, TIMER_PERIOD);
                    }
                }
                catch (Exception exception)
                {
                    Global.Logger.Error(exception.Message, exception);
                    lock (locker)
                    {
                        timer.Change(Timeout.Infinite, Timeout.Infinite);
                    }
                }
                finally
                {
                    Monitor.Exit(singleThread);
                }
            }
        }
        public List<int> RemoveFile(File file)
        {
            CRMSecurity.DemandDelete(file);

            var eventIDs = new List<int>();

            using (var tagdao = FilesIntegration.GetTagDao())
            {
                var tags = tagdao.GetTags(file.ID, FileEntryType.File, TagType.System).ToList().FindAll(tag => tag.TagName.StartsWith("RelationshipEvent_"));
                eventIDs = tags.Select(item => Convert.ToInt32(item.TagName.Split(new[] { '_' })[1])).ToList();
            }
            using (var dao = FilesIntegration.GetFileDao())
            {
                dao.DeleteFile(file.ID);
            }

            foreach (var eventID in eventIDs)
            {
                if (GetFiles(eventID).Count == 0)
                {
                    using (var db = GetDb())
                    {
                        db.ExecuteNonQuery(Update("crm_relationship_event").Set("have_files", false).Where("id", eventID));
                    }
                }
            }

            using (var db = GetDb())
            {
                db.ExecuteNonQuery(Update("crm_invoice").Set("file_id", 0).Where("file_id", file.ID));
            }

            return eventIDs;
        }
 private File ConvertId(File file)
 {
     file.ID = ConvertId(file.ID);
     file.FolderID = ConvertId(file.FolderID);
     return file;
 }
        public static File ExecDuplicate(File file, string doc, out Folder toFolder)
        {
            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);
                    }
                    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);
                }
        }
 public bool IsExistOnStorage(File file)
 {
     var fileId = file.ID;
     var selector = GetSelector(fileId);
     file.ID = selector.ConvertId(fileId);
     var exist = selector.GetFileDao(fileId).IsExistOnStorage(file);
     file.ID = fileId; //Restore
     return exist;
 }
        internal void GenerateImageThumb(File file)
        {
            if (file == null || FileUtility.GetFileTypeByFileName(file.Title) != FileType.Image) return;

            try
            {
                using (var filedao = FilesIntegration.GetFileDao())
                {
                    using (var stream = filedao.GetFileStream(file))
                    {
                        var ii = new ImageInfo();
                        ImageHelper.GenerateThumbnail(stream, GetThumbPath(file.ID), ref ii, 128, 96, projectsStore);
                    }
                }
            }
            catch (Exception ex)
            {
                LogManager.GetLogger("ASC.Web.Projects").Error(ex);
            }
        }
Beispiel #27
0
        private Feed ToFeed(File file)
        {
            var rootFolder = new FolderDao(Tenant, DbId).GetFolder(file.FolderID);

            if (file.SharedToMeOn.HasValue)
            {
                var feed = new Feed(new Guid(file.SharedToMeBy), file.SharedToMeOn.Value, true)
                    {
                        Item = sharedFileItem,
                        ItemId = string.Format("{0}_{1}", file.ID, file.CreateByString),
                        ItemUrl = CommonLinkUtility.GetFileRedirectPreviewUrl(file.ID, true),
                        Product = Product,
                        Module = Name,
                        Title = file.Title,
                        AdditionalInfo = file.ContentLengthString,
                        AdditionalInfo2 = rootFolder.FolderType == FolderType.DEFAULT ? rootFolder.Title : string.Empty,
                        AdditionalInfo3 = rootFolder.FolderType == FolderType.DEFAULT ? CommonLinkUtility.GetFileRedirectPreviewUrl(file.FolderID, false) : string.Empty,
                        Keywords = string.Format("{0}", file.Title),
                        HasPreview = false,
                        CanComment = false,
                        Target = file.CreateByString,
                        GroupId = GetGroupId(sharedFileItem, new Guid(file.SharedToMeBy), file.FolderID.ToString())
                    };

                return feed;
            }

            var updated = file.Version != 1;
            return new Feed(file.ModifiedBy, file.ModifiedOn)
                {
                    Item = fileItem,
                    ItemId = string.Format("{0}_{1}", file.ID, file.Version > 1 ? 1 : 0),
                    ItemUrl = CommonLinkUtility.GetFileRedirectPreviewUrl(file.ID, true),
                    Product = Product,
                    Module = Name,
                    Action = updated ? FeedAction.Updated : FeedAction.Created,
                    Title = file.Title,
                    AdditionalInfo = file.ContentLengthString,
                    AdditionalInfo2 = rootFolder.FolderType == FolderType.DEFAULT ? rootFolder.Title : string.Empty,
                    AdditionalInfo3 = rootFolder.FolderType == FolderType.DEFAULT ? CommonLinkUtility.GetFileRedirectPreviewUrl(file.FolderID, false) : string.Empty,
                    Keywords = string.Format("{0}", file.Title),
                    HasPreview = false,
                    CanComment = false,
                    Target = null,
                    GroupId = GetGroupId(fileItem, file.ModifiedBy, file.FolderID.ToString(), updated ? 1 : 0)
                };
        }
Beispiel #28
0
        public static bool CanEdit(File file)
        {
            if (!(IsAdmin || file.CreateBy == SecurityContext.CurrentAccount.ID || file.ModifiedBy == SecurityContext.CurrentAccount.ID))
                return false;

            if ((file.FileStatus & FileStatus.IsEditing) == FileStatus.IsEditing)
                return false;

            return true;
        }
        private static File SaveConvertedFile(File file, string convertedFileUrl)
        {
            var fileSecurity = Global.GetFilesSecurity();

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

                    if (!FilesSettings.StoreOriginalFiles && fileSecurity.CanEdit(file))
                    {
                        newFile = (File)file.Clone();
                        newFile.Version++;
                    }
                    else
                    {
                        var folderId = Global.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 (FilesSettings.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 = new File {
                                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);

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

                    return(newFile);
                }
        }
Beispiel #30
0
 public static void DemandEdit(File file)
 {
     if (!CanEdit(file)) throw CreateSecurityException();
 }
Beispiel #31
0
 public static bool Check(string key, bool checkRead, IFileDao fileDao, out File file)
 {
     var fileShare = Check(key, fileDao, out file);
     return (!checkRead && fileShare == FileShare.ReadWrite) || (checkRead && fileShare <= FileShare.Read);
 }
 public void SaveEditHistory(File file, string changes, Stream differenceStream)
 {
     var fileId = file.ID;
     var selector = GetSelector(fileId);
     file.ID = selector.ConvertId(fileId);
     selector.GetFileDao(fileId).SaveEditHistory(file, changes, differenceStream);
     file.ID = fileId; //Restore
 }
Beispiel #33
0
        private static void SaveFile(IFileDao fileDao, object folder, string filePath, IDataStore storeTemp)
        {
            using (var stream = storeTemp.IronReadStream("", filePath, 10))
            {
                var fileName = Path.GetFileName(filePath);
                var file = new File
                    {
                        Title = fileName,
                        ContentLength = stream.Length,
                        FolderID = folder,
                    };
                stream.Position = 0;
                try
                {
                    file = fileDao.SaveFile(file, stream);

                    FileMarker.MarkAsNew(file);
                }
                catch (Exception ex)
                {
                    Logger.Error(ex);
                }
            }
        }
 public static Stream Exec(File file)
 {
     return(Exec(file, FileUtility.GetInternalExtension(file.Title)));
 }