Created
November 22, 2023 17:29
-
-
Save aaadipop/8ecea5a9977d5f5cf24ff696fc5a892f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { Subject, BehaviorSubject } from 'rxjs'; | |
import { environment } from '@env/environment'; | |
import { HttpClient } from '@angular/common/http'; | |
import { takeUntil } from 'rxjs/operators'; | |
import { AuthService } from '@app-common/service/auth.service'; | |
import { BackgroundGeolocationPlugin, Location } from "cordova-background-geolocation-plugin"; | |
declare let BackgroundGeolocation: BackgroundGeolocationPlugin; | |
@Injectable() | |
export class TrackService { | |
private tracking = new BehaviorSubject<any>({ active: false, actionId: undefined, acc: 2000, error: undefined, lat: undefined, lng: undefined, time: undefined }); | |
public trackingObs = this.tracking.asObservable(); | |
private onDestroy$: Subject<void> = new Subject<void>(); | |
constructor(private readonly http: HttpClient, | |
private authService: AuthService) {} | |
base(path): string{ | |
return `${environment.actionApi}/` + ( path != undefined ? path : '' )} | |
track(actionId, userResponse){ | |
this.http.post<boolean>(this.base(actionId + '/track'), userResponse)} | |
// ---------- | |
status(){ | |
BackgroundGeolocation.checkStatus((status) => { | |
console.log('[INFO] BackgroundGeolocation service is running', status.isRunning); | |
console.log('[INFO] BackgroundGeolocation services enabled', status.locationServicesEnabled); | |
console.log('[INFO] BackgroundGeolocation auth status: ' + status.authorization); | |
this.tracking.next({ ...this.tracking.value, active: status.isRunning }) | |
// if (status.authorization === 0) //BackgroundGeolocation.NOT_AUTHORIZED) { | |
// BackgroundGeolocation.showAppSettings() | |
// if (status.locationServicesEnabled === false) | |
// BackgroundGeolocation.showLocationSettings() | |
}, (error) => { console.log("check status err: ", error)}) | |
} | |
start(actionId){ | |
this.stop(); // clear everithing | |
this.tracking.next({ ...this.tracking.value, active: true, actionId: actionId }) | |
BackgroundGeolocation.configure({ | |
locationProvider: BackgroundGeolocation.RAW_PROVIDER, //DISTANCE_FILTER_PROVIDER | |
desiredAccuracy: BackgroundGeolocation.HIGH_ACCURACY, | |
distanceFilter: 0, | |
stopOnTerminate: true, | |
notificationTitle: "App name", | |
notificationText: "App will get your location", | |
interval: 5000, | |
fastestInterval: 3000, | |
debug: true, | |
startForeground: true, | |
maxLocations: 3, | |
notificationIconLarge: "bg_notification", | |
notificationIconSmall: "bg_notification", | |
url: `${environment.actionApi}/${actionId}/track`, | |
postTemplate: { trackLat: '@latitude', trackLng: '@longitude', trackAcc: '@accuracy', trackAlt: '@altitude', trackTimestamp: '@time' }, | |
httpHeaders: { 'Authorization': `Bearer ${localStorage.getItem('jwt_token')}` } | |
}); | |
BackgroundGeolocation.on("location").subscribe(async (_: Location) => { | |
await this.locationUpdate();}); | |
BackgroundGeolocation.on("authorization").subscribe( | |
(status) => { | |
if (status === BackgroundGeolocation.NOT_AUTHORIZED) | |
BackgroundGeolocation.showAppSettings()}); | |
BackgroundGeolocation.on("abort_requested").subscribe( | |
(data) => this.stop()); | |
BackgroundGeolocation.on("error").subscribe( | |
(error) => this.tracking.next({ ...this.tracking.value, error: 'Așteptare coordonate' })); //${error.message} | |
BackgroundGeolocation.start(); | |
this.authService.jwtObs.pipe(takeUntil(this.onDestroy$)) | |
.subscribe(data => this.jwtUpdate(data)) | |
this.currentLocation(); | |
} | |
async locationUpdate() { | |
let locations = await BackgroundGeolocation.getValidLocations(); //getValidLocationsAndDelete(); | |
if (locations.length == 0) | |
return; | |
let location = locations.reduce(function(prev, curr) { | |
return prev.accuracy < curr.accuracy ? prev : curr;}); | |
if (location.accuracy < 25){ | |
BackgroundGeolocation.stop(); // add some sleep here? | |
BackgroundGeolocation.configure({ interval: 15000, fastestInterval: 15000, distanceFilter: 15 }); | |
BackgroundGeolocation.start(); | |
} | |
if (location) | |
this.tracking.next({ ...this.tracking.value, lat: location.latitude, lng: location.longitude, acc: location.accuracy })} | |
currentLocation(){ | |
BackgroundGeolocation.getCurrentLocation(location => { | |
this.tracking.next({ ...this.tracking.value, lat: location.latitude, lng: location.longitude, acc: location.accuracy }) | |
// this.track(this.tracking.value.actionId, {trackLat: location.latitude, trackLng: location.longitude, trackAcc: location.accuracy, trackAlt: location.altitude}) | |
// .subscribe( | |
// data => {}) | |
}, error => console.log(error), {timeout: Infinity, maximumAge: 0, enableHighAccuracy: true})} | |
jwtUpdate(jwt){ | |
if (this.tracking.value.active) | |
BackgroundGeolocation.configure({ httpHeaders: {'Authorization': `Bearer ${jwt}`} })} | |
stop(){ | |
BackgroundGeolocation.stop(); | |
BackgroundGeolocation.removeAllListeners(); | |
this.onDestroy$.next(); | |
this.onDestroy$.complete(); | |
this.tracking.next({ ...this.tracking.value, active: false, actionId: undefined, acc: 2000, error: undefined, lat: undefined, lng: undefined, time: undefined })} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment