local-notification-util.js 10 KB

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