local-notification-util.js 10 KB

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