Example #1
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 #2
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 #3
0
        public ActionResult DocumentView(long uri)
        {
            Logger.Info($"Document View");
            var file = DocManagerHelper.GetDocumentForView(uri, AppUserState.UserName, AppUserState.Wgs, AppUserState.Ds, AppUserState.UserId);
            var conn = new InforConnection(tu: _tu, tup: _tup);
            var rec  = (InforRecord)conn.GetRecordWeb(uri, AppUserState.UserName, AppUserState.Wgs, AppUserState.Ds);
            var hvm  = new FileViewModel
            {
                Edit         = false,
                ErrorDisplay = ErrorDisplay,
                AppUserState = AppUserState,
                RecordNumber = rec.RecordNumber,
                Title        = rec.Title,
                FileModel    = new FileModel
                {
                    TypeDesktop  = true,
                    FileName     = file,
                    AppUserState = AppUserState,
                    RecordUri    = rec.Uri
                },
                Uri = uri
            };

            Logger.Info($"{hvm.FileModel.FileUri}");
            Logger.Info($"{hvm.FileModel.Key}");
            Logger.Info($"{hvm.FileModel.DocumentType}");
            return(PartialView("_DocumentView", hvm));
        }
        public ActionResult Sample(string fileExt)
        {
            var fileName = DocManagerHelper.CreateDemo(fileExt);

            Response.Redirect(Url.Action("Editor", "Home", new { fileName = fileName }));
            return(null);
        }
Example #5
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);
        }
        private static void Files(HttpContext context)
        {
            List <Dictionary <string, object> > files = null;

            try
            {
                var jss = new JavaScriptSerializer();
                context.Response.ContentType = "application/json";

                if (context.Request["fileId"] == null)
                {
                    files = DocManagerHelper.GetFilesInfo();
                    context.Response.Write(jss.Serialize(files));
                }
                else
                {
                    var fileId = context.Request["fileId"];
                    files = DocManagerHelper.GetFilesInfo(fileId);
                    if (files.Count == 0)
                    {
                        context.Response.Write("\"File not found\"");
                    }
                    else
                    {
                        context.Response.Write(jss.Serialize(files));
                    }
                }
            }
            catch (Exception e)
            {
                context.Response.Write("{ \"error\": \"" + e.Message + "\"}");
            }
        }
Example #7
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 #8
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 #9
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);
        }
        private static void Convert(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                var fileName = Path.GetFileName(context.Request["filename"]);
                var fileUri  = DocManagerHelper.GetFileUri(fileName, true);

                var extension         = (Path.GetExtension(fileUri) ?? "").Trim('.');
                var internalExtension = DocManagerHelper.GetInternalExtension(FileUtility.GetFileType(fileName)).Trim('.');

                if (DocManagerHelper.ConvertExts.Contains("." + extension) &&
                    !string.IsNullOrEmpty(internalExtension))
                {
                    var key = ServiceConverter.GenerateRevisionId(fileUri);

                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(fileUri, extension, internalExtension, key, true, out newFileUri);
                    if (result != 100)
                    {
                        context.Response.Write("{ \"step\" : \"" + result + "\", \"filename\" : \"" + fileName + "\"}");
                        return;
                    }

                    var correctName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "." + internalExtension);

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

                    using (var stream = req.GetResponse().GetResponseStream())
                    {
                        if (stream == null)
                        {
                            throw new Exception("Stream is null");
                        }
                        const int bufferSize = 4096;

                        using (var fs = File.Open(DocManagerHelper.StoragePath(correctName), FileMode.Create))
                        {
                            var buffer = new byte[bufferSize];
                            int readed;
                            while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                            {
                                fs.Write(buffer, 0, readed);
                            }
                        }
                    }

                    Remove(fileName);
                    fileName = correctName;
                    DocManagerHelper.CreateMeta(fileName, context.Request.Cookies.GetOrDefault("uid", ""), context.Request.Cookies.GetOrDefault("uname", ""));
                }

                context.Response.Write("{ \"filename\" : \"" + fileName + "\"}");
            }
            catch (Exception e)
            {
                context.Response.Write("{ \"error\": \"" + e.Message + "\"}");
            }
        }
        public ActionResult Sample(string fileExt, bool?sample)
        {
            var fileName = DocManagerHelper.CreateDemo(fileExt, sample ?? false);

            DocManagerHelper.CreateMeta(fileName, Request.Cookies.GetOrDefault("uid", ""), Request.Cookies.GetOrDefault("uname", ""));
            Response.Redirect(Url.Action("Editor", "Home", new { fileName = fileName }));
            return(null);
        }
        // creating a sample document
        public ActionResult Sample(string fileExt, bool?sample)
        {
            var fileName = DocManagerHelper.CreateDemo(fileExt, sample ?? false);  // create a sample document
            var id       = Request.Cookies.GetOrDefault("uid", null);
            var user     = Users.getUser(id);

            DocManagerHelper.CreateMeta(fileName, user.id, user.name);  // create meta information for the sample document
            Response.Redirect(Url.Action("Editor", "Home", new { fileName = fileName }));
            return(null);
        }
Example #13
0
        public void CheckinDocument(long uri)
        {
            Logger.Info($"File Checked in  {uri}");
            DocManagerHelper.CheckinDocument(uri, AppUserState.UserName, AppUserState.Wgs, AppUserState.Ds);
            var filename = InforConnection.GetFileNameSansExtension(Convert.ToInt64(uri), AppUserState.UserName, AppUserState.Wgs, AppUserState.Ds);

            if (System.IO.File.Exists(Path.Combine(PdPath, filename)))
            {
                System.IO.File.Delete(Path.Combine(PdPath, filename));
            }
        }
        private static void Remove(string fileName)
        {
            var path    = DocManagerHelper.StoragePath(fileName, null);
            var histDir = DocManagerHelper.HistoryDir(path);

            if (File.Exists(path))
            {
                File.Delete(path);
            }
            if (Directory.Exists(histDir))
            {
                Directory.Delete(histDir, true);
            }
        }
        // upload a file
        private static void Upload(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                DocManagerHelper.VerifySSL();

                var    httpPostedFile = context.Request.Files[0];
                string fileName;

                // check from which browser the request came for
                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    var files = httpPostedFile.FileName.Split(new char[] { '\\' });
                    fileName = files[files.Length - 1];  // get file name
                }
                else
                {
                    fileName = httpPostedFile.FileName;
                }

                var curSize = httpPostedFile.ContentLength;
                if (DocManagerHelper.MaxFileSize < curSize || curSize <= 0)  // check if the file size exceeds the maximum file size
                {
                    throw new Exception("File size is incorrect");
                }

                var curExt = (Path.GetExtension(fileName) ?? "").ToLower();
                if (!DocManagerHelper.FileExts.Contains(curExt))  // check if the file extension is supported by the editor
                {
                    throw new Exception("File type is not supported");
                }

                fileName = DocManagerHelper.GetCorrectName(fileName);  // get the correct file name if such a name already exists
                var documentType = FileUtility.GetFileType(fileName).ToString().ToLower();

                var savedFileName = DocManagerHelper.StoragePath(fileName); // get the storage path to the uploading file
                httpPostedFile.SaveAs(savedFileName);                       // and save it
                // get file meta information or create the default one
                var id   = context.Request.Cookies.GetOrDefault("uid", null);
                var user = Users.getUser(id);
                DocManagerHelper.CreateMeta(fileName, user.id, user.name);

                context.Response.Write("{ \"filename\": \"" + fileName + "\", \"documentType\": \"" + documentType + "\"}");
            }
            catch (Exception e)
            {
                context.Response.Write("{ \"error\": \"" + e.Message + "\"}");
            }
        }
        private static void Download(HttpContext context)
        {
            try
            {
                var fileName = Path.GetFileName(context.Request["filename"]);

                var filePath = DocManagerHelper.ForcesavePath(fileName, null, false);
                if (filePath.Equals(""))
                {
                    filePath = DocManagerHelper.StoragePath(fileName, null);
                }
                download(filePath, context);
            }
            catch (Exception)
            {
                context.Response.Write("{ \"error\": \"File not found!\"}");
            }
        }
        private static void Upload(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                var    httpPostedFile = context.Request.Files[0];
                string fileName;

                if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
                {
                    var files = httpPostedFile.FileName.Split(new char[] { '\\' });
                    fileName = files[files.Length - 1];
                }
                else
                {
                    fileName = httpPostedFile.FileName;
                }

                var curSize = httpPostedFile.ContentLength;
                if (DocManagerHelper.MaxFileSize < curSize || curSize <= 0)
                {
                    throw new Exception("File size is incorrect");
                }

                var curExt = (Path.GetExtension(fileName) ?? "").ToLower();
                if (!DocManagerHelper.FileExts.Contains(curExt))
                {
                    throw new Exception("File type is not supported");
                }

                fileName = DocManagerHelper.GetCorrectName(fileName);

                var savedFileName = DocManagerHelper.StoragePath(fileName);
                httpPostedFile.SaveAs(savedFileName);
                DocManagerHelper.CreateMeta(fileName, context.Request.Cookies.GetOrDefault("uid", ""), context.Request.Cookies.GetOrDefault("uname", ""));

                context.Response.Write("{ \"filename\": \"" + fileName + "\"}");
            }
            catch (Exception e)
            {
                context.Response.Write("{ \"error\": \"" + e.Message + "\"}");
            }
        }
        // download a history file
        private static void DownloadHistory(HttpContext context)
        {
            try
            {
                var fileName    = Path.GetFileName(context.Request["fileName"]);
                var userAddress = Path.GetFileName(context.Request["userAddress"]);
                var version     = System.Convert.ToInt32(context.Request["ver"]);
                var file        = Path.GetFileName(context.Request["file"]);

                if (JwtManager.Enabled)
                {
                    string JWTheader = WebConfigurationManager.AppSettings["files.docservice.header"].Equals("") ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];

                    if (context.Request.Headers.AllKeys.Contains(JWTheader, StringComparer.InvariantCultureIgnoreCase))
                    {
                        var    headerToken = context.Request.Headers.Get(JWTheader).Substring("Bearer ".Length);
                        string token       = JwtManager.Decode(headerToken);

                        if (token == null || token.Equals(""))
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                            context.Response.Write("JWT validation failed");
                            return;
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                        context.Response.Write("JWT validation failed");
                        return;
                    }
                }
                var histPath = DocManagerHelper.HistoryDir(DocManagerHelper.StoragePath(fileName, userAddress));
                var filePath = Path.Combine(DocManagerHelper.VersionDir(histPath, version), file);  // get the path to document version

                download(filePath, context);
            }
            catch (Exception)
            {
                context.Response.Write("{ \"error\": \"File not found!\"}");
            }
        }
        // download a file
        private static void Download(HttpContext context)
        {
            try
            {
                var fileName = Path.IsPathRooted(WebConfigurationManager.AppSettings["storage-path"]) ? context.Request["fileName"]
                    : Path.GetFileName(context.Request["fileName"]);
                var userAddress = context.Request["userAddress"];
                var isEmbedded  = context.Request["dmode"];

                if (JwtManager.Enabled && isEmbedded == null)
                {
                    string JWTheader = WebConfigurationManager.AppSettings["files.docservice.header"].Equals("") ? "Authorization" : WebConfigurationManager.AppSettings["files.docservice.header"];

                    if (context.Request.Headers.AllKeys.Contains(JWTheader, StringComparer.InvariantCultureIgnoreCase))
                    {
                        var    headerToken = context.Request.Headers.Get(JWTheader).Substring("Bearer ".Length);
                        string token       = JwtManager.Decode(headerToken);
                        if (token == null || token.Equals(""))
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Forbidden;
                            context.Response.Write("JWT validation failed");
                            return;
                        }
                    }
                }

                var filePath = DocManagerHelper.ForcesavePath(fileName, userAddress, false);  // get the path to the force saved document version
                if (filePath.Equals(""))
                {
                    filePath = DocManagerHelper.StoragePath(fileName, userAddress);  // or to the original document
                }
                download(filePath, context);
            }
            catch (Exception)
            {
                context.Response.Write("{ \"error\": \"File not found!\"}");
            }
        }
Example #20
0
        private static void Save(HttpContext context)
        {
            context.Response.ContentType = "text/plain";

            var downloadUri = context.Request["fileuri"];
            var fileName    = context.Request["filename"];

            if (string.IsNullOrEmpty(downloadUri) || string.IsNullOrEmpty(fileName))
            {
                context.Response.Write("error");
                return;
            }

            var newType     = Path.GetExtension(downloadUri).Trim('.');
            var currentType = (context.Request["filetype"] ?? Path.GetExtension(fileName)).Trim('.');

            if (newType.ToLower() != currentType.ToLower())
            {
                var key = ServiceConverter.GenerateRevisionId(downloadUri);

                string newFileUri;
                try
                {
                    var result = ServiceConverter.GetConvertedUri(downloadUri, newType, currentType, key, false, out newFileUri);
                    if (result != 100)
                    {
                        throw new Exception();
                    }
                }
                catch (Exception)
                {
                    context.Response.Write("error");
                    return;
                }
                downloadUri = newFileUri;
                newType     = currentType;
            }

            fileName = Path.GetFileNameWithoutExtension(fileName) + "." + newType;

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

            try
            {
                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("stream is null");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(DocManagerHelper.StoragePath(fileName), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);
                        }
                    }
                }
            }
            catch (Exception)
            {
                context.Response.Write("error");
                return;
            }

            context.Response.Write("success");
        }
Example #21
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));
        }
        // convert a file
        private static void Convert(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                string fileData;

                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        fileData = readStream.ReadToEnd();
                        if (string.IsNullOrEmpty(fileData))
                        {
                            context.Response.Write("{\"error\":1,\"message\":\"Request stream is empty\"}");
                        }
                    }

                var jss  = new JavaScriptSerializer();
                var body = jss.Deserialize <Dictionary <string, object> >(fileData);

                var fileName = Path.GetFileName(body["filename"].ToString());
                var lang     = context.Request.Cookies.GetOrDefault("ulang", null);
                var filePass = body["filePass"] != null ? body["filePass"].ToString() : null;
                var fileUri  = DocManagerHelper.GetDownloadUrl(fileName);

                var extension         = (Path.GetExtension(fileName).ToLower() ?? "").Trim('.');
                var internalExtension = DocManagerHelper.GetInternalExtension(FileUtility.GetFileType(fileName)).Trim('.');

                // check if the file with such an extension can be converted
                if (DocManagerHelper.ConvertExts.Contains("." + extension) &&
                    !string.IsNullOrEmpty(internalExtension))
                {
                    // generate document key
                    var key = ServiceConverter.GenerateRevisionId(fileUri);

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

                    // get the url to the converted file
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri.ToString(), extension, internalExtension, key, true, out newFileUri, filePass, lang);
                    if (result != 100)
                    {
                        context.Response.Write("{ \"step\" : \"" + result + "\", \"filename\" : \"" + fileName + "\"}");
                        return;
                    }

                    // get a file name of an internal file extension with an index if the file with such a name already exists
                    var correctName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "." + internalExtension);

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

                    DocManagerHelper.VerifySSL();

                    using (var stream = req.GetResponse().GetResponseStream())  // get response stream of the converting file
                    {
                        if (stream == null)
                        {
                            throw new Exception("Stream is null");
                        }
                        const int bufferSize = 4096;

                        using (var fs = File.Open(DocManagerHelper.StoragePath(correctName), FileMode.Create))
                        {
                            var buffer = new byte[bufferSize];
                            int readed;
                            while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                            {
                                fs.Write(buffer, 0, readed);  // write bytes to the output stream
                            }
                        }
                    }

                    Remove(fileName);       // remove the original file and its history if it exists
                    fileName = correctName; // create meta information about the converted file with user id and name specified
                    var id   = context.Request.Cookies.GetOrDefault("uid", null);
                    var user = Users.getUser(id);
                    DocManagerHelper.CreateMeta(fileName, user.id, user.name);
                }

                var documentType = FileUtility.GetFileType(fileName).ToString().ToLower();
                context.Response.Write("{ \"filename\" : \"" + fileName + "\", \"documentType\": \"" + documentType + "\" }");
            }
            catch (Exception e)
            {
                context.Response.Write("{ \"error\": \"" + e.Message + "\"}");
            }
        }
Example #23
0
        private static void Track(HttpContext context)
        {
            Logger.Info($"track");
            string documentContents;

            using (var receiveStream = context.Request.InputStream)
            {
                using (var readStream = new StreamReader(receiveStream, Encoding.UTF8))
                {
                    documentContents = readStream.ReadToEnd();
                }
            }

            Logger.Info($"request {documentContents}");


            var userAddress = context.Request["userAddress"];
            var fileName    = context.Request["fileName"];

            Logger.Info($"{userAddress} and {fileName} ");
            var storagePath = "";
            var userdata    = "";
            var recUri      = 0;
            var key         = "";
            var status      = TrackerStatus.NotFound;
            var downloadUri = "";

            try
            {
                dynamic data = JObject.Parse(documentContents);
                key    = (string)data.key;
                recUri = Convert.ToInt32(key.Split(new[] { "__" }, StringSplitOptions.None)[0]);
                var userUri = key.Split(new[] { "__" }, StringSplitOptions.None)[1];
                storagePath = DocManagerHelper.StoragePath(Convert.ToInt64(userUri)) + $"\\{fileName}";
                Logger.Info($"{storagePath} ");

                status = data.status;
                Logger.Info($"status is {status} ");

                downloadUri = (string)data.url;
                Logger.Info($"url is {downloadUri}");

                userdata = (string)data.userdata;
                Logger.Info($"userdata is {userdata}");
            }
            catch (Exception e)
            {
                context.Response.Write("{\"error\":0}");
                Logger.Info($"error {e.Message} ");
            }

            string body;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        body = readStream.ReadToEnd();
                    }
            }
            catch (Exception e)
            {
                context.Response.Write("{\"error\":0}");
                Logger.Info($"saving error");
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var docController = new DocumentController();

            switch (status)
            {
            case TrackerStatus.Closed:
                //WriteDocumentFile(downloadUri, storagePath);
                if (userdata != null)
                {
                    if (userdata.Contains("checkin"))
                    {
                        docController.DropUser(key, userdata);
                    }
                }
                break;

            case TrackerStatus.MustSave:
            case TrackerStatus.Corrupted:
            case TrackerStatus.Saved:

                //if (!File.Exists(Path.Combine(_PDPath, Path.GetFileNameWithoutExtension(storagePath))))
                //{
                //    var f = File.Create(Path.Combine(_PDPath, Path.GetFileNameWithoutExtension(storagePath)));
                //    f.Close();
                //}


                WriteDocumentFile(downloadUri, storagePath);
                if (userdata != null)
                {
                    if (userdata.Contains("checkin"))
                    {
                        docController.CheckinDocument(recUri, userdata.Split(new[] { "||" }, StringSplitOptions.None)[3],
                                                      userdata.Split(new[] { "||" }, StringSplitOptions.None)[4],
                                                      userdata.Split(new[] { "||" }, StringSplitOptions.None)[2]);
                    }
                    else
                    {
                        if (File.Exists(Path.Combine(_PDPath, Path.GetFileNameWithoutExtension(storagePath))))
                        {
                            File.Delete(Path.Combine(_PDPath, Path.GetFileNameWithoutExtension(storagePath)));
                        }
                    }
                }
                else
                {
                    if (File.Exists(Path.Combine(_PDPath, Path.GetFileNameWithoutExtension(storagePath))))
                    {
                        File.Delete(Path.Combine(_PDPath, Path.GetFileNameWithoutExtension(storagePath)));
                    }
                }


                break;
            }


            context.Response.Write("{ \"error\" : \"" + 0 + "\"}");
        }
Example #24
0
 public void CancelDocument(long uri)
 {
     Logger.Info($"File Edit Canceled in  {uri}");
     DocManagerHelper.CancelDocument(uri, AppUserState.UserName, AppUserState.Wgs, AppUserState.Ds);
 }
        private static void SaveAs(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                string fileData;
                try
                {
                    using (var receiveStream = context.Request.InputStream)
                        using (var readStream = new StreamReader(receiveStream))
                        {
                            fileData = readStream.ReadToEnd();
                            if (string.IsNullOrEmpty(fileData))
                            {
                                context.Response.Write("{\"error\":\"Request stream is empty\"}");
                            }
                        }
                }
                catch (Exception e)
                {
                    throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
                }

                var jss       = new JavaScriptSerializer();
                var body      = jss.Deserialize <Dictionary <string, object> >(fileData);
                var fileUrl   = (string)body["url"];
                var title     = (string)body["title"];
                var fileName  = DocManagerHelper.GetCorrectName(title);
                var extension = "." + (Path.GetExtension(fileName).ToLower() ?? "").Trim('.');

                var allExt = DocManagerHelper.ConvertExts
                             .Concat(DocManagerHelper.EditedExts)
                             .Concat(DocManagerHelper.ViewedExts)
                             .Concat(DocManagerHelper.FillFormExts)
                             .ToArray();

                if (!allExt.Contains(extension))
                {
                    context.Response.Write("{\"error\":\"File type is not supported\"}");
                }

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

                DocManagerHelper.VerifySSL();

                using (var stream = req.GetResponse().GetResponseStream())
                {
                    if (stream == null || req.GetResponse().ContentLength <= 0 || req.GetResponse().ContentLength > DocManagerHelper.MaxFileSize)
                    {
                        context.Response.Write("{\"error\": \"File size is incorrect\"}");
                    }
                    const int bufferSize = 4096;

                    using (var fs = File.Open(DocManagerHelper.StoragePath(fileName, null), FileMode.Create))
                    {
                        var buffer = new byte[bufferSize];
                        int readed;
                        while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                        {
                            fs.Write(buffer, 0, readed);  // write bytes to the output stream
                        }
                    }
                }

                var id   = context.Request.Cookies.GetOrDefault("uid", null);
                var user = Users.getUser(id);  // get the user
                DocManagerHelper.CreateMeta(fileName, user.id, user.name, null);

                context.Response.Write("{ \"file\": \"" + fileName + "\"}");
            }
            catch (Exception e)
            {
                context.Response.Write("{ \"error\": \"" + 1 + "\", \"message\": \"" + e.Message + "\"}");
            }
        }
        private static void Track(HttpContext context)
        {
            var userAddress = context.Request["userAddress"];
            var fileName    = context.Request["fileName"];

            var storagePath = DocManagerHelper.StoragePath(fileName, userAddress);

            string body;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        body = readStream.ReadToEnd();
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(body))
            {
                return;
            }
            var fileData = jss.Deserialize <Dictionary <string, object> >(body);
            var status   = (TrackerStatus)(int)fileData["status"];

            switch (status)
            {
            case TrackerStatus.MustSave:
            case TrackerStatus.Corrupted:
                var downloadUri = (string)fileData["url"];

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

                var saved = 1;
                try
                {
                    using (var stream = req.GetResponse().GetResponseStream())
                    {
                        if (stream == null)
                        {
                            throw new Exception("stream is null");
                        }
                        const int bufferSize = 4096;

                        using (var fs = File.Open(storagePath, FileMode.Create))
                        {
                            var buffer = new byte[bufferSize];
                            int readed;
                            while ((readed = stream.Read(buffer, 0, bufferSize)) != 0)
                            {
                                fs.Write(buffer, 0, readed);
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    saved = 0;
                }

                break;
            }
            context.Response.Write("{\"error\":0}");
        }
Example #27
0
 public void ViewDocumentWebSessionEnd(long uri)
 {
     DocManagerHelper.ViewDocumentWebSessionEnd(uri, AppUserState.UserName, AppUserState.Wgs, AppUserState.Ds);
 }
Example #28
0
 public void CheckinDocument(long uri, string wgs, string ds, string userName)
 {
     Logger.Info($"File Checked in  {uri}");
     DocManagerHelper.CheckinDocument(uri, userName, wgs, ds);
 }
Example #29
0
        private static void Track(HttpContext context)
        {
            var userAddress = context.Request["userAddress"];
            var fileName    = context.Request["fileName"];

            string body;

            try
            {
                using (var receiveStream = context.Request.InputStream)
                    using (var readStream = new StreamReader(receiveStream))
                    {
                        body = readStream.ReadToEnd();
                    }
            }
            catch (Exception e)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, e.Message);
            }

            var jss = new JavaScriptSerializer();

            if (string.IsNullOrEmpty(body))
            {
                return;
            }
            var fileData = jss.Deserialize <Dictionary <string, object> >(body);

            if (JwtManager.Enabled)
            {
                if (fileData.ContainsKey("token"))
                {
                    fileData = jss.Deserialize <Dictionary <string, object> >(JwtManager.Decode(fileData["token"].ToString()));
                }
                else if (context.Request.Headers.AllKeys.Contains("Authorization", StringComparer.InvariantCultureIgnoreCase))
                {
                    var headerToken = context.Request.Headers.Get("Authorization").Substring("Bearer ".Length);
                    fileData = (Dictionary <string, object>)jss.Deserialize <Dictionary <string, object> >(JwtManager.Decode(headerToken))["payload"];
                }
                else
                {
                    throw new Exception("Expected JWT");
                }
            }

            var status = (TrackerStatus)(int)fileData["status"];

            switch (status)
            {
            case TrackerStatus.MustSave:
            case TrackerStatus.Corrupted:
                var downloadUri = (string)fileData["url"];

                var saved = 1;
                try
                {
                    var storagePath = DocManagerHelper.StoragePath(fileName, userAddress);
                    var histDir     = DocManagerHelper.HistoryDir(storagePath);
                    var versionDir  = DocManagerHelper.VersionDir(histDir, DocManagerHelper.GetFileVersion(histDir) + 1);

                    if (!Directory.Exists(versionDir))
                    {
                        Directory.CreateDirectory(versionDir);
                    }

                    File.Copy(storagePath, Path.Combine(versionDir, "prev" + Path.GetExtension(fileName)));

                    DownloadToFile(downloadUri, DocManagerHelper.StoragePath(fileName, userAddress));
                    DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip"));

                    var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;
                    if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
                    {
                        hist = jss.Serialize(fileData["history"]);
                    }

                    if (!string.IsNullOrEmpty(hist))
                    {
                        File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist);
                    }

                    File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]);
                }
                catch (Exception)
                {
                    saved = 0;
                }

                break;
            }
            context.Response.Write("{\"error\":0}");
        }
Example #30
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);
            }
        }