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