local-notification-util.js 11 KB

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