You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

316 lines
13 KiB

  1. using Common.Models.Confiq;
  2. using Common.Models.Enums;
  3. using Common.Models.Notification;
  4. using Common.Models.RequestResponse;
  5. using Common.Utility;
  6. using log4net;
  7. using MoreLinq;
  8. using Newtonsoft.Json;
  9. using Repository.DAO.ThirdParty;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Configuration;
  13. using System.Dynamic;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Text;
  18. using System.Threading.Tasks;
  19. using System.Web.Script.Serialization;
  20. namespace Business.BusinessLogic.NotificationApiService
  21. {
  22. public class FireBaseService
  23. {
  24. private readonly ILog _log = LogManager.GetLogger(typeof(FireBaseService));
  25. private readonly IThirdPartyRepo _thirdPartyRepo;
  26. public FireBaseService()
  27. {
  28. _thirdPartyRepo = new ThirdPartyRepo();
  29. }
  30. public TPResponse PushNotify(SendNotificationRequest model)
  31. {
  32. TPResponse _tPResponse = new TPResponse();
  33. //_log.Info($"IsBulkNotification {model.IsBulkNotification}");
  34. List<TPResponse> tPResponses = new List<TPResponse>();
  35. Task.Run(() =>
  36. {
  37. Notify(model);
  38. }).ContinueWith(y =>
  39. {
  40. _log.Debug($"PushNotify Responses {JsonConvert.SerializeObject(tPResponses)}");
  41. //tPResponses.Where(x => x.ResponseCode.Equals("0")).ToList().ForEach(z =>
  42. //{
  43. // _thirdPartyRepo.UpdateNotificationStatus(z.Id);
  44. //});
  45. });
  46. _tPResponse.ResponseCode = "0";
  47. _tPResponse.Msg = "PushNotify Sent Sucessfully.";
  48. return _tPResponse;
  49. }
  50. private void Notify(SendNotificationRequest model)
  51. {
  52. try
  53. {
  54. if (!model.Recipients.Any())
  55. {
  56. _log.Info("Recipient(s) are empty.");
  57. return;
  58. }
  59. var applicationId = ConfigurationManager.AppSettings["FcmAuthorizationHeader"];
  60. var senderId = ConfigurationManager.AppSettings["fcmSenderId"];
  61. var langauge = string.IsNullOrEmpty(model.Language) ? ConfigurationManager.AppSettings["lang"] : model.Language;
  62. var serializer = new JavaScriptSerializer();
  63. if (model.IsBulkNotification)
  64. {
  65. foreach (var batch in model.Recipients.GroupBy(c => c.DeviceType).ToList())
  66. {
  67. var templatejson = Helpers.GetMapping(Common.Models.Enums.MappingType.PUSH_NOTIFY_TEMPLATE, model.Template.ToString(), langauge);
  68. var deviceType = batch.Key;
  69. var title = batch.First().NotificationContent.Title ?? GetStatic.ReadWebConfig("PushNotifyAlertTitle", "");
  70. var body = batch.First().NotificationContent.Body;
  71. var image = batch.First().NotificationContent.Image;
  72. var navigateURL = batch.First().NotificationContent.NavigateURL;
  73. var clickActivity = batch.First().NotificationContent.ClickActivity;
  74. var messageType = batch.First().NotificationContent.MessageType;
  75. if (model.Template != NotifyTemplate.NONE)
  76. {
  77. if (!string.IsNullOrEmpty(body))
  78. {
  79. List<Mapping> mappings = JsonConvert.DeserializeObject<List<Mapping>>(body);
  80. body = templatejson.SText;
  81. mappings.ForEach(x =>
  82. {
  83. body = body.Replace(string.Format("{{{0}}}", x.SValue), x.SText);
  84. });
  85. }
  86. title = templatejson.DText;
  87. }
  88. foreach (var batchDevice in batch.Batch(100))
  89. {
  90. var recipientsList = batchDevice.Select(c => c.Address).Distinct().ToList();
  91. string json;
  92. if (deviceType == DeviceType.Android.ToString())
  93. {
  94. var data = new
  95. {
  96. registration_ids = recipientsList.ToArray(),
  97. notification = new
  98. {
  99. body,
  100. title,
  101. sound = "Enabled",
  102. click_action = clickActivity ?? string.Empty,
  103. message_type = messageType ?? string.Empty
  104. },
  105. data = new
  106. {
  107. image = image ?? string.Empty,
  108. url = navigateURL ?? string.Empty
  109. }
  110. };
  111. json = serializer.Serialize(data);
  112. }
  113. else
  114. {
  115. var data = new
  116. {
  117. registration_ids = recipientsList.ToArray(),
  118. content_available = true,
  119. mutable_content = true,
  120. notification = new
  121. {
  122. body,
  123. title,
  124. sound = "Enabled",
  125. click_action = clickActivity ?? string.Empty,
  126. message_type = messageType ?? string.Empty
  127. },
  128. data = new
  129. {
  130. mediaUrl = string.IsNullOrEmpty(image) ? string.Empty : ConfigurationManager.AppSettings["ApplicationMainUrl"] + "api/" + image,
  131. url = navigateURL ?? string.Empty
  132. }
  133. };
  134. json = serializer.Serialize(data);
  135. }
  136. Invoke(applicationId, senderId, json);
  137. }
  138. }
  139. // _thirdPartyRepo.UpdateNotificationStatus(model.ToString());
  140. }
  141. else
  142. {
  143. string body;
  144. string title;
  145. var templatejson = Helpers.GetMapping(Common.Models.Enums.MappingType.PUSH_NOTIFY_TEMPLATE, model.Template.ToString(), langauge);
  146. foreach (var batch in model.Recipients)
  147. {
  148. if (model.Template != NotifyTemplate.NONE)
  149. {
  150. body = templatejson.SText;
  151. if (!string.IsNullOrEmpty(batch.NotificationContent.Body))
  152. {
  153. List<Mapping> mappings = JsonConvert.DeserializeObject<List<Mapping>>(batch.NotificationContent.Body);
  154. mappings.ForEach(x =>
  155. {
  156. body = body.Replace(string.Format("{{{0}}}", x.SValue), x.SText);
  157. });
  158. }
  159. title = templatejson.DText;
  160. }
  161. else
  162. {
  163. body = batch.NotificationContent.Body;
  164. title = batch.NotificationContent.Title ?? GetStatic.ReadWebConfig("PushNotifyAlertTitle", "JME");
  165. }
  166. string json;
  167. if (batch.DeviceType == DeviceType.Android.ToString())
  168. {
  169. var data = new
  170. {
  171. to = batch.Address,
  172. notification = new
  173. {
  174. body = body,
  175. title = batch.NotificationContent.Title ?? GetStatic.ReadWebConfig("PushNotifyAlertTitle", "JME"),
  176. sound = "Enabled",
  177. click_action = batch.NotificationContent.ClickActivity ?? string.Empty,
  178. message_type = batch.NotificationContent.MessageType ?? string.Empty
  179. },
  180. data = new
  181. {
  182. image = batch.NotificationContent.Image ?? string.Empty,
  183. url = batch.NotificationContent.NavigateURL ?? string.Empty
  184. }
  185. };
  186. json = serializer.Serialize(data);
  187. }
  188. else
  189. {
  190. var data = new
  191. {
  192. to = batch.Address,
  193. content_available = true,
  194. mutable_content = true,
  195. notification = new
  196. {
  197. body = body,
  198. title = batch.NotificationContent.Title ?? GetStatic.ReadWebConfig("PushNotifyAlertTitle", "JME"),
  199. sound = "Enabled",
  200. click_action = batch.NotificationContent.ClickActivity ?? string.Empty,
  201. message_type = batch.NotificationContent.MessageType ?? string.Empty
  202. },
  203. data = new
  204. {
  205. url = batch.NotificationContent.NavigateURL ?? string.Empty,
  206. mediaUrl = string.IsNullOrEmpty(batch.NotificationContent.Image) ? string.Empty : ConfigurationManager.AppSettings["ApplicationMainUrl"] + "api/" + batch.NotificationContent.Image
  207. }
  208. };
  209. json = serializer.Serialize(data);
  210. }
  211. Invoke(applicationId, senderId, json);
  212. }
  213. }
  214. model.Recipients.ForEach(x =>
  215. {
  216. _thirdPartyRepo.UpdateNotificationStatus(x.BroadCastNoticeId.ToString());
  217. });
  218. }
  219. catch (Exception ex)
  220. {
  221. _log.Error("FireBaseService Exception", ex);
  222. }
  223. }
  224. private void Invoke(string applicationId, string senderId, string json)
  225. {
  226. var tRequest = WebRequest.Create(ConfigurationManager.AppSettings["GoogleFcm"].ToString());
  227. tRequest.Method = "post";
  228. tRequest.ContentType = "application/json";
  229. var byteArray = Encoding.UTF8.GetBytes(json);
  230. tRequest.Headers.Add($"Authorization: key={applicationId}");
  231. tRequest.Headers.Add($"Sender: id={senderId}");
  232. tRequest.ContentLength = byteArray.Length;
  233. var serializer = new JavaScriptSerializer();
  234. try
  235. {
  236. using (var dataStream = tRequest.GetRequestStream())
  237. {
  238. dataStream.Write(byteArray, 0, byteArray.Length);
  239. using (var tResponse = tRequest.GetResponse())
  240. {
  241. using (var dataStreamResponse = tResponse.GetResponseStream())
  242. {
  243. using (var tReader = new StreamReader(dataStreamResponse))
  244. {
  245. var sResponseFromServer = tReader.ReadToEnd();
  246. var str = sResponseFromServer;
  247. try
  248. {
  249. //dynamic reply = new System.Dynamic.ExpandoObject();
  250. //reply.Response = str;
  251. //reply.Data = str;
  252. var js = new JavaScriptSerializer();
  253. _log.Info($"REQUEST {json} | RESPONSE {str}");
  254. }
  255. catch (Exception)
  256. {
  257. // ignored
  258. }
  259. }
  260. }
  261. }
  262. }
  263. }
  264. catch (Exception ex)
  265. {
  266. _log.Error("Google FCM Api Invoke failed Exception", ex);
  267. }
  268. }
  269. }
  270. }