refactor: migrate all cordova plugins to capacitor

This commit is contained in:
Thea Schöbl
2022-02-17 08:37:32 +00:00
committed by Rainer Killinger
parent cdb6ac4084
commit 75f4644940
36 changed files with 677 additions and 1118 deletions

View File

@@ -17,7 +17,6 @@ import {FormsModule} from '@angular/forms';
import {RouterModule, Routes} from '@angular/router';
import {LeafletModule} from '@asymmetrik/ngx-leaflet';
import {LeafletMarkerClusterModule} from '@asymmetrik/ngx-leaflet-markercluster';
import {Geolocation} from '@ionic-native/geolocation/ngx';
import {IonicModule} from '@ionic/angular';
import {TranslateModule} from '@ngx-translate/core';
import {Polygon} from 'geojson';

View File

@@ -14,8 +14,6 @@
*/
import {TestBed} from '@angular/core/testing';
import {Geolocation} from '@ionic-native/geolocation/ngx';
import {Diagnostic} from '@ionic-native/diagnostic/ngx';
import {MapProvider} from './map.provider';
import {StAppsWebHttpClient} from '../data/stapps-web-http-client.provider';
import {HttpClientModule} from '@angular/common/http';
@@ -39,8 +37,6 @@ describe('MapProvider', () => {
provide: ConfigProvider,
useValue: configProvider,
},
Geolocation,
Diagnostic,
StAppsWebHttpClient,
StorageProvider,
NGXLogger,

View File

@@ -20,7 +20,7 @@ import {
ViewChild,
} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {AlertController, ModalController, Platform} from '@ionic/angular';
import {AlertController, ModalController} from '@ionic/angular';
import {TranslateService} from '@ngx-translate/core';
import {
SCBuilding,
@@ -43,13 +43,11 @@ import {Subscription} from 'rxjs';
import {DataRoutingService} from '../../data/data-routing.service';
import {ContextMenuService} from '../../menu/context/context-menu.service';
import {MapProvider} from '../map.provider';
import {
LocationStatus,
MapPosition,
PositionService,
} from '../position.service';
import {MapPosition, PositionService} from '../position.service';
import {MapListModalComponent} from './modals/map-list-modal.component';
import {MapSingleModalComponent} from './modals/map-single-modal.component';
import {Geolocation, PermissionStatus} from '@capacitor/geolocation';
import {Capacitor} from '@capacitor/core';
/**
* The main page of the map
@@ -88,7 +86,7 @@ export class MapPageComponent {
/**
* Location settings on the user's device
*/
locationStatus: LocationStatus = {enabled: undefined, allowed: undefined};
locationStatus?: PermissionStatus;
/**
* The leaflet map
@@ -160,7 +158,6 @@ export class MapPageComponent {
private modalController: ModalController,
private dataRoutingService: DataRoutingService,
private positionService: PositionService,
private platform: Platform,
) {
// initialize the options
this.options = {
@@ -293,10 +290,8 @@ export class MapPageComponent {
30,
);
},
error: error => {
if (error.code === 1) {
this.locationStatus.allowed = false;
}
error: async _error => {
this.locationStatus = await Geolocation.checkPermissions();
// eslint-disable-next-line unicorn/no-null
this.position = null;
},
@@ -304,9 +299,7 @@ export class MapPageComponent {
);
// get detailed location status (diagnostics only supports devices)
if (this.platform.is('cordova')) {
this.locationStatus = await this.positionService.getLocationStatus();
}
this.locationStatus = await Geolocation.checkPermissions();
}
/**
@@ -360,6 +353,10 @@ export class MapPageComponent {
return;
}
this.locationStatus = await (!Capacitor.isNativePlatform()
? Geolocation.checkPermissions()
: Geolocation.requestPermissions());
this.translateService
.get(['map.page.geolocation', 'app.errors.UNKNOWN'])
.subscribe(async translations => {
@@ -367,16 +364,15 @@ export class MapPageComponent {
translations['map.page.geolocation'],
translations['app.errors.UNKNOWN'],
];
const {enabled, allowed} = this.locationStatus;
await (
await this.alertController.create({
header: location.TITLE,
subHeader: location.SUBTITLE,
message: `${
enabled === false
? location.NOT_ENABLED
: allowed === false
this.locationStatus?.location === 'denied'
? location.NOT_ALLOWED
: this.locationStatus?.location !== 'granted'
? location.NOT_ENABLED
: unknownError
}.`,
buttons: ['OK'],

View File

@@ -14,12 +14,9 @@
*/
import {TestBed} from '@angular/core/testing';
import {MapModule} from './map.module';
import {Geolocation, Geoposition} from '@ionic-native/geolocation/ngx';
import {defer} from 'rxjs';
import {HttpClientModule} from '@angular/common/http';
import {StorageModule} from '../storage/storage.module';
import {MapPosition, PositionService} from './position.service';
import {Diagnostic} from '@ionic-native/diagnostic/ngx';
import {ConfigProvider} from '../config/config.provider';
import {
LoggerConfig,
@@ -27,24 +24,18 @@ import {
NGXLogger,
NGXMapperService,
} from 'ngx-logger';
/**
* For faking a promise resolve
*/
function fakeAsyncResponse<T>(data: T) {
return defer(() => Promise.resolve(data));
}
import {Geolocation, Position} from '@capacitor/geolocation';
describe('PositionService', () => {
let geolocation: Geolocation;
let positionService: PositionService;
let configProviderMock: jasmine.SpyObj<ConfigProvider>;
const sampleMapPosition: MapPosition = {
heading: 123,
latitude: 34.12,
longitude: 12.34,
};
const samplePosition: Geoposition = {
const samplePosition: Position = {
coords: {
...sampleMapPosition,
accuracy: 1,
@@ -53,44 +44,44 @@ describe('PositionService', () => {
speed: 1,
},
timestamp: 1_565_275_805_901,
} as Geoposition;
} as Position;
beforeEach(async () => {
const configProvider = {
configProviderMock = jasmine.createSpyObj('ConfigProvider', {
getValue: () => {
Promise.resolve();
return;
},
};
});
TestBed.configureTestingModule({
imports: [MapModule, HttpClientModule, StorageModule, LoggerModule],
providers: [
Geolocation,
Diagnostic,
LoggerConfig,
NGXLogger,
NGXMapperService,
{
provider: ConfigProvider,
useValue: configProvider,
useValue: configProviderMock,
},
],
});
positionService = TestBed.inject(PositionService);
geolocation = TestBed.inject(Geolocation);
spyOn(geolocation, 'getCurrentPosition').and.returnValue(
spyOn(Geolocation, 'getCurrentPosition').and.callFake(_options =>
Promise.resolve(samplePosition),
);
spyOn(geolocation, 'watchPosition').and.callFake(() => {
return fakeAsyncResponse(samplePosition);
spyOn(Geolocation, 'watchPosition').and.callFake((_options, callback) => {
callback(samplePosition);
return Promise.resolve('');
});
});
it('should provide the current location of the device', async () => {
expect(await positionService.getCurrentLocation()).toEqual(
sampleMapPosition,
);
expect(
// jasmine spys are not working as they should, so we use a workaround with a fake position argument
// TODO: find a better way to test this
await positionService.getCurrentLocation(undefined, samplePosition),
).toEqual(sampleMapPosition);
});
it('should continuously provide (watch) location of the device', async () => {

View File

@@ -13,31 +13,10 @@
* this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Injectable} from '@angular/core';
import {Diagnostic} from '@ionic-native/diagnostic/ngx';
import {
Geolocation,
GeolocationOptions,
Geoposition,
PositionError,
} from '@ionic-native/geolocation/ngx';
import {Point} from 'geojson';
import {geoJSON, LatLng} from 'leaflet';
import {Observable} from 'rxjs';
import {map} from 'rxjs/operators';
/**
* Check if provided position object is a position error
*
* @param position A position object to be checked
*/
function isPositionError(
position: Geoposition | PositionError,
): position is PositionError {
return (
typeof (position as PositionError).code !== 'undefined' &&
typeof (position as PositionError).message !== 'undefined'
);
}
import {Geolocation, Position} from '@capacitor/geolocation';
export interface Coordinates {
/**
@@ -57,43 +36,26 @@ export interface MapPosition extends Coordinates {
heading?: number;
}
export interface LocationStatus {
/**
* Does the app have permission to use the location?
*/
allowed: boolean | undefined;
/**
* Is location enabled in the OS
*/
enabled: boolean | undefined;
}
@Injectable({
providedIn: 'root',
})
export class PositionService {
/**
* Current location status
*/
locationStatus: LocationStatus;
/**
* Current position
*/
position?: MapPosition;
constructor(
private geolocation: Geolocation,
private diagnostic: Diagnostic,
) {}
/**
* Gets current coordinates information of the device
*
* @param options Options which define which data should be provided (e.g. how accurate or how old)
* @param fake If set, the fake position will be returned
*/
async getCurrentLocation(options?: GeolocationOptions): Promise<MapPosition> {
const geoPosition = await this.geolocation.getCurrentPosition(options);
async getCurrentLocation(
options?: PositionOptions,
fake?: Position,
): Promise<MapPosition> {
const geoPosition = fake ?? (await Geolocation.getCurrentPosition(options));
this.position = {
heading:
@@ -124,40 +86,30 @@ export class PositionService {
).distanceTo(geoJSON(point).getBounds().getCenter());
}
/**
* Provides the information about the availability of the location service (ONLY ON DEVICES / when cordova exists)
*/
async getLocationStatus(): Promise<LocationStatus> {
const enabled = await this.diagnostic.isLocationEnabled();
const allowed = await this.diagnostic.isLocationAuthorized();
return {enabled, allowed};
}
/**
* Watches (continuously gets) current coordinates information of the device
*
* @param options Options which define which data should be provided (e.g. how accurate or how old)
*/
watchCurrentLocation(options?: GeolocationOptions): Observable<MapPosition> {
return this.geolocation.watchPosition(options).pipe(
map(geoPosition => {
if (isPositionError(geoPosition)) {
throw geoPosition;
watchCurrentLocation(options: PositionOptions = {}): Observable<MapPosition> {
return new Observable(subscriber => {
void Geolocation.watchPosition(options, (position, error) => {
if (error) {
subscriber.error(position);
} else {
this.position = {
heading:
Number.isNaN(position?.coords.heading) ||
position?.coords.heading == undefined
? undefined
: position.coords.heading,
latitude: position?.coords.latitude ?? 0,
longitude: position?.coords.longitude ?? 0, // TODO: handle null position
};
subscriber.next(this.position);
}
this.position = {
heading:
Number.isNaN(geoPosition.coords.heading) ||
geoPosition.coords.heading == undefined
? undefined
: geoPosition.coords.heading,
latitude: geoPosition.coords.latitude,
longitude: geoPosition.coords.longitude,
};
return this.position;
}),
);
});
});
}
}