Example #1
0
        public void GetMailMergeConfig(out string dataMailMergeRecipients)
        {
            var jss = new JavaScriptSerializer();

            var mailMergeUrl = new UriBuilder(DocManagerHelper.GetServerUrl(true))
            {
                Path =
                    HttpRuntime.AppDomainAppVirtualPath
                    + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                    + "webeditor.ashx",
                Query = "type=csv"
            };

            var mailMergeConfig = new Dictionary <string, object>
            {
                { "fileType", "csv" },
                { "url", mailMergeUrl.ToString() }
            };

            if (JwtManager.Enabled)
            {
                var mailmergeToken = JwtManager.Encode(mailMergeConfig);
                mailMergeConfig.Add("token", mailmergeToken);
            }

            dataMailMergeRecipients = jss.Serialize(mailMergeConfig);
        }
Example #2
0
        public void GetCompareFileData(out string compareConfig)
        {
            var jss = new JavaScriptSerializer();

            var compareFileUrl = new UriBuilder(DocManagerHelper.GetServerUrl(true))
            {
                Path = HttpRuntime.AppDomainAppVirtualPath
                       + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                       + "webeditor.ashx",
                Query = "type=assets&fileName=" + HttpUtility.UrlEncode("sample.docx")
            };

            var dataCompareFile = new Dictionary <string, object>
            {
                { "fileType", "docx" },
                { "url", compareFileUrl.ToString() }
            };

            if (JwtManager.Enabled)
            {
                var compareFileToken = JwtManager.Encode(dataCompareFile);
                dataCompareFile.Add("token", compareFileToken);
            }

            compareConfig = jss.Serialize(dataCompareFile);
        }
Example #3
0
        public void GetLogoConfig(out string logoUrl)
        {
            var jss = new JavaScriptSerializer();

            var mailMergeUrl = new UriBuilder(DocManagerHelper.GetServerUrl(true))
            {
                Path = HttpRuntime.AppDomainAppVirtualPath
                       + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                       + "Content\\images\\logo.png"
            };

            var logoConfig = new Dictionary <string, object>
            {
                { "fileType", "png" },
                { "url", mailMergeUrl.ToString() }
            };

            if (JwtManager.Enabled)
            {
                var token = JwtManager.Encode(logoConfig);
                logoConfig.Add("token", token);
            }

            logoUrl = jss.Serialize(logoConfig).Replace("{", "").Replace("}", "");
        }
Example #4
0
        // get a mail merge config
        public void GetMailMergeConfig(out string dataMailMergeRecipients)
        {
            var jss = new JavaScriptSerializer();

            // get the path to the recipients data for mail merging
            var mailMergeUrl = new UriBuilder(DocManagerHelper.GetServerUrl(true))
            {
                Path =
                    HttpRuntime.AppDomainAppVirtualPath
                    + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                    + "webeditor.ashx",
                Query = "type=csv"
            };

            // create a mail merge config
            var mailMergeConfig = new Dictionary <string, object>
            {
                { "fileType", "csv" },
                { "url", mailMergeUrl.ToString() }
            };

            if (JwtManager.Enabled)                                      // if the secret key to generate token exists
            {
                var mailmergeToken = JwtManager.Encode(mailMergeConfig); // encode mailMergeConfig into the token
                mailMergeConfig.Add("token", mailmergeToken);            // and add it to the mail merge config
            }

            dataMailMergeRecipients = jss.Serialize(mailMergeConfig);
        }
Example #5
0
        // get a logo config
        public void GetLogoConfig(out string logoUrl)
        {
            var jss = new JavaScriptSerializer();

            // get the path to the logo image
            var mailMergeUrl = new UriBuilder(DocManagerHelper.GetServerUrl(true))
            {
                Path = HttpRuntime.AppDomainAppVirtualPath
                       + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                       + "Content\\images\\logo.png"
            };

            // create a logo config
            var logoConfig = new Dictionary <string, object>
            {
                { "fileType", "png" },
                { "url", mailMergeUrl.ToString() }
            };

            if (JwtManager.Enabled)                        // if the secret key to generate token exists
            {
                var token = JwtManager.Encode(logoConfig); // encode logoConfig into the token
                logoConfig.Add("token", token);            // and add it to the logo config
            }

            logoUrl = jss.Serialize(logoConfig).Replace("{", "").Replace("}", "");
        }
Example #6
0
        // get a document which will be compared with the current document
        public void GetCompareFileData(out string compareConfig)
        {
            var jss = new JavaScriptSerializer();

            // get the path to the compared file
            var compareFileUrl = new UriBuilder(DocManagerHelper.GetServerUrl(true))
            {
                Path = HttpRuntime.AppDomainAppVirtualPath
                       + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                       + "webeditor.ashx",
                Query = "type=assets&fileName=" + HttpUtility.UrlEncode("sample.docx")
            };

            // create an object with the information about the compared file
            var dataCompareFile = new Dictionary <string, object>
            {
                { "fileType", "docx" },
                { "url", compareFileUrl.ToString() }
            };

            if (JwtManager.Enabled)                                        // if the secret key to generate token exists
            {
                var compareFileToken = JwtManager.Encode(dataCompareFile); // encode the dataCompareFile object into the token
                dataCompareFile.Add("token", compareFileToken);            // and add it to the dataCompareFile object
            }

            compareConfig = jss.Serialize(dataCompareFile);
        }
Example #7
0
        public VarlikResult <TokenUser> Login(string mail, string password)
        {
            var loginResult = _userOperation.Login(mail, password);

            if (loginResult.IsSuccess)
            {
                var jwtManager = new JwtManager();
                loginResult.Data.Token = jwtManager.Encode(loginResult.Data).Data;
            }
            return(loginResult);
        }
        public string Login(LoginCredentials credentials)
        {
            UserAccount userAccount = _accountWrapper.Repository.GetMatching(account
                                                                             =>
                                                                             account.Credentials.Email == credentials.Email &&
                                                                             account.Credentials.Password == credentials.Password
                                                                             ).FirstOrDefault();

            if (userAccount != default)
            {
                if (!userAccount.IsActivated)
                {
                    throw new BadRequestException("Account not activated.");
                }
                return(_jwtManager.Encode(MapAccountToUserToken(userAccount)));
            }

            return(null);
        }
Example #9
0
        /// <summary>
        ///     The method is to convert the file to the required format
        /// </summary>
        /// <param name="documentUri">Uri for the document to convert</param>
        /// <param name="fromExtension">Document extension</param>
        /// <param name="toExtension">Extension to which to convert</param>
        /// <param name="documentRevisionId">Key for caching on service</param>
        /// <param name="isAsync">Perform conversions asynchronously</param>
        /// <param name="convertedDocumentUri">Uri to the converted document</param>
        /// <returns>The percentage of completion of conversion</returns>
        /// <example>
        /// string convertedDocumentUri;
        /// GetConvertedUri("http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", ".pdf", ".docx", "http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", false, out convertedDocumentUri);
        /// </example>
        /// <exception>
        /// </exception>
        public static int GetConvertedUri(string documentUri,
                                          string fromExtension,
                                          string toExtension,
                                          string documentRevisionId,
                                          bool isAsync,
                                          out string convertedDocumentUri)
        {
            convertedDocumentUri = string.Empty;

            fromExtension = string.IsNullOrEmpty(fromExtension) ? Path.GetExtension(documentUri) : fromExtension;

            var title = Path.GetFileName(documentUri);

            title = string.IsNullOrEmpty(title) ? Guid.NewGuid().ToString() : title;

            documentRevisionId = string.IsNullOrEmpty(documentRevisionId)
                                     ? documentUri
                                     : documentRevisionId;
            documentRevisionId = GenerateRevisionId(documentRevisionId);

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

            request.Method      = "POST";
            request.ContentType = "application/json";
            request.Accept      = "application/json";
            request.Timeout     = ConvertTimeout;

            var body = new Dictionary <string, object>()
            {
                { "async", isAsync },
                { "filetype", fromExtension.Trim('.') },
                { "key", documentRevisionId },
                { "outputtype", toExtension.Trim('.') },
                { "title", title },
                { "url", documentUri }
            };

            if (JwtManager.Enabled)
            {
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };

                var payloadToken = JwtManager.Encode(payload);
                var bodyToken    = JwtManager.Encode(body);
                request.Headers.Add("Authorization", "Bearer " + payloadToken);

                body.Add("token", bodyToken);
            }

            var bytes = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(body));

            request.ContentLength = bytes.Length;
            using (var requestStream = request.GetRequestStream())
            {
                requestStream.Write(bytes, 0, bytes.Length);
            }

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

            string dataResponse;

            using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("Response is null");
                    }

                    using (var reader = new StreamReader(stream))
                    {
                        dataResponse = reader.ReadToEnd();
                    }
                }

            return(GetResponseUri(dataResponse, out convertedDocumentUri));
        }
Example #10
0
        /// <summary>
        ///     The method is to convert the file to the required format
        /// </summary>
        /// <param name="documentUri">Uri for the document to convert</param>
        /// <param name="fromExtension">Document extension</param>
        /// <param name="toExtension">Extension to which to convert</param>
        /// <param name="documentRevisionId">Key for caching on service</param>
        /// <param name="isAsync">Perform conversions asynchronously</param>
        /// <param name="convertedDocumentUri">Uri to the converted document</param>
        /// <returns>The percentage of conversion completion</returns>
        /// <example>
        /// string convertedDocumentUri;
        /// GetConvertedUri("http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", ".pdf", ".docx", "http://helpcenter.onlyoffice.com/content/GettingStarted.pdf", false, out convertedDocumentUri);
        /// </example>
        /// <exception>
        /// </exception>
        public static int GetConvertedUri(string documentUri,
                                          string fromExtension,
                                          string toExtension,
                                          string documentRevisionId,
                                          bool isAsync,
                                          out string convertedDocumentUri,
                                          string filePass = null,
                                          string lang     = null)
        {
            convertedDocumentUri = string.Empty;

            // check if the fromExtension parameter is defined; if not, get it from the document url
            fromExtension = string.IsNullOrEmpty(fromExtension) ? Path.GetExtension(documentUri).ToLower() : fromExtension;

            // check if the file name parameter is defined; if not, get random uuid for this file
            var title = Path.GetFileName(documentUri);

            title = string.IsNullOrEmpty(title) ? Guid.NewGuid().ToString() : title;

            // get document key
            documentRevisionId = string.IsNullOrEmpty(documentRevisionId)
                                     ? documentUri
                                     : documentRevisionId;
            documentRevisionId = GenerateRevisionId(documentRevisionId);

            // specify request parameters
            var request = (HttpWebRequest)WebRequest.Create(DocumentConverterUrl);

            request.Method      = "POST";
            request.ContentType = "application/json";
            request.Accept      = "application/json";
            request.Timeout     = ConvertTimeout;

            // write all the necessary parameters to the body object
            var body = new Dictionary <string, object>()
            {
                { "async", isAsync },
                { "filetype", fromExtension.Trim('.') },
                { "key", documentRevisionId },
                { "outputtype", toExtension.Trim('.') },
                { "title", title },
                { "url", documentUri },
                { "password", filePass },
                { "region", lang }
            };

            if (JwtManager.Enabled)
            {
                // create payload object
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };

                var payloadToken = JwtManager.Encode(payload); // encode the payload object to the payload token
                var bodyToken    = JwtManager.Encode(body);    // encode the body object to the body token
                // create header token
                string JWTheader = WebConfigurationManager.AppSettings["files.docservice.header"].Equals("") ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];
                request.Headers.Add(JWTheader, "Bearer " + payloadToken);  // and add it to the request headers with the Bearer prefix

                body.Add("token", bodyToken);
            }

            var bytes = Encoding.UTF8.GetBytes(new JavaScriptSerializer().Serialize(body));

            request.ContentLength = bytes.Length;
            using (var requestStream = request.GetRequestStream()) // get the request stream
            {
                requestStream.Write(bytes, 0, bytes.Length);       // and write the serialized body object to it
            }

            _Default.VerifySSL();

            string dataResponse;

            using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream()) // get the response stream
                {
                    if (stream == null)
                    {
                        throw new Exception("Response is null");
                    }

                    using (var reader = new StreamReader(stream))
                    {
                        dataResponse = reader.ReadToEnd(); // and read it
                    }
                }

            return(GetResponseUri(dataResponse, out convertedDocumentUri));
        }
Example #11
0
        public string GetDocConfig(HttpRequest request, UrlHelper url)
        {
            var jss = new JavaScriptSerializer();

            var ext         = Path.GetExtension(FileName);
            var editorsMode = Mode ?? "edit";

            var canEdit    = DocManagerHelper.EditedExts.Contains(ext);
            var mode       = canEdit && editorsMode != "view" ? "edit" : "view";
            var submitForm = canEdit && (editorsMode.Equals("edit") || editorsMode.Equals("fillForms"));

            var           userId       = request.Cookies.GetOrDefault("uid", "uid-1");
            var           uname        = userId.Equals("uid-0") ? null : request.Cookies.GetOrDefault("uname", "John Smith");
            string        userGroup    = null;
            List <string> reviewGroups = null;

            if (userId.Equals("uid-2"))
            {
                userGroup    = "group-2";
                reviewGroups = new List <string>()
                {
                    "group-2", ""
                };
            }
            if (userId.Equals("uid-3"))
            {
                userGroup    = "group-3";
                reviewGroups = new List <string>()
                {
                    "group-2"
                };
            }

            object favorite = null;

            if (!string.IsNullOrEmpty(request.Cookies.GetOrDefault("uid", null)))
            {
                favorite = request.Cookies.GetOrDefault("uid", null).Equals("uid-2");
            }

            var actionLink = request.GetOrDefault("actionLink", null);
            var actionData = string.IsNullOrEmpty(actionLink) ? null : jss.DeserializeObject(actionLink);

            var config = new Dictionary <string, object>
            {
                { "type", Type ?? "desktop" },
                { "documentType", DocumentType },
                {
                    "document", new Dictionary <string, object>
                    {
                        { "title", FileName },
                        { "url", FileUri },
                        { "fileType", ext.Trim('.') },
                        { "key", Key },
                        {
                            "info", new Dictionary <string, object>
                            {
                                { "owner", "Me" },
                                { "uploaded", DateTime.Now.ToShortDateString() },
                                { "favorite", favorite }
                            }
                        },
                        {
                            "permissions", new Dictionary <string, object>
                            {
                                { "comment", editorsMode != "view" && editorsMode != "fillForms" && editorsMode != "embedded" && editorsMode != "blockcontent" },
                                { "download", true },
                                { "edit", canEdit&& (editorsMode == "edit" || editorsMode == "filter") || editorsMode == "blockcontent" },
                                { "fillForms", editorsMode != "view" && editorsMode != "comment" && editorsMode != "embedded" && editorsMode != "blockcontent" },
                                { "modifyFilter", editorsMode != "filter" },
                                { "modifyContentControl", editorsMode != "blockcontent" },
                                { "review", editorsMode == "edit" || editorsMode == "review" },
                                { "reviewGroups", reviewGroups }
                            }
                        }
                    }
                },
                {
                    "editorConfig", new Dictionary <string, object>
                    {
                        { "actionLink", actionData },
                        { "mode", mode },
                        { "lang", request.Cookies.GetOrDefault("ulang", "en") },
                        { "callbackUrl", CallbackUrl },
                        {
                            "user", new Dictionary <string, object>
                            {
                                { "id", userId },
                                { "name", uname },
                                { "group", userGroup }
                            }
                        },
                        {
                            "embedded", new Dictionary <string, object>
                            {
                                { "saveUrl", FileUriUser },
                                { "embedUrl", FileUriUser },
                                { "shareUrl", FileUriUser },
                                { "toolbarDocked", "top" }
                            }
                        },
                        {
                            "customization", new Dictionary <string, object>
                            {
                                { "about", true },
                                { "feedback", true },
                                { "forcesave", false },
                                { "submitForm", submitForm },
                                {
                                    "goback", new Dictionary <string, object>
                                    {
                                        { "url", url.Action("Index", "Home") }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            if (JwtManager.Enabled)
            {
                var token = JwtManager.Encode(config);
                config.Add("token", token);
            }

            return(jss.Serialize(config));
        }
Example #12
0
        public void GetHistory(out string history, out string historyData)
        {
            var jss     = new JavaScriptSerializer();
            var histDir = DocManagerHelper.HistoryDir(DocManagerHelper.StoragePath(FileName, null));

            history     = null;
            historyData = null;

            if (DocManagerHelper.GetFileVersion(histDir) > 0)
            {
                var currentVersion = DocManagerHelper.GetFileVersion(histDir);
                var hist           = new List <Dictionary <string, object> >();
                var histData       = new Dictionary <string, object>();

                for (var i = 1; i <= currentVersion; i++)
                {
                    var obj     = new Dictionary <string, object>();
                    var dataObj = new Dictionary <string, object>();
                    var verDir  = DocManagerHelper.VersionDir(histDir, i);

                    var key = i == currentVersion ? Key : File.ReadAllText(Path.Combine(verDir, "key.txt"));

                    obj.Add("key", key);
                    obj.Add("version", i);

                    if (i == 1)
                    {
                        var infoPath = Path.Combine(histDir, "createdInfo.json");

                        if (File.Exists(infoPath))
                        {
                            var info = jss.Deserialize <Dictionary <string, object> >(File.ReadAllText(infoPath));
                            obj.Add("created", info["created"]);
                            obj.Add("user", new Dictionary <string, object>()
                            {
                                { "id", info["id"] },
                                { "name", info["name"] },
                            });
                        }
                    }

                    dataObj.Add("key", key);
                    dataObj.Add("url", i == currentVersion ? FileUri : DocManagerHelper.GetPathUri(Directory.GetFiles(verDir, "prev.*")[0].Substring(HttpRuntime.AppDomainAppPath.Length)));
                    dataObj.Add("version", i);
                    if (i > 1)
                    {
                        var changes = jss.Deserialize <Dictionary <string, object> >(File.ReadAllText(Path.Combine(DocManagerHelper.VersionDir(histDir, i - 1), "changes.json")));
                        var change  = ((Dictionary <string, object>)((ArrayList)changes["changes"])[0]);

                        obj.Add("changes", changes["changes"]);
                        obj.Add("serverVersion", changes["serverVersion"]);
                        obj.Add("created", change["created"]);
                        obj.Add("user", change["user"]);

                        var prev = (Dictionary <string, object>)histData[(i - 2).ToString()];
                        dataObj.Add("previous", new Dictionary <string, object>()
                        {
                            { "key", prev["key"] },
                            { "url", prev["url"] },
                        });
                        dataObj.Add("changesUrl", DocManagerHelper.GetPathUri(Path.Combine(DocManagerHelper.VersionDir(histDir, i - 1), "diff.zip").Substring(HttpRuntime.AppDomainAppPath.Length)));
                    }
                    if (JwtManager.Enabled)
                    {
                        var token = JwtManager.Encode(dataObj);
                        dataObj.Add("token", token);
                    }
                    hist.Add(obj);
                    histData.Add((i - 1).ToString(), dataObj);
                }

                history = jss.Serialize(new Dictionary <string, object>()
                {
                    { "currentVersion", currentVersion },
                    { "history", hist }
                });
                historyData = jss.Serialize(histData);
            }
        }
        public string GetDocConfig(HttpRequest request, UrlHelper url)
        {
            var jss = new JavaScriptSerializer();

            var ext         = Path.GetExtension(FileName);
            var editorsMode = Mode ?? "edit";

            var canEdit = DocManagerHelper.EditedExts.Contains(ext);
            var mode    = canEdit && editorsMode != "view" ? "edit" : "view";

            var actionLink = request.GetOrDefault("actionLink", null);
            var actionData = string.IsNullOrEmpty(actionLink) ? null : jss.DeserializeObject(actionLink);

            var config = new Dictionary <string, object>
            {
                { "type", Type ?? "desktop" },
                { "documentType", DocumentType },
                {
                    "document", new Dictionary <string, object>
                    {
                        { "title", FileName },
                        { "url", FileUri },
                        { "fileType", ext.Trim('.') },
                        { "key", Key },
                        {
                            "info", new Dictionary <string, object>
                            {
                                { "author", "Me" },
                                { "created", DateTime.Now.ToShortDateString() }
                            }
                        },
                        {
                            "permissions", new Dictionary <string, object>
                            {
                                { "comment", editorsMode != "view" && editorsMode != "fillForms" && editorsMode != "embedded" && editorsMode != "blockcontent" },
                                { "download", true },
                                { "edit", canEdit&& (editorsMode == "edit" || editorsMode == "filter") || editorsMode == "blockcontent" },
                                { "fillForms", editorsMode != "view" && editorsMode != "comment" && editorsMode != "embedded" && editorsMode != "blockcontent" },
                                { "modifyFilter", editorsMode != "filter" },
                                { "modifyContentControl", editorsMode != "blockcontent" },
                                { "review", editorsMode == "edit" || editorsMode == "review" }
                            }
                        }
                    }
                },
                {
                    "editorConfig", new Dictionary <string, object>
                    {
                        { "actionLink", actionData },
                        { "mode", mode },
                        { "lang", request.Cookies.GetOrDefault("ulang", "en") },
                        { "callbackUrl", CallbackUrl },
                        {
                            "user", new Dictionary <string, object>
                            {
                                { "id", request.Cookies.GetOrDefault("uid", "uid-1") },
                                { "name", request.Cookies.GetOrDefault("uname", "John Smith") }
                            }
                        },
                        {
                            "embedded", new Dictionary <string, object>
                            {
                                { "saveUrl", FileUri },
                                { "embedUrl", FileUri },
                                { "shareUrl", FileUri },
                                { "toolbarDocked", "top" }
                            }
                        },
                        {
                            "customization", new Dictionary <string, object>
                            {
                                { "about", true },
                                { "feedback", true },
                                {
                                    "goback", new Dictionary <string, object>
                                    {
                                        { "url", url.Action("Index", "Home") }
                                    }
                                }
                            }
                        }
                    }
                }
            };

            if (JwtManager.Enabled)
            {
                var token = JwtManager.Encode(config);
                config.Add("token", token);
            }

            return(jss.Serialize(config));
        }
Example #14
0
        // get the document config
        public string GetDocConfig(HttpRequest request, UrlHelper url)
        {
            var jss = new JavaScriptSerializer();

            var ext         = Path.GetExtension(FileName).ToLower(); // get file extension
            var editorsMode = Mode ?? "edit";                        // get editor mode

            var canEdit = DocManagerHelper.EditedExts.Contains(ext); // check if the file with such an extension can be edited

            var id   = request.Cookies.GetOrDefault("uid", null);
            var user = Users.getUser(id);  // get the user

            if ((!canEdit && editorsMode.Equals("edit") || editorsMode.Equals("fillForms")) && DocManagerHelper.FillFormExts.Contains(ext))
            {
                editorsMode = "fillForms";
                canEdit     = true;
            }
            var submitForm = editorsMode.Equals("fillForms") && id.Equals("uid-1") && false; // check if the Submit form button is displayed or not
            var mode       = canEdit && editorsMode != "view" ? "edit" : "view";             // set the mode parameter: change it to view if the document can't be edited

            // favorite icon state
            bool?favorite = user.favorite;

            var actionLink = request.GetOrDefault("actionLink", null);                                    // get the action link (comment or bookmark) if it exists
            var actionData = string.IsNullOrEmpty(actionLink) ? null : jss.DeserializeObject(actionLink); // get action data for the action link

            var createUrl         = DocManagerHelper.GetCreateUrl(FileUtility.GetFileType(FileName));
            var templatesImageUrl = DocManagerHelper.GetTemplateImageUrl(FileUtility.GetFileType(FileName)); // image url for templates
            var templates         = new List <Dictionary <string, string> >
            {
                new Dictionary <string, string>()
                {
                    { "image", "" },
                    { "title", "Blank" },
                    { "url", createUrl },
                },
                new Dictionary <string, string>()
                {
                    { "image", templatesImageUrl },
                    { "title", "With sample content" },
                    { "url", createUrl + "&sample=true" },
                }
            };

            // specify the document config
            var config = new Dictionary <string, object>
            {
                { "type", Type ?? "desktop" },
                { "documentType", DocumentType },
                {
                    "document", new Dictionary <string, object>
                    {
                        { "title", FileName },
                        { "url", DownloadUrl },
                        { "fileType", ext.Trim('.') },
                        { "key", Key },
                        {
                            "info", new Dictionary <string, object>
                            {
                                { "owner", "Me" },
                                { "uploaded", DateTime.Now.ToShortDateString() },
                                { "favorite", favorite }
                            }
                        },
                        {
                            // the permission for the document to be edited and downloaded or not
                            "permissions", new Dictionary <string, object>
                            {
                                { "comment", editorsMode != "view" && editorsMode != "fillForms" && editorsMode != "embedded" && editorsMode != "blockcontent" },
                                { "copy", !user.deniedPermissions.Contains("copy") },
                                { "download", !user.deniedPermissions.Contains("download") },
                                { "edit", canEdit&& (editorsMode == "edit" || editorsMode == "view" || editorsMode == "filter" || editorsMode == "blockcontent") },
                                { "print", !user.deniedPermissions.Contains("print") },
                                { "fillForms", editorsMode != "view" && editorsMode != "comment" && editorsMode != "embedded" && editorsMode != "blockcontent" },
                                { "modifyFilter", editorsMode != "filter" },
                                { "modifyContentControl", editorsMode != "blockcontent" },
                                { "review", canEdit&& (editorsMode == "edit" || editorsMode == "review") },
                                { "reviewGroups", user.reviewGroups },
                                { "commentGroups", user.commentGroups },
                                { "userInfoGroups", user.userInfoGroups }
                            }
                        }
                    }
                },
                {
                    "editorConfig", new Dictionary <string, object>
                    {
                        { "actionLink", actionData },
                        { "mode", mode },
                        { "lang", request.Cookies.GetOrDefault("ulang", "en") },
                        { "callbackUrl", CallbackUrl },          // absolute URL to the document storage service
                        { "createUrl", !user.id.Equals("uid-0") ? createUrl : null },
                        { "templates", user.templates ? templates : null },
                        {
                            // the user currently viewing or editing the document
                            "user", new Dictionary <string, object>
                            {
                                { "id", !user.id.Equals("uid-0") ? user.id : null },
                                { "name", user.name },
                                { "group", user.group }
                            }
                        },
                        {
                            // the parameters for the embedded document type
                            "embedded", new Dictionary <string, object>
                            {
                                { "saveUrl", FileUriUser },             // the absolute URL that will allow the document to be saved onto the user personal computer
                                { "embedUrl", FileUriUser },            // the absolute URL to the document serving as a source file for the document embedded into the web page
                                { "shareUrl", FileUriUser },            // the absolute URL that will allow other users to share this document
                                { "toolbarDocked", "top" }              // the place for the embedded viewer toolbar (top or bottom)
                            }
                        },
                        {
                            // the parameters for the editor interface
                            "customization", new Dictionary <string, object>
                            {
                                { "about", true },                             // the About section display
                                { "comments", true },
                                { "feedback", true },                          // the Feedback & Support menu button display
                                { "forcesave", false },                        // adds the request for the forced file saving to the callback handler
                                { "submitForm", submitForm },                  // if the Submit form button is displayed or not
                                {
                                    "goback", new Dictionary <string, object>  // settings for the Open file location menu button and upper right corner button
                                    {
                                        { "url", url.Action("Index", "Home") } // the absolute URL to the website address which will be opened when clicking the Open file location menu button
                                    }
                                }
                            }
                        }
                    }
                }
            };

            // if the secret key to generate token exists
            if (JwtManager.Enabled)
            {
                // encode the document config into a token
                var token = JwtManager.Encode(config);
                config.Add("token", token);
            }

            return(jss.Serialize(config));
        }
Example #15
0
        // get the document history
        public void GetHistory(out string history, out string historyData)
        {
            var storagePath = WebConfigurationManager.AppSettings["storage-path"];
            var jss         = new JavaScriptSerializer();
            var histDir     = DocManagerHelper.HistoryDir(DocManagerHelper.StoragePath(FileName, null));

            history     = null;
            historyData = null;

            if (DocManagerHelper.GetFileVersion(histDir) > 0)  // if the file was modified (the file version is greater than 0)
            {
                var currentVersion = DocManagerHelper.GetFileVersion(histDir);
                var hist           = new List <Dictionary <string, object> >();
                var histData       = new Dictionary <string, object>();

                for (var i = 1; i <= currentVersion; i++)  // run through all the file versions
                {
                    var obj     = new Dictionary <string, object>();
                    var dataObj = new Dictionary <string, object>();
                    var verDir  = DocManagerHelper.VersionDir(histDir, i);                                   // get the path to the given file version

                    var key = i == currentVersion ? Key : File.ReadAllText(Path.Combine(verDir, "key.txt")); // get document key

                    obj.Add("key", key);
                    obj.Add("version", i);

                    if (i == 1)                                                   // check if the version number is equal to 1
                    {
                        var infoPath = Path.Combine(histDir, "createdInfo.json"); // get meta data of this file

                        if (File.Exists(infoPath))
                        {
                            var info = jss.Deserialize <Dictionary <string, object> >(File.ReadAllText(infoPath));
                            obj.Add("created", info["created"]);  // write meta information to the object (user information and creation date)
                            obj.Add("user", new Dictionary <string, object>()
                            {
                                { "id", info["id"] },
                                { "name", info["name"] },
                            });
                        }
                    }

                    var ext = Path.GetExtension(FileName).ToLower();
                    dataObj.Add("fileType", ext.Replace(".", ""));
                    dataObj.Add("key", key);
                    // write file url to the data object
                    string prevFileUrl;
                    if (Path.IsPathRooted(storagePath) && !string.IsNullOrEmpty(storagePath))
                    {
                        prevFileUrl = i == currentVersion?DocManagerHelper.GetHistoryDownloadUrl(FileName, i.ToString(), "prev" + ext)
                                          : DocManagerHelper.GetDownloadUrl(Directory.GetFiles(verDir, "prev.*")[0].Replace(storagePath + "\\", ""));
                    }
                    else
                    {
                        prevFileUrl = i == currentVersion ? FileUri
                        : DocManagerHelper.GetHistoryDownloadUrl(FileName, i.ToString(), "prev" + ext);
                    }

                    dataObj.Add("url", prevFileUrl);
                    dataObj.Add("version", i);
                    if (i > 1)  // check if the version number is greater than 1 (the file was modified)
                    {
                        // get the path to the changes.json file
                        var changes      = jss.Deserialize <Dictionary <string, object> >(File.ReadAllText(Path.Combine(DocManagerHelper.VersionDir(histDir, i - 1), "changes.json")));
                        var changesArray = (ArrayList)changes["changes"];
                        var change       = changesArray.Count > 0
                            ? (Dictionary <string, object>)changesArray[0]
                            : new Dictionary <string, object>();

                        // write information about changes to the object
                        obj.Add("changes", change.Count > 0 ? changes["changes"] : null);
                        obj.Add("serverVersion", changes["serverVersion"]);
                        obj.Add("created", change.Count > 0  ? change["created"] : null);
                        obj.Add("user", change.Count > 0 ? change["user"] : null);

                        var prev = (Dictionary <string, object>)histData[(i - 2).ToString()]; // get the history data from the previous file version
                        dataObj.Add("previous", new Dictionary <string, object>()             // write information about previous file version to the data object
                        {
                            { "fileType", prev["fileType"] },
                            { "key", prev["key"] },  // write key and url information about previous file version
                            { "url", prev["url"] },
                        });
                        // write the path to the diff.zip archive with differences in this file version
                        var changesUrl = DocManagerHelper.GetHistoryDownloadUrl(FileName, (i - 1).ToString(), "diff.zip");
                        dataObj.Add("changesUrl", changesUrl);
                    }
                    if (JwtManager.Enabled)
                    {
                        var token = JwtManager.Encode(dataObj);
                        dataObj.Add("token", token);
                    }
                    hist.Add(obj);                             // add object dictionary to the hist list
                    histData.Add((i - 1).ToString(), dataObj); // write data object information to the history data
                }

                // write history information about the current file version to the history object
                history = jss.Serialize(new Dictionary <string, object>()
                {
                    { "currentVersion", currentVersion },
                    { "history", hist }
                });
                historyData = jss.Serialize(histData);
            }
        }