public static string DocbuilderRequest( FileUtility fileUtility, 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 } }; 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 = 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")); }
/// <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")); }
/// <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 }); } }
/// <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="thumbnail">Thumbnail settings</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( FileUtility fileUtility, string documentConverterUrl, string documentUri, string fromExtension, string toExtension, string documentRevisionId, string password, ThumbnailData thumbnail, SpreadsheetLayout spreadsheetLayout, 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, Thumbnail = thumbnail, SpreadsheetLayout = spreadsheetLayout, Url = documentUri, }; if (!string.IsNullOrEmpty(password)) { body.Password = password; } 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; 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)); }
/// <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.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; } using (var response = request.GetResponse()) using (var stream = response.GetResponseStream()) { if (stream == null) { throw new WebException("Could not get an answer"); } var xDocumentResponse = XDocument.Load(new XmlTextReader(stream)); string externalUri; GetResponseUri(xDocumentResponse, out externalUri); return(externalUri); } }
/// <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="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, 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.Timeout = Timeout; var body = new ConvertionBody { Async = isAsync, FileType = fromExtension.Trim('.'), Key = documentRevisionId, OutputType = toExtension.Trim('.'), Title = title, Url = documentUri, }; if (!string.IsNullOrEmpty(signatureSecret)) { var payload = new Dictionary <string, object> { { "payload", body } }; JsonWebToken.JsonSerializer = new JwtSerializer(); var token = JsonWebToken.Encode(payload, signatureSecret, JwtHashAlgorithm.HS256); request.Headers.Add(FileUtility.SignatureHeader, "Bearer " + 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; } XDocument xDocumentResponse; WebResponse response = null; try { var countTry = 0; Stream stream = null; while (countTry < MaxTry) { try { countTry++; response = request.GetResponse(); stream = 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 (stream == null) { throw new WebException("Could not get an answer"); } xDocumentResponse = XDocument.Load(new XmlTextReader(stream)); stream.Dispose(); } finally { if (response != null) { response.Dispose(); } } return(GetResponseUri(xDocumentResponse, out convertedDocumentUri)); }
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")); }