Files
mapo-core/MP.Data/Services/MessageService.cs
T
2023-12-13 18:18:45 +01:00

692 lines
20 KiB
C#

using Blazored.LocalStorage;
using Blazored.SessionStorage;
using EgwCoreLib.Utils;
using Microsoft.Extensions.Configuration;
using MP.Data.DatabaseModels;
using MP.Data.DTO;
using Newtonsoft.Json;
using NLog;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace MP.Data.Services
{
public class MessageService
{
#region Public Fields
public const string KeyCommDtRif = "DtRifComm";
public const string KeyCommText = "ValComm";
public int orarioDip = 0;
#endregion Public Fields
#region Public Constructors
public MessageService(IConfiguration configuration, ILocalStorageService genLocalStorage, ISessionStorageService sessStore, TabDataService tdService, SharedMemService smServ)
{
_configuration = configuration;
// gestione sessioni in browser
localStorage = genLocalStorage;
sessionStore = sessStore;
TDService = tdService;
SMService = smServ;
// setup compoenti REDIS
redisConn = ConnectionMultiplexer.Connect(_configuration.GetConnectionString("Redis"));
redisDb = redisConn.GetDatabase();
}
#endregion Public Constructors
#region Public Events
public event Action EA_OperUpdated = null!;
public event Action EA_PageUpdated = null!;
public event Action EA_ResetFooterTimer = null!;
#endregion Public Events
#if false
protected bool _tReset { get; set; } = false;
protected bool tReset
{
get => _tReset;
set
{
if (_tReset != value)
{
_tReset = value;
resetTimer();
}
}
}
protected void resetTimer()
{
if (EA_ResetFooterTimer != null)
{
EA_ResetFooterTimer?.Invoke();
}
}
#endif
#region Public Properties
public string CognomeNome
{
get
{
string answ = "";
//int answ = -1;
if (_rigaOper != null)
{
answ = $"{_rigaOper.Cognome} {_rigaOper.Nome}";
}
return answ;
}
}
/// <summary>
/// Dizionario macchine
/// </summary>
public Dictionary<string, string> DictMacchine
{
get
{
Dictionary<string, string> answ = new Dictionary<string, string>();
var pUpd = Task.Run(async () =>
{
answ = await localStorage.GetItemAsync<Dictionary<string, string>>(KeyMacDict);
});
pUpd.Wait();
return answ;
}
set
{
var pUpd = Task.Run(async () =>
{
await localStorage.SetItemAsync(KeyMacDict, value);
});
pUpd.Wait();
}
}
public DateTime dtLastAction { get; set; } = DateTime.Now;
public DateTime dtLastSave { get; set; } = DateTime.Now;
public int MatrOpr
{
get
{
int answ = -1;
if (_rigaOper != null)
{
answ = _rigaOper.MatrOpr;
}
return answ;
}
}
public AnagOperatoriModel? RigaOper
{
get => _rigaOper;
set
{
// salvo
_rigaOper = value;
if (EA_OperUpdated != null)
{
EA_OperUpdated?.Invoke();
}
}
}
public string UserAuthKey
{
get
{
string answ = "";
if (_rigaOper != null)
{
answ = _rigaOper.authKey;
}
return answ;
}
}
/// <summary>
/// Dizionario totale preferenze utente
/// </summary>
public Dictionary<string, string> UsersPrefDict
{
get => redisHashDictGet((RedisKey)$"{redisBaseKey}:{MatrOpr}");
set => redisHashDictSet((RedisKey)$"{redisBaseKey}:{MatrOpr}", value);
}
#endregion Public Properties
#region Public Methods
public async Task ClearLocalStor()
{
await localStorage.ClearAsync();
}
public async Task ClearSessionStor()
{
await sessionStore.ClearAsync();
}
/// <summary>
/// DateTime riferimento evento x commento fermata
/// </summary>
/// <param name="remAfter"></param>
/// <returns></returns>
public async Task<DateTime> CommentoDtRifGet(bool remAfter)
{
DateTime answ = DateTime.Now;
bool hasKey = await sessionStore.ContainKeyAsync(KeyCommDtRif);
if (hasKey)
{
answ = await sessionStore.GetItemAsync<DateTime>(KeyCommDtRif);
// svuoto data registrata se richiesto
if (remAfter)
{
await sessionStore.RemoveItemAsync(KeyCommDtRif);
}
}
return answ;
}
/// <summary>
/// Macchine attualmente selezionata
/// </summary>
public async Task CommentoDtRifSet(DateTime DtRif)
{
await sessionStore.SetItemAsync(KeyCommDtRif, DtRif);
}
/// <summary>
/// Commento fermata x recupero in editing
/// </summary>
/// <param name="remAfter"></param>
/// <returns></returns>
public async Task<string> CommentoValGet(bool remAfter)
{
string answ = "";
bool hasKey = await sessionStore.ContainKeyAsync(KeyCommText);
if (hasKey)
{
// recupero
answ = await sessionStore.GetItemAsync<string>(KeyCommText);
// svuoto data registrata se richiesto
if (remAfter)
{
await sessionStore.RemoveItemAsync(KeyCommText);
}
}
return answ;
}
/// <summary>
/// Macchine attualmente selezionata
/// </summary>
public async Task CommentoValSet(string Valore)
{
await sessionStore.SetItemAsync(KeyCommText, Valore);
}
public string DecryptData(string encData)
{
return SteamCrypto.DecryptString(encData, Constants.passPhrase);
}
public async Task<bool> DoLogIn(string decodValue, bool saveOpr)
{
bool answ = false;
//expDays = SMService.GetConfInt("cookieDayExpire");
//var expDT = DateTime.Now.AddDays(expDays);
var devGuid = await GetCurrDevGuidLSAsync();
// decifro i valori..
var decrVal = DecryptData(decodValue);
var opData = JsonConvert.DeserializeObject<userTknDTO>(decrVal);
if (opData != null)
{
var rigaOpr = await TDService.OperatoreSearch(opData.currOpr.MatrOpr, opData.currOpr.authKey);
if (rigaOpr != null)
{
userTknDTO newUserTkn = new userTknDTO()
{
currOpr = rigaOpr,
DevGuid = devGuid
};
var jsonTkn = JsonConvert.SerializeObject(newUserTkn);
string hash = TDService.EncryptData(jsonTkn);
RigaOper = rigaOpr;
await SetLastMatrOprAsync(rigaOpr.MatrOpr);
await SetCurrOperDtoLSAsync(hash);
if (saveOpr)
{
await TDService.OperatoreSetRedis(rigaOpr.MatrOpr, hash, devGuid);
}
answ = true;
}
}
return answ;
}
public string EncryptData(string rawData)
{
return SteamCrypto.EncryptString(rawData, Constants.passPhrase);
}
/// <summary>
/// Restituisce il record device GUID da localstorage
/// </summary>
/// <returns></returns>
public async Task<Guid> GetCurrDevGuidLSAsync()
{
Guid answ = new Guid();
var result = await localStorage.GetItemAsync<string>("devGuid");
if (result != null)
{
answ = Guid.Parse(result);
}
return answ;
}
/// <summary>
/// Restituisce il record OperatoreDTO da localstorage
/// </summary>
/// <returns></returns>
public async Task<string> GetCurrOperDtoLSAsync()
{
string answ = "";
var result = await localStorage.GetItemAsync<string>("currTkn");
if (result != null)
{
answ = result;
}
return answ;
}
/// <summary>
/// Restituisce il valore Ipv4 del Device da localstorage
/// </summary>
/// <returns></returns>
public async Task<string> getDevIpAsync()
{
string answ = "";
var result = await localStorage.GetItemAsync<string>(KeyDevIp4);
if (result != null)
{
answ = result;
}
return answ;
}
/// <summary>
/// Restituisce il valore di DeviceSecret da localstorage
/// </summary>
/// <returns></returns>
public async Task<string> getDevSecretAsync()
{
string answ = "";
var result = await localStorage.GetItemAsync<string>(KeyDevSec);
if (result != null)
{
answ = result;
}
return answ;
}
/// <summary>
/// Restituisce ultima matrOpr registrata da localstorage
/// </summary>
/// <returns></returns>
public async Task<int> GetLastMatrOprAsync()
{
int answ = -1;
var result = await localStorage.GetItemAsync<string>("lastMatrOpr");
if (!string.IsNullOrEmpty(result))
{
answ = int.Parse(result);
}
return answ;
}
/// <summary>
/// Recupero dati MSE x macchina
/// </summary>
/// <param name="idxMacchina"></param>
/// <returns></returns>
public async Task<MappaStatoExpl?> GetMachineMse(string idxMacchina)
{
MappaStatoExpl answ = null;
string rawData = await localStorage.GetItemAsync<string>(machineMse(idxMacchina));
if (rawData != "")
{
answ = JsonConvert.DeserializeObject<MappaStatoExpl>(rawData);
}
return answ;
}
/// <summary>
/// Macchine attualmente selezionata
/// </summary>
public async Task<string> IdxMaccGet()
{
return await localStorage.GetItemAsync<string>("CurrMach");
}
/// <summary>
/// Imposta Macchina
/// </summary>
public async Task IdxMaccSet(string machSel)
{
await localStorage.SetItemAsync("CurrMach", machSel);
}
/// <summary>
/// Scrive sul local storage pagina corrente
/// </summary>
public async Task<string> LastOpenedPageGet()
{
return await localStorage.GetItemAsync<string>("LastPage");
}
/// <summary>
/// Ottiene sul local storage pagina corrente
/// </summary>
public async Task LastOpenedPageSet(string lastPage)
{
await localStorage.SetItemAsync("LastPage", lastPage);
}
/// <summary>
/// Effettua salvataggio in localstorage dei dati MSE correnti
/// </summary>
/// <param name="currListMSE"></param>
/// <returns></returns>
/// <exception cref="NotImplementedException"></exception>
public async Task SaveMse(List<MappaStatoExpl> currListMSE)
{
foreach (var item in currListMSE)
{
string serVal = JsonConvert.SerializeObject(item);
await localStorage.SetItemAsync(machineMse(item.IdxMacchina), serVal);
}
}
/// <summary>
/// Verifico esistenza chiave in session store
/// </summary>
/// <param name="keyName"></param>
/// <returns></returns>
public async Task<bool> SessHasVal(string keyName)
{
bool hasKey = await sessionStore.ContainKeyAsync(keyName);
return hasKey;
}
/// <summary>
/// scrive il record OperatoreDTO nel localstorage
/// </summary>
/// <returns></returns>
public async Task<bool> SetCurrOperDtoLSAsync(string currTkn)
{
bool answ = false;
await localStorage.SetItemAsync("currTkn", currTkn);
answ = true;
return answ;
}
/// <summary>
/// scrive il record Device GUID nel localstorage
/// </summary>
/// <returns></returns>
public async Task<bool> SetCurrDevGuidLSAsync(Guid currDevGuid)
{
bool answ = false;
await localStorage.SetItemAsync("devGuid", currDevGuid.ToString());
answ = true;
return answ;
}
/// <summary>
/// Scrive il valore di IPV4 del device nel localstoragee
/// </summary>
/// <param name="newVal"></param>
/// <returns></returns>
public async Task<bool> setDevIpv4Async(string newVal)
{
bool answ = false;
try
{
await localStorage.SetItemAsync(KeyDevIp4, newVal);
answ = true;
}
catch (Exception ex)
{
Log.Error($"Eccezione in setDevIpv4Async{Environment.NewLine}{ex}");
}
return answ;
}
/// <summary>
/// Scrive il valore di DeviceSecret nel localstoragee
/// </summary>
/// <param name="newVal"></param>
/// <returns></returns>
public async Task<bool> setDevSecretAsync(string newVal)
{
bool answ = false;
try
{
await localStorage.SetItemAsync(KeyDevSec, newVal);
answ = true;
}
catch (Exception ex)
{
Log.Error($"Eccezione in setDevSecretAsync{Environment.NewLine}{ex}");
}
return answ;
}
/// <summary>
/// Salva matrOpr nel localstorage
/// </summary>
/// <returns></returns>
public async Task<bool> SetLastMatrOprAsync(int matrOpr)
{
bool answ = false;
await localStorage.SetItemAsync("lastMatrOpr", matrOpr);
answ = true;
return answ;
}
/// <summary>
/// Recupero singola preferenza utente
/// </summary>
/// <param name="chiave"></param>
/// <returns></returns>
public string UserPrefGet(string chiave)
{
string answ = "";
var currDict = UsersPrefDict;
if (currDict.ContainsKey(chiave))
{
answ = currDict[chiave];
}
return answ;
}
/// <summary>
/// Salvo singola preferenza utente
/// </summary>
/// <param name="chiave"></param>
/// <param name="valore"></param>
/// <returns></returns>
public bool UserPrefSet(string chiave, string valore)
{
bool done = false;
var currDict = UsersPrefDict;
if (currDict.ContainsKey(chiave))
{
currDict[chiave] = valore;
}
else
{
currDict.Add(chiave, valore);
}
UsersPrefDict = currDict;
return done;
}
/// <summary>
/// Recupero singola preferenza utente se presente, oppure imposto quella di default
/// indicata e la rendo
/// </summary>
/// <param name="chiave"></param>
/// <returns></returns>
public string UserPrefSetup(string chiave, string defValue)
{
string answ = defValue;
var currDict = UsersPrefDict;
if (currDict.ContainsKey(chiave))
{
answ = currDict[chiave];
}
else
{
if (MatrOpr > 0)
{
UserPrefSet(chiave, defValue);
}
}
return answ;
}
#endregion Public Methods
#region Protected Fields
protected const string KeyDevIp4 = "DevIpv4";
protected const string KeyDevSec = "DevSec";
protected const string KeyMacDict = "MachineDict";
protected static IConfiguration _configuration = null!;
/// <summary>
/// Oggetto per connessione a REDIS
/// </summary>
protected ConnectionMultiplexer redisConn = null!;
/// <summary>
/// Oggetto DB redis da impiegare x chiamate R/W
/// </summary>
protected IDatabase redisDb = null!;
#endregion Protected Fields
#region Protected Properties
protected int expDays { get; set; } = 0;
protected ILocalStorageService localStorage { get; set; } = null!;
protected ISessionStorageService sessionStore { get; set; } = null!;
protected SharedMemService SMService { get; set; } = null!;
protected TabDataService TDService { get; set; } = null!;
#endregion Protected Properties
#region Private Fields
private AnagOperatoriModel? _rigaOper;
/// <summary>
/// Durata cache lunga IN SECONDI
/// </summary>
private int cacheTtlLong = 60 * 5;
/// <summary>
/// Durata cache breve IN SECONDI
/// </summary>
private int cacheTtlShort = 60 * 1;
private Logger Log = LogManager.GetCurrentClassLogger();
private string redisBaseKey = "MP:TAB:User";
private Random rnd = new Random();
#endregion Private Fields
#region Private Properties
private Dictionary<string, string> UserPrefs { get; set; } = new Dictionary<string, string>();
#endregion Private Properties
#region Private Methods
private string machineMse(string idxMacc)
{
return $"MSE_{idxMacc}";
}
/// <summary>
/// Recupero HashSet redis come Dictionary
/// </summary>
/// <param name="currKey"></param>
/// <param name="dict"></param>
private Dictionary<string, string> redisHashDictGet(RedisKey currKey)
{
Dictionary<string, string> answ = new Dictionary<string, string>();
try
{
answ = redisDb
.HashGetAll(currKey)
.ToDictionary(x => $"{x.Name}", x => $"{x.Value}");
}
catch (Exception exc)
{
Log.Info($"Errore redisHashDictGet | currKey: {currKey}{Environment.NewLine}{exc}");
}
return answ;
}
/// <summary>
/// Salvataggio Dictionary come HashSet Redis
/// </summary>
/// <param name="currKey"></param>
/// <param name="dict"></param>
private bool redisHashDictSet(RedisKey currKey, Dictionary<string, string> dict)
{
bool fatto = false;
try
{
HashEntry[] data2ins = new HashEntry[dict.Count];
int i = 0;
foreach (KeyValuePair<string, string> kvp in dict)
{
data2ins[i] = new HashEntry(kvp.Key, kvp.Value);
i++;
}
// salvo!
redisDb.HashSet(currKey, data2ins);
fatto = true;
}
catch (Exception exc)
{
Log.Error($"Eccezione in redisHashDictSet | currKey: {currKey}{Environment.NewLine}{exc}");
}
return fatto;
}
#endregion Private Methods
}
}