PageRenderTime 43ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/front/plugins/com.phonegap.plugins.PushPlugin/src/wp8/PushPlugin.cs

https://gitlab.com/boxnia/NFU_MOVIL
C# | 258 lines | 224 code | 32 blank | 2 comment | 12 complexity | 1dd46fed28a5d30c8570313544487690 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Runtime.Serialization;
  6. using System.Windows;
  7. using Microsoft.Phone.Controls;
  8. using Microsoft.Phone.Notification;
  9. using Microsoft.Phone.Shell;
  10. using Newtonsoft.Json;
  11. namespace WPCordovaClassLib.Cordova.Commands
  12. {
  13. public class PushPlugin : BaseCommand
  14. {
  15. private const string InvalidRegistrationError = "Unable to open a channel with the specified name. The most probable cause is that you have already registered a channel with a different name. Call unregister(old-channel-name) or uninstall and redeploy your application.";
  16. private const string MissingChannelError = "Couldn't find a channel with the specified name.";
  17. private Options pushOptions;
  18. public void register(string options)
  19. {
  20. if (!TryDeserializeOptions(options, out this.pushOptions))
  21. {
  22. this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
  23. return;
  24. }
  25. var pushChannel = HttpNotificationChannel.Find(this.pushOptions.ChannelName);
  26. if (pushChannel == null)
  27. {
  28. pushChannel = new HttpNotificationChannel(this.pushOptions.ChannelName);
  29. SubscribePushChannelEvents(pushChannel);
  30. try
  31. {
  32. var count = 0;
  33. while(count < 3 && pushChannel.ChannelUri == null)
  34. {
  35. pushChannel.Open();
  36. count++;
  37. }
  38. }
  39. catch (InvalidOperationException)
  40. {
  41. this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, InvalidRegistrationError));
  42. return;
  43. }
  44. pushChannel.BindToShellToast();
  45. pushChannel.BindToShellTile();
  46. }
  47. else
  48. {
  49. SubscribePushChannelEvents(pushChannel);
  50. }
  51. var result = new RegisterResult
  52. {
  53. ChannelName = this.pushOptions.ChannelName,
  54. Uri = pushChannel.ChannelUri == null ? string.Empty : pushChannel.ChannelUri.ToString()
  55. };
  56. this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, result));
  57. }
  58. public void unregister(string options)
  59. {
  60. Options unregisterOptions;
  61. if (!TryDeserializeOptions(options, out unregisterOptions))
  62. {
  63. this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
  64. return;
  65. }
  66. var pushChannel = HttpNotificationChannel.Find(unregisterOptions.ChannelName);
  67. if (pushChannel != null)
  68. {
  69. pushChannel.UnbindToShellTile();
  70. pushChannel.UnbindToShellToast();
  71. pushChannel.Close();
  72. pushChannel.Dispose();
  73. this.DispatchCommandResult(new PluginResult(PluginResult.Status.OK, "Channel " + unregisterOptions.ChannelName + " is closed!"));
  74. }
  75. else
  76. {
  77. this.DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, MissingChannelError));
  78. }
  79. }
  80. public void showToastNotification(string options)
  81. {
  82. ShellToast toast;
  83. if (!TryDeserializeOptions(options, out toast))
  84. {
  85. this.DispatchCommandResult(new PluginResult(PluginResult.Status.JSON_EXCEPTION));
  86. return;
  87. }
  88. Deployment.Current.Dispatcher.BeginInvoke(toast.Show);
  89. }
  90. void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
  91. {
  92. // return uri to js
  93. var result = new RegisterResult
  94. {
  95. ChannelName = this.pushOptions.ChannelName,
  96. Uri = e.ChannelUri.ToString()
  97. };
  98. this.ExecuteCallback(this.pushOptions.UriChangedCallback, JsonConvert.SerializeObject(result));
  99. }
  100. void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
  101. {
  102. // call error handler and return uri
  103. var err = new RegisterError
  104. {
  105. Code = e.ErrorCode.ToString(),
  106. Message = e.Message
  107. };
  108. this.ExecuteCallback(this.pushOptions.ErrorCallback, JsonConvert.SerializeObject(err));
  109. }
  110. void PushChannel_ShellToastNotificationReceived(object sender, NotificationEventArgs e)
  111. {
  112. var toast = new PushNotification
  113. {
  114. Type = "toast"
  115. };
  116. foreach (var item in e.Collection)
  117. {
  118. toast.JsonContent.Add(item.Key, item.Value);
  119. }
  120. this.ExecuteCallback(this.pushOptions.NotificationCallback, JsonConvert.SerializeObject(toast));
  121. }
  122. void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
  123. {
  124. var raw = new PushNotification
  125. {
  126. Type = "raw"
  127. };
  128. using (var reader = new StreamReader(e.Notification.Body))
  129. {
  130. raw.JsonContent.Add("Body", reader.ReadToEnd());
  131. }
  132. this.ExecuteCallback(this.pushOptions.NotificationCallback, JsonConvert.SerializeObject(raw));
  133. }
  134. void ExecuteCallback(string callback, string callbackResult)
  135. {
  136. Deployment.Current.Dispatcher.BeginInvoke(() =>
  137. {
  138. PhoneApplicationFrame frame;
  139. PhoneApplicationPage page;
  140. CordovaView cView;
  141. if (TryCast(Application.Current.RootVisual, out frame) &&
  142. TryCast(frame.Content, out page) &&
  143. TryCast(page.FindName("CordovaView"), out cView))
  144. {
  145. cView.Browser.Dispatcher.BeginInvoke(() =>
  146. {
  147. try
  148. {
  149. cView.Browser.InvokeScript("execScript", callback + "(" + callbackResult + ")");
  150. }
  151. catch (Exception ex)
  152. {
  153. Debug.WriteLine("ERROR: Exception in InvokeScriptCallback :: " + ex.Message);
  154. }
  155. });
  156. }
  157. });
  158. }
  159. static bool TryDeserializeOptions<T>(string options, out T result) where T : class
  160. {
  161. result = null;
  162. try
  163. {
  164. var args = JsonConvert.DeserializeObject<string[]>(options);
  165. result = JsonConvert.DeserializeObject<T>(args[0]);
  166. return true;
  167. }
  168. catch
  169. {
  170. return false;
  171. }
  172. }
  173. static bool TryCast<T>(object obj, out T result) where T : class
  174. {
  175. result = obj as T;
  176. return result != null;
  177. }
  178. void SubscribePushChannelEvents(HttpNotificationChannel channel)
  179. {
  180. channel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
  181. channel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
  182. channel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
  183. channel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
  184. }
  185. [DataContract]
  186. public class Options
  187. {
  188. [DataMember(Name = "channelName", IsRequired = true)]
  189. public string ChannelName { get; set; }
  190. [DataMember(Name = "ecb", IsRequired = false)]
  191. public string NotificationCallback { get; set; }
  192. [DataMember(Name = "errcb", IsRequired = false)]
  193. public string ErrorCallback { get; set; }
  194. [DataMember(Name = "uccb", IsRequired = false)]
  195. public string UriChangedCallback { get; set; }
  196. }
  197. [DataContract]
  198. public class RegisterResult
  199. {
  200. [DataMember(Name = "uri", IsRequired = true)]
  201. public string Uri { get; set; }
  202. [DataMember(Name = "channel", IsRequired = true)]
  203. public string ChannelName { get; set; }
  204. }
  205. [DataContract]
  206. public class PushNotification
  207. {
  208. public PushNotification()
  209. {
  210. this.JsonContent = new Dictionary<string, object>();
  211. }
  212. [DataMember(Name = "jsonContent", IsRequired = true)]
  213. public IDictionary<string, object> JsonContent { get; set; }
  214. [DataMember(Name = "type", IsRequired = true)]
  215. public string Type { get; set; }
  216. }
  217. [DataContract]
  218. public class RegisterError
  219. {
  220. [DataMember(Name = "code", IsRequired = true)]
  221. public string Code { get; set; }
  222. [DataMember(Name = "message", IsRequired = true)]
  223. public string Message { get; set; }
  224. }
  225. }
  226. }