예제 #1
0
        private static string GetUrlToFile(Stream docxStream)
        {
            var externalUri = Files.Classes.PathProvider.GetTempUrl(docxStream, FormatDocx);

            externalUri = DocumentServiceConnector.ReplaceCommunityAdress(externalUri);
            log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri);

            var    revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());
            string urlToFile;

            DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, false, out urlToFile);

            log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile);
            return(urlToFile);
        }
예제 #2
0
        private static string GetUrlToFile(Stream docxStream)
        {
            var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());

            var externalUri = DocumentServiceConnector.GetExternalUri(docxStream, "text/plain", revisionId);

            log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri);

            string urlToFile;

            DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, false, out urlToFile);

            log4net.LogManager.GetLogger("ASC.CRM").DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile);
            return(urlToFile);
        }
예제 #3
0
        private static string ConvertFile(string downloadUrl, string fromExt, Token token)
        {
            Global.Logger.Debug("GoogleDriveApp: convert file");

            if (string.IsNullOrEmpty(downloadUrl))
            {
                Global.Logger.Error("GoogleDriveApp: downloadUrl is null");
                throw new Exception("downloadUrl is null");
            }

            var request = (HttpWebRequest)WebRequest.Create(downloadUrl);

            request.Method = "GET";
            request.Headers.Add("Authorization", "Bearer " + token);

            try
            {
                using (var response = request.GetResponse())
                    using (var fileStream = new ResponseStream(response))
                    {
                        Global.Logger.Debug("GoogleDriveApp: GetExternalUri - " + downloadUrl);

                        var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                        downloadUrl = DocumentServiceConnector.GetExternalUri(fileStream, response.ContentType, key);
                    }
            }
            catch (WebException e)
            {
                Global.Logger.Error("GoogleDriveApp: Error GetExternalUri", e);
                request.Abort();
            }

            var toExt = FileUtility.GetInternalExtension(fromExt);

            try
            {
                Global.Logger.Debug("GoogleDriveApp: GetConvertedUri- " + downloadUrl);

                var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                DocumentServiceConnector.GetConvertedUri(downloadUrl, fromExt, toExt, key, false, out downloadUrl);
            }
            catch (Exception e)
            {
                Global.Logger.Error("GoogleDriveApp: Error GetConvertedUri", e);
            }

            return(downloadUrl);
        }
예제 #4
0
        private string GetUrlToFile(Stream docxStream)
        {
            var externalUri = _filesPathProvider.GetTempUrl(docxStream, FormatDocx);

            externalUri = _documentServiceConnector.ReplaceCommunityAdress(externalUri);

            _logger.DebugFormat("PdfCreator. GetUrlToFile. externalUri = {0}", externalUri);

            var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());

            string urlToFile;

            _documentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, null, null, null, false, out urlToFile);

            _logger.DebugFormat("PdfCreator. GetUrlToFile. urlToFile = {0}", urlToFile);

            return(urlToFile);
        }
예제 #5
0
        public static ConverterData StartCreationFileAsync(Invoice data)
        {
            using (var docxStream = GetStreamDocx(data))
            {
                var externalUri = Files.Classes.PathProvider.GetTempUrl(docxStream, FormatDocx);
                externalUri = DocumentServiceConnector.ReplaceCommunityAdress(externalUri);

                var    revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());
                string urlToFile;
                DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, true, out urlToFile);

                return(new ConverterData
                {
                    StorageUrl = externalUri,
                    RevisionId = revisionId,
                    InvoiceId = data.ID,
                });
            }
        }
예제 #6
0
        public static ConverterData StartCreationFileAsync(Invoice data)
        {
            using (var docxStream = GetStreamDocx(data))
            {
                var revisionId = DocumentServiceConnector.GenerateRevisionId(Guid.NewGuid().ToString());

                var externalUri = DocumentServiceConnector.GetExternalUri(docxStream, MimeMapping.GetMimeMapping(FormatDocx), revisionId);

                string urlToFile;
                DocumentServiceConnector.GetConvertedUri(externalUri, FormatDocx, FormatPdf, revisionId, true, out urlToFile);

                return(new ConverterData
                {
                    StorageUrl = externalUri,
                    RevisionId = revisionId,
                    InvoiceId = data.ID,
                });
            }
        }
예제 #7
0
        private static string ConvertFile(string fileId, string fromExt)
        {
            Global.Logger.Debug("GoogleDriveApp: convert file");

            var downloadUrl = GetFileStreamUrl(fileId);

            var toExt = FileUtility.GetInternalExtension(fromExt);

            try
            {
                Global.Logger.Debug("GoogleDriveApp: GetConvertedUri- " + downloadUrl);

                var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                DocumentServiceConnector.GetConvertedUri(downloadUrl, fromExt, toExt, key, false, out downloadUrl);
            }
            catch (Exception e)
            {
                Global.Logger.Error("GoogleDriveApp: Error GetConvertedUri", e);
            }

            return(downloadUrl);
        }
        public static File SaveEditing(String fileId, string fileExtension, string downloadUri, Stream stream, String doc, string comment = null, bool checkRight = true, bool encrypted = false, ForcesaveType?forcesave = null)
        {
            var newExtension = string.IsNullOrEmpty(fileExtension)
                              ? FileUtility.GetFileExtension(downloadUri)
                              : fileExtension;

            var app = ThirdPartySelector.GetAppByFileId(fileId);

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

            File file;

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

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

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

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

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

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

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

                file.Encrypted = encrypted;

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

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

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

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

                    file.ConvertedType = null;
                }

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

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

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

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }
예제 #9
0
        public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream)
        {
            Logger.Debug("BoxApp: save file stream " + fileId +
                         (stream == null
                                     ? " from - " + downloadUrl
                                     : " from stream"));
            fileId = ThirdPartySelector.GetFileId(fileId.ToString());

            var token = TokenHelper.GetToken(AppAttr);

            var boxFile = GetBoxFile(fileId.ToString(), token);

            if (boxFile == null)
            {
                Logger.Error("BoxApp: file is null");
                throw new Exception("File not found");
            }

            var jsonFile    = JObject.Parse(boxFile);
            var title       = Global.ReplaceInvalidCharsAndTruncate(jsonFile.Value <string>("name"));
            var currentType = FileUtility.GetFileExtension(title);

            if (!fileType.Equals(currentType))
            {
                try
                {
                    if (stream != null)
                    {
                        downloadUrl = PathProvider.GetTempUrl(stream, fileType);
                        downloadUrl = DocumentServiceConnector.ReplaceCommunityAdress(downloadUrl);
                    }

                    Logger.Debug("BoxApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl);

                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                    DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, null, null, null, false, out downloadUrl);
                    stream = null;
                }
                catch (Exception e)
                {
                    Logger.Error("BoxApp: Error convert", e);
                }
            }

            var request = (HttpWebRequest)WebRequest.Create(BoxUrlUpload.Replace("{fileId}", fileId));

            using (var tmpStream = new MemoryStream())
            {
                var boundary = DateTime.UtcNow.Ticks.ToString("x");

                var metadata     = string.Format("Content-Disposition: form-data; name=\"filename\"; filename=\"{0}\"\r\nContent-Type: application/octet-stream\r\n\r\n", title);
                var metadataPart = string.Format("--{0}\r\n{1}", boundary, metadata);
                var bytes        = Encoding.UTF8.GetBytes(metadataPart);
                tmpStream.Write(bytes, 0, bytes.Length);

                if (stream != null)
                {
                    stream.CopyTo(tmpStream);
                }
                else
                {
                    var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl);
                    using var downloadStream = new ResponseStream(downloadRequest.GetResponse());
                    downloadStream.CopyTo(tmpStream);
                }

                var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary);
                bytes = Encoding.UTF8.GetBytes(mediaPartEnd);
                tmpStream.Write(bytes, 0, bytes.Length);

                request.Method = "POST";
                request.Headers.Add("Authorization", "Bearer " + token);
                request.ContentType   = "multipart/form-data; boundary=" + boundary;
                request.ContentLength = tmpStream.Length;
                Logger.Debug("BoxApp: save file totalSize - " + tmpStream.Length);

                const int bufferSize = 2048;
                var       buffer     = new byte[bufferSize];
                int       readed;
                tmpStream.Seek(0, SeekOrigin.Begin);
                while ((readed = tmpStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    request.GetRequestStream().Write(buffer, 0, readed);
                }
            }

            try
            {
                using var response       = request.GetResponse();
                using var responseStream = response.GetResponseStream();
                string result = null;
                if (responseStream != null)
                {
                    using var readStream = new StreamReader(responseStream);
                    result = readStream.ReadToEnd();
                }

                Logger.Debug("BoxApp: save file response - " + result);
            }
            catch (WebException e)
            {
                Logger.Error("BoxApp: Error save file", e);
                request.Abort();
                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden || httpResponse.StatusCode == HttpStatusCode.Unauthorized)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
                throw;
            }
        }
예제 #10
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

            try
            {
                if (string.IsNullOrEmpty(RequestFileUrl))
                {
                    var app = ThirdPartySelector.GetAppByFileId(RequestFileId);
                    if (app == null)
                    {
                        var ver = string.IsNullOrEmpty(Request[FilesLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[FilesLinkUtility.Version]);
                        file = DocumentServiceHelper.GetParams(RequestFileId, ver, RequestShareLinkKey, editPossible, !RequestView, true, out _configuration);
                    }
                    else
                    {
                        isExtenral = true;

                        bool editable;
                        _thirdPartyApp = true;
                        file           = app.GetFile(RequestFileId, out editable);
                        file           = DocumentServiceHelper.GetParams(file, true, editPossible ? FileShare.ReadWrite : FileShare.Read, false, editable, editable, editable, true, out _configuration);

                        _configuration.Document.Url = app.GetFileStreamUrl(file);
                        _configuration.EditorConfig.Customization.GobackUrl = string.Empty;
                    }
                }
                else
                {
                    isExtenral = true;

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

                    if (CoreContext.Configuration.Standalone)
                    {
                        try
                        {
                            var webRequest = (HttpWebRequest)WebRequest.Create(RequestFileUrl);

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

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

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

                    file = DocumentServiceHelper.GetParams(file, true, FileShare.Read, false, false, false, false, false, out _configuration);
                    _configuration.Document.Permissions.Edit          = editPossible && !CoreContext.Configuration.Standalone;
                    _configuration.Document.Permissions.Rename        = false;
                    _configuration.Document.Permissions.Review        = false;
                    _configuration.Document.Permissions.ChangeHistory = false;
                    _editByUrl = true;

                    _configuration.Document.Url = fileUri;
                }
                ErrorMessage = _configuration.ErrorMessage;
            }
            catch (Exception ex)
            {
                Global.Logger.Warn("DocEditor", ex);
                ErrorMessage = ex.Message;
                return;
            }

            if (_configuration.EditorConfig.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception ex)
                {
                    _configuration = null;
                    Global.Logger.Error("DocEditor", ex);
                    ErrorMessage = ex.Message;
                    return;
                }

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

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

            Title = file.Title;

            if (_configuration.EditorConfig.Customization.Goback == null || string.IsNullOrEmpty(_configuration.EditorConfig.Customization.Goback.Url))
            {
                _configuration.EditorConfig.Customization.GobackUrl = Request[FilesLinkUtility.FolderUrl] ?? "";
            }

            _configuration.EditorConfig.Customization.IsRetina = TenantLogoManager.IsRetina(Request);

            if (RequestEmbedded)
            {
                _configuration.Type = Services.DocumentService.Configuration.EditorType.Embedded;

                _configuration.EditorConfig.Embedded.ShareLinkParam = string.IsNullOrEmpty(RequestShareLinkKey) ? string.Empty : "&" + FilesLinkUtility.DocShareKey + "=" + RequestShareLinkKey;
            }
            else
            {
                _configuration.Type = IsMobile ? Services.DocumentService.Configuration.EditorType.Mobile : Services.DocumentService.Configuration.EditorType.Desktop;

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

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

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_configuration.EditorConfig.ModeWrite)
            {
                _tabId = FileTracker.Add(file.ID);
                if (SecurityContext.IsAuthenticated)
                {
                    _configuration.EditorConfig.FileChoiceUrl  = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.ParamFilterExt + "=xlsx&" + FileChoice.MailMergeParam + "=true";
                    _configuration.EditorConfig.MergeFolderUrl = CommonLinkUtility.GetFullAbsolutePath(MailMerge.GetUrl);
                }
            }
            else
            {
                _linkToEdit = _editByUrl
                                  ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                  : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_configuration.Document.Info.File))
                {
                    _editByUrl = true;
                }
            }
        }
예제 #11
0
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded && !IsMobile;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

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

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

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

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

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

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

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

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

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

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

                        _docParams.FileUri = fileUri;
                    }
                }
                catch (Exception ex)
                {
                    _errorMessage = ex.Message;
                    return;
                }
            }
            else
            {
                FileType tryType;
                try
                {
                    tryType = (FileType)Enum.Parse(typeof(FileType), Request[FilesLinkUtility.TryParam]);
                }
                catch
                {
                    tryType = FileType.Document;
                }

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

                    path += "new";
                }

                path += FileUtility.InternalExtension[tryType];

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

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

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

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

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

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

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

            Title = HeaderStringHelper.GetPageTitle(file.Title);

            _newScheme = FileUtility.ExtsNewService.Contains(FileUtility.GetFileExtension(file.Title));
            if (_newScheme)
            {
                DocServiceApiUrl = FilesLinkUtility.DocServiceApiUrlNew;
            }

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

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

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

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

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

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

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

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

            if (CoreContext.Configuration.Personal && IsMobile)
            {
                _docParams.CanEdit = false;
            }
        }
예제 #12
0
        public void SaveFile(string fileId, string downloadUrl)
        {
            Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId + " from - " + downloadUrl);
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var driveFile = GetDriveFile(fileId, token);

            if (driveFile == null)
            {
                Global.Logger.Error("GoogleDriveApp: file is null");
                throw new Exception("File not found");
            }

            var jsonFile = JObject.Parse(driveFile);
            var curExt   = GetCorrectExt(jsonFile);
            var newExt   = FileUtility.GetFileExtension(downloadUrl);

            if (curExt != newExt)
            {
                try
                {
                    Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + newExt + " to " + curExt + " - " + downloadUrl);

                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                    DocumentServiceConnector.GetConvertedUri(downloadUrl, newExt, curExt, key, false, out downloadUrl);
                }
                catch (Exception e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error convert", e);
                }
            }

            var downloadRequest = WebRequest.Create(downloadUrl);

            using (var downloadResponse = downloadRequest.GetResponse())
                using (var downloadStream = new ResponseStream(downloadResponse))
                {
                    var request = (HttpWebRequest)WebRequest.Create(GoogleUrlUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId));
                    request.Method = "PUT";
                    request.Headers.Add("Authorization", "Bearer " + token.AccessToken);
                    request.ContentType   = downloadResponse.ContentType;
                    request.ContentLength = downloadResponse.ContentLength;

                    const int bufferSize = 2048;
                    var       buffer     = new byte[bufferSize];
                    int       readed;
                    while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0)
                    {
                        request.GetRequestStream().Write(buffer, 0, readed);
                    }

                    try
                    {
                        using (var response = request.GetResponse())
                            using (var stream = response.GetResponseStream())
                            {
                                var result = stream != null ? new StreamReader(stream).ReadToEnd() : null;

                                Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result);
                            }
                    }
                    catch (WebException e)
                    {
                        Global.Logger.Error("GoogleDriveApp: Error save file stream", e);
                        request.Abort();
                        var httpResponse = (HttpWebResponse)e.Response;
                        if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
                        {
                            throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                        }
                        throw;
                    }
                }
        }
예제 #13
0
        private static void SaveFile(HttpContext context)
        {
            try
            {
                var shareLinkKey = context.Request[CommonLinkUtility.DocShareKey] ?? "";

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

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

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

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

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

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

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

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

                    file.ConvertedType = newType;

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

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

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

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

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

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

                    FileMarker.MarkAsNew(file);
                    FileMarker.RemoveMarkAsNew(file);
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error(ex.Message, ex);
                context.Response.Write("{ \"error\": \"true\", \"message\": \"" + ex.Message + "\" }");
            }
        }
        private void PageLoad()
        {
            var editPossible = !RequestEmbedded;
            var isExtenral   = false;

            File file;
            var  fileUri = string.Empty;

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

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

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

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

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

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

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

                    if (CoreContext.Configuration.Standalone)
                    {
                        try
                        {
                            var webRequest = (HttpWebRequest)WebRequest.Create(RequestFileUrl);

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

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

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

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

                    _docParams.FileUri = fileUri;
                }
            }
            catch (Exception ex)
            {
                Global.Logger.Error("DocEditor", ex);
                _errorMessage = ex.Message;
                return;
            }

            if (_docParams.ModeWrite && FileConverter.MustConvert(file))
            {
                try
                {
                    file = FileConverter.ExecDuplicate(file, RequestShareLinkKey);
                }
                catch (Exception ex)
                {
                    _docParams = null;
                    Global.Logger.Error("DocEditor", ex);
                    _errorMessage = ex.Message;
                    return;
                }

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

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

            Title = file.Title;

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

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

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

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

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

                FileMarker.RemoveMarkAsNew(file);
            }

            if (_docParams.ModeWrite)
            {
                _tabId        = FileTracker.Add(file.ID, _fileNew);
                _fixedVersion = FileTracker.FixedVersion(file.ID);
                if (SecurityContext.IsAuthenticated)
                {
                    _docParams.FileChoiceUrl  = CommonLinkUtility.GetFullAbsolutePath(FileChoice.Location) + "?" + FileChoice.ParamFilterExt + "=xlsx&" + FileChoice.MailMergeParam + "=true";
                    _docParams.MergeFolderUrl = CommonLinkUtility.GetFullAbsolutePath(MailMerge.GetUrl);
                }
            }
            else
            {
                if (!RequestView && FileTracker.IsEditingAlone(file.ID))
                {
                    var editingBy = FileTracker.GetEditingBy(file.ID).FirstOrDefault();
                    _errorMessage = string.Format(FilesCommonResource.ErrorMassage_EditingMobile, Global.GetUserName(editingBy));
                }

                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorExternalUrl(fileUri, file.Title))
                                            : CommonLinkUtility.GetFullAbsolutePath(FilesLinkUtility.GetFileWebEditorUrl(file.ID));

                if (FileConverter.MustConvert(_docParams.File))
                {
                    _editByUrl = true;
                }
            }
        }
예제 #15
0
        public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream)
        {
            Global.Logger.Debug("GoogleDriveApp: save file stream " + fileId +
                                (stream == null
                                     ? " from - " + downloadUrl
                                     : " from stream"));
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var driveFile = GetDriveFile(fileId, token);

            if (driveFile == null)
            {
                Global.Logger.Error("GoogleDriveApp: file is null");
                throw new Exception("File not found");
            }

            var jsonFile    = JObject.Parse(driveFile);
            var currentType = GetCorrectExt(jsonFile);

            if (!fileType.Equals(currentType))
            {
                try
                {
                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl ?? Guid.NewGuid().ToString());
                    if (stream != null)
                    {
                        using (var tmpStream = new MemoryStream())
                        {
                            stream.CopyTo(tmpStream);

                            Global.Logger.Debug("GoogleDriveApp: GetExternalUri format: " + fileType);
                            downloadUrl = DocumentServiceConnector.GetExternalUri(tmpStream, fileType, key);
                        }
                    }

                    Global.Logger.Debug("GoogleDriveApp: GetConvertedUri from " + fileType + " to " + currentType + " - " + downloadUrl);

                    DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, false, out downloadUrl);
                    stream = null;
                }
                catch (Exception e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error convert", e);
                }
            }

            var request = (HttpWebRequest)WebRequest.Create(GoogleLoginProvider.GoogleUrlFileUpload + "/{fileId}?uploadType=media".Replace("{fileId}", fileId));

            request.Method = "PATCH";
            request.Headers.Add("Authorization", "Bearer " + token);
            request.ContentType = MimeMapping.GetMimeMapping(currentType);

            if (stream != null)
            {
                request.ContentLength = stream.Length;

                const int bufferSize = 2048;
                var       buffer     = new byte[bufferSize];
                int       readed;
                while ((readed = stream.Read(buffer, 0, bufferSize)) > 0)
                {
                    request.GetRequestStream().Write(buffer, 0, readed);
                }
            }
            else
            {
                var downloadRequest = (HttpWebRequest)WebRequest.Create(downloadUrl);
                using (var downloadStream = new ResponseStream(downloadRequest.GetResponse()))
                {
                    request.ContentLength = downloadStream.Length;

                    const int bufferSize = 2048;
                    var       buffer     = new byte[bufferSize];
                    int       readed;
                    while ((readed = downloadStream.Read(buffer, 0, bufferSize)) > 0)
                    {
                        request.GetRequestStream().Write(buffer, 0, readed);
                    }
                }
            }

            try
            {
                using (var response = request.GetResponse())
                    using (var responseStream = response.GetResponseStream())
                    {
                        string result = null;
                        if (responseStream != null)
                        {
                            using (var readStream = new StreamReader(responseStream))
                            {
                                result = readStream.ReadToEnd();
                            }
                        }

                        Global.Logger.Debug("GoogleDriveApp: save file stream response - " + result);
                    }
            }
            catch (WebException e)
            {
                Global.Logger.Error("GoogleDriveApp: Error save file stream", e);
                request.Abort();
                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
                throw;
            }
        }
예제 #16
0
        public static File SaveEditing(String fileId, int version, Guid tabId, string fileExtension, string downloadUri, Stream stream, bool asNew, String shareLinkKey, string comment = null, bool checkRight = true)
        {
            var newExtension = string.IsNullOrEmpty(fileExtension)
                              ? FileUtility.GetFileExtension(downloadUri)
                              : fileExtension;

            var app = ThirdPartySelector.GetAppByFileId(fileId);

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

            File file;

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

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

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

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

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

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

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

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

                    file.ConvertedType = null;
                }

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

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

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

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

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }
예제 #17
0
        public static File SaveEditing(String fileId, int version, Guid tabId, string downloadUri, bool asNew, String shareLinkKey, string comment = null, bool checkRight = true)
        {
            var app = ThirdPartySelector.GetAppByFileId(fileId);

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

            File file;

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

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

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

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

                file.ConvertedType = newType;

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

                    file.ConvertedType = currentType;
                }

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

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

            FileMarker.MarkAsNew(file);
            FileMarker.RemoveMarkAsNew(file);
            return(file);
        }