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 */ /// public class MyCronJob1 : CronJobService { /// Configuration public IConfiguration Configuration { get; } /// Startup private readonly ILogger _logger; /// Costruttore public MyCronJob1(IScheduleConfig config, ILogger logger, IConfiguration configuration) : base(config.CronExpression, config.TimeZoneInfo) { _logger = logger; Configuration = configuration; } /// public override Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("MessagePushJob 1 starts."); return base.StartAsync(cancellationToken); } /// public override Task DoWork(CancellationToken cancellationToken) { _logger.LogInformation("{now} MessagePushJob 1 is working.", DateTime.Now.ToString("T")); try { //cerco le notifiche da mandare List 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 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; } /// public override Task StopAsync(CancellationToken cancellationToken) { _logger.LogInformation("MessagePushJob 1 is stopping."); return base.StopAsync(cancellationToken); } private List readNotify() { List lst = new List(); #region Marrocco var optionsBuilder = new DbContextOptionsBuilder(); 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 lst) { #region MARRO var optionsBuilder = new DbContextOptionsBuilder(); 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 lst) { #region MARRO var optionsBuilder = new DbContextOptionsBuilder(); 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 fillMex(List lst) { List mess = new List(); var optionsBuilder = new DbContextOptionsBuilder(); 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() { { "myData3", "1234522222" } } }, Token = registrationToken, Data = new Dictionary() { { "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 { /// tenant azienda public string? tenant { get; set; } /// utente login public string? usr { get; set; } /// token device public string? token { get; set; } /// title public string? title { get; set; } /// body public string? body { get; set; } /// not public Notifiche? notifi { get; set; } } } }