local-notification-util.js 11 KB

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