local-notification-util.js 11 KB

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