ApiMantenzioniV2/ApiPolo/Services/MyCronJob1.cs

666 lines
23 KiB
C#

using FirebaseAdmin.Messaging;
using FirebaseAdmin;
using Google.Apis.Auth.OAuth2;
using static ApiPolo.Controllers.PoloController;
using static Google.Apis.Requests.BatchRequest;
using System.Text;
using ApiPolo.Models.Marrocco_dbcontext;
using ApiPolo.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;
using System.Net;
using Newtonsoft.Json;
using RestSharp;
using System.Net.Http.Headers;
using Nancy.Json;
namespace ApiPolo.Services
{
/* https://www.netiq.com/documentation/cloud-manager-2-5/ncm-reference/data/bexyssf.html sintassi intervalli cron */
/// <summary></summary>
public class MyCronJob1 : CronJobService
{
/// <summary>Configuration</summary>
public IConfiguration Configuration { get; }
/// <summary>Startup</summary>
private readonly ILogger<MyCronJob1> _logger;
/// <summary>Costruttore</summary>
public MyCronJob1(IScheduleConfig<MyCronJob1> config, ILogger<MyCronJob1> logger, IConfiguration configuration) : base(config.CronExpression, config.TimeZoneInfo)
{
_logger = logger;
Configuration = configuration;
}
/// <summary></summary>
public override Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("MessagePushJob 1 starts.");
return base.StartAsync(cancellationToken);
}
/// <summary></summary>
public override Task DoWork(CancellationToken cancellationToken)
{
_logger.LogInformation("{now} MessagePushJob 1 is working.", DateTime.Now.ToString("T"));
try
{
//cerco le notifiche da mandare
List<Notifiche> l = readNotify();
//List<Notifiche> l=new List<Notifiche> ();
foreach (Notifiche n in l)
{
StringBuilder sb = new StringBuilder();
sb.Append("tecnico: " + n.picodtec + " ");
sb.Append("azienda: " + n.picodazi + " ");
sb.Append("data: " + n.piserial + " ");
_logger.LogInformation(sb.ToString());
}
//se ci sono cerco il token dispositivo per l'invio
//e li metto in una lista di oggetti pronti per l'invio
List<MexPush> ll = fillMex(l);
foreach (MexPush p in ll)
{
//PushFCM_Sync(p.token, "Title", p.body);
//PushFCM_SyncNew(null, "Title", "test");
GenerateFCM_Auth_SendNotifcn(p.token);
}
//TODO logica di aggiornamento della tabella delle notifiche
//markNotify(ll);
markNotify2(l);
}
catch (Exception ex)
{
string errmsg = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
_logger.LogInformation(" MessagePushJob KO !!!! :"+errmsg, string.Empty);
}
return Task.CompletedTask;
}
/// <summary></summary>
public override Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("MessagePushJob 1 is stopping.");
return base.StopAsync(cancellationToken);
}
private List<Notifiche> readNotify()
{
List<Notifiche> lst = new List<Notifiche>();
#region Marrocco
var optionsBuilder = new DbContextOptionsBuilder<MARRO_NOTIFICHEDbContext>();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("MARRO"));
using (var dbContext = new MARRO_NOTIFICHEDbContext(optionsBuilder.Options))
{
var listaNot = dbContext.Notif.Where(t => t.pidattim == null&& t.picodazi!=null && t.picodazi.Equals("MARRO") && t.picodtec!=null && t.picodtec.Equals("ZZZ")).OrderBy(t=>t.piserial).Take(1).ToList();
foreach(Notifiche n in listaNot)
{
lst.Add(n);
}
}
#endregion
return lst;
}
private void markNotify(List<MexPush> lst)
{
#region MARRO
var optionsBuilder = new DbContextOptionsBuilder<MARRO_NOTIFICHEDbContext>();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("MARRO"));
using (var dbContext = new MARRO_NOTIFICHEDbContext(optionsBuilder.Options))
{
foreach (MexPush n in lst)
{
Notifiche r = n.notifi;
r.pidattim = DateTime.Now;
dbContext.Entry(r).State = EntityState.Modified;
dbContext.SaveChanges();
}
}
#endregion
}
private void markNotify2(List<Notifiche> lst)
{
#region MARRO
var optionsBuilder = new DbContextOptionsBuilder<MARRO_NOTIFICHEDbContext>();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("MARRO"));
using (var dbContext = new MARRO_NOTIFICHEDbContext(optionsBuilder.Options))
{
foreach (Notifiche n in lst)
{
Notifiche r = n;
r.pidattim = DateTime.Now;
dbContext.Entry(r).State = EntityState.Modified;
dbContext.SaveChanges();
}
}
#endregion
}
private List<MexPush> fillMex(List<Notifiche> lst)
{
List<MexPush> mess = new List<MexPush>();
var optionsBuilder = new DbContextOptionsBuilder<TokenDbContext>();
optionsBuilder.UseSqlServer(Configuration.GetConnectionString("ApiStr"));
foreach(Notifiche nn in lst)
{
using (var dbContext = new TokenDbContext(optionsBuilder.Options))
{
string rif = nn.piserial;
var t= dbContext.tok.Where(c=>c.usr.Equals(nn.picodtec)&& c.tenant.Equals(nn.picodazi)).ToList();
foreach (Token n in t)
{
MexPush m = new MexPush();
m.tenant = n.tenant;
m.usr = n.usr;
m.token = n.token;
m.body = rif;
m.notifi = nn;
mess.Add(m);
}
//TODO logica di aggiornamento della tabella delle notifiche
}
}
return mess;
}
//private void pushMex(string title,string body, string tokenDevice)
//{
// //string log = string.Empty;
// StringBuilder sb = new StringBuilder();
// string _title = title +"-"+ getCpccchk(4);
// string _body = body + "-" + DateTime.Now.ToString("yyyyMMddHHmmss");
// //_logger.LogInformation("{now} MessagePushJob is working.", DateTime.Now.ToString("T"));
// try
// {
// if (FirebaseApp.DefaultInstance == null)
// {
// FirebaseApp.Create(new AppOptions()
// {
// Credential = GoogleCredential.FromFile("private_key.json")
// });
// }
// //var registrationToken = "dDxUDIC3QcWytp6UeVMDyT:APA91bH9y0N7Iff39Ncv0m_EjJ-hv7YTWYaL_5P37-2dob2PRuArvpfl6kmrk10GO2eJiAQ2tVT3tZX9khUD-NPyfljGbpBn1iUyjbTpL6tDF-0IgJN960v95I4_2SWM_crtSH-ZrXAK";
// var registrationToken = tokenDevice;
// var message = new Message()
// {
// Apns = new ApnsConfig()
// {
// Aps = new Aps()
// {
// //Change this for the sound you would like
// Sound = "default"
// }
// },
// Android = new AndroidConfig()
// {
// Notification = new AndroidNotification()
// {
// Sound = "default",
// Priority = NotificationPriority.MAX
// },
// Data = new Dictionary<string, string>()
// {
// { "myData3", "1234522222" }
// }
// },
// Token = registrationToken,
// Data = new Dictionary<string, string>()
// {
// { "myData", "123457777" }
// },
// Notification = new Notification()
// {
// Title = _title,
// Body = _body
// }
// };
// string response = FirebaseMessaging.DefaultInstance.SendAsync(message).Result;
// //string response = FirebaseMessaging.DefaultInstance.SendMulticastAsync(msg2send).Result;
// sb.AppendLine("MessagePushJob OK");
// sb.AppendLine("response:" + response);
// sb.AppendLine("title:" + _title);
// sb.AppendLine("body:" + _body);
// sb.AppendLine("===================");
// _logger.LogInformation(sb.ToString());
// }
// catch (Exception ex)
// {
// string errmsg = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
// _logger.LogInformation(" MessagePushJob KO !!!! :", errmsg);
// }
// // return log;
//}
private string PushFCM_Notification(string deviceId, string title, string body)
{
StringBuilder sb = new StringBuilder();
string _title = title + "-" + getCpccchk(4);
string _body = body + "-" + DateTime.Now.ToString("yyyyMMddHHmmss");
try
{
string SERVER_API_KEY = "AAAAGBwLmNY:APA91bG5GmgYcaxsU8HrOqvZbb9r82tH9RAEifgKhwoj_zwBe7qei8u3BSxMzFl9Dwykd0TWRuM7ffNe6ehhDDRUqaRPj_vKM9KreJnNrqB6f2hxjPAxzk5De2Ys437-dnSAuS_8SVJV";
var SENDER_ID = "103549737174";
var value = body;
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
var msg = new
{
to = deviceId,
data = new
{
body = _body,
title = _title
}
};
//var serializer = new JavaScriptSerializer();
//var json = serializer.Serialize(data);
var json = JsonConvert.SerializeObject(msg, Formatting.Indented);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
sb.AppendLine("MessagePushJob OK");
sb.AppendLine("response:" + sResponseFromServer);
sb.AppendLine("title:" + _title);
sb.AppendLine("body:" + _body);
sb.AppendLine("===================");
_logger.LogInformation(sb.ToString());
return sResponseFromServer;
}
catch (Exception ex)
{
string errmsg = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
_logger.LogInformation(" MessagePushJob KO !!!! :", errmsg);
return errmsg;
}
}
private string PushFCM_Sync(string deviceId, string title, string body)
{
StringBuilder sb = new StringBuilder();
string _title = title + "-" + getCpccchk(4);
string _body = body + "-" + DateTime.Now.ToString("yyyyMMddHHmmss");
//try
//{
string SERVER_API_KEY = "AAAAGBwLmNY:APA91bG5GmgYcaxsU8HrOqvZbb9r82tH9RAEifgKhwoj_zwBe7qei8u3BSxMzFl9Dwykd0TWRuM7ffNe6ehhDDRUqaRPj_vKM9KreJnNrqB6f2hxjPAxzk5De2Ys437-dnSAuS_8SVJV";
var SENDER_ID = "103549737174";
var value = body;
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
tRequest.Method = "post";
tRequest.ContentType = "application/json";
tRequest.Headers.Add(string.Format("Authorization: key={0}", SERVER_API_KEY));
tRequest.Headers.Add(string.Format("Sender: id={0}", SENDER_ID));
var msg = new
{
to = deviceId,
data = new
{
bg_sync = true
}
};
//var serializer = new JavaScriptSerializer();
//var json = serializer.Serialize(data);
var json = JsonConvert.SerializeObject(msg, Formatting.Indented);
Byte[] byteArray = Encoding.UTF8.GetBytes(json);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
sb.AppendLine("MessagePushJob Sync OK");
sb.AppendLine("response:" + sResponseFromServer);
sb.AppendLine("===================");
_logger.LogInformation(sb.ToString());
return sResponseFromServer;
//}
//catch (Exception ex)
//{
// string errmsg = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
// _logger.LogInformation(" MessagePushJob KO !!!! :", errmsg);
// return errmsg;
//}
}
#region HTTP V1 API FCM Auth & Send Notification To Mobile //notify FCM Code
public class Data
{
public string body
{
get;
set;
}
public string title
{
get;
set;
}
public string key_1
{
get;
set;
}
public string key_2
{
get;
set;
}
}
public class Message
{
public string token
{
get;
set;
}
public Data data
{
get;
set;
}
public Notification notification
{
get;
set;
}
}
public class Notification
{
public string title
{
get;
set;
}
public string body
{
get;
set;
}
}
public class Root
{
public Message message
{
get;
set;
}
}
public void GenerateFCM_Auth_SendNotifcn(string deviceID)
{
//----------Generating Bearer token for FCM---------------
string fileName = Path.Combine(Directory.GetCurrentDirectory(), "apipolo-952c6-firebase-adminsdk-tioa9-fbb9ba6d66.json") ; //Download from Firebase Console ServiceAccount
string scopes = "https://www.googleapis.com/auth/firebase.messaging";
var bearertoken = ""; // Bearer Token in this variable
using (var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
{
bearertoken = GoogleCredential
.FromStream(stream) // Loads key file
.CreateScoped(scopes) // Gathers scopes requested
.UnderlyingCredential // Gets the credentials
.GetAccessTokenForRequestAsync().Result; // Gets the Access Token
}
_logger.LogInformation("bearertoken: " + bearertoken);
///--------Calling FCM-----------------------------
var clientHandler = new HttpClientHandler();
var client = new HttpClient(clientHandler);
client.BaseAddress = new Uri("https://fcm.googleapis.com/v1/projects/apipolo-952c6/messages:send"); // FCM HttpV1 API
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.Accept.Add("Authorization", "Bearer " + bearertoken);
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", bearertoken); // Authorization Token in this variable
//---------------Assigning Of data To Model --------------
Root rootObj = new Root();
rootObj.message = new Message();
//rootObj.message.token = "dfYGNx8lTtuCIJZCDKg4WU:APA91bHVY4tBrXKOvnqJvWA5s2By_8Nt8XyRnadDkuGey0C3E45CoasJUUACVp0PCgNkZcXiDnA2WAfX1jfJXcPgM5L6EJFa4IAOccj_GR0uRBO9gXOcwNkh6dSYWb6fOvGFHhuSEoXz"; //FCM Token id
rootObj.message.token = deviceID;
rootObj.message.data = new Data();
rootObj.message.data.title = "Data Title";
rootObj.message.data.body = "Data Body";
rootObj.message.data.key_1 = "Sample Key";
rootObj.message.data.key_2 = "Sample Key2";
rootObj.message.notification = new Notification();
rootObj.message.notification.title = "Notify Title";
rootObj.message.notification.body = "Notify Body";
//-------------Convert Model To JSON ----------------------
var jsonObj = new JavaScriptSerializer().Serialize(rootObj);
//------------------------Calling Of FCM Notify API-------------------
var data = new StringContent(jsonObj, Encoding.UTF8, "application/json");
data.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync("https://fcm.googleapis.com/v1/projects/apipolo-952c6/messages:send", data).Result; // Calling The FCM httpv1 API
//---------- Deserialize Json Response from API ----------------------------------
var jsonResponse = response.Content.ReadAsStringAsync().Result;
_logger.LogInformation("RESPONSE: "+jsonResponse);
var responseObj = new JavaScriptSerializer().DeserializeObject(jsonResponse);
}
#endregion
//private async Task<string?> getAuthToken()
//{
// var scopes = new string[] { "https://www.googleapis.com/auth/firebase.messaging" };
// var path = Path.Combine(Directory.GetCurrentDirectory(), "apipolo-952c6-firebase-adminsdk-tioa9-fbb9ba6d66.json");
// var cred = GoogleCredential.FromFile(path).CreateScoped(scopes);
// var token = await cred.UnderlyingCredential.GetAccessTokenForRequestAsync();
// return token;
//}
//private (bool, T) SendRequest<T>(string url, object requestBody = null, Method method = Method.Post)
//{
// ServicePointManager.Expect100Continue = true;
// ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// RestClient client = new(url);
// var request = new RestRequest();
// var token = getAuthToken().Result;
// request.AddHeader("Content-Type", "application/json");
// request.AddHeader("Authorization", $"Bearer {token}");
// request.AddHeader("access_token_auth", "true");
// request.AddHeader("project_id", "SENDER_ID");
// request.Method = Method.Post;
// if (requestBody != null)
// {
// request.AddJsonBody(JsonConvert.SerializeObject(requestBody));
// }
// RestResponse iResponse = client.Execute(request);
// if (iResponse.StatusCode != HttpStatusCode.OK)
// {
// return (false, default(T));
// }
// else
// {
// try
// {
// return (true, JsonConvert.DeserializeObject<T>(iResponse.Content));
// }
// catch (Exception)
// {
// return (false, default(T));
// }
// }
//}
//public NotificationMessageResponse sendMessageToGroup(string notification_key, object notification, object data)
//{
// var requestObj = new
// {
// token = notification_key, //to
// data = data,
// notification = notification,
// apns = new
// {
// payload = new
// {
// aps = new
// {
// alert = notification,
// sound = "default",
// badge = 1,
// data
// }
// }
// }
// };
// var baseUrl = "https://fcm.googleapis.com/v1/projects/{PROJECT_ID}/messages:send";
// var resp = SendRequest<NotificationMessageResponse>(baseUrl, requestObj);
// return resp.Item2;
//}
private class MexPush
{
/// <summary>tenant azienda</summary>
public string? tenant { get; set; }
/// <summary>utente login</summary>
public string? usr { get; set; }
/// <summary>token device</summary>
public string? token { get; set; }
/// <summary>title</summary>
public string? title { get; set; }
/// <summary>body</summary>
public string? body { get; set; }
/// <summary>not</summary>
public Notifiche? notifi { get; set; }
}
}
}