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;
}
}
///
/// Dizionario macchine
///
public Dictionary DictMacchine
{
get
{
Dictionary answ = new Dictionary();
var pUpd = Task.Run(async () =>
{
answ = await localStorage.GetItemAsync>(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;
}
}
///
/// Dizionario totale preferenze utente
///
public Dictionary 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();
}
///
/// DateTime riferimento evento x commento fermata
///
///
///
public async Task CommentoDtRifGet(bool remAfter)
{
DateTime answ = DateTime.Now;
bool hasKey = await sessionStore.ContainKeyAsync(KeyCommDtRif);
if (hasKey)
{
answ = await sessionStore.GetItemAsync(KeyCommDtRif);
// svuoto data registrata se richiesto
if (remAfter)
{
await sessionStore.RemoveItemAsync(KeyCommDtRif);
}
}
return answ;
}
///
/// Macchine attualmente selezionata
///
public async Task CommentoDtRifSet(DateTime DtRif)
{
await sessionStore.SetItemAsync(KeyCommDtRif, DtRif);
}
///
/// Commento fermata x recupero in editing
///
///
///
public async Task CommentoValGet(bool remAfter)
{
string answ = "";
bool hasKey = await sessionStore.ContainKeyAsync(KeyCommText);
if (hasKey)
{
// recupero
answ = await sessionStore.GetItemAsync(KeyCommText);
// svuoto data registrata se richiesto
if (remAfter)
{
await sessionStore.RemoveItemAsync(KeyCommText);
}
}
return answ;
}
///
/// Macchine attualmente selezionata
///
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 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(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);
}
///
/// Restituisce il record device GUID da localstorage
///
///
public async Task GetCurrDevGuidLSAsync()
{
Guid answ = new Guid();
var result = await localStorage.GetItemAsync("devGuid");
if (result != null)
{
answ = Guid.Parse(result);
}
return answ;
}
///
/// Restituisce il record OperatoreDTO da localstorage
///
///
public async Task GetCurrOperDtoLSAsync()
{
string answ = "";
var result = await localStorage.GetItemAsync("currTkn");
if (result != null)
{
answ = result;
}
return answ;
}
///
/// Restituisce il valore Ipv4 del Device da localstorage
///
///
public async Task getDevIpAsync()
{
string answ = "";
var result = await localStorage.GetItemAsync(KeyDevIp4);
if (result != null)
{
answ = result;
}
return answ;
}
///
/// Restituisce il valore di DeviceSecret da localstorage
///
///
public async Task getDevSecretAsync()
{
string answ = "";
var result = await localStorage.GetItemAsync(KeyDevSec);
if (result != null)
{
answ = result;
}
return answ;
}
///
/// Restituisce ultima matrOpr registrata da localstorage
///
///
public async Task GetLastMatrOprAsync()
{
int answ = -1;
var result = await localStorage.GetItemAsync("lastMatrOpr");
if (!string.IsNullOrEmpty(result))
{
answ = int.Parse(result);
}
return answ;
}
///
/// Recupero dati MSE x macchina
///
///
///
public async Task GetMachineMse(string idxMacchina)
{
MappaStatoExpl answ = null;
string rawData = await localStorage.GetItemAsync(machineMse(idxMacchina));
if (rawData != "")
{
answ = JsonConvert.DeserializeObject(rawData);
}
return answ;
}
///
/// Macchine attualmente selezionata
///
public async Task IdxMaccGet()
{
return await localStorage.GetItemAsync("CurrMach");
}
///
/// Imposta Macchina
///
public async Task IdxMaccSet(string machSel)
{
await localStorage.SetItemAsync("CurrMach", machSel);
}
///
/// Scrive sul local storage pagina corrente
///
public async Task LastOpenedPageGet()
{
return await localStorage.GetItemAsync("LastPage");
}
///
/// Ottiene sul local storage pagina corrente
///
public async Task LastOpenedPageSet(string lastPage)
{
await localStorage.SetItemAsync("LastPage", lastPage);
}
///
/// Effettua salvataggio in localstorage dei dati MSE correnti
///
///
///
///
public async Task SaveMse(List currListMSE)
{
foreach (var item in currListMSE)
{
string serVal = JsonConvert.SerializeObject(item);
await localStorage.SetItemAsync(machineMse(item.IdxMacchina), serVal);
}
}
///
/// Verifico esistenza chiave in session store
///
///
///
public async Task SessHasVal(string keyName)
{
bool hasKey = await sessionStore.ContainKeyAsync(keyName);
return hasKey;
}
///
/// scrive il record OperatoreDTO nel localstorage
///
///
public async Task SetCurrOperDtoLSAsync(string currTkn)
{
bool answ = false;
await localStorage.SetItemAsync("currTkn", currTkn);
answ = true;
return answ;
}
///
/// scrive il record Device GUID nel localstorage
///
///
public async Task SetCurrDevGuidLSAsync(Guid currDevGuid)
{
bool answ = false;
await localStorage.SetItemAsync("devGuid", currDevGuid.ToString());
answ = true;
return answ;
}
///
/// Scrive il valore di IPV4 del device nel localstoragee
///
///
///
public async Task 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;
}
///
/// Scrive il valore di DeviceSecret nel localstoragee
///
///
///
public async Task 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;
}
///
/// Salva matrOpr nel localstorage
///
///
public async Task SetLastMatrOprAsync(int matrOpr)
{
bool answ = false;
await localStorage.SetItemAsync("lastMatrOpr", matrOpr);
answ = true;
return answ;
}
///
/// Recupero singola preferenza utente
///
///
///
public string UserPrefGet(string chiave)
{
string answ = "";
var currDict = UsersPrefDict;
if (currDict.ContainsKey(chiave))
{
answ = currDict[chiave];
}
return answ;
}
///
/// Salvo singola preferenza utente
///
///
///
///
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;
}
///
/// Recupero singola preferenza utente se presente, oppure imposto quella di default
/// indicata e la rendo
///
///
///
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!;
///
/// Oggetto per connessione a REDIS
///
protected ConnectionMultiplexer redisConn = null!;
///
/// Oggetto DB redis da impiegare x chiamate R/W
///
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;
///
/// Durata cache lunga IN SECONDI
///
private int cacheTtlLong = 60 * 5;
///
/// Durata cache breve IN SECONDI
///
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 UserPrefs { get; set; } = new Dictionary();
#endregion Private Properties
#region Private Methods
private string machineMse(string idxMacc)
{
return $"MSE_{idxMacc}";
}
///
/// Recupero HashSet redis come Dictionary
///
///
///
private Dictionary redisHashDictGet(RedisKey currKey)
{
Dictionary answ = new Dictionary();
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;
}
///
/// Salvataggio Dictionary come HashSet Redis
///
///
///
private bool redisHashDictSet(RedisKey currKey, Dictionary dict)
{
bool fatto = false;
try
{
HashEntry[] data2ins = new HashEntry[dict.Count];
int i = 0;
foreach (KeyValuePair 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
}
}