local-notification-util.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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: 'res://platform_default',
  29. badge: undefined,
  30. data: undefined,
  31. icon: undefined,
  32. trigger: { type: 'calendar' },
  33. actions: [],
  34. actionGroupId: undefined,
  35. attachments: [],
  36. progressBar: false
  37. };
  38. // Listener
  39. exports._listener = {};
  40. /**
  41. * Merge platform specific properties into the default ones.
  42. *
  43. * @return [ Void ]
  44. */
  45. exports.applyPlatformSpecificOptions = function () {
  46. var defaults = this._defaults;
  47. switch (device.platform) {
  48. case 'Android':
  49. defaults.icon = 'res://icon';
  50. defaults.smallIcon = undefined;
  51. defaults.sticky = false;
  52. defaults.autoClear = true;
  53. defaults.led = true;
  54. defaults.color = undefined;
  55. defaults.vibrate = false;
  56. defaults.lockscreen = true;
  57. defaults.showWhen = true;
  58. defaults.priority = 0;
  59. defaults.defaults = 0;
  60. break;
  61. }
  62. };
  63. /**
  64. * Merge custom properties with the default values.
  65. *
  66. * @param [ Object ] options Set of custom values.
  67. *
  68. * @retrun [ Object ]
  69. */
  70. exports.mergeWithDefaults = function (options) {
  71. var defaults = this.getDefaults();
  72. options.text = this.getValueFor(options, 'text', 'message');
  73. options.data = this.getValueFor(options, 'data', 'json');
  74. if (defaults.hasOwnProperty('autoClear')) {
  75. options.autoClear = this.getValueFor(options, 'autoClear', 'autoCancel');
  76. }
  77. if (options.autoClear !== true && options.ongoing) {
  78. options.autoClear = false;
  79. }
  80. for (var key in defaults) {
  81. if (options[key] === null || options[key] === undefined) {
  82. if (options.hasOwnProperty(key) && ['data','sound'].indexOf(key) > -1) {
  83. options[key] = undefined;
  84. } else {
  85. var obj = defaults[key];
  86. options[key] = typeof obj === 'object' ? Object.assign({}, obj) : obj;
  87. }
  88. }
  89. }
  90. for (key in options) {
  91. if (!defaults.hasOwnProperty(key)) {
  92. // delete options[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.text) {
  121. options.text = options.text.toString();
  122. }
  123. if (options.badge) {
  124. options.badge = parseToInt('badge', options);
  125. }
  126. if (options.priority) {
  127. options.priority = parseToInt('priority', options);
  128. }
  129. if (options.defaults) {
  130. options.defaults = parseToInt('defaults', options);
  131. }
  132. if (typeof options.data == 'object') {
  133. options.data = JSON.stringify(options.data);
  134. }
  135. this.convertTrigger(options);
  136. this.convertActions(options);
  137. this.convertProgressBar(options);
  138. return options;
  139. };
  140. /**
  141. * Convert the passed values to their required type, modifying them
  142. * directly for Android and passing the converted list back for iOS.
  143. *
  144. * @param [ Map ] options Set of custom values.
  145. *
  146. * @return [ Map ] Interaction object with category & actions.
  147. */
  148. exports.convertActions = function (options) {
  149. if (!options.actions)
  150. return null;
  151. var actions = [];
  152. for (var i = 0, action; i < options.actions.length; i++) {
  153. action = options.actions[i];
  154. if (!action.id) {
  155. console.warn(
  156. 'Action with title ' + action.title + ' has no id and will not be added.');
  157. continue;
  158. }
  159. action.id = action.id.toString();
  160. actions.push(action);
  161. }
  162. options.category = (options.category || 'DEFAULT_GROUP').toString();
  163. options.actions = actions;
  164. return options;
  165. };
  166. /**
  167. * Convert the passed values for the trigger to their required type.
  168. *
  169. * @param [ Map ] options Set of custom values.
  170. *
  171. * @return [ Map ] Interaction object with trigger spec.
  172. */
  173. exports.convertTrigger = function (options) {
  174. var trigger = options.trigger || {},
  175. date = this.getValueFor(trigger, 'at', 'firstAt', 'date');
  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 cfg = options.progressBar;
  223. if (typeof cfg === 'boolean') {
  224. options.progressBar = { enabled: cfg };
  225. }
  226. return options;
  227. };
  228. /**
  229. * Create a callback function to get executed within a specific scope.
  230. *
  231. * @param [ Function ] fn The function to be exec as the callback.
  232. * @param [ Object ] scope The callback function's scope.
  233. *
  234. * @return [ Function ]
  235. */
  236. exports.createCallbackFn = function (fn, scope) {
  237. if (typeof fn != 'function')
  238. return;
  239. return function () {
  240. fn.apply(scope || this, arguments);
  241. };
  242. };
  243. /**
  244. * Convert the IDs to numbers.
  245. *
  246. * @param [ Array ] ids
  247. *
  248. * @return [ Array<Number> ]
  249. */
  250. exports.convertIds = function (ids) {
  251. var convertedIds = [];
  252. for (var i = 0; i < ids.length; i++) {
  253. convertedIds.push(Number(ids[i]));
  254. }
  255. return convertedIds;
  256. };
  257. /**
  258. * First found value for the given keys.
  259. *
  260. * @param [ Object ] options Object with key-value properties.
  261. * @param [ *Array<String> ] keys List of keys.
  262. *
  263. * @return [ Object ]
  264. */
  265. exports.getValueFor = function (options) {
  266. var keys = Array.apply(null, arguments).slice(1);
  267. for (var i = 0; i < keys.length; i++) {
  268. var key = keys[i];
  269. if (options.hasOwnProperty(key)) {
  270. return options[key];
  271. }
  272. }
  273. };
  274. /**
  275. * Fire the event with given arguments.
  276. *
  277. * @param [ String ] event The event's name.
  278. * @param [ *Array] args The callback's arguments.
  279. *
  280. * @return [ Void]
  281. */
  282. exports.fireEvent = function (event) {
  283. var args = Array.apply(null, arguments).slice(1),
  284. listener = this._listener[event];
  285. if (!listener)
  286. return;
  287. for (var i = 0; i < listener.length; i++) {
  288. var fn = listener[i][0],
  289. scope = listener[i][1];
  290. fn.apply(scope, args);
  291. }
  292. };
  293. /**
  294. * Execute the native counterpart.
  295. *
  296. * @param [ String ] action The name of the action.
  297. * @param [ Array ] args Array of arguments.
  298. * @param [ Function] callback The callback function.
  299. * @param [ Object ] scope The scope for the function.
  300. *
  301. * @return [ Void ]
  302. */
  303. exports.exec = function (action, args, callback, scope) {
  304. var fn = this.createCallbackFn(callback, scope),
  305. params = [];
  306. if (Array.isArray(args)) {
  307. params = args;
  308. } else if (args) {
  309. params.push(args);
  310. }
  311. exec(fn, null, 'LocalNotification', action, params);
  312. };
  313. // Called after 'deviceready' event
  314. channel.deviceready.subscribe(function () {
  315. // Device is ready now, the listeners are registered
  316. // and all queued events can be executed.
  317. exports.exec('ready');
  318. });
  319. // Called before 'deviceready' event
  320. channel.onCordovaReady.subscribe(function () {
  321. // Set launchDetails object
  322. exports.exec('launch');
  323. // Device plugin is ready now
  324. channel.onCordovaInfoReady.subscribe(function () {
  325. // Merge platform specifics into defaults
  326. exports.applyPlatformSpecificOptions();
  327. });
  328. });