#113 and a fix for rhymes page

This commit is contained in:
Hamid Reza Mohammadi 2021-05-12 08:32:21 +04:30
parent 559a3fe45d
commit 39027ac835
5 changed files with 238 additions and 9 deletions

View File

@ -152,6 +152,8 @@
</div>
<partial name="_InlineLoginPartialForSearch" model="Model" />
<partial name="_FooterPartial" model="null" />
</div>

View File

@ -1,14 +1,23 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using DNTPersianUtils.Core;
using GanjooRazor.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using RMuseum.Models.Auth.Memory;
using RMuseum.Models.Ganjoor.ViewModels;
using RMuseum.Services;
using RSecurityBackend.Models.Auth.Memory;
using RSecurityBackend.Models.Auth.ViewModels;
using RSecurityBackend.Models.Generic;
namespace GanjooRazor.Pages
@ -27,16 +36,24 @@ namespace GanjooRazor.Pages
/// </summary>
private readonly IGanjoorService _ganjoorService;
/// <summary>
/// HttpClient instance
/// </summary>
private readonly HttpClient _httpClient;
/// <summary>
/// constructor
/// </summary>
/// <param name="memoryCache"></param>
/// <param name="ganjoorService"></param>
public SearchModel(IMemoryCache memoryCache, IGanjoorService ganjoorService)
/// <param name="httpClient"></param>
public SearchModel(IMemoryCache memoryCache, IGanjoorService ganjoorService, HttpClient httpClient)
{
_memoryCache = memoryCache;
_ganjoorService = ganjoorService;
_httpClient = httpClient;
}
public List<GanjoorPoetViewModel> Poets { get; set; }
@ -48,6 +65,14 @@ namespace GanjooRazor.Pages
public List<GanjoorPoemCompleteViewModel> Poems { get; set; }
public string PagingToolsHtml { get; set; }
/// <summary>
/// is logged on
/// </summary>
public bool LoggedIn { get; set; }
[BindProperty]
public LoginViewModel LoginViewModel { get; set; }
private async Task preparePoets(bool includeBio)
{
var cacheKey = $"/api/ganjoor/poets?includeBio={includeBio}";
@ -81,8 +106,10 @@ namespace GanjooRazor.Pages
Poet = poet;
}
public async Task<IActionResult> OnGet()
public async Task<IActionResult> OnGetAsync()
{
LoggedIn = !string.IsNullOrEmpty(Request.Cookies["Token"]);
Query = Request.Query["s"].ApplyCorrectYeKe().Trim();
PoetId = string.IsNullOrEmpty(Request.Query["author"]) ? 0 : int.Parse(Request.Query["author"]);
CatId = string.IsNullOrEmpty(Request.Query["cat"]) ? 0 : int.Parse(Request.Query["cat"]);
@ -127,7 +154,7 @@ namespace GanjooRazor.Pages
);
Poems = new List<GanjoorPoemCompleteViewModel>(searchRes.Result.Items);
Poems = searchRes.Result.Items == null ? new List<GanjoorPoemCompleteViewModel>() : new List<GanjoorPoemCompleteViewModel>(searchRes.Result.Items);
if (Poems != null)
{
// highlight searched word
@ -201,7 +228,7 @@ namespace GanjooRazor.Pages
{
string htmlText = "<p style=\"text-align: center;\">";
if (paginationMetadata.totalPages > 1)
if (paginationMetadata != null && paginationMetadata.totalPages > 1)
{
if (paginationMetadata.currentPage > 3)
{
@ -232,6 +259,100 @@ namespace GanjooRazor.Pages
htmlText += $"</p>{Environment.NewLine}";
return htmlText;
}
/// <summary>
/// Login
/// </summary>
/// <returns></returns>
public async Task<IActionResult> OnPostLoginAsync()
{
if (!ModelState.IsValid)
{
return BadRequest();
}
LoginViewModel.ClientAppName = "GanjooRazor";
LoginViewModel.Language = "fa-IR";
var stringContent = new StringContent(JsonConvert.SerializeObject(LoginViewModel), Encoding.UTF8, "application/json");
var loginUrl = $"{APIRoot.Url}/api/users/login";
var response = await _httpClient.PostAsync(loginUrl, stringContent);
if (response.StatusCode != HttpStatusCode.OK)
{
return Redirect($"/login?redirect={Request.Path}&error={await response.Content.ReadAsStringAsync()}");
}
LoggedOnUserModel loggedOnUser = JsonConvert.DeserializeObject<LoggedOnUserModel>(await response.Content.ReadAsStringAsync());
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(365),
};
Response.Cookies.Append("UserId", loggedOnUser.User.Id.ToString(), cookieOption);
Response.Cookies.Append("SessionId", loggedOnUser.SessionId.ToString(), cookieOption);
Response.Cookies.Append("Token", loggedOnUser.Token, cookieOption);
Response.Cookies.Append("Username", loggedOnUser.User.Username, cookieOption);
Response.Cookies.Append("Name", $"{loggedOnUser.User.FirstName} {loggedOnUser.User.SureName}", cookieOption);
Response.Cookies.Append("NickName", $"{loggedOnUser.User.NickName}", cookieOption);
bool canEditContent = false;
var ganjoorEntity = loggedOnUser.SecurableItem.Where(s => s.ShortName == RMuseumSecurableItem.GanjoorEntityShortName).SingleOrDefault();
if (ganjoorEntity != null)
{
var op = ganjoorEntity.Operations.Where(o => o.ShortName == SecurableItem.ModifyOperationShortName).SingleOrDefault();
if (op != null)
{
canEditContent = op.Status;
}
}
Response.Cookies.Append("CanEdit", canEditContent.ToString(), cookieOption);
return Redirect(Request.Path);
}
/// <summary>
/// logout
/// </summary>
/// <returns></returns>
public async Task<IActionResult> OnPostLogoutAsync()
{
if (!ModelState.IsValid)
{
return BadRequest();
}
if (!string.IsNullOrEmpty(Request.Cookies["SessionId"]) && !string.IsNullOrEmpty(Request.Cookies["UserId"]))
{
using (HttpClient secureClient = new HttpClient())
{
if (await GanjoorSessionChecker.PrepareClient(secureClient, Request, Response))
{
var logoutUrl = $"{APIRoot.Url}/api/users/delsession?userId={Request.Cookies["UserId"]}&sessionId={Request.Cookies["SessionId"]}";
await secureClient.DeleteAsync(logoutUrl);
}
}
}
var cookieOption = new CookieOptions()
{
Expires = DateTime.Now.AddDays(-1)
};
foreach (var cookieName in new string[] { "UserId", "SessionId", "Token", "Username", "Name", "NickName", "CanEdit" })
{
if (Request.Cookies[cookieName] != null)
{
Response.Cookies.Append(cookieName, "", cookieOption);
}
}
return Redirect(Request.Path);
}
}
}

View File

@ -0,0 +1,106 @@
@model GanjooRazor.Pages.SearchModel
@if (Model.LoggedIn)
{
<div class="fab">
<span class="fab-action-button">
<i class="fab-action-button-loggedin__icon"></i>
</span>
<ul class="fab-buttons">
<li class="fab-buttons__item">
<a asp-page="Index" asp-area="User" class="fab-buttons__link" data-tooltip="پیشخان">
<i class="icon-material icon-material_panel"></i>
</a>
</li>
<li class="fab-buttons__item">
<form method="post" id="logoutform" action="?handler=Logout">
</form>
<a href="javascript:document.getElementById('logoutform').submit();" class="fab-buttons__link" data-tooltip="خروج">
<i class="icon-material icon-material_exit"></i>
</a>
</li>
</ul>
</div>
}
else
{
<div class="fab">
<span class="fab-action-button">
<a role="button" class="actionlink" onclick="document.getElementById('id01').style.display='block'" data-tooltip="ورود کاربر" title="ورود کاربر">
<i class="fab-action-button__icon"></i>
</a>
</span>
</div>
<!-- The Modal -->
<div id="id01" class="modal">
<span onclick="document.getElementById('id01').style.display='none'"
class="close" title="بستن">&times;</span>
<!-- Modal Content -->
<form class="modal-content animate" method="post" action="?handler=Login">
<div class="imgcontainer">
<img src="/image/login.png" alt="گنجور" class="avatar">
</div>
<table style="width:100%">
<tr>
<td colspan="2">
<h2>
ورود به گنجور
</h2>
</td>
</tr>
<tr>
<td>
<span class="inputlabel">پست الکترونیکی: </span>
</td>
<td>
<input type="email" style="text-align:left;direction:ltr;width:100%" placeholder="پست الکترونیکی" asp-for="LoginViewModel.Username" />
</td>
</tr>
<tr>
<td>
<span class="inputlabel">گذرواژه: </span>
</td>
<td>
<input type="password" id="password" style="text-align:left;direction:ltr;width:100%" placeholder="گذرواژه" asp-for="LoginViewModel.Password" />
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="submit" style="width:100%;cursor:pointer" id="submit" value="ورود" /></td>
</tr>
<tr>
<td></td>
<td>
<table style="width:100%; margin:0">
<tr>
<td>
<input type="button" onclick="location.href='https://museum.ganjoor.net/signup'" class="cancelbtn" style="width:100%;text-align:center;cursor:pointer" value="ثبت نام" />
</td>
<td>
<input type="button" onclick="document.getElementById('id01').style.display='none'" style="width: 100%; text-align: center; cursor: pointer" value="انصراف" />
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2">
<p>
اگر پیشتر در <a href="https://museum.ganjoor.net">گنجینه</a> یا <a href="https://museum.ganjoor.net">پیشخان خوانشگران</a> گنجور ثبت نام کرده‌اید می‌توانید با همان اطلاعات کاربری به گنجور وارد شوید.
</p>
</td>
</tr>
</table>
</form>
</div>
}

View File

@ -29,7 +29,7 @@ namespace GanjooRazor.Pages
}
string metre = Request.Query["v"];
int poetId = string.IsNullOrEmpty(Request.Query["a"]) ? 0 : int.Parse(Request.Query["a"]);
int? poetId = string.IsNullOrEmpty(Request.Query["a"]) ? null : int.Parse(Request.Query["a"]);
var poemsRes = await _ganjoorService.GetSimilarPoems
(
@ -39,12 +39,12 @@ namespace GanjooRazor.Pages
PageSize = 20
},
metre: metre,
rhyme: null,
rhyme: "",
poetId: poetId
);
GanjoorPage.Title = "شعرهای ";
if (poetId != 0)
if (poetId != null)
{
GanjoorPage.Title += $"{Poets.Where(p => p.Id == poetId).Single().Name} ";
}
@ -56,7 +56,7 @@ namespace GanjooRazor.Pages
string htmlText = "";
if (poetId != 0)
if (poetId != null)
{
htmlText += $"<div class=\"sitem\" id=\"all\">{Environment.NewLine}";
htmlText += $"<h2>{Environment.NewLine}";

View File

@ -7,7 +7,7 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RSecurityBackend", "RSecuri
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "RMuseum", "RMuseum\RMuseum.csproj", "{113EF3DE-E8A9-40EF-9DA0-8DFABB3CDD68}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GanjooRazor", "GanjooRazor\GanjooRazor.csproj", "{48F9CDFA-625F-4743-BF21-BD556F6F33E8}"
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GanjooRazor", "GanjooRazor\GanjooRazor.csproj", "{48F9CDFA-625F-4743-BF21-BD556F6F33E8}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution