local-notification-util.js 11 KB

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