431 lines
15 KiB
C#
431 lines
15 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;
|
|
|
|
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();
|
|
|
|
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);
|
|
}
|
|
|
|
|
|
//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).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;
|
|
//}
|
|
}
|
|
|
|
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; }
|
|
}
|
|
|
|
}
|
|
}
|