local-notification-util.js 11 KB

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