UNPKG

@transistorsoft/capacitor-background-geolocation

Version:

The most sophisticated cross platform Capacitor background location tracking & geofencing module with battery-conscious motion-detection intelligence

1,092 lines 43.1 kB
import { __awaiter, __generator } from "tslib"; import { registerPlugin } from '@capacitor/core'; import { LogLevel, DesiredAccuracy, PersistMode, AuthorizationStatus, AccuracyAuthorization, LocationRequest, AuthorizationStrategy, LocationFilterPolicy, KalmanProfile, NotificationPriority, HttpMethod, TriggerActivity, ActivityType, Event } from '@transistorsoft/background-geolocation-types'; var NativeModule = registerPlugin('BackgroundGeolocation'); /** * Logger */ var LOGGER_LOG_LEVEL_DEBUG = "debug"; var LOGGER_LOG_LEVEL_NOTICE = "notice"; var LOGGER_LOG_LEVEL_INFO = "info"; var LOGGER_LOG_LEVEL_WARN = "warn"; var LOGGER_LOG_LEVEL_ERROR = "error"; var ORDER_ASC = 1; var ORDER_DESC = -1; function log(level, msg) { return NativeModule.log({ level: level, message: msg }); } function validateQuery(query) { if (typeof (query) !== 'object') return {}; if (query.hasOwnProperty('start') && isNaN(query.start)) { throw new Error('Invalid SQLQuery.start. Expected unix timestamp but received: ' + query.start); } if (query.hasOwnProperty('end') && isNaN(query.end)) { throw new Error('Invalid SQLQuery.end. Expected unix timestamp but received: ' + query.end); } return query; } var Logger = /** @class */ (function () { function Logger() { } Object.defineProperty(Logger, "ORDER_ASC", { get: function () { return ORDER_ASC; }, enumerable: false, configurable: true }); Object.defineProperty(Logger, "ORDER_DESC", { get: function () { return ORDER_DESC; }, enumerable: false, configurable: true }); Logger.debug = function (msg) { return log(LOGGER_LOG_LEVEL_DEBUG, msg); }; Logger.error = function (msg) { return log(LOGGER_LOG_LEVEL_ERROR, msg); }; Logger.warn = function (msg) { return log(LOGGER_LOG_LEVEL_WARN, msg); }; Logger.info = function (msg) { return log(LOGGER_LOG_LEVEL_INFO, msg); }; Logger.notice = function (msg) { return log(LOGGER_LOG_LEVEL_NOTICE, msg); }; Logger.getLog = function (query) { query = validateQuery(query); return new Promise(function (resolve, reject) { NativeModule.getLog({ options: query }).then(function (result) { resolve(result.log); }).catch(function (error) { reject(error.message); }); }); }; Logger.destroyLog = function () { return new Promise(function (resolve, reject) { NativeModule.destroyLog().then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; Logger.emailLog = function (email, query) { query = validateQuery(query); return new Promise(function (resolve, reject) { NativeModule.emailLog({ email: email, query: query }).then(function (result) { resolve(result); }).catch(function (error) { reject(error.message); }); }); }; Logger.uploadLog = function (url, query) { query = validateQuery(query); return new Promise(function (resolve, reject) { NativeModule.uploadLog({ url: url, query: query }).then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; return Logger; }()); /** * TransistorAuthorizationToken */ var DEFAULT_URL = 'http://tracker.transistorsoft.com'; var DUMMY_TOKEN = 'DUMMY_TOKEN'; var REFRESH_PAYLOAD = { refresh_token: '{refreshToken}' }; var LOCATIONS_PATH = '/api/locations'; var REFRESH_TOKEN_PATH = '/api/refresh_token'; var TransistorAuthorizationToken = /** @class */ (function () { function TransistorAuthorizationToken() { } TransistorAuthorizationToken.findOrCreate = function (orgname, username, url) { if (url === void 0) { url = DEFAULT_URL; } return new Promise(function (resolve, reject) { NativeModule.getTransistorToken({ org: orgname, username: username, url: url }).then(function (result) { if (result.success) { var token = result.token; token.url = url; resolve(token); } else { console.warn('[TransistorAuthorizationToken findOrCreate] ERROR: ', result); if (result.status == '403') { reject(result); return; } resolve({ accessToken: DUMMY_TOKEN, refreshToken: DUMMY_TOKEN, expires: -1, url: url }); } }).catch(function (error) { reject(error); }); }); }; TransistorAuthorizationToken.destroy = function (url) { if (url === void 0) { url = DEFAULT_URL; } return new Promise(function (resolve, reject) { NativeModule.destroyTransistorToken({ url: url }).then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; TransistorAuthorizationToken.applyIf = function (config) { if (!config.transistorAuthorizationToken) return config; var token = config.transistorAuthorizationToken; delete config.transistorAuthorizationToken; if (!config.http) { config.http = {}; } config.http.url = token.url + LOCATIONS_PATH; config.authorization = { strategy: 'JWT', accessToken: token.accessToken, refreshToken: token.refreshToken, refreshUrl: token.url + REFRESH_TOKEN_PATH, refreshPayload: REFRESH_PAYLOAD, expires: token.expires }; return config; }; return TransistorAuthorizationToken; }()); /** * DeviceSettings */ var IGNORE_BATTERY_OPTIMIZATIONS = "IGNORE_BATTERY_OPTIMIZATIONS"; var POWER_MANAGER = "POWER_MANAGER"; var resolveSettingsRequest = function (resolve, request) { // lastSeenAt arrives from the native bridge as a unix timestamp (number); convert to Date. var lastSeenAt = request.lastSeenAt; if (lastSeenAt > 0) { request.lastSeenAt = new Date(lastSeenAt); } resolve(request); }; var DeviceSettings = /** @class */ (function () { function DeviceSettings() { } DeviceSettings.isIgnoringBatteryOptimizations = function () { return new Promise(function (resolve, reject) { NativeModule.isIgnoringBatteryOptimizations().then(function (result) { resolve(result.isIgnoringBatteryOptimizations); }).catch(function (error) { reject(error.message); }); }); }; DeviceSettings.showIgnoreBatteryOptimizations = function () { return new Promise(function (resolve, reject) { var args = { action: IGNORE_BATTERY_OPTIMIZATIONS }; NativeModule.requestSettings(args).then(function (result) { resolveSettingsRequest(resolve, result); }).catch(function (error) { reject(error.message); }); }); }; DeviceSettings.showPowerManager = function () { return new Promise(function (resolve, reject) { var args = { action: POWER_MANAGER }; NativeModule.requestSettings(args).then(function (result) { resolveSettingsRequest(resolve, result); }).catch(function (error) { reject(error.message); }); }); }; DeviceSettings.show = function (request) { return new Promise(function (resolve, reject) { var args = { action: request.action }; NativeModule.showSettings(args).then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; return DeviceSettings; }()); var TAG = "TSLocationManager"; /// Container for event-subscriptions. var EVENT_SUBSCRIPTIONS = []; /// Container for watchPosition subscriptions, keyed by watchId. var WATCH_POSITION_SUBSCRIPTIONS = new Map(); /// Event handler Subscription /// var Subscription = /** @class */ (function () { function Subscription(event, subscription, callback) { this.event = event; this.subscription = subscription; this.callback = callback; } return Subscription; }()); var LOG_LEVEL_OFF = LogLevel.Off; var LOG_LEVEL_ERROR = LogLevel.Error; var LOG_LEVEL_WARNING = LogLevel.Warning; var LOG_LEVEL_INFO = LogLevel.Info; var LOG_LEVEL_DEBUG = LogLevel.Debug; var LOG_LEVEL_VERBOSE = LogLevel.Verbose; var DESIRED_ACCURACY_NAVIGATION = DesiredAccuracy.Navigation; var DESIRED_ACCURACY_HIGH = DesiredAccuracy.High; var DESIRED_ACCURACY_MEDIUM = DesiredAccuracy.Medium; var DESIRED_ACCURACY_LOW = DesiredAccuracy.Low; var DESIRED_ACCURACY_VERY_LOW = DesiredAccuracy.VeryLow; var DESIRED_ACCURACY_LOWEST = DesiredAccuracy.Lowest; var AUTHORIZATION_STATUS_NOT_DETERMINED = AuthorizationStatus.NotDetermined; var AUTHORIZATION_STATUS_RESTRICTED = AuthorizationStatus.Restricted; var AUTHORIZATION_STATUS_DENIED = AuthorizationStatus.Denied; var AUTHORIZATION_STATUS_ALWAYS = AuthorizationStatus.Always; var AUTHORIZATION_STATUS_WHEN_IN_USE = AuthorizationStatus.WhenInUse; var NOTIFICATION_PRIORITY_DEFAULT = NotificationPriority.Default; var NOTIFICATION_PRIORITY_HIGH = NotificationPriority.High; var NOTIFICATION_PRIORITY_LOW = NotificationPriority.Low; var NOTIFICATION_PRIORITY_MAX = NotificationPriority.Max; var NOTIFICATION_PRIORITY_MIN = NotificationPriority.Min; var ACTIVITY_TYPE_OTHER = ActivityType.Other; var ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION = ActivityType.AutomotiveNavigation; var ACTIVITY_TYPE_FITNESS = ActivityType.Fitness; var ACTIVITY_TYPE_OTHER_NAVIGATION = ActivityType.OtherNavigation; var ACTIVITY_TYPE_AIRBORNE = ActivityType.Airborne; var LOCATION_AUTHORIZATION_ALWAYS = LocationRequest.Always; var LOCATION_AUTHORIZATION_WHEN_IN_USE = LocationRequest.WhenInUse; var LOCATION_AUTHORIZATION_ANY = LocationRequest.Any; var PERSIST_MODE_ALL = PersistMode.All; var PERSIST_MODE_LOCATION = PersistMode.Location; var PERSIST_MODE_GEOFENCE = PersistMode.Geofence; var PERSIST_MODE_NONE = PersistMode.None; var ACCURACY_AUTHORIZATION_FULL = AccuracyAuthorization.Full; var ACCURACY_AUTHORIZATION_REDUCED = AccuracyAuthorization.Reduced; /// BackgroundGeolocation JS API var BackgroundGeolocation = /** @class */ (function () { function BackgroundGeolocation() { } Object.defineProperty(BackgroundGeolocation, "LogLevel", { get: function () { return LogLevel; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "DesiredAccuracy", { get: function () { return DesiredAccuracy; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "PersistMode", { get: function () { return PersistMode; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "AuthorizationStatus", { get: function () { return AuthorizationStatus; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "AccuracyAuthorization", { get: function () { return AccuracyAuthorization; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "AuthorizationStrategy", { get: function () { return AuthorizationStrategy; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LocationFilterPolicy", { get: function () { return LocationFilterPolicy; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "KalmanProfile", { get: function () { return KalmanProfile; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "HttpMethod", { get: function () { return HttpMethod; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "TriggerActivity", { get: function () { return TriggerActivity; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_BOOT", { /// Events get: function () { return Event.Boot; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_TERMINATE", { get: function () { return Event.Terminate; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_LOCATION", { get: function () { return Event.Location; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_MOTIONCHANGE", { get: function () { return Event.MotionChange; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_HTTP", { get: function () { return Event.Http; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_HEARTBEAT", { get: function () { return Event.Heartbeat; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_PROVIDERCHANGE", { get: function () { return Event.ProviderChange; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_ACTIVITYCHANGE", { get: function () { return Event.ActivityChange; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_LOCATIONFILTER", { get: function () { return Event.LocationFilter; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_GEOFENCE", { get: function () { return Event.Geofence; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_GEOFENCESCHANGE", { get: function () { return Event.GeofencesChange; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_ENABLEDCHANGE", { get: function () { return Event.EnabledChange; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_CONNECTIVITYCHANGE", { get: function () { return Event.ConnectivityChange; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_SCHEDULE", { get: function () { return Event.Schedule; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_POWERSAVECHANGE", { get: function () { return Event.PowerSaveChange; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_NOTIFICATIONACTION", { get: function () { return "notificationaction"; } // <-- TODO : Add to background-geolocation-types , enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "EVENT_AUTHORIZATION", { get: function () { return Event.Authorization; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_OFF", { get: function () { return LOG_LEVEL_OFF; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_ERROR", { get: function () { return LOG_LEVEL_ERROR; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_WARNING", { get: function () { return LOG_LEVEL_WARNING; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_INFO", { get: function () { return LOG_LEVEL_INFO; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_DEBUG", { get: function () { return LOG_LEVEL_DEBUG; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LOG_LEVEL_VERBOSE", { get: function () { return LOG_LEVEL_VERBOSE; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "ACTIVITY_TYPE_OTHER", { get: function () { return ACTIVITY_TYPE_OTHER; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION", { get: function () { return ACTIVITY_TYPE_AUTOMOTIVE_NAVIGATION; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "ACTIVITY_TYPE_FITNESS", { get: function () { return ACTIVITY_TYPE_FITNESS; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "ACTIVITY_TYPE_OTHER_NAVIGATION", { get: function () { return ACTIVITY_TYPE_OTHER_NAVIGATION; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "ACTIVITY_TYPE_AIRBORNE", { get: function () { return ACTIVITY_TYPE_AIRBORNE; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_NAVIGATION", { get: function () { return DESIRED_ACCURACY_NAVIGATION; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_HIGH", { get: function () { return DESIRED_ACCURACY_HIGH; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_MEDIUM", { get: function () { return DESIRED_ACCURACY_MEDIUM; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_LOW", { get: function () { return DESIRED_ACCURACY_LOW; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_VERY_LOW", { get: function () { return DESIRED_ACCURACY_VERY_LOW; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "DESIRED_ACCURACY_LOWEST", { get: function () { return DESIRED_ACCURACY_LOWEST; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_NOT_DETERMINED", { get: function () { return AUTHORIZATION_STATUS_NOT_DETERMINED; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_RESTRICTED", { get: function () { return AUTHORIZATION_STATUS_RESTRICTED; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_DENIED", { get: function () { return AUTHORIZATION_STATUS_DENIED; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_ALWAYS", { get: function () { return AUTHORIZATION_STATUS_ALWAYS; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "AUTHORIZATION_STATUS_WHEN_IN_USE", { get: function () { return AUTHORIZATION_STATUS_WHEN_IN_USE; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_DEFAULT", { get: function () { return NOTIFICATION_PRIORITY_DEFAULT; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_HIGH", { get: function () { return NOTIFICATION_PRIORITY_HIGH; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_LOW", { get: function () { return NOTIFICATION_PRIORITY_LOW; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_MAX", { get: function () { return NOTIFICATION_PRIORITY_MAX; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "NOTIFICATION_PRIORITY_MIN", { get: function () { return NOTIFICATION_PRIORITY_MIN; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LOCATION_AUTHORIZATION_ALWAYS", { get: function () { return LOCATION_AUTHORIZATION_ALWAYS; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LOCATION_AUTHORIZATION_WHEN_IN_USE", { get: function () { return LOCATION_AUTHORIZATION_WHEN_IN_USE; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "LOCATION_AUTHORIZATION_ANY", { get: function () { return LOCATION_AUTHORIZATION_ANY; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "PERSIST_MODE_ALL", { get: function () { return PERSIST_MODE_ALL; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "PERSIST_MODE_LOCATION", { get: function () { return PERSIST_MODE_LOCATION; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "PERSIST_MODE_GEOFENCE", { get: function () { return PERSIST_MODE_GEOFENCE; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "PERSIST_MODE_NONE", { get: function () { return PERSIST_MODE_NONE; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "ACCURACY_AUTHORIZATION_FULL", { get: function () { return ACCURACY_AUTHORIZATION_FULL; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "ACCURACY_AUTHORIZATION_REDUCED", { get: function () { return ACCURACY_AUTHORIZATION_REDUCED; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "logger", { get: function () { return Logger; }, enumerable: false, configurable: true }); Object.defineProperty(BackgroundGeolocation, "deviceSettings", { get: function () { return DeviceSettings; }, enumerable: false, configurable: true }); BackgroundGeolocation.ready = function (config) { return NativeModule.ready({ options: config }); }; BackgroundGeolocation.reset = function (config) { return NativeModule.reset({ options: config }); }; BackgroundGeolocation.start = function () { return NativeModule.start(); }; BackgroundGeolocation.stop = function () { return NativeModule.stop(); }; BackgroundGeolocation.startSchedule = function () { return NativeModule.startSchedule(); }; BackgroundGeolocation.stopSchedule = function () { return NativeModule.stopSchedule(); }; BackgroundGeolocation.startGeofences = function () { return NativeModule.startGeofences(); }; BackgroundGeolocation.setConfig = function (config) { return NativeModule.setConfig({ options: config }); }; BackgroundGeolocation.getState = function () { return NativeModule.getState(); }; BackgroundGeolocation.changePace = function (isMoving) { return new Promise(function (resolve, reject) { NativeModule.changePace({ isMoving: isMoving }).then(function () { resolve(); }).catch(function (error) { reject(error.errorMessage); }); }); }; BackgroundGeolocation.getCurrentPosition = function (options) { options = options || {}; return new Promise(function (resolve, reject) { NativeModule.getCurrentPosition({ options: options }).then(function (result) { resolve(result); }).catch(function (error) { reject(error.code); }); }); }; BackgroundGeolocation.watchPosition = function (options, onLocation, onError) { options = options || {}; var isRemoved = false; var nativeWatchId = null; var subscriptionProxy = { remove: function () { isRemoved = true; if (nativeWatchId !== null) { var listener = WATCH_POSITION_SUBSCRIPTIONS.get(nativeWatchId); if (listener) { listener.remove(); WATCH_POSITION_SUBSCRIPTIONS.delete(nativeWatchId); } NativeModule.stopWatchPosition({ watchId: nativeWatchId }); nativeWatchId = null; } } }; var handler = function (response) { if (response.hasOwnProperty("error") && (response.error != null)) { if (typeof (onError) === 'function') { onError(response.error.code); } else { console.warn('[BackgroundGeolocation watchPosition] DEFAULT ERROR HANDLER. Provide an onError callback to watchPosition to receive this message: ', response.error); } } else { onLocation(response); } }; NativeModule.addListener("watchposition", handler).then(function (listener) { NativeModule.watchPosition({ options: options }).then(function (result) { nativeWatchId = result.watchId; if (isRemoved) { // remove() was called before the native async call resolved — honour it now. listener.remove(); NativeModule.stopWatchPosition({ watchId: nativeWatchId }); } else { WATCH_POSITION_SUBSCRIPTIONS.set(nativeWatchId, listener); } }).catch(function () { listener.remove(); }); }); return subscriptionProxy; }; BackgroundGeolocation.stopWatchPosition = function (watchId) { if (watchId !== undefined) { var listener = WATCH_POSITION_SUBSCRIPTIONS.get(watchId); if (listener) { listener.remove(); WATCH_POSITION_SUBSCRIPTIONS.delete(watchId); } NativeModule.stopWatchPosition({ watchId: watchId }); } }; BackgroundGeolocation.requestPermission = function () { return new Promise(function (resolve, reject) { NativeModule.requestPermission().then(function (result) { if (result.success) { resolve(result.status); } else { reject(result.status); } }); }); }; BackgroundGeolocation.requestTemporaryFullAccuracy = function (purpose) { return new Promise(function (resolve, reject) { NativeModule.requestTemporaryFullAccuracy({ purpose: purpose }).then(function (result) { resolve(result.accuracyAuthorization); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.getProviderState = function () { return NativeModule.getProviderState(); }; /// Locations database /// BackgroundGeolocation.getLocations = function () { return new Promise(function (resolve, reject) { NativeModule.getLocations().then(function (result) { resolve(result.locations); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.insertLocation = function (params) { return new Promise(function (resolve, reject) { NativeModule.insertLocation({ options: params }).then(function (result) { resolve(result.uuid); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.destroyLocations = function () { return new Promise(function (resolve, reject) { NativeModule.destroyLocations().then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.destroyLocation = function (uuid) { return new Promise(function (resolve, reject) { NativeModule.destroyLocation({ uuid: uuid }).then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.getCount = function () { return new Promise(function (resolve, reject) { NativeModule.getCount().then(function (result) { resolve(result.count); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.sync = function () { return new Promise(function (resolve, reject) { NativeModule.sync().then(function (result) { resolve(result.locations); }).catch(function (error) { reject(error.message); }); }); }; /// Geofencing /// BackgroundGeolocation.addGeofence = function (params) { return new Promise(function (resolve, reject) { NativeModule.addGeofence({ options: params }).then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.addGeofences = function (params) { return new Promise(function (resolve, reject) { NativeModule.addGeofences({ options: params }).then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.getGeofences = function () { return new Promise(function (resolve, reject) { NativeModule.getGeofences().then(function (result) { resolve(result.geofences); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.getGeofence = function (identifier) { return new Promise(function (resolve, reject) { if (identifier === null) { reject('identifier is null'); return; } NativeModule.getGeofence({ identifier: identifier }).then(function (result) { resolve(result); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.geofenceExists = function (identifier) { return new Promise(function (resolve, reject) { if (identifier === null) { reject('identifier is null'); return; } NativeModule.geofenceExists({ identifier: identifier }).then(function (result) { resolve(result.exists); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.removeGeofence = function (identifier) { return new Promise(function (resolve, reject) { if (identifier === null) { reject('identifier is null'); return; } NativeModule.removeGeofence({ identifier: identifier }).then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.removeGeofences = function (identifiers) { identifiers = identifiers || []; return new Promise(function (resolve, reject) { NativeModule.removeGeofences({ identifiers: identifiers }).then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; /// Odometer /// BackgroundGeolocation.getOdometer = function () { return new Promise(function (resolve, reject) { NativeModule.getOdometer().then(function (result) { resolve(result.odometer); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.setOdometer = function (value) { return new Promise(function (resolve, reject) { NativeModule.setOdometer({ "odometer": value }).then(function (result) { resolve(result); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.resetOdometer = function () { return BackgroundGeolocation.setOdometer(0); }; /// Background Tasks /// BackgroundGeolocation.startBackgroundTask = function () { return new Promise(function (resolve, reject) { NativeModule.startBackgroundTask().then(function (result) { resolve(result.taskId); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.stopBackgroundTask = function (taskId) { return new Promise(function (resolve, reject) { NativeModule.stopBackgroundTask({ taskId: taskId }).then(function () { resolve(); }).catch(function (error) { reject(error.message); }); }); }; /// @alias stopBackgroundTask BackgroundGeolocation.finish = function (taskId) { return BackgroundGeolocation.stopBackgroundTask(taskId); }; BackgroundGeolocation.getDeviceInfo = function () { return NativeModule.getDeviceInfo(); }; BackgroundGeolocation.playSound = function (soundId) { return NativeModule.playSound({ soundId: soundId }); }; BackgroundGeolocation.isPowerSaveMode = function () { return new Promise(function (resolve, reject) { NativeModule.isPowerSaveMode().then(function (result) { resolve(result.isPowerSaveMode); }).catch(function (error) { reject(error.message); }); }); }; BackgroundGeolocation.getSensors = function () { return NativeModule.getSensors(); }; /// TransistorAuthorizationToken /// BackgroundGeolocation.findOrCreateTransistorAuthorizationToken = function (orgname, username, url) { return TransistorAuthorizationToken.findOrCreate(orgname, username, url); }; BackgroundGeolocation.destroyTransistorAuthorizationToken = function (url) { return TransistorAuthorizationToken.destroy(url); }; /// Event Handling /// BackgroundGeolocation.onLocation = function (cb, onError) { return BackgroundGeolocation.addListener(Event.Location, cb, onError); }; BackgroundGeolocation.onMotionChange = function (cb) { return BackgroundGeolocation.addListener(Event.MotionChange, cb); }; BackgroundGeolocation.onHttp = function (cb) { return BackgroundGeolocation.addListener(Event.Http, cb); }; BackgroundGeolocation.onHeartbeat = function (cb) { return BackgroundGeolocation.addListener(Event.Heartbeat, cb); }; BackgroundGeolocation.onProviderChange = function (cb) { return BackgroundGeolocation.addListener(Event.ProviderChange, cb); }; BackgroundGeolocation.onActivityChange = function (cb) { return BackgroundGeolocation.addListener(Event.ActivityChange, cb); }; BackgroundGeolocation.onLocationFilter = function (cb) { return BackgroundGeolocation.addListener(Event.LocationFilter, cb); }; BackgroundGeolocation.onGeofence = function (cb) { return BackgroundGeolocation.addListener(Event.Geofence, cb); }; BackgroundGeolocation.onGeofencesChange = function (cb) { return BackgroundGeolocation.addListener(Event.GeofencesChange, cb); }; BackgroundGeolocation.onSchedule = function (cb) { return BackgroundGeolocation.addListener(Event.Schedule, cb); }; BackgroundGeolocation.onEnabledChange = function (cb) { return BackgroundGeolocation.addListener(Event.EnabledChange, cb); }; BackgroundGeolocation.onConnectivityChange = function (cb) { return BackgroundGeolocation.addListener(Event.ConnectivityChange, cb); }; BackgroundGeolocation.onPowerSaveChange = function (cb) { return BackgroundGeolocation.addListener(Event.PowerSaveChange, cb); }; BackgroundGeolocation.onNotificationAction = function (cb) { return BackgroundGeolocation.addListener("notificationaction", cb); }; BackgroundGeolocation.onAuthorization = function (cb) { return BackgroundGeolocation.addListener(Event.Authorization, cb); }; /// /// Listen to a plugin event /// BackgroundGeolocation.addListener = function (event, success, failure) { var handler = function (response) { if (response.hasOwnProperty("value")) { response = response.value; } if (response.hasOwnProperty("error") && (response.error != null)) { if (typeof (failure) === 'function') { failure(response.error); } else { success(response); } } else { success(response); } }; // Create a flag to capture edge-case where the developer subscribes to an event then IMMEDIATELY calls subscription.remove() // before NativeModule.addListener has resolved. // The developer would have to do something weird like this: // const subscription = BackgroundGeolocation.onLocation(this.onLocation); // subscription.remove(); // // The reason for this is I don't want developers to have to await calls to BackgroundGeolocation.onXXX(myHandler). // var isRemoved = false; var subscriptionProxy = { remove: function () { // EmptyFn until NativeModule.addListener resolves and re-writes this function isRemoved = true; console.warn('[BackgroundGeolocation.addListener] Unexpected call to subscription.remove() on subscriptionProxy. Waiting for NativeModule.addListener to resolve.'); } }; // Now add the listener and re-write subscriptionProxy.remove. NativeModule.addListener(event, handler).then(function (listener) { var subscription = new Subscription(event, listener, success); EVENT_SUBSCRIPTIONS.push(subscription); subscriptionProxy.remove = function () { listener.remove(); // Remove from EVENT_SUBSCRIPTIONS. if (EVENT_SUBSCRIPTIONS.indexOf(subscription) >= 0) { EVENT_SUBSCRIPTIONS.splice(EVENT_SUBSCRIPTIONS.indexOf(subscription), 1); } }; if (isRemoved) { // Caught edge-case. Developer added an event-handler then immediately call subscription.remove(). subscriptionProxy.remove(); } }); return subscriptionProxy; }; BackgroundGeolocation.removeListener = function (event, callback) { console.warn('BackgroundGeolocation.removeListener is deprecated. Event-listener methods (eg: onLocation) now return a Subscription instance. Call subscription.remove() on the returned subscription instead. Eg:\nconst subscription = BackgroundGeolocation.onLocation(myLocationHandler)\n...\nsubscription.remove()'); return new Promise(function (resolve, reject) { var found = null; for (var n = 0, len = EVENT_SUBSCRIPTIONS.length; n < len; n++) { var sub = EVENT_SUBSCRIPTIONS[n]; if ((sub.event === event) && (sub.callback === callback)) { found = sub; break; } } if (found !== null) { EVENT_SUBSCRIPTIONS.splice(EVENT_SUBSCRIPTIONS.indexOf(found), 1); found.subscription.remove(); resolve(); } else { console.warn(TAG + ' Failed to find listener for event ' + event); reject(); } }); }; BackgroundGeolocation.removeListeners = function () { var _this = this; return new Promise(function (resolve) { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) { switch (_a.label) { case 0: EVENT_SUBSCRIPTIONS = []; return [4 /*yield*/, NativeModule.removeAllEventListeners()]; case 1: _a.sent(); resolve(); return [2 /*return*/]; } }); }); }); }; return BackgroundGeolocation; }()); export default BackgroundGeolocation; //# sourceMappingURL=index.js.map