Example #1
0
        public async Task <IActionResult> OnGetAsync()
        {
            LoggedIn = !string.IsNullOrEmpty(Request.Cookies["Token"]);

            Query = Request.Query["s"].ApplyCorrectYeKe().Trim();
            bool quotes = Query.IndexOf("\"") != -1;

            Query = LanguageUtils.MakeTextSearchable(Query); //replace zwnj with space
            if (quotes)
            {
                Query = $"\"{Query}\"";
            }
            PoetId = string.IsNullOrEmpty(Request.Query["author"]) ? 0 : int.Parse(Request.Query["author"]);
            CatId  = string.IsNullOrEmpty(Request.Query["cat"]) ? 0 : int.Parse(Request.Query["cat"]);

            ViewData["GoogleAnalyticsCode"] = Configuration["GoogleAnalyticsCode"];

            //todo: use html master layout or make it partial
            // 1. poets
            if (false == (await preparePoets()))
            {
                return(Page());
            }

            var poetName = Poets.SingleOrDefault(p => p.Id == PoetId);

            if (poetName != null)
            {
                ViewData["Title"] = $"گنجور » نتایج جستجو برای {Query} در آثار {poetName?.Name}";
            }
            else
            {
                if (!string.IsNullOrEmpty(Query))
                {
                    ViewData["Title"] = $"گنجور » نتایج جستجو برای {Query}";
                }
                else
                {
                    ViewData["Title"] = $"گنجور » جستجو";
                }
            }

            if (PoetId != 0)
            {
                if (false == (await preparePoet()))
                {
                    return(Page());
                }
            }

            // 2. search verses
            int pageNumber = 1;

            if (!string.IsNullOrEmpty(Request.Query["page"]))
            {
                pageNumber = int.Parse(Request.Query["page"]);
            }

            HttpResponseMessage searchQueryResponse = null;

            if (!string.IsNullOrEmpty(Query))
            {
                searchQueryResponse = await _httpClient.GetAsync($"{APIRoot.Url}/api/ganjoor/poems/search?term={Query}&poetId={PoetId}&catId={CatId}&PageNumber={pageNumber}&PageSize=20");

                if (!searchQueryResponse.IsSuccessStatusCode)
                {
                    LastError = JsonConvert.DeserializeObject <string>(await searchQueryResponse.Content.ReadAsStringAsync());
                    return(Page());
                }

                Poems = JArray.Parse(await searchQueryResponse.Content.ReadAsStringAsync()).ToObject <List <GanjoorPoemCompleteViewModel> >();
            }


            if (Poems != null && Poems.Count == 0)
            {
                Poems = null;
            }

            if (Poems != null)
            {
                // highlight searched word
                string[] queryParts = Query.IndexOf('"') == 0 && Query.LastIndexOf('"') == (Query.Length - 1) ?
                                      new string[] { Query.Replace("\"", "") }
                       :
                Query.Replace("\"", "").Split(' ', StringSplitOptions.RemoveEmptyEntries);

                foreach (var poem in Poems)
                {
                    string[]   lines          = poem.PlainText.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries);
                    List <int> linesInExcerpt = new List <int>();
                    for (int i = 0; i < lines.Length; i++)
                    {
                        foreach (var queryPart in queryParts)
                        {
                            if (lines[i].IndexOf(queryPart) != -1)
                            {
                                if (i > 0)
                                {
                                    if (linesInExcerpt.IndexOf(i - 1) == -1)
                                    {
                                        linesInExcerpt.Add(i - 1);
                                    }
                                }
                                if (linesInExcerpt.IndexOf(i) == -1)
                                {
                                    linesInExcerpt.Add(i);
                                }

                                if (i < (lines.Length - 1))
                                {
                                    linesInExcerpt.Add(i + 1);
                                }

                                break;
                            }
                        }
                    }


                    string plainText = "";
                    for (int i = 0; i < linesInExcerpt.Count; i++)
                    {
                        if (linesInExcerpt[i] > 0 && linesInExcerpt.IndexOf(linesInExcerpt[i] - 1) == -1)
                        {
                            plainText += "... ";
                        }
                        plainText += $"{lines[linesInExcerpt[i]]}";
                        if (linesInExcerpt[i] < (lines.Length - 1) && linesInExcerpt.IndexOf(linesInExcerpt[i] + 1) == -1)
                        {
                            plainText += " ...";
                        }
                        plainText += $"{Environment.NewLine}";
                    }

                    string finalPlainText = "";
                    foreach (string line in plainText.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries))
                    {
                        finalPlainText += $"<p>{line}</p>";
                    }
                    poem.PlainText = finalPlainText;

                    for (int i = 0; i < queryParts.Length; i++)
                    {
                        string cssClass = i % 3 == 0 ? "hilite" : i % 3 == 1 ? "hilite2" : "hilite3";
                        poem.PlainText = Regex.Replace(poem.PlainText, queryParts[i], $"<span class=\"{cssClass}\">{queryParts[i]}</span>", RegexOptions.IgnoreCase | RegexOptions.RightToLeft);;
                    }
                }

                if (searchQueryResponse != null)
                {
                    string paginationMetadataJsonValue = searchQueryResponse.Headers.GetValues("paging-headers").FirstOrDefault();

                    if (!string.IsNullOrEmpty(paginationMetadataJsonValue))
                    {
                        PaginationMetadata paginationMetadata = JsonConvert.DeserializeObject <PaginationMetadata>(paginationMetadataJsonValue);
                        string             catQuery           = "";
                        if (!string.IsNullOrEmpty(Request.Query["cat"]))
                        {
                            catQuery = $"&cat={Request.Query["cat"]}";
                        }
                        PagingToolsHtml = GeneratePagingBarHtml(paginationMetadata, $"/search?s={WebUtility.UrlEncode(Query)}&amp;author={PoetId}{catQuery}");
                    }
                }
            }



            return(Page());
        }