示例#1
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);
        }
示例#2
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);
        }
示例#3
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,
                });
            }
        }
示例#4
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;
            }
        }
        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;
                }
            }
        }
        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;
            }
        }
示例#7
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);
        }
示例#8
0
        public void SaveFile(string fileId, string fileType, string downloadUrl, Stream stream)
        {
            Global.Logger.Debug("BoxApp: save file stream " + fileId +
                                (stream == null
                                     ? " from - " + downloadUrl
                                     : " from stream"));
            fileId = ThirdPartySelector.GetFileId(fileId);

            var token = Token.GetToken(AppAttr);

            var boxFile = GetBoxFile(fileId, token);

            if (boxFile == null)
            {
                Global.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
                {
                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl ?? Guid.NewGuid().ToString());
                    if (stream != null)
                    {
                        using (var tmpStream = new MemoryStream())
                        {
                            stream.CopyTo(tmpStream);

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

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

                    DocumentServiceConnector.GetConvertedUri(downloadUrl, fileType, currentType, key, false, out downloadUrl);
                    stream = null;
                }
                catch (Exception e)
                {
                    Global.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;
                Global.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())
                    {
                        var result = responseStream != null ? new StreamReader(responseStream).ReadToEnd() : null;

                        Global.Logger.Debug("BoxApp: save file response - " + result);
                    }
            }
            catch (WebException e)
            {
                Global.Logger.Error("BoxApp: Error save file", e);
                request.Abort();
                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
                throw;
            }
        }
        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;
                }
            }
        }
示例#10
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 = !string.IsNullOrEmpty(Request[UrlConstant.New]) && Request[UrlConstant.New] == "true";

                        var ver = string.IsNullOrEmpty(Request[CommonLinkUtility.Version]) ? -1 : Convert.ToInt32(Request[CommonLinkUtility.Version]);

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

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

                        fileUri = RequestFileUrl;
                        var fileTitle = Request[CommonLinkUtility.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))
                                    {
                                        fileUri = DocumentServiceConnector.GetExternalUri(responseStream, MimeMapping.GetMimeMapping(fileTitle), "new");
                                    }
                            }
                            catch (Exception error)
                            {
                                Global.Logger.Error("Cannot receive external url for \"" + RequestFileUrl + "\"", error);
                            }
                        }

                        file = new File
                        {
                            ID    = fileUri.GetHashCode(),
                            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[CommonLinkUtility.TryParam]);
                }
                catch
                {
                    tryType = FileType.Document;
                }

                var fileTitle = "Demo";
                fileTitle += FileUtility.InternalExtension[tryType];

                var relativeUri = string.Format(CommonLinkUtility.FileHandlerPath + UrlConstant.ParamsDemo, tryType);
                fileUri = new Uri(Request.Url, relativeUri).ToString();

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

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

                _docParams.FileUri = fileUri;
                _editByUrl         = true;
            }

            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(CommonLinkUtility.GetFileWebEditorUrl(file.ID) + comment);
                return;
            }

            Title = HeaderStringHelper.GetPageTitle(file.Title);

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

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

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

                if (FileSharing.CanSetAccess(file))
                {
                    _docParams.SharingSettingsUrl = CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.FilesBaseAbsolutePath + "share.aspx" + "?" + CommonLinkUtility.FileId + "=" + file.ID + "&" + CommonLinkUtility.FileTitle + "=" + HttpUtility.UrlEncode(file.Title));
                }
            }

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

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

            if (_docParams.ModeWrite)
            {
                _tabId       = FileLocker.Add(file.ID, _fileNew);
                _lockVersion = FileLocker.LockVersion(file.ID);

                if (ItsTry)
                {
                    AppendAuthControl();
                }
            }
            else
            {
                _docParams.LinkToEdit = _editByUrl
                                            ? CommonLinkUtility.GetFullAbsolutePath(string.Format(CommonLinkUtility.FileWebEditorExternalUrlString, HttpUtility.UrlEncode(fileUri), file.Title))
                                            : FileConverter.MustConvert(_docParams.File)
                                                  ? CommonLinkUtility.GetFullAbsolutePath(CommonLinkUtility.GetFileWebEditorUrl(file.ID))
                                                  : string.Empty;
            }

            if (CoreContext.Configuration.YourDocsDemo && IsMobile)
            {
                _docParams.CanEdit = false;
            }
        }