// get file information
        public static List <Dictionary <string, object> > GetFilesInfo(string fileId = null)
        {
            var files = new List <Dictionary <string, object> >();

            // run through all the stored files
            foreach (var file in GetStoredFiles())
            {
                // write all the parameters to the map
                var dictionary = new Dictionary <string, object>();
                dictionary.Add("version", GetFileVersion(file.Name, null));
                dictionary.Add("id", ServiceConverter.GenerateRevisionId(DocManagerHelper.CurUserHostAddress() + "/" + file.Name + "/" + File.GetLastWriteTime(DocManagerHelper.StoragePath(file.Name, null)).GetHashCode()));
                dictionary.Add("contentLength", Math.Round(file.Length / 1024.0, 2) + " KB");
                dictionary.Add("pureContentLength", file.Length);
                dictionary.Add("title", file.Name);
                dictionary.Add("updated", file.LastWriteTime.ToString());

                // get file information by its id
                if (fileId != null)
                {
                    if (fileId.Equals(dictionary["id"]))
                    {
                        files.Add(dictionary);
                        break;
                    }
                }
                else
                {
                    files.Add(dictionary);
                }
            }

            return(files);
        }
        // get url to the created file
        public static string GetCreateUrl(FileUtility.FileType fileType)
        {
            var createUrl = new UriBuilder(GetServerUrl(false))
            {
                Path =
                    HttpRuntime.AppDomainAppVirtualPath
                    + (HttpRuntime.AppDomainAppVirtualPath.EndsWith("/") ? "" : "/")
                    + "Sample",
                Query = "fileExt=" + DocManagerHelper.GetInternalExtension(fileType).Trim('.')
            };

            return(createUrl.ToString());
        }
Пример #3
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);

                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
            }

            DocManagerHelper.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));
        }
Пример #4
0
        // file saving process
        public static int processSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            if (fileData["url"].Equals(null))
            {
                throw new Exception("DownloadUrl is null");
            }
            var    downloadUri = (string)fileData["url"];
            string curExt      = Path.GetExtension(fileName).ToLower(); // get current file extension

            var downloadExt = fileData.ContainsKey("filetype")
                ? "." + (string)fileData["filetype"]
                : Path.GetExtension(downloadUri).ToLower() ?? ""; // TODO: Delete in version 7.0 or higher. Support for versions below 7.0

            var newFileName = fileName;

            // convert downloaded file to the file with the current extension if these extensions aren't equal
            if (!curExt.Equals(downloadExt, StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    // convert file and give url to a new file
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        // get the correct file name if it already exists
                        newFileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            DocManagerHelper.VerifySSL();

            var storagePath = DocManagerHelper.StoragePath(newFileName, userAddress); // get the file path
            var histDir     = DocManagerHelper.HistoryDir(storagePath);               // get the path to the history directory

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

            var versionDir = DocManagerHelper.VersionDir(histDir, DocManagerHelper.GetFileVersion(histDir));  // get the path to the file version

            if (!Directory.Exists(versionDir))
            {
                Directory.CreateDirectory(versionDir);                                 // if the path doesn't exist, create it
            }
            // get the path to the previous file version and move it to the storage directory
            File.Move(DocManagerHelper.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));

            DownloadToFile(downloadUri, storagePath);                                             // save file to the storage directory
            DownloadToFile((string)fileData["changesurl"], Path.Combine(versionDir, "diff.zip")); // save file changes to the diff.zip archive

            var hist = fileData.ContainsKey("changeshistory") ? (string)fileData["changeshistory"] : null;

            if (string.IsNullOrEmpty(hist) && fileData.ContainsKey("history"))
            {
                var jss = new JavaScriptSerializer();
                hist = jss.Serialize(fileData["history"]);
            }

            if (!string.IsNullOrEmpty(hist))
            {
                File.WriteAllText(Path.Combine(versionDir, "changes.json"), hist);  // write the history changes to the changes.json file
            }

            File.WriteAllText(Path.Combine(versionDir, "key.txt"), (string)fileData["key"]);        // write the key value to the key.txt file

            string forcesavePath = DocManagerHelper.ForcesavePath(newFileName, userAddress, false); // get the path to the forcesaved file version

            if (!forcesavePath.Equals(""))                                                          // if the forcesaved file version exists
            {
                File.Delete(forcesavePath);                                                         // remove it
            }

            return(0);
        }
Пример #5
0
        // create a command request
        public static void commandRequest(string method, string key, object meta = null)
        {
            DocManagerHelper.VerifySSL();

            string documentCommandUrl = WebConfigurationManager.AppSettings["files.docservice.url.site"] + WebConfigurationManager.AppSettings["files.docservice.url.command"];

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

            request.Method      = "POST";
            request.ContentType = "application/json";

            var body = new Dictionary <string, object>()
            {
                { "c", method },
                { "key", key }
            };

            if (meta != null)
            {
                body.Add("meta", meta);
            }

            // check if a secret key to generate token exists or not
            if (JwtManager.Enabled)
            {
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };

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

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

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

            request.ContentLength = bytes.Length;
            using (var requestStream = request.GetRequestStream())
            {
                // write bytes to the output stream
                requestStream.Write(bytes, 0, bytes.Length);
            }

            string dataResponse;

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

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

            // convert stream to json string
            var jss         = new JavaScriptSerializer();
            var responseObj = jss.Deserialize <Dictionary <string, object> >(dataResponse);

            if (!responseObj["error"].ToString().Equals("0"))
            {
                throw new Exception(dataResponse);
            }
        }
Пример #6
0
        // file force saving process
        public static int processForceSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            if (fileData["url"].Equals(null))
            {
                throw new Exception("DownloadUrl is null");
            }
            var downloadUri = (string)fileData["url"];

            string curExt = Path.GetExtension(fileName).ToLower();  // get current file extension

            var downloadExt = fileData.ContainsKey("filetype")
                ? "." + (string)fileData["filetype"]
                : Path.GetExtension(downloadUri).ToLower(); // TODO: Delete in version 7.0 or higher. Support for versions below 7.0

            Boolean newFileName = false;

            // convert downloaded file to the file with the current extension if these extensions aren't equal
            if (!curExt.Equals(downloadExt))
            {
                try
                {
                    // convert file and give url to a new file
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = true;
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = true;
                }
            }

            DocManagerHelper.VerifySSL();

            string  forcesavePath = "";
            Boolean isSubmitForm  = fileData["forcesavetype"].ToString().Equals("3"); // SubmitForm

            if (isSubmitForm)                                                         // if the form is submitted
            {
                if (newFileName)
                {
                    fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + downloadExt, userAddress);  // get the correct file name if it already exists
                }
                else
                {
                    fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + "-form" + curExt, userAddress);
                }
                forcesavePath = DocManagerHelper.StoragePath(fileName, userAddress);
            }
            else
            {
                if (newFileName)
                {
                    fileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
                forcesavePath = DocManagerHelper.ForcesavePath(fileName, userAddress, false);
                if (forcesavePath.Equals(""))  // create forcesave path if it doesn't exist
                {
                    forcesavePath = DocManagerHelper.ForcesavePath(fileName, userAddress, true);
                }
            }

            DownloadToFile(downloadUri, forcesavePath);

            if (isSubmitForm)
            {
                var jss     = new JavaScriptSerializer();
                var actions = jss.Deserialize <List <object> >(jss.Serialize(fileData["actions"]));
                var action  = jss.Deserialize <Dictionary <string, object> >(jss.Serialize(actions[0]));
                var user    = action["userid"].ToString();                                // get the user id
                DocManagerHelper.CreateMeta(fileName, user, "Filling Form", userAddress); // create meta data for the forcesaved file
            }

            return(0);
        }
        public static int processSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            var    downloadUri = (string)fileData["url"];
            string curExt      = Path.GetExtension(fileName);
            string downloadExt = Path.GetExtension(downloadUri) ?? "";
            var    newFileName = fileName;

            if (!curExt.Equals(downloadExt, StringComparison.InvariantCultureIgnoreCase))
            {
                try
                {
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            var storagePath = DocManagerHelper.StoragePath(newFileName, userAddress);
            var histDir     = DocManagerHelper.HistoryDir(storagePath);

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

            var versionDir = DocManagerHelper.VersionDir(histDir, DocManagerHelper.GetFileVersion(histDir));

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

            File.Move(DocManagerHelper.StoragePath(fileName, userAddress), Path.Combine(versionDir, "prev" + curExt));

            DownloadToFile(downloadUri, storagePath);
            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"))
            {
                var jss = new JavaScriptSerializer();
                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"]);

            string forcesavePath = DocManagerHelper.ForcesavePath(newFileName, userAddress, false);

            if (!forcesavePath.Equals(""))
            {
                File.Delete(forcesavePath);
            }

            return(0);
        }
        public static int processForceSave(Dictionary <string, object> fileData, string fileName, string userAddress)
        {
            var downloadUri = (string)fileData["url"];

            string curExt      = Path.GetExtension(fileName);
            string downloadExt = Path.GetExtension(downloadUri);
            var    newFileName = fileName;

            if (!curExt.Equals(downloadExt))
            {
                try
                {
                    string newFileUri;
                    var    result = ServiceConverter.GetConvertedUri(downloadUri, downloadExt, curExt, ServiceConverter.GenerateRevisionId(downloadUri), false, out newFileUri);
                    if (string.IsNullOrEmpty(newFileUri))
                    {
                        newFileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                    }
                    else
                    {
                        downloadUri = newFileUri;
                    }
                }
                catch (Exception)
                {
                    newFileName = DocManagerHelper.GetCorrectName(Path.GetFileNameWithoutExtension(fileName) + downloadExt, userAddress);
                }
            }

            string  forcesavePath = "";
            Boolean isSubmitForm  = fileData["forcesavetype"].ToString().Equals("3");

            if (isSubmitForm)
            {
                if (newFileName.Equals(fileName))
                {
                    newFileName = DocManagerHelper.GetCorrectName(fileName, userAddress);
                }
                forcesavePath = DocManagerHelper.StoragePath(newFileName, userAddress);
            }
            else
            {
                forcesavePath = DocManagerHelper.ForcesavePath(newFileName, userAddress, false);
                if (forcesavePath.Equals(""))
                {
                    forcesavePath = DocManagerHelper.ForcesavePath(newFileName, userAddress, true);
                }
            }

            DownloadToFile(downloadUri, forcesavePath);

            if (isSubmitForm)
            {
                var jss     = new JavaScriptSerializer();
                var actions = jss.Deserialize <List <object> >(jss.Serialize(fileData["actions"]));
                var action  = jss.Deserialize <Dictionary <string, object> >(jss.Serialize(actions[0]));
                var user    = action["userid"].ToString();
                DocManagerHelper.CreateMeta(newFileName, user, "Filling Form", userAddress);
            }

            return(0);
        }