Ejemplo n.º 1
0
        /// <summary>
        /// Request to Document Server with command
        /// </summary>
        /// <param name="documentTrackerUrl">Url to the command service</param>
        /// <param name="method">Name of method</param>
        /// <param name="documentRevisionId">Key for caching on service, whose used in editor</param>
        /// <param name="callbackUrl">Url to the callback handler</param>
        /// <param name="users">users id for drop</param>
        /// <param name="meta">file meta data for update</param>
        /// <param name="signatureSecret">Secret key to generate the token</param>
        /// <param name="version">server version</param>
        /// <returns>Response</returns>
        public static CommandResultTypes CommandRequest(
            string documentTrackerUrl,
            CommandMethod method,
            string documentRevisionId,
            string callbackUrl,
            string[] users,
            MetaData meta,
            string signatureSecret,
            out string version)
        {
            var request = (HttpWebRequest)WebRequest.Create(documentTrackerUrl);

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

            var body = new CommandBody
            {
                Command = method,
                Key     = documentRevisionId,
            };

            if (!string.IsNullOrEmpty(callbackUrl))
            {
                body.Callback = callbackUrl;
            }
            if (users != null && users.Length > 0)
            {
                body.Users = users;
            }
            if (meta != null)
            {
                body.Meta = meta;
            }

            if (!string.IsNullOrEmpty(signatureSecret))
            {
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };
                JsonWebToken.JsonSerializer = new JwtSerializer();
                var token = JsonWebToken.Encode(payload, signatureSecret, JwtHashAlgorithm.HS256);
                //todo: remove old scheme
                request.Headers.Add(FileUtility.SignatureHeader, "Bearer " + token);

                token      = JsonWebToken.Encode(body, signatureSecret, JwtHashAlgorithm.HS256);
                body.Token = token;
            }

            var bodyString = JsonConvert.SerializeObject(body);

            var bytes = Encoding.UTF8.GetBytes(bodyString ?? "");

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

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (WorkContext.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();
                    }
                }

            var jResponse = JObject.Parse(dataResponse);

            try
            {
                version = jResponse.Value <string>("version");
            }
            catch (Exception)
            {
                version = "0";
            }

            return((CommandResultTypes)jResponse.Value <int>("error"));
        }
Ejemplo n.º 2
0
        public static string DocbuilderRequest(
            string docbuilderUrl,
            string requestKey,
            string scriptUrl,
            bool isAsync,
            string signatureSecret,
            out Dictionary <string, string> urls)
        {
            if (string.IsNullOrEmpty(docbuilderUrl))
            {
                throw new ArgumentNullException("docbuilderUrl");
            }

            if (string.IsNullOrEmpty(requestKey) && string.IsNullOrEmpty(scriptUrl))
            {
                throw new ArgumentException("requestKey or inputScript is empty");
            }

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

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

            var body = new BuilderBody
            {
                Async = isAsync,
                Key   = requestKey,
                Url   = scriptUrl
            };

            if (!string.IsNullOrEmpty(signatureSecret))
            {
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };

                JsonWebToken.JsonSerializer = new JwtSerializer();
                var token = JsonWebToken.Encode(payload, signatureSecret, JwtHashAlgorithm.HS256);
                //todo: remove old scheme
                request.Headers.Add(FileUtility.SignatureHeader, "Bearer " + token);

                token      = JsonWebToken.Encode(body, signatureSecret, JwtHashAlgorithm.HS256);
                body.Token = token;
            }

            var bodyString = JsonConvert.SerializeObject(body);

            var bytes = Encoding.UTF8.GetBytes(bodyString ?? "");

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

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

            string dataResponse = null;

            using (var response = (HttpWebResponse)request.GetResponse())
                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            dataResponse = reader.ReadToEnd();
                        }
                    }
                }

            if (string.IsNullOrEmpty(dataResponse))
            {
                throw new Exception("Invalid response");
            }

            var responseFromService = JObject.Parse(dataResponse);

            if (responseFromService == null)
            {
                throw new Exception("Invalid answer format");
            }

            var errorElement = responseFromService.Value <string>("error");

            if (!string.IsNullOrEmpty(errorElement))
            {
                DocumentServiceException.ProcessResponseError(errorElement);
            }

            var isEnd = responseFromService.Value <bool>("end");

            urls = null;
            if (isEnd)
            {
                IDictionary <string, JToken> rates = (JObject)responseFromService["urls"];

                urls = rates.ToDictionary(pair => pair.Key, pair => pair.Value.ToString());
            }

            return(responseFromService.Value <string>("key"));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// The method is to convert the file to the required format
        /// </summary>
        /// <param name="documentConverterUrl">Url to the service of conversion</param>
        /// <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="password">Password</param>
        /// <param name="isAsync">Perform conversions asynchronously</param>
        /// <param name="signatureSecret">Secret key to generate the token</param>
        /// <param name="convertedDocumentUri">Uri to the converted document</param>
        /// <returns>The percentage of completion of conversion</returns>
        /// <example>
        /// string convertedDocumentUri;
        /// GetConvertedUri("http://helpcenter.teamlab.com/content/GettingStarted.pdf", ".pdf", ".docx", "469971047", false, out convertedDocumentUri);
        /// </example>
        /// <exception>
        /// </exception>
        public static int GetConvertedUri(
            string documentConverterUrl,
            string documentUri,
            string fromExtension,
            string toExtension,
            string documentRevisionId,
            string password,
            bool isAsync,
            string signatureSecret,
            out string convertedDocumentUri)
        {
            fromExtension = string.IsNullOrEmpty(fromExtension) ? Path.GetExtension(documentUri) : fromExtension;
            if (string.IsNullOrEmpty(fromExtension))
            {
                throw new ArgumentNullException("fromExtension", "Document's extension for conversion is not known");
            }
            if (string.IsNullOrEmpty(toExtension))
            {
                throw new ArgumentNullException("toExtension", "Extension for conversion is not known");
            }

            var title = Path.GetFileName(documentUri ?? "");

            title = string.IsNullOrEmpty(title) || title.Contains("?") ? 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     = Timeout;

            var body = new ConvertionBody
            {
                Async      = isAsync,
                FileType   = fromExtension.Trim('.'),
                Key        = documentRevisionId,
                OutputType = toExtension.Trim('.'),
                Title      = title,
                Url        = documentUri,
            };

            if (!string.IsNullOrEmpty(password))
            {
                body.Password = password;
            }

            if (!string.IsNullOrEmpty(signatureSecret))
            {
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };
                JsonWebToken.JsonSerializer = new JwtSerializer();
                var token = JsonWebToken.Encode(payload, signatureSecret, JwtHashAlgorithm.HS256);
                //todo: remove old scheme
                request.Headers.Add(FileUtility.SignatureHeader, "Bearer " + token);

                token      = JsonWebToken.Encode(body, signatureSecret, JwtHashAlgorithm.HS256);
                body.Token = token;
            }

            var bodyString = JsonConvert.SerializeObject(body);

            var bytes = Encoding.UTF8.GetBytes(bodyString ?? "");

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

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

            string      dataResponse;
            WebResponse response       = null;
            Stream      responseStream = null;

            try
            {
                var countTry = 0;
                while (countTry < MaxTry)
                {
                    try
                    {
                        countTry++;
                        response       = request.GetResponse();
                        responseStream = response.GetResponseStream();
                        break;
                    }
                    catch (WebException ex)
                    {
                        if (ex.Status != WebExceptionStatus.Timeout)
                        {
                            throw new HttpException((int)HttpStatusCode.BadRequest, ex.Message, ex);
                        }
                    }
                }
                if (countTry == MaxTry)
                {
                    throw new WebException("Timeout", WebExceptionStatus.Timeout);
                }

                if (responseStream == null)
                {
                    throw new WebException("Could not get an answer");
                }
                using (var reader = new StreamReader(responseStream))
                {
                    dataResponse = reader.ReadToEnd();
                }
            }
            finally
            {
                if (responseStream != null)
                {
                    responseStream.Dispose();
                }
                if (response != null)
                {
                    response.Dispose();
                }
            }

            return(GetResponseUri(dataResponse, out convertedDocumentUri));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Generate document from docbuilder script code
        /// </summary>
        /// <param name="docbuilderUrl">Url to the docbuilder service</param>
        /// <param name="requestKey">Key for re-query in asynchronous mode</param>
        /// <param name="inputScript">docbuilder script</param>
        /// <param name="isAsync">Perform operation asynchronously</param>
        /// <param name="signatureSecret">Secret key to generate the token</param>
        /// <returns>Response from the docbuilder service</returns>
        public static DocbuilderResponse DocbuilderRequest(
            string docbuilderUrl,
            string requestKey,
            string inputScript,
            bool isAsync,
            string signatureSecret)
        {
            if (string.IsNullOrEmpty(docbuilderUrl))
            {
                throw new ArgumentNullException("docbuilderUrl");
            }

            if (string.IsNullOrEmpty(requestKey) && string.IsNullOrEmpty(inputScript))
            {
                throw new ArgumentException("requestKey or inputScript is empty");
            }

            docbuilderUrl = String.Format("{0}?async={1}&key={2}",
                                          docbuilderUrl,
                                          isAsync.ToString().ToLowerInvariant(),
                                          requestKey);

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

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

            if (!string.IsNullOrEmpty(signatureSecret))
            {
                var payload = new Dictionary <string, object>
                {
                    {
                        "query", new Dictionary <string, string>
                        {
                            {
                                "async", isAsync.ToString().ToLowerInvariant()
                            },
                            {
                                "key", requestKey
                            }
                        }
                    }
                };

                JsonWebToken.JsonSerializer = new JwtSerializer();
                var token = JsonWebToken.Encode(payload, signatureSecret, JwtHashAlgorithm.HS256);
                request.Headers.Add(FileUtility.SignatureHeader, "Bearer " + token);
            }

            var bytes = Encoding.UTF8.GetBytes(inputScript ?? "");

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

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

            DocbuilderResponse res = null;

            using (var response = (HttpWebResponse)request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    if (stream != null)
                    {
                        var responseString = new StreamReader(stream).ReadToEnd();

                        if (!string.IsNullOrEmpty(responseString))
                        {
                            res = JsonConvert.DeserializeObject <DocbuilderResponse>(responseString);
                        }
                    }
                }

            return(res);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Placing the document in the storage service
        /// </summary>
        /// <param name="documentStorageUrl">Url to the storage service</param>
        /// <param name="fileStream">Stream of document</param>
        /// <param name="contentType">Mime type</param>
        /// <param name="documentRevisionId">Key for caching on service, whose used in editor</param>
        /// <param name="signatureSecret">Secret key to generate the token</param>
        /// <returns>Uri to document in the storage</returns>
        public static string GetExternalUri(
            string documentStorageUrl,
            Stream fileStream,
            string contentType,
            string documentRevisionId,
            string signatureSecret)
        {
            var urlTostorage = String.Format("{0}?key={1}",
                                             documentStorageUrl,
                                             documentRevisionId);

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

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

            if (!string.IsNullOrEmpty(signatureSecret))
            {
                var payload = new Dictionary <string, object>
                {
                    {
                        "query", new Dictionary <string, string>
                        {
                            {
                                "key", documentRevisionId
                            }
                        }
                    }
                };
                JsonWebToken.JsonSerializer = new JwtSerializer();
                var token = JsonWebToken.Encode(payload, signatureSecret, JwtHashAlgorithm.HS256);
                request.Headers.Add(FileUtility.SignatureHeader, "Bearer " + token);
            }

            if (fileStream != null)
            {
                if (fileStream.Length > 0)
                {
                    request.ContentLength = fileStream.Length;
                }

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

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (WorkContext.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 WebException("Could not get an answer");
                    }

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

            string externalUri;

            GetResponseUri(dataResponse, out externalUri);
            return(externalUri);
        }
Ejemplo n.º 6
0
        public static string DocbuilderRequest(
            string docbuilderUrl,
            string requestKey,
            string scriptUrl,
            bool isAsync,
            string signatureSecret,
            out Dictionary <string, string> urls)
        {
            if (string.IsNullOrEmpty(docbuilderUrl))
            {
                throw new ArgumentNullException("docbuilderUrl");
            }

            if (string.IsNullOrEmpty(requestKey) && string.IsNullOrEmpty(scriptUrl))
            {
                throw new ArgumentException("requestKey or inputScript is empty");
            }

            docbuilderUrl = String.Format("{0}?async={1}&key={2}&url={3}",
                                          docbuilderUrl,
                                          isAsync.ToString().ToLowerInvariant(),
                                          HttpUtility.UrlEncode(requestKey),
                                          HttpUtility.UrlEncode(scriptUrl));

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

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

            if (!string.IsNullOrEmpty(signatureSecret))
            {
                var payload = new Dictionary <string, object>
                {
                    {
                        "query", new Dictionary <string, string>
                        {
                            {
                                "async", isAsync.ToString().ToLowerInvariant()
                            },
                            {
                                "key", requestKey
                            },
                            {
                                "url", scriptUrl
                            }
                        }
                    }
                };

                JsonWebToken.JsonSerializer = new JwtSerializer();
                var token = JsonWebToken.Encode(payload, signatureSecret, JwtHashAlgorithm.HS256);
                request.Headers.Add(FileUtility.SignatureHeader, "Bearer " + token);
            }

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

            string dataResponse = null;

            using (var response = (HttpWebResponse)request.GetResponse())
                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream != null)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            dataResponse = reader.ReadToEnd();
                        }
                    }
                }


            if (string.IsNullOrEmpty(dataResponse))
            {
                throw new Exception("Invalid response");
            }

            var responseFromService = JObject.Parse(dataResponse);

            if (responseFromService == null)
            {
                throw new WebException("Invalid answer format");
            }

            var errorElement = responseFromService.Value <string>("error");

            if (!string.IsNullOrEmpty(errorElement))
            {
                ProcessResponseError(Convert.ToInt32(errorElement));
            }

            var isEnd = responseFromService.Value <bool>("end");

            urls = null;
            if (isEnd)
            {
                IDictionary <string, JToken> rates = (JObject)responseFromService["urls"];

                urls = rates.ToDictionary(pair => pair.Key, pair => pair.Value.ToString());
            }

            return(responseFromService.Value <string>("key"));
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Request to Document Server with command
        /// </summary>
        /// <param name="documentTrackerUrl">Url to the command service</param>
        /// <param name="method">Name of method</param>
        /// <param name="documentRevisionId">Key for caching on service, whose used in editor</param>
        /// <param name="callbackUrl">Url to the callback handler</param>
        /// <param name="users">users id for drop</param>
        /// <param name="meta">file meta data for update</param>
        /// <param name="signatureSecret">Secret key to generate the token</param>
        /// <param name="version">server version</param>
        /// <returns>Response</returns>
        public static CommandResponse CommandRequest(FileUtility fileUtility,
                                                     string documentTrackerUrl,
                                                     CommandMethod method,
                                                     string documentRevisionId,
                                                     string callbackUrl,
                                                     string[] users,
                                                     MetaData meta,
                                                     string signatureSecret)
        {
            var request = (HttpWebRequest)WebRequest.Create(documentTrackerUrl);

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

            var body = new CommandBody
            {
                Command = method,
                Key     = documentRevisionId,
            };

            if (!string.IsNullOrEmpty(callbackUrl))
            {
                body.Callback = callbackUrl;
            }
            if (users != null && users.Length > 0)
            {
                body.Users = users;
            }
            if (meta != null)
            {
                body.Meta = meta;
            }

            if (!string.IsNullOrEmpty(signatureSecret))
            {
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };

                var token = JsonWebToken.Encode(payload, signatureSecret);
                //todo: remove old scheme
                request.Headers.Add(fileUtility.SignatureHeader, "Bearer " + token);

                token      = JsonWebToken.Encode(body, signatureSecret);
                body.Token = token;
            }

            var bodyString = System.Text.Json.JsonSerializer.Serialize(body, new System.Text.Json.JsonSerializerOptions()
            {
                IgnoreNullValues = true,
                Encoder          = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });

            var bytes = Encoding.UTF8.GetBytes(bodyString ?? "");

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

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (WorkContext.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();
                }


            try
            {
                var commandResponse = JsonConvert.DeserializeObject <CommandResponse>(dataResponse);
                return(commandResponse);
            }
            catch (Exception ex)
            {
                return(new CommandResponse
                {
                    Error = CommandResponse.ErrorTypes.ParseError,
                    ErrorString = ex.Message
                });
            }
        }