local-notification-util.js 10 KB

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