local-notification-util.js 10 KB

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