local-notification-util.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 i = 0, len = options.actions.length; i < len; i++) {
  151. var action = options.actions[i];
  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.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. var dateToNum = function (date) {
  174. var num = typeof date == 'object' ? date.getTime() : date;
  175. return Math.round(num);
  176. };
  177. if (!options.trigger)
  178. return;
  179. if (!trigger.type) {
  180. trigger.type = trigger.center ? 'location' : 'calendar';
  181. }
  182. var isCal = trigger.type == 'calendar';
  183. if (isCal && !date) {
  184. date = this.getValueFor(options, 'at', 'firstAt', 'date');
  185. }
  186. if (isCal && !trigger.every && options.every) {
  187. trigger.every = options.every;
  188. }
  189. if (isCal && (trigger.in || trigger.every)) {
  190. date = null;
  191. }
  192. if (isCal && date) {
  193. trigger.at = dateToNum(date);
  194. }
  195. if (isCal && trigger.firstAt) {
  196. trigger.firstAt = dateToNum(trigger.firstAt);
  197. }
  198. if (isCal && trigger.before) {
  199. trigger.before = dateToNum(trigger.before);
  200. }
  201. if (isCal && trigger.after) {
  202. trigger.after = dateToNum(trigger.after);
  203. }
  204. if (!trigger.count && device.platform == 'windows') {
  205. trigger.count = trigger.every ? 5 : 1;
  206. }
  207. if (trigger.count && device.platform == 'iOS') {
  208. console.warn('trigger: { count: } is not supported on iOS.');
  209. }
  210. if (!isCal) {
  211. trigger.notifyOnEntry = !!trigger.notifyOnEntry;
  212. trigger.notifyOnExit = trigger.notifyOnExit === true;
  213. trigger.radius = trigger.radius || 5;
  214. trigger.single = !!trigger.single;
  215. }
  216. if (!isCal || trigger.at) {
  217. delete trigger.every;
  218. }
  219. delete options.every;
  220. delete options.at;
  221. delete options.firstAt;
  222. delete options.date;
  223. options.trigger = trigger;
  224. return options;
  225. };
  226. /**
  227. * Convert the passed values for the progressBar to their required type.
  228. *
  229. * @param [ Map ] options Set of custom values.
  230. *
  231. * @return [ Map ] Interaction object with trigger spec.
  232. */
  233. exports.convertProgressBar = function (options) {
  234. var isAndroid = device.platform == 'Android',
  235. cfg = options.progressBar;
  236. if (cfg === undefined)
  237. return;
  238. if (typeof cfg === 'boolean') {
  239. cfg = options.progressBar = { enabled: cfg };
  240. }
  241. if (typeof cfg.enabled !== 'boolean') {
  242. cfg.enabled = !!(cfg.value || cfg.maxValue || cfg.indeterminate !== null);
  243. }
  244. cfg.value = cfg.value || 0;
  245. if (isAndroid) {
  246. cfg.maxValue = cfg.maxValue || 100;
  247. cfg.indeterminate = !!cfg.indeterminate;
  248. }
  249. cfg.enabled = !!cfg.enabled;
  250. return options;
  251. };
  252. /**
  253. * Create a callback function to get executed within a specific scope.
  254. *
  255. * @param [ Function ] fn The function to be exec as the callback.
  256. * @param [ Object ] scope The callback function's scope.
  257. *
  258. * @return [ Function ]
  259. */
  260. exports.createCallbackFn = function (fn, scope) {
  261. if (typeof fn != 'function')
  262. return;
  263. return function () {
  264. fn.apply(scope || this, arguments);
  265. };
  266. };
  267. /**
  268. * Convert the IDs to numbers.
  269. *
  270. * @param [ Array ] ids
  271. *
  272. * @return [ Array<Number> ]
  273. */
  274. exports.convertIds = function (ids) {
  275. var convertedIds = [];
  276. for (var i = 0, len = ids.length; i < len; i++) {
  277. convertedIds.push(Number(ids[i]));
  278. }
  279. return convertedIds;
  280. };
  281. /**
  282. * First found value for the given keys.
  283. *
  284. * @param [ Object ] options Object with key-value properties.
  285. * @param [ *Array<String> ] keys List of keys.
  286. *
  287. * @return [ Object ]
  288. */
  289. exports.getValueFor = function (options) {
  290. var keys = Array.apply(null, arguments).slice(1);
  291. for (var i = 0, key = keys[i], len = keys.length; i < len; key = keys[++i]) {
  292. if (options.hasOwnProperty(key)) {
  293. return options[key];
  294. }
  295. }
  296. return null;
  297. };
  298. /**
  299. * Convert a value to an array.
  300. *
  301. * @param [ Object ] obj Any kind of object.
  302. *
  303. * @return [ Array ] An array with the object as first item.
  304. */
  305. exports.toArray = function (obj) {
  306. return Array.isArray(obj) ? Array.from(obj) : [obj];
  307. };
  308. /**
  309. * Fire the event with given arguments.
  310. *
  311. * @param [ String ] event The event's name.
  312. * @param [ *Array] args The callback's arguments.
  313. *
  314. * @return [ Void]
  315. */
  316. exports.fireEvent = function (event) {
  317. var args = Array.apply(null, arguments).slice(1),
  318. listener = this._listener[event];
  319. if (!listener)
  320. return;
  321. if (args[0] && typeof args[0].data === 'string') {
  322. args[0].data = JSON.parse(args[0].data);
  323. }
  324. for (var i = 0; i < listener.length; i++) {
  325. var fn = listener[i][0],
  326. scope = listener[i][1];
  327. fn.apply(scope, args);
  328. }
  329. };
  330. /**
  331. * Execute the native counterpart.
  332. *
  333. * @param [ String ] action The name of the action.
  334. * @param [ Array ] args Array of arguments.
  335. * @param [ Function] callback The callback function.
  336. * @param [ Object ] scope The scope for the function.
  337. *
  338. * @return [ Void ]
  339. */
  340. exports.exec = function (action, args, callback, scope) {
  341. var fn = this.createCallbackFn(callback, scope),
  342. params = [];
  343. if (Array.isArray(args)) {
  344. params = args;
  345. } else if (args) {
  346. params.push(args);
  347. }
  348. exec(fn, null, 'LocalNotification', action, params);
  349. };
  350. exports.setLaunchDetails = function () {
  351. exports.exec('launch', null, function (details) {
  352. if (details) {
  353. cordova.plugins.notification.local.launchDetails = details;
  354. }
  355. });
  356. };
  357. // Called after 'deviceready' event
  358. channel.deviceready.subscribe(function () {
  359. if (['Android', 'windows', 'iOS'].indexOf(device.platform) > -1) {
  360. exports.exec('ready');
  361. }
  362. });
  363. // Called before 'deviceready' event
  364. channel.onCordovaReady.subscribe(function () {
  365. channel.onCordovaInfoReady.subscribe(function () {
  366. if (['Android', 'windows', 'iOS'].indexOf(device.platform) > -1) {
  367. exports.setLaunchDetails();
  368. }
  369. });
  370. });
  371. // Polyfill for Object.assign
  372. if (typeof Object.assign != 'function') {
  373. Object.assign = function(target) {
  374. 'use strict';
  375. if (target == null) {
  376. throw new TypeError('Cannot convert undefined or null to object');
  377. }
  378. target = Object(target);
  379. for (var index = 1; index < arguments.length; index++) {
  380. var source = arguments[index];
  381. if (source != null) {
  382. for (var key in source) {
  383. if (Object.prototype.hasOwnProperty.call(source, key)) {
  384. target[key] = source[key];
  385. }
  386. }
  387. }
  388. }
  389. return target;
  390. };
  391. }
  392. // Production steps of ECMA-262, Edition 6, 22.1.2.1
  393. // Reference: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-array.from
  394. if (!Array.from) {
  395. Array.from = (function () {
  396. var toStr = Object.prototype.toString;
  397. var isCallable = function (fn) {
  398. return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
  399. };
  400. var toInteger = function (value) {
  401. var number = Number(value);
  402. if (isNaN(number)) { return 0; }
  403. if (number === 0 || !isFinite(number)) { return number; }
  404. return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
  405. };
  406. var maxSafeInteger = Math.pow(2, 53) - 1;
  407. var toLength = function (value) {
  408. var len = toInteger(value);
  409. return Math.min(Math.max(len, 0), maxSafeInteger);
  410. };
  411. // The length property of the from method is 1.
  412. return function from(arrayLike/*, mapFn, thisArg */) {
  413. // 1. Let C be the this value.
  414. var C = this;
  415. // 2. Let items be ToObject(arrayLike).
  416. var items = Object(arrayLike);
  417. // 3. ReturnIfAbrupt(items).
  418. if (arrayLike == null) {
  419. throw new TypeError("Array.from requires an array-like object - not null or undefined");
  420. }
  421. // 4. If mapfn is undefined, then let mapping be false.
  422. var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
  423. var T;
  424. if (typeof mapFn !== 'undefined') {
  425. // 5. else
  426. // 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
  427. if (!isCallable(mapFn)) {
  428. throw new TypeError('Array.from: when provided, the second argument must be a function');
  429. }
  430. // 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
  431. if (arguments.length > 2) {
  432. T = arguments[2];
  433. }
  434. }
  435. // 10. Let lenValue be Get(items, "length").
  436. // 11. Let len be ToLength(lenValue).
  437. var len = toLength(items.length);
  438. // 13. If IsConstructor(C) is true, then
  439. // 13. a. Let A be the result of calling the [[Construct]] internal method of C with an argument list containing the single item len.
  440. // 14. a. Else, Let A be ArrayCreate(len).
  441. var A = isCallable(C) ? Object(new C(len)) : new Array(len);
  442. // 16. Let k be 0.
  443. var k = 0;
  444. // 17. Repeat, while k < len… (also steps a - h)
  445. var kValue;
  446. while (k < len) {
  447. kValue = items[k];
  448. if (mapFn) {
  449. A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
  450. } else {
  451. A[k] = kValue;
  452. }
  453. k += 1;
  454. }
  455. // 18. Let putStatus be Put(A, "length", len, true).
  456. A.length = len;
  457. // 20. Return A.
  458. return A;
  459. };
  460. }());
  461. }