Ejemplo n.º 1
0
        public async static Task <Dictionary <string, object> > GoogleNaturalLanguageUnderstanding(AppSettings appSettings, string text)
        {
            string methodName = "GoogleNaturalLanguageUnderstanding";
            Dictionary <string, object> result = new Dictionary <string, object>();

            try
            {
                CommonService.SetGoogleCredentials(@"googleAI-Harima.json");
                var client = LanguageServiceClient.Create();
                AnalyzeSentimentResponse analyzeSentimentResponse = new AnalyzeSentimentResponse();
                try
                {
                    analyzeSentimentResponse = await client.AnalyzeSentimentAsync(new Document()
                    {
                        Content = text,
                        Type    = Document.Types.Type.PlainText
                    });
                }
                catch (Exception e)
                {
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {text}");
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), $"02{Assembly.GetExecutingAssembly().GetName().Name}", MethodBase.GetCurrentMethod().ReflectedType.Name, methodName, $"Watson error: {e.Source + Environment.NewLine + e.Message}");
                }

                AnalyzeEntitiesResponse analyzeEntitiesResponse = new AnalyzeEntitiesResponse();
                try
                {
                    analyzeEntitiesResponse = await client.AnalyzeEntitiesAsync(new Document()
                    {
                        Content = text,
                        Type    = Document.Types.Type.PlainText
                    });
                }
                catch (Exception e)
                {
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {text}");
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), $"02{Assembly.GetExecutingAssembly().GetName().Name}", MethodBase.GetCurrentMethod().ReflectedType.Name, methodName, $"Watson error: {e.Source + Environment.NewLine + e.Message}");
                }

                ClassifyTextResponse classifyTextResponse = new ClassifyTextResponse();
                try
                {
                    LanguageTranslatorRequest languageTranslatorRequest = new LanguageTranslatorRequest();
                    languageTranslatorRequest.Text   = text;
                    languageTranslatorRequest.Source = "es";
                    languageTranslatorRequest.Target = "en";
                    string translation = await LanguageTranslatorService.GoogleLanguageTranslator(appSettings, languageTranslatorRequest);

                    classifyTextResponse = await client.ClassifyTextAsync(new Document()
                    {
                        Content = translation,
                        Type    = Document.Types.Type.PlainText
                    });
                }
                catch (Exception e)
                {
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {text}");
                    Log.Write(appSettings, LogEnum.ERROR.ToString(), $"02{Assembly.GetExecutingAssembly().GetName().Name}", MethodBase.GetCurrentMethod().ReflectedType.Name, methodName, $"Watson error: {e.Source + Environment.NewLine + e.Message}");
                }
                result["sentiment"] = analyzeSentimentResponse;
                result["entities"]  = analyzeEntitiesResponse;
                result["clasifiy"]  = classifyTextResponse;
                return(result);
            }
            catch (Exception e)
            {
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {text}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                throw e;
            }
        }
Ejemplo n.º 2
0
        public static async Task <byte[]> DownloadHMAC(AppSettings appSettings, Dictionary <string, object> requestBody)
        {
            string methodName = "DownloadHMAC";
            Dictionary <string, object> result = new Dictionary <string, object>();

            try
            {
                string   accessKey  = requestBody["accessKey"].ToString();
                string   secretKey  = requestBody["secretKey"].ToString();
                string   host       = requestBody["host"].ToString();
                string   region     = "";
                string   endpoint   = "https://" + host;
                DateTime time       = DateTime.UtcNow;
                string   datestamp  = time.ToString("yyyyMMdd");
                string   timestamp  = datestamp + "T" + time.ToString("HHmmss") + "Z";
                int      expiration = 86400;
                string   standardizedQuerystring = "X-Amz-Algorithm=AWS4-HMAC-SHA256" +
                                                   "&X-Amz-Credential=" + Uri.EscapeDataString(accessKey + "/" + datestamp + "/" + region + "/s3/aws4_request") +
                                                   "&X-Amz-Date=" + timestamp +
                                                   "&X-Amz-Expires=" + expiration.ToString() +
                                                   "&X-Amz-SignedHeaders=host";

                string standardizedResource = "/" + requestBody["bucket"] + "/" + requestBody["objectkey"];

                string payloadHash         = "UNSIGNED-PAYLOAD";
                string standardizedHeaders = "host:" + host;
                string signedHeaders       = "host";

                string standardizedRequest = HttpMethod.Get + "\n" +
                                             standardizedResource + "\n" +
                                             standardizedQuerystring + "\n" +
                                             standardizedHeaders + "\n" +
                                             "\n" +
                                             signedHeaders + "\n" +
                                             payloadHash;

                // assemble string-to-sign
                string hashingAlgorithm = "AWS4-HMAC-SHA256";
                string credentialScope  = datestamp + "/" + region + "/" + "s3" + "/" + "aws4_request";
                string sts = hashingAlgorithm + "\n" +
                             timestamp + "\n" +
                             credentialScope + "\n" +
                             hashHex(standardizedRequest);

                // generate the signature
                byte[] signatureKey = createSignatureKey(secretKey, datestamp, region, "s3");
                string signature    = hmacHex(signatureKey, sts);

                // create and send the request
                string requestUrl = endpoint + "/" +
                                    requestBody["bucket"] + "/" +
                                    requestBody["objectkey"] + "?" +
                                    standardizedQuerystring +
                                    "&X-Amz-Signature=" +
                                    signature;

                HttpResponseMessage response = await CommonService.HttpRequestGetUri(appSettings, requestUrl, null);

                return(await response.Content.ReadAsByteArrayAsync());
            }
            catch (Exception e)
            {
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {JsonConvert.SerializeObject(requestBody)}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                throw e;
            }
        }
Ejemplo n.º 3
0
        public static async Task <Dictionary <string, object> > MultipartUpload(AppSettings appSettings, IFormCollection requestBody)
        {
            string methodName = "MultipartUpload";
            Dictionary <string, object> result = new Dictionary <string, object>();

            try
            {
                Dictionary <string, object> iamToken = await IamToken(appSettings, requestBody["apikey"].ToString());

                if (iamToken["_statuscode"].ToString().StartsWith("4"))
                {
                    throw new Exception(iamToken["errorMessage"].ToString());
                }
                string url = requestBody["url"];
                Dictionary <string, string> headers = new Dictionary <string, string>();
                headers.Add("ibm-service-instance-id", requestBody["resourceid"].ToString());
                HttpResponseMessage response = new HttpResponseMessage();
                response = await CommonService.HttpRequestContent(appSettings, url, requestBody["bucket"] + "/" + requestBody["objectkey"] + "?uploads=", "POST", null, headers, "Bearer", iamToken["access_token"].ToString());

                string responseString = await response.Content.ReadAsStringAsync();

                JObject responseJSON = CommonService.XMLToJObject(responseString);
                string  uploadId     = responseJSON["InitiateMultipartUploadResult"]["UploadId"].ToString();

                const int MAX_BUFFER = 20 * 1024 * 1024; //20MB this is the chunk size read from file
                byte[]    buffer     = new byte[MAX_BUFFER];
                long      bytes      = requestBody.Files[0].Length;
                double    parts      = Math.Ceiling((double)bytes / (double)MAX_BUFFER);

                Dictionary <string, string> queryparams = new Dictionary <string, string>();
                XmlDocument xmlDocument             = new XmlDocument();
                XmlElement  completeMultipartUpload = xmlDocument.CreateElement("CompleteMultipartUpload");
                HttpContent streamContent;
                using (Stream stream = requestBody.Files[0].OpenReadStream())
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        int partNumber = 1;
                        for (int i = 0; i < parts; i++)
                        {
                            int read = stream.Read(buffer, 0, buffer.Length); //read each chunk
                            ms.Write(buffer, 0, read);                        //write chunk to [wherever]
                            queryparams = new Dictionary <string, string>
                            {
                                { "partNumber", partNumber.ToString() },
                                { "uploadId", uploadId }
                            };
                            if (requestBody.Files[0].ContentType.Contains("text/"))
                            {
                                streamContent = new StringContent(await new StreamReader(new MemoryStream(buffer)).ReadToEndAsync(), Encoding.UTF8);
                            }
                            else
                            {
                                streamContent = new StreamContent(new MemoryStream(buffer));
                            }
                            response = await CommonService.HttpRequestContent(appSettings, url, requestBody["bucket"] + "/" + requestBody["objectkey"] + QueryString.Create(queryparams), "PUT", streamContent, headers, "Bearer", iamToken["access_token"].ToString());

                            XmlElement part       = xmlDocument.CreateElement("Part");
                            XmlElement partnumber = xmlDocument.CreateElement("PartNumber");
                            partnumber.InnerText = partNumber.ToString();
                            XmlElement etag = xmlDocument.CreateElement("ETag");
                            etag.InnerText = response.Headers.ETag.Tag.Replace("\"", "");
                            part.AppendChild(partnumber);
                            part.AppendChild(etag);
                            completeMultipartUpload.AppendChild(part);
                            partNumber += 1;
                        }
                    }
                }
                xmlDocument.AppendChild(completeMultipartUpload);
                queryparams = new Dictionary <string, string>
                {
                    { "uploadId", uploadId }
                };
                response = await CommonService.HttpRequestXML(appSettings, url, requestBody["bucket"] + "/" + requestBody["objectkey"] + QueryString.Create(queryparams), "POST", xmlDocument.InnerXml, headers, "Bearer", iamToken["access_token"].ToString());

                result["result"] = await response.Content.ReadAsStringAsync();

                result["_statuscode"] = ((int)response.StatusCode).ToString() + response.StatusCode;
                return(result);
            }
            catch (Exception e)
            {
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {JsonConvert.SerializeObject(requestBody)}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                throw e;
            }
        }
Ejemplo n.º 4
0
        public static async Task <JObject> PutResource(AppSettings appSettings, string resource, Dictionary <string, object> data)
        {
            string  methodName = "PutResource";
            JObject result     = new JObject();

            try
            {
                // Basic
                string url = appSettings.PrestashopSettings.UrlApiBase;
                Dictionary <string, string> headers = new Dictionary <string, string>();
                headers["Output-Format"] = "JSON";

                // Get Element
                HttpResponseMessage getresponse = await CommonService.HttpRequestContent(appSettings, url, resource + "/" + data["id"].ToString(), "GET", null, null, "Basic", GetAuthKey(appSettings));

                var r = await getresponse.Content.ReadAsStringAsync();

                r = Regex.Replace(r, "<!\\[CDATA\\[", "");
                r = Regex.Replace(r, "]]>", "");
                JObject jObject      = CommonService.XMLToJObject(r);
                string  resourcepath = GetResourcePath(resource);

                // Update Element
                foreach (var d in data)
                {
                    if (!d.Key.Contains("zyxme") && !d.Key.Contains("associations"))
                    {
                        if (d.Value.GetType().Name == "JObject")
                        {
                            jObject["prestashop"][resourcepath][d.Key] = JObject.Parse(d.Value.ToString());
                        }
                        else
                        {
                            jObject["prestashop"][resourcepath][d.Key] = new JValue(d.Value);
                        }
                    }
                }
                jObject = CheckValidsKey(resourcepath, jObject);

                XmlDocument xmlDocument = JsonConvert.DeserializeXmlNode(jObject.ToString());

                if (data.ContainsKey("associations"))
                {
                    foreach (var d in JObject.FromObject(data["associations"]))
                    {
                        if (xmlDocument.SelectSingleNode($"//prestashop/{resourcepath}/associations/{d.Key}") == null)
                        {
                            XmlNode fatherElem = xmlDocument.CreateNode("element", d.Key, "");
                            xmlDocument.SelectSingleNode($"//prestashop/{resourcepath}/associations").AppendChild(fatherElem);
                        }
                        xmlDocument.SelectSingleNode($"//prestashop/{resourcepath}/associations/{d.Key}").RemoveAll();

                        foreach (JObject d2 in CommonService.JArrayToListJObject(d.Value))
                        {
                            foreach (var d3 in CommonService.JObjectToDictionary(d2))
                            {
                                // Create a new element node.
                                XmlElement idElem = xmlDocument.CreateElement("id");
                                idElem.InnerText = d3.Value.ToString();
                                XmlElement childElem = xmlDocument.CreateElement(d3.Key);
                                childElem.AppendChild(idElem);
                                xmlDocument.SelectSingleNode($"//prestashop/{resourcepath}/associations/{d.Key}").AppendChild(childElem);
                            }
                        }
                    }
                }

                HttpResponseMessage updateresponse = await CommonService.HttpRequestXML(appSettings, url, resource, "PUT", xmlDocument.InnerXml, headers, "Basic", GetAuthKey(appSettings));

                result = CommonService.StringToJObject(await updateresponse.Content.ReadAsStringAsync());

                if (resource == "customers")
                {
                    Dictionary <string, string> loginparams = new Dictionary <string, string>();
                    loginparams.Add("back", "my-account");
                    loginparams.Add("email", xmlDocument["prestashop"][resourcepath]["email"].InnerText);
                    loginparams.Add("password", xmlDocument["prestashop"][resourcepath]["passwd"].InnerText);
                    loginparams.Add("submitLogin", "1");
                    result["accessurl"] = appSettings.PrestashopSettings.LoginUrl + QueryString.Create(loginparams);
                }

                result["_statuscode"] = ((int)updateresponse.StatusCode).ToString() + updateresponse.StatusCode;
                return(result);
            }
            catch (Exception e)
            {
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {resource}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                throw e;
            }
        }
Ejemplo n.º 5
0
        public static async Task <JObject> PostResource(AppSettings appSettings, string resource, Dictionary <string, object> data)
        {
            string  methodName = "PostResource";
            JObject result     = new JObject();

            try
            {
                // Basic
                string url = appSettings.PrestashopSettings.UrlApiBase;
                Dictionary <string, string> headers = new Dictionary <string, string>();
                headers["Output-Format"] = "JSON";

                Dictionary <string, object> search = new Dictionary <string, object>();
                search["zyxme"] = new Dictionary <string, object>();
                switch (resource)
                {
                case "addresses":
                    search["zyxme"] = new Dictionary <string, object>()
                    {
                        { "filter[id_country]", data["id_country"] },
                        { "filter[alias]", data["alias"] },
                        { "filter[lastname]", data["lastname"] },
                        { "filter[firstname]", data["firstname"] },
                        { "filter[city]", data["city"] },
                        { "filter[address1]", data["address1"] }
                    };
                    break;

                case "categories":
                    search["zyxme"] = new Dictionary <string, object>()
                    {
                        { "filter[name]", data["name"] }
                    };
                    break;

                case "countries":
                    search["zyxme"] = new Dictionary <string, object>()
                    {
                        { "filter[id_zone]", data["id_zone"] },
                        { "filter[iso_code]", data["iso_code"] },
                        { "filter[name]", data["name"] }
                    };
                    break;

                case "customers":
                    search["zyxme"] = new Dictionary <string, object>()
                    {
                        { "filter[email]", data["email"] }
                    };
                    break;

                case "products":
                    search["zyxme"] = new Dictionary <string, object>()
                    {
                        { "filter[name]", data["name"] }
                    };
                    break;

                case "stores":
                    search["zyxme"] = new Dictionary <string, object>()
                    {
                        { "filter[id_country]", data["id_country"] },
                        { "filter[city]", data["city"] },
                        { "filter[name]", data["name"] },
                        { "filter[address1]", data["address1"] }
                    };
                    break;

                case "taxes":
                    search["zyxme"] = new Dictionary <string, object>()
                    {
                        { "filter[name]", data["name"] }
                    };
                    break;

                case "zones":
                    search["zyxme"] = new Dictionary <string, object>()
                    {
                        { "filter[name]", data["name"] }
                    };
                    break;

                default:
                    break;
                }
                JObject searchresult = await GetResource(appSettings, resource, search);

                if (searchresult[resource] != null && searchresult[resource].HasValues)
                {
                    data["id"] = searchresult[resource][0]["id"].ToString();
                    result     = await PutResource(appSettings, resource, data);
                }
                else
                {
                    // New Element
                    Dictionary <string, string> queryparams = new Dictionary <string, string>();
                    queryparams.Add("schema", "blank");
                    HttpResponseMessage blankresponse = await CommonService.HttpRequestContent(appSettings, url, resource + QueryString.Create(queryparams), "GET", null, null, "Basic", GetAuthKey(appSettings));

                    JObject jObject      = CommonService.XMLToJObject(await blankresponse.Content.ReadAsStringAsync());
                    string  resourcepath = GetResourcePath(resource);
                    jObject = CreateBasicElement(resourcepath, jObject, data);
                    HttpResponseMessage newresponse = await CommonService.HttpRequestXML(appSettings, url, resource, "POST", JsonConvert.DeserializeXmlNode(jObject.ToString()).InnerXml, headers, "Basic", GetAuthKey(appSettings));

                    jObject = CommonService.StringToJObject(await newresponse.Content.ReadAsStringAsync());

                    // Get Basic Element Created
                    HttpResponseMessage getresponse = await CommonService.HttpRequestContent(appSettings, url, resource + "/" + jObject[resourcepath]["id"].ToString(), "GET", null, null, "Basic", GetAuthKey(appSettings));

                    var r = await getresponse.Content.ReadAsStringAsync();

                    r       = Regex.Replace(r, "<!\\[CDATA\\[", "");
                    r       = Regex.Replace(r, "]]>", "");
                    jObject = CommonService.XMLToJObject(r);

                    // Update Element
                    foreach (var d in data)
                    {
                        if (!d.Key.Contains("zyxme") && !d.Key.Contains("associations"))
                        {
                            if (d.Value.GetType().Name == "JObject")
                            {
                                jObject["prestashop"][resourcepath][d.Key] = JObject.Parse(d.Value.ToString());
                            }
                            else
                            {
                                jObject["prestashop"][resourcepath][d.Key] = new JValue(d.Value);
                            }
                        }
                    }
                    jObject = CheckValidsKey(resourcepath, jObject);

                    XmlDocument xmlDocument = JsonConvert.DeserializeXmlNode(jObject.ToString());

                    if (data.ContainsKey("associations"))
                    {
                        foreach (var d in JObject.FromObject(data["associations"]))
                        {
                            if (xmlDocument.SelectSingleNode($"//prestashop/{resourcepath}/associations/{d.Key}") == null)
                            {
                                XmlNode fatherElem = xmlDocument.CreateNode("element", d.Key, "");
                                xmlDocument.SelectSingleNode($"//prestashop/{resourcepath}/associations").AppendChild(fatherElem);
                            }
                            xmlDocument.SelectSingleNode($"//prestashop/{resourcepath}/associations/{d.Key}").RemoveAll();

                            foreach (JObject d2 in CommonService.JArrayToListJObject(d.Value))
                            {
                                foreach (var d3 in CommonService.JObjectToDictionary(d2))
                                {
                                    // Create a new element node.
                                    XmlElement idElem = xmlDocument.CreateElement("id");
                                    idElem.InnerText = d3.Value.ToString();
                                    XmlElement childElem = xmlDocument.CreateElement(d3.Key);
                                    childElem.AppendChild(idElem);
                                    xmlDocument.SelectSingleNode($"//prestashop/{resourcepath}/associations/{d.Key}").AppendChild(childElem);
                                }
                            }
                        }
                    }

                    HttpResponseMessage updateresponse = await CommonService.HttpRequestXML(appSettings, url, resource, "PUT", JsonConvert.DeserializeXmlNode(jObject.ToString()).InnerXml, headers, "Basic", GetAuthKey(appSettings));

                    result = CommonService.StringToJObject(await updateresponse.Content.ReadAsStringAsync());

                    if (resource == "customers")
                    {
                        Dictionary <string, string> loginparams = new Dictionary <string, string>();
                        loginparams.Add("back", "my-account");
                        loginparams.Add("email", xmlDocument["prestashop"][resourcepath]["email"].InnerText);
                        loginparams.Add("password", xmlDocument["prestashop"][resourcepath]["passwd"].InnerText);
                        loginparams.Add("submitLogin", "1");
                        result["accessurl"] = appSettings.PrestashopSettings.LoginUrl + QueryString.Create(loginparams);
                    }

                    result["_statuscode"] = ((int)updateresponse.StatusCode).ToString() + updateresponse.StatusCode;
                }
                return(result);
            }
            catch (Exception e)
            {
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {resource}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                throw e;
            }
        }
Ejemplo n.º 6
0
        public static dynamic TextToSpeech(AppSettings appSettings, TextToSpeechRequest requestBody)
        {
            string  methodName = "TextToSpeech";
            dynamic result     = new ExpandoObject();

            try
            {
                WatsonSettings   settings      = appSettings.WatsonServices.TextToSpeech;
                IamAuthenticator authenticator = new IamAuthenticator(apikey: $"{requestBody.Apikey}");
                IBM.Watson.TextToSpeech.v1.TextToSpeechService textToSpeech = new IBM.Watson.TextToSpeech.v1.TextToSpeechService(authenticator);
                textToSpeech.SetServiceUrl($"{requestBody.Endpoint}");
                DetailedResponse <MemoryStream> ms = new DetailedResponse <MemoryStream>();
                ms = textToSpeech.Synthesize(
                    text: requestBody.Text,
                    accept: requestBody.Accept != null ? requestBody.Accept : "audio/mp3",
                    voice: requestBody.Voice != null ? requestBody.Voice : "es-ES_LauraV3Voice"
                    );
                string filename = CommonService.GetExternalPlatforms(appSettings).STTAudioFilePath + Guid.NewGuid() + ".mp3";
                if (Directory.Exists(Path.Combine(CommonService.GetExternalPlatforms(appSettings).STTAudioFilePath)) == false)
                {
                    Directory.CreateDirectory(CommonService.GetExternalPlatforms(appSettings).STTAudioFilePath + Guid.NewGuid());
                }
                using (FileStream fs = File.Create(filename))
                {
                    ms.Result.WriteTo(fs);
                    fs.Close();
                    ms.Result.Close();
                }
                result = filename.Replace(CommonService.GetExternalPlatforms(appSettings).STTAudioFilePath, CommonService.GetExternalPlatforms(appSettings).STTAudioFileUrl);
                return(result);
            }
            catch (Exception e)
            {
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {JsonConvert.SerializeObject(requestBody)}");
                Log.Write(appSettings, LogEnum.ERROR.ToString(), label, className, methodName, $"ERROR: {e.Source + Environment.NewLine + e.Message + Environment.NewLine + e.StackTrace}");
                throw e;
            }
        }