local-notification-util.js 9.0 KB

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