private async Task <string> ExecuteKScriptNodeAsync(KScriptNode node, Dictionary <string, AliasReference> classNameAlias, bool isRepeat)
        {
            try
            {
                StringBuilder resultString = new StringBuilder("");
                string        apiUrl       = string.Copy(node.API);
                string        input        = "";
                if (!string.IsNullOrEmpty(node.Input))
                {
                    input = string.Copy(node.Input);
                }
                string headers = "";
                if (!string.IsNullOrEmpty(node.Headers))
                {
                    headers = string.Copy(node.Headers);
                }
                bool cacheEnabled = true;
                if (!string.IsNullOrEmpty(node.IsCacheEnabledString))
                {
                    string cacheEnabledStr = await evaluator.EvaluateExpressionAsync(node.IsCacheEnabledString, classNameAlias);

                    bool.TryParse(cacheEnabledStr, out cacheEnabled);
                }
                if (!cacheEnabled)
                {
                    CacheableResult = false;
                }
                if (!string.IsNullOrEmpty(apiUrl))
                {
                    if (!string.IsNullOrEmpty(input))
                    {
                        var inputMatches = Constant.WidgetRegulerExpression.Matches(input);
                        Dictionary <string, string> matchDict = new Dictionary <string, string>();

                        //Handle the (,) withing the expression business.name.replace('hello',''). it was spliting by comma so used unique pattern
                        for (var i = 0; i < inputMatches.Count; i++)
                        {
                            matchDict.Add($"##__{i}__##", inputMatches[i].Value);
                            input = input.Replace(inputMatches[i].Value, $"##__{i}__##");
                        }

                        var inputArray = input.Split(',');

                        int count = 0;
                        foreach (var inputVal in inputArray)
                        {
                            var elem = inputVal;
                            foreach (var placHolder in matchDict)
                            {
                                elem = elem.Replace(placHolder.Key, placHolder.Value);
                            }
                            if (elem.Contains("]") || elem.Contains("["))
                            {
                                dynamic outputObject = await evaluator.EvaluateExpressionAsync(elem, classNameAlias);

                                var output = outputObject.ToString();
                                apiUrl = apiUrl.Replace("{" + count + "}", output.Trim('\''));
                            }
                            else
                            {
                                apiUrl = apiUrl.Replace("{" + count + "}", elem);
                            }
                            count++;
                        }
                    }

                    var headerDict = new Dictionary <string, string>();
                    if (!string.IsNullOrEmpty(headers))
                    {
                        var headersArray = Helper.TrimDelimiters(headers).Split(',');
                        foreach (var header in headersArray)
                        {
                            var separator = header.Split(':');
                            if (!headerDict.ContainsKey(separator[0].Trim()))
                            {
                                headerDict.Add(separator[0].Trim().Trim('\''), separator[1].Trim().Trim('\''));
                            }
                        }
                    }
                    //var result = GetResponseFromKScript(apiUrl, headerDict, cacheEnabled, functionLog);
                    var result = await ApiHelper.GetResponseFromKScriptAsync(apiUrl, headerDict, cacheEnabled, rootAliasUri, functionLog, websiteId);

                    if (result != null)
                    {
                        evaluator.ChangePropertiesToLowerCase(result);
                        classNameAlias.Remove("kresult");
                        classNameAlias.Add("kresult", new AliasReference {
                            iteration = -1, maxIteration = -1, referenceObject = result
                        });
                    }
                    string res = await ProcessNodesAsync(node.Children, classNameAlias, isRepeat);

                    resultString.Append(res);
                    classNameAlias.Remove("kresult");
                }
                return(resultString.ToString());
            }
            catch (Exception e)
            {
                CacheableResult = false;
                ConsoleLogger.Write($"ERROR: ExecuteKScriptNodeAsync: \t {e.ToString()}, source:" + page.SourcePath);
            }
            return("");
        }
Exemplo n.º 2
0
        private HtmlNode ProcessExtractBlocksNode(HtmlNode node)
        {
            HtmlNode returnNode = node;

            bool isKTag = false;

            if (nodeNameBlockDescriptors.Contains(node.Name))
            {
                if (node.Name.Equals(LanguageAttributes.KScript.GetDescription().ToLower()))
                {
                    var       apiUrl          = decodeExpression(node.GetAttributeValue("get-api", null));
                    var       input           = node.GetAttributeValue("input", null);
                    var       headers         = node.GetAttributeValue("headers", null)?.Trim()?.Trim('[')?.Trim(']');
                    string    cacheEnabledStr = node.GetAttributeValue("cacheenabled", null);
                    BlockNode bNode           = new KScriptNode(apiUrl, input, headers, cacheEnabledStr);
                    HtmlNode  tempNode        = node.OwnerDocument.CreateTextNode(GenerateBlockIdentifier());
                    returnNode = tempNode;
                    blockNodeReferenceList.Add(currentBlockNumber, bNode);
                    node.ParentNode.InsertAfter(tempNode, node);
                    node.Remove();
                    var htmlDoc = new HtmlDocument();
                    htmlDoc.LoadHtml("<div></div>");
                    HtmlNode newNode = htmlDoc.DocumentNode.FirstChild;
                    newNode.AppendChildren(node.ChildNodes);

                    bNode.Children.AddRange(GetNodes(newNode, true));
                    return(tempNode);
                }
                else if (node.Name.Equals(LanguageAttributes.KTag.GetDescription().ToLower()))
                {
                    isKTag = true;
                }
                //Removed the srcset as its domain specific (some cdn was not configured so that it was not working on some domain)
                //else if (node.Name.Equals("img"))
                //{
                //    if (node.Attributes.Any(x => "src" == x.Name?.ToLower()))
                //    {
                //        node.Attributes.Remove("srcset");
                //        node.Attributes.Add("srcset", $"[[getSrcSet({node.Attributes["src"].Value.Replace(@"[[", @"\[\[").Replace(@"]]", @"\]\]")})]]");
                //    }
                //}
            }

            List <HtmlAttribute> attributeList = node.Attributes.Where(x => attributeNameBlockDescriptors.Contains(x.Name)).ToList();

            if (attributeList.Count > 0)
            {
                HtmlAttribute repeatAttribute = null;
                repeatAttribute = attributeList.FirstOrDefault(x => x.Name == LanguageAttributes.KRepeat.GetDescription().ToLower());
                foreach (HtmlAttribute attribute in attributeList)
                {
                    BlockNode blockNode = null;
                    switch (attribute.Name.ToLower())
                    {
                    case "k-show":
                        blockNode = new KShowNode(decodeExpression(attribute.Value.Replace("[[", "").Replace("]]", "")));
                        break;

                    case "k-hide":
                        blockNode = new KHideNode(decodeExpression(attribute.Value.Replace("[[", "").Replace("]]", "")));
                        break;

                    case "k-pay-amount":
                    {
                        node.Attributes.Add("k-pay-checksum", $"[[getChecksum({attribute.Value.Replace("[[", "").Replace("]]", "")})]]");
                    }
                    break;

                    case "k-norepeat":
                        blockNode = new KNoRepeatNode();
                        break;
                    }
                    if (blockNode != null)
                    {
                        attribute.Remove();
                        if (node.ParentNode != null)
                        {
                            HtmlNode tempNode = node.OwnerDocument.CreateTextNode(GenerateBlockIdentifier());
                            blockNodeReferenceList.Add(currentBlockNumber, blockNode);
                            node.ParentNode.InsertAfter(tempNode, node);
                            node.Remove();
                            //exclude the top node if isKtag to remove ktag node
                            blockNode.Children.AddRange(GetNodes(node, isKTag && repeatAttribute == null ? true : false));
                            return(tempNode);
                        }
                        else
                        {
                            return(HtmlNode.CreateNode("<!-- Invalid node -->"));
                        }
                    }
                }

                if (repeatAttribute != null)
                {
                    var repeatNode = ProcessRepeatNode(node, repeatAttribute, isKTag);
                    if (repeatNode != null)
                    {
                        return(repeatNode);
                    }
                }
            }
            return(returnNode);
        }