local-notification-util.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. /*
  2. * Apache 2.0 License
  3. *
  4. * Copyright (c) Sebastian Katzer 2017
  5. *
  6. * This file contains Original Code and/or Modifications of Original Code
  7. * as defined in and that are subject to the Apache License
  8. * Version 2.0 (the 'License'). You may not use this file except in
  9. * compliance with the License. Please obtain a copy of the License at
  10. * http://opensource.org/licenses/Apache-2.0/ and read it before using this
  11. * file.
  12. *
  13. * The Original Code and all software distributed under the License are
  14. * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
  15. * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
  16. * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
  17. * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
  18. * Please see the License for the specific language governing rights and
  19. * limitations under the License.
  20. */
  21. var exec = require('cordova/exec'),
  22. channel = require('cordova/channel');
  23. // Default values
  24. exports._defaults = {
  25. id: 0,
  26. text: '',
  27. title: '',
  28. sound: 'res://platform_default',
  29. badge: undefined,
  30. data: undefined,
  31. trigger: { type: 'calendar' },
  32. actions: [],
  33. actionGroupId: undefined,
  34. attachments: []
  35. };
  36. // Listener
  37. exports._listener = {};
  38. /**
  39. * Merge platform specific properties into the default ones.
  40. *
  41. * @return [ Void ]
  42. */
  43. exports.applyPlatformSpecificOptions = function () {
  44. var defaults = this._defaults;
  45. switch (device.platform) {
  46. case 'Android':
  47. defaults.icon = 'res://ic_popup_reminder';
  48. defaults.smallIcon = undefined;
  49. defaults.ongoing = false;
  50. defaults.autoClear = true;
  51. defaults.led = undefined;
  52. defaults.color = undefined;
  53. break;
  54. }
  55. };
  56. /**
  57. * Merge custom properties with the default values.
  58. *
  59. * @param [ Object ] options Set of custom values.
  60. *
  61. * @retrun [ Object ]
  62. */
  63. exports.mergeWithDefaults = function (options) {
  64. var defaults = this.getDefaults();
  65. options.text = this.getValueFor(options, 'text', 'message');
  66. options.data = this.getValueFor(options, 'data', 'json');
  67. if (defaults.hasOwnProperty('autoClear')) {
  68. options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
  69. }
  70. if (options.autoClear !== true && options.ongoing) {
  71. options.autoClear = false;
  72. }
  73. for (var key in defaults) {
  74. if (options[key] === null || options[key] === undefined) {
  75. if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
  76. options[key] = undefined;
  77. } else {
  78. options[key] = defaults[key];
  79. }
  80. }
  81. }
  82. for (key in options) {
  83. if (!defaults.hasOwnProperty(key)) {
  84. // delete options[key];
  85. console.warn('Unknown property: ' + key);
  86. }
  87. }
  88. return options;
  89. };
  90. /**
  91. * Convert the passed values to their required type.
  92. *
  93. * @param [ Object ] options Properties to convert for.
  94. *
  95. * @return [ Object ] The converted property list
  96. */
  97. exports.convertProperties = function (options) {
  98. if (options.id) {
  99. if (isNaN(options.id)) {
  100. options.id = this.getDefaults().id;
  101. console.warn('Id is not a number: ' + options.id);
  102. } else {
  103. options.id = Number(options.id);
  104. }
  105. }
  106. if (options.title) {
  107. options.title = options.title.toString();
  108. }
  109. if (options.text) {
  110. options.text = options.text.toString();
  111. }
  112. if (options.badge) {
  113. if (isNaN(options.badge)) {
  114. options.badge = this.getDefaults().badge;
  115. console.warn('Badge number is not a number: ' + options.id);
  116. } else {
  117. options.badge = Number(options.badge);
  118. }
  119. }
  120. if (typeof options.data == 'object') {
  121. options.data = JSON.stringify(options.data);
  122. }
  123. this.convertTrigger(options);
  124. this.convertActions(options);
  125. return options;
  126. };
  127. /**
  128. * Convert the passed values to their required type, modifying them
  129. * directly for Android and passing the converted list back for iOS.
  130. *
  131. * @param [ Map ] options Set of custom values.
  132. *
  133. * @return [ Map ] Interaction object with category & actions.
  134. */
  135. exports.convertActions = function (options) {
  136. if (!options.actions)
  137. return null;
  138. var actions = [];
  139. for (var i = 0, action; i < options.actions.length; i++) {
  140. action = options.actions[i];
  141. if (!action.id) {
  142. console.warn(
  143. 'Action with title ' + action.title + ' has no id and will not be added.');
  144. continue;
  145. }
  146. action.id = action.id.toString();
  147. actions.push(action);
  148. }
  149. options.category = (options.category || 'DEFAULT_GROUP').toString();
  150. options.actions = actions;
  151. return options;
  152. };
  153. /**
  154. * Convert the passed values for the trigger to their required type.
  155. *
  156. * @param [ Map ] options Set of custom values.
  157. *
  158. * @return [ Map ] Interaction object with trigger spec.
  159. */
  160. exports.convertTrigger = function (options) {
  161. var cfg = options.trigger,
  162. isDate = Date.prototype.isPrototypeOf(cfg),
  163. isObject = Object.prototype.isPrototypeOf(cfg),
  164. trigger = !isDate && isObject ? cfg : {},
  165. date = this.getValueFor(trigger, 'at', 'firstAt', 'date');
  166. if (!trigger.type) {
  167. trigger.type = trigger.center ? 'location' : 'calendar';
  168. }
  169. var isCal = trigger.type == 'calendar';
  170. if (isCal && !date) {
  171. date = this.getValueFor(options, 'trigger', 'at', 'firstAt', 'date');
  172. date = date || new Date();
  173. }
  174. if (isCal) {
  175. date = typeof date == 'object' ? date.getTime() : date;
  176. trigger.at = Math.round(date / 1000);
  177. }
  178. if (isCal && !trigger.every && options.every) {
  179. trigger.every = options.every;
  180. }
  181. if (!isCal) {
  182. trigger.notifyOnEntry = !!trigger.notifyOnEntry;
  183. trigger.notifyOnExit = trigger.notifyOnExit === true;
  184. trigger.radius = trigger.radius || 5;
  185. }
  186. delete options.every;
  187. delete options.at;
  188. delete options.firstAt;
  189. delete options.date;
  190. options.trigger = trigger;
  191. return options;
  192. };
  193. /**
  194. * Create a callback function to get executed within a specific scope.
  195. *
  196. * @param [ Function ] fn The function to be exec as the callback.
  197. * @param [ Object ] scope The callback function's scope.
  198. *
  199. * @return [ Function ]
  200. */
  201. exports.createCallbackFn = function (fn, scope) {
  202. if (typeof fn != 'function')
  203. return;
  204. return function () {
  205. fn.apply(scope || this, arguments);
  206. };
  207. };
  208. /**
  209. * Convert the IDs to numbers.
  210. *
  211. * @param [ Array ] ids
  212. *
  213. * @return [ Array<Number> ]
  214. */
  215. exports.convertIds = function (ids) {
  216. var convertedIds = [];
  217. for (var i = 0; i < ids.length; i++) {
  218. convertedIds.push(Number(ids[i]));
  219. }
  220. return convertedIds;
  221. };
  222. /**
  223. * First found value for the given keys.
  224. *
  225. * @param [ Object ] options Object with key-value properties.
  226. * @param [ *Array<String> ] keys List of keys.
  227. *
  228. * @return [ Object ]
  229. */
  230. exports.getValueFor = function (options) {
  231. var keys = Array.apply(null, arguments).slice(1);
  232. for (var i = 0; i < keys.length; i++) {
  233. var key = keys[i];
  234. if (options.hasOwnProperty(key)) {
  235. return options[key];
  236. }
  237. }
  238. };
  239. /**
  240. * Fire the event with given arguments.
  241. *
  242. * @param [ String ] event The event's name.
  243. * @param [ *Array] args The callback's arguments.
  244. *
  245. * @return [ Void]
  246. */
  247. exports.fireEvent = function (event) {
  248. var args = Array.apply(null, arguments).slice(1),
  249. listener = this._listener[event];
  250. if (!listener)
  251. return;
  252. for (var i = 0; i < listener.length; i++) {
  253. var fn = listener[i][0],
  254. scope = listener[i][1];
  255. fn.apply(scope, args);
  256. }
  257. };
  258. /**
  259. * Execute the native counterpart.
  260. *
  261. * @param [ String ] action The name of the action.
  262. * @param [ Array ] args Array of arguments.
  263. * @param [ Function] callback The callback function.
  264. * @param [ Object ] scope The scope for the function.
  265. *
  266. * @return [ Void ]
  267. */
  268. exports.exec = function (action, args, callback, scope) {
  269. var fn = this.createCallbackFn(callback, scope),
  270. params = [];
  271. if (Array.isArray(args)) {
  272. params = args;
  273. } else if (args) {
  274. params.push(args);
  275. }
  276. exec(fn, null, 'LocalNotification', action, params);
  277. };
  278. // Called after 'deviceready' event
  279. channel.deviceready.subscribe(function () {
  280. // Device is ready now, the listeners are registered
  281. // and all queued events can be executed.
  282. exports.exec('deviceready');
  283. });
  284. // Called before 'deviceready' event
  285. channel.onCordovaReady.subscribe(function () {
  286. // Set launchDetails object
  287. exports.exec('launchDetails');
  288. // Device plugin is ready now
  289. channel.onCordovaInfoReady.subscribe(function () {
  290. // Merge platform specifics into defaults
  291. exports.applyPlatformSpecificOptions();
  292. });
  293. });