docs: #307 duplicating the search page for an independent similarity finder page

This commit is contained in:
Hamid Reza Mohammadi 2022-04-23 14:36:46 +04:30
parent 59a8dbaf41
commit 4fc0d0baf1
3 changed files with 554 additions and 2 deletions

View File

@ -0,0 +1,212 @@
@page
@model GanjooRazor.Pages.SimiModel
@{
Layout = null;
}
<!DOCTYPE html>
<html lang="fa-IR" dir="rtl">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>
@ViewData["Title"]
</title>
<link href="/css/p8.css?version=40" rel="stylesheet" type="text/css" />
<link href="/css/fab.css" rel="stylesheet" type="text/css" />
<link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" />
<link rel="search" type="application/opensearchdescription+xml" title="گنجور" href="https://ganjoor.net/search.xml" />
</head>
<body>
@if (!string.IsNullOrEmpty(Model.LastError))
{
@Model.LastError
}
else
{
<div id="hdr2" class="clearfix">
<h1><a href="/" title="گنجور"><img src="/image/gmgk.png" alt="گنجور" /></a></h1>
<div class="actionbox">
<form action="/search" method="get" id="searchform">
<input type="text" name="s" id="s" class="inputText" value="@Model.Query" placeholder="جستجو" />
<select name="author" id="author" onchange="onSelectedPoetChanged()">
@{
if (Model.PoetId != 0)
{
<option value="0">در آثار همهٔ سخنوران</option>
}
else
{
<option value="0" selected>در آثار همهٔ سخنوران</option>
}
if (Model.Poets != null)
{
foreach (RMuseum.Models.Ganjoor.ViewModels.GanjoorPoetViewModel poet in Model.Poets)
{
if (poet.Id == Model.PoetId)
{
<option value="@poet.Id" selected>@poet.Name</option>
}
else
{
<option value="@poet.Id">@poet.Name</option>
}
}
}
}
</select>
@{
if (Model.Poet != null)
{
<select name="cat" id="cat" style="width:150px">
@if (Model.CatId == 0)
{
<option value="0" selected>در همهٔ بخشها</option>
}
else
{
<option value="0">در همهٔ بخشها</option>
}
@{
foreach (var gran in Model.Poet.Cat.Ancestors)
{
@if (Model.CatId == gran.Id)
{
<option value="@gran.Id" selected>@gran.Title</option>
}
else
{
<option value="@gran.Id">@gran.Title</option>
}
}
@if (Model.CatId == Model.Poet.Cat.Id)
{
<option value="@Model.Poet.Cat.Id" selected>@Model.Poet.Cat.Title</option>
}
else
{
<option value="@Model.Poet.Cat.Id">@Model.Poet.Cat.Title</option>
}
foreach (var child in Model.Poet.Cat.Children)
{
@if (Model.CatId == child.Id)
{
<option value="@child.Id" selected>@child.Title</option>
}
else
{
<option value="@child.Id">@child.Title</option>
}
}
}
</select>
}
}
<input type="submit" value="بیاب" />
</form>
</div><!-- .actionbox -->
</div><!-- #hdr2 -->
<div id="fa">
<div id="maincnt">
<div class="spacer">&nbsp;</div>
@if (Model.Poems == null)
{
<div class="poem">
<h2>شعری با مشخصات مورد نظر شما پیدا نشد.</h2>
<p>
<strong>توصیه‌هایی برای دستیابی به نتیجهٔ مطلوبتر در جستجو:</strong>
</p>
<p>
الف) <strong>به جای جستجوی متن کامل یک بیت بهتر است حروف کلیدی آن را وارد کنید.</strong> از آنجا که اشعار به صورتهای مختلف در نسخه‌های متفاوت نقل شده‌اند ممکن است چیزی که شما در ذهن دارید با چیزی که در پایگاه ما ثبت شده متفاوت باشد. به عنوان نمونه مصرع «کشتی شکستگانیم ای باد شرطه برخیز» از حافظ در بعضی از نسخه‌ها به صورت «کشتی نشستگانیم ای باد شرطه برخیز» ضبط شده و شما با تایپ صورت صورت دوم آن را در گنجور نخواهید یافت. بهتر است برای یافتن این شعر کلماتی مانند کشتی و شرطه را جستجو کنیم.
</p>
<p>
ب) کلماتی را که ممکن است به صورت جدا یا سر هم نوشته شوند در گام اول به صورت جدا امتحان کنید (<strong>می شود</strong> و نه <del>میشود</del> یا <del>می‌شود</del>).
</p>
<p>
ج) در صورتی که نام شاعر را می‌دانید بهتر است از طریق لیست بازشوی جلوی جعبهٔ جستجو نام او را انتخاب کنید. این توصیه برای زمانی مناسب است که جستجوی عبارت مورد نظر شما باعث می‌شود آثار شاعرانی که مورد نظر شما نیستند در صدر نتایج قرار گیرد و به این وسیله شما می‌خواهید به فهرست محدودتری از نتایج دست پیدا کنید.
</p>
<p>
د) در صورتی که با فنون اولیهٔ جستجو آشنا نیستید یا <strong>معمولاً جستجوهایتان به نتیجهٔ مطلوب نمی‌رسد</strong> بد نیست نگاهی به <a href="http://hrmoh.ir/1385/04/18/howto-search-better/" title="توصیه هایی برای جستجوی بهتر در اینترنت">این نوشته</a> بیندازید.
</p>
</div>
}
else
foreach (var poem in Model.Poems)
{
<div class="sitem">
<h2>
<a href="@poem.FullUrl">@poem.FullTitle</a>
</h2>
<div class="spacer">&nbsp;</div>
<div class="sit">
@Html.Raw(poem.PlainText)
<p>
<br>
<a href="@poem.FullUrl">متن کامل شعر را ببینید ...</a>
</p>
</div>
<img src="@($"{GanjooRazor.APIRoot.InternetUrl}{poem.Category.Poet.ImageUrl}")" alt="@($"{poem.Category.Poet.Name}")" />
<div class="spacer">&nbsp;</div>
</div>
}
<div class="spacer">&nbsp;</div>
@Html.Raw(Model.PagingToolsHtml)
</div>
<partial name="_InlineLoginPartial" model="Model" />
<partial name="_FooterPartial" model="null" />
</div>
<script src="/lib/jquery/dist/jquery.min.js"></script>
<script src="/js/bk.js?version=24"></script>
<script src="/js/vaabd.js"></script>
@if (!string.IsNullOrEmpty(ViewData["GoogleAnalyticsCode"].ToString()))
{
<script>
(function (i, s, o, g, r, a, m) {
i['GoogleAnalyticsObject'] = r; i[r] = i[r] || function () {
(i[r].q = i[r].q || []).push(arguments)
}, i[r].l = 1 * new Date(); a = s.createElement(o),
m = s.getElementsByTagName(o)[0]; a.async = 1; a.src = g; m.parentNode.insertBefore(a, m)
})(window, document, 'script', 'https://www.google-analytics.com/analytics.js', 'ga');
ga('create', '@ViewData["GoogleAnalyticsCode"]', 'auto');
ga('send', 'pageview');
</script>
}
}
</body>
</html>

View File

@ -0,0 +1,340 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DNTPersianUtils.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RMuseum.Models.Ganjoor.ViewModels;
using RMuseum.Services.Implementation;
using RSecurityBackend.Models.Generic;
namespace GanjooRazor.Pages
{
[IgnoreAntiforgeryToken(Order = 1001)]
public class SimiModel : LoginPartialEnabledPageModel
{
/// <summary>
/// memory cache
/// </summary>
private readonly IMemoryCache _memoryCache;
/// <summary>
/// configration file reader (appsettings.json)
/// </summary>
private readonly IConfiguration Configuration;
/// <summary>
/// constructor
/// </summary>
/// <param name="httpClient"></param>
/// <param name="memoryCache"></param>
/// <param name="configuration"></param>
public SimiModel(HttpClient httpClient, IMemoryCache memoryCache, IConfiguration configuration) : base(httpClient)
{
_memoryCache = memoryCache;
Configuration
= configuration;
}
/// <summary>
/// aggressive cache
/// </summary>
public bool AggressiveCacheEnabled
{
get
{
try
{
return bool.Parse(Configuration["AggressiveCacheEnabled"]);
}
catch
{
return false;
}
}
}
public List<GanjoorPoetViewModel> Poets { get; set; }
public string Query { get; set; }
public int PoetId { get; set; }
public int CatId { get; set; }
public GanjoorPoetCompleteViewModel Poet { get; set; }
public List<GanjoorPoemCompleteViewModel> Poems { get; set; }
public string PagingToolsHtml { get; set; }
public string LastError { get; set; }
private async Task<bool> preparePoets()
{
var cacheKey = $"/api/ganjoor/poets";
if (!_memoryCache.TryGetValue(cacheKey, out List<GanjoorPoetViewModel> poets))
{
var response = await _httpClient.GetAsync($"{APIRoot.Url}/api/ganjoor/poets");
if (!response.IsSuccessStatusCode)
{
LastError = JsonConvert.DeserializeObject<string>(await response.Content.ReadAsStringAsync());
return false;
}
poets = JArray.Parse(await response.Content.ReadAsStringAsync()).ToObject<List<GanjoorPoetViewModel>>();
if (AggressiveCacheEnabled)
{
_memoryCache.Set(cacheKey, poets);
}
}
Poets = poets;
return true;
}
private async Task<bool> preparePoet()
{
var cacheKey = $"/api/ganjoor/poet/{PoetId}";
if (!_memoryCache.TryGetValue(cacheKey, out GanjoorPoetCompleteViewModel poet))
{
var poetResponse = await _httpClient.GetAsync($"{APIRoot.Url}/api/ganjoor/poet/{PoetId}");
if (!poetResponse.IsSuccessStatusCode)
{
LastError = JsonConvert.DeserializeObject<string>(await poetResponse.Content.ReadAsStringAsync());
return false;
}
poet = JObject.Parse(await poetResponse.Content.ReadAsStringAsync()).ToObject<GanjoorPoetCompleteViewModel>();
if (AggressiveCacheEnabled)
{
_memoryCache.Set(cacheKey, poet);
}
}
Poet = poet;
return true;
}
public async Task<IActionResult> OnGetPoetInformationAsync(int id)
{
if (id == 0)
return new OkObjectResult(null);
var cacheKey = $"/api/ganjoor/poet/{id}";
if (!_memoryCache.TryGetValue(cacheKey, out GanjoorPoetCompleteViewModel poet))
{
var poetResponse = await _httpClient.GetAsync($"{APIRoot.Url}/api/ganjoor/poet/{id}");
if (!poetResponse.IsSuccessStatusCode)
{
return BadRequest(JsonConvert.DeserializeObject<string>(await poetResponse.Content.ReadAsStringAsync()));
}
poet = JObject.Parse(await poetResponse.Content.ReadAsStringAsync()).ToObject<GanjoorPoetCompleteViewModel>();
if (AggressiveCacheEnabled)
{
_memoryCache.Set(cacheKey, poet);
}
}
return new OkObjectResult(poet);
}
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();
}
private string GeneratePagingBarHtml(PaginationMetadata paginationMetadata, string routeStartWithQueryStrings)
{
string htmlText = "<p style=\"text-align: center;\">";
if (paginationMetadata != null && paginationMetadata.totalPages > 1)
{
if (paginationMetadata.currentPage > 3)
{
htmlText += $"[<a href=\"{routeStartWithQueryStrings.Replace("\"", "%22")}&amp;page=1\">صفحهٔ اول</a>] …";
}
for (int i = (paginationMetadata.currentPage - 2); i <= (paginationMetadata.currentPage + 2); i++)
{
if (i >= 1 && i <= paginationMetadata.totalPages)
{
htmlText += " [";
if (i == paginationMetadata.currentPage)
{
htmlText += i.ToPersianNumbers();
}
else
{
htmlText += $"<a href=\"{routeStartWithQueryStrings.Replace("\"", "%22")}&amp;page={i}\">{i.ToPersianNumbers()}</a>";
}
htmlText += "] ";
}
}
if (paginationMetadata.totalPages > (paginationMetadata.currentPage + 2))
{
htmlText += $"… [<a href=\"{routeStartWithQueryStrings.Replace("\"", "%22")}&amp;page={paginationMetadata.totalPages}\">صفحهٔ آخر</a>]";
}
}
htmlText += $"</p>{Environment.NewLine}";
return htmlText;
}
}
}

View File

@ -8,8 +8,8 @@
}, },
"AllowedHosts": "*", "AllowedHosts": "*",
"GoogleAnalyticsCode": "", "GoogleAnalyticsCode": "",
"APIRoot": "http://130.185.76.215:8080", "APIRoot": "https://api.ganjoor.net",
"GlobalAPIRoot": "http://130.185.76.215:8080", "GlobalAPIRoot": "https://api.ganjoor.net",
"SiteUrl": "http://localhost:33081", "SiteUrl": "http://localhost:33081",
"MockSpotify": "False", "MockSpotify": "False",
"Spotify": { "Spotify": {