Fixes für input fields, #60 -> AuditService

This commit is contained in:
2024-09-12 19:48:29 +02:00
parent d2f6b3ec3f
commit 40ba402c70
13 changed files with 155 additions and 104 deletions

View File

@@ -1,9 +1,10 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { BehaviorSubject, lastValueFrom, Observable } from 'rxjs';
import { ListingEvent } from '../../../../bizmatch-server/src/models/db.model';
import { EventTypeEnum, ListingEvent } from '../../../../bizmatch-server/src/models/db.model';
import { LogMessage } from '../../../../bizmatch-server/src/models/main.model';
import { environment } from '../../environments/environment';
import { GeoService } from './geo.service';
@Injectable({
providedIn: 'root',
@@ -20,47 +21,26 @@ export class AuditService {
private geoLocationSubject = new BehaviorSubject<any>(null);
public geoLocation$: Observable<any> = this.geoLocationSubject.asObservable();
constructor(private http: HttpClient) {}
constructor(private http: HttpClient, private geoService: GeoService) {}
async log(message: LogMessage): Promise<void> {
lastValueFrom(this.http.post(`${this.apiBaseUrl}/bizmatch/log`, message));
}
async createEvent(event: ListingEvent): Promise<void> {
lastValueFrom(this.http.post(`${this.apiBaseUrl}/bizmatch/event`, event));
}
// Function to get the IP address
private getIpAddress(): Observable<{ ip: string }> {
return this.http.get<{ ip: string }>(`/ipinfo?format=json`);
}
// Function to get geolocation using IP address
private getGeolocation(ip: string): Observable<any> {
return this.http.get(`/ipinfo/${ip}?token=${this.apiKey}`);
}
// Fetch IP and Geolocation only once, if not already fetched
fetchIpAndGeoLocation(): void {
if (!this.geoLocationSubject.getValue()) {
this.getIpAddress().subscribe({
next: response => {
this.getGeolocation(response.ip).subscribe({
next: geoData => {
this.geoLocationSubject.next(geoData); // Store the geolocation data
},
error: geoError => {
console.error('Error fetching geolocation:', geoError);
},
});
},
error: ipError => {
console.error('Error fetching IP address:', ipError);
},
});
}
}
// Method to provide the stored geolocation data
getGeoLocationData(): Observable<any> {
return this.geoLocation$; // Returns the observable for other components to subscribe
async createEvent(id: string, eventType: EventTypeEnum, userId: string): Promise<void> {
const ipInfo = await this.geoService.getIpInfo();
const [latitude, longitude] = ipInfo.loc ? ipInfo.loc.split(',') : [null, null]; //.map(Number);
const listingEvent: ListingEvent = {
listingId: id,
eventType,
eventTimestamp: new Date(),
userAgent: navigator.userAgent,
email: userId,
userIp: ipInfo.ip,
locationCountry: ipInfo.country,
locationCity: ipInfo.city,
locationLat: latitude,
locationLng: longitude,
};
lastValueFrom(this.http.post(`${this.apiBaseUrl}/bizmatch/event`, listingEvent));
}
}

View File

@@ -1,6 +1,6 @@
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { BehaviorSubject, lastValueFrom, Observable } from 'rxjs';
import { CityAndStateResult, CountyResult, GeoResult, IpInfo } from '../../../../bizmatch-server/src/models/main.model';
import { Place } from '../../../../bizmatch-server/src/models/server.model';
import { environment } from '../../environments/environment';
@@ -11,6 +11,9 @@ import { environment } from '../../environments/environment';
export class GeoService {
private apiBaseUrl = environment.apiBaseUrl;
private baseUrl: string = 'https://nominatim.openstreetmap.org/search';
private ipInfo$ = new BehaviorSubject<IpInfo | null>(null);
private fetchingData: Observable<IpInfo> | null = null;
private readonly storageKey = 'ipInfo';
constructor(private http: HttpClient) {}
findCitiesStartingWith(prefix: string, state?: string): Observable<GeoResult[]> {
@@ -27,7 +30,49 @@ export class GeoService {
let headers = new HttpHeaders().set('X-Hide-Loading', 'true').set('Accept-Language', 'en-US');
return this.http.get(`${this.baseUrl}?q=${prefix},US&format=json&addressdetails=1&limit=5`, { headers }) as Observable<Place[]>;
}
fetchIpAndGeoLocation(): Observable<IpInfo> {
private fetchIpAndGeoLocation(): Observable<IpInfo> {
return this.http.get<IpInfo>(`${this.apiBaseUrl}/bizmatch/geo/ipinfo/georesult/wysiwyg`);
}
// getIpInfo(): Observable<IpInfo | null> {
// if (this.ipInfo$.getValue() !== null) {
// // Wenn wir bereits Daten haben, geben wir sie sofort zurück
// return this.ipInfo$.asObservable();
// } else if (this.fetchingData) {
// // Wenn wir gerade Daten abrufen, geben wir diesen Observable zurück
// return this.fetchingData;
// } else {
// // Ansonsten initiieren wir den Abruf
// this.fetchingData = this.fetchIpAndGeoLocation().pipe(
// tap(data => this.ipInfo$.next(data)),
// catchError(error => {
// console.error('Error fetching IP info:', error);
// this.ipInfo$.next(null);
// return of(null);
// }),
// shareReplay(1),
// );
// return this.fetchingData;
// }
// }
async getIpInfo(): Promise<IpInfo | null> {
// Versuche zuerst, die Daten aus dem sessionStorage zu holen
const storedData = sessionStorage.getItem(this.storageKey);
if (storedData) {
return JSON.parse(storedData);
}
try {
// Wenn keine Daten im Storage, hole sie vom Server
const data = await lastValueFrom(this.http.get<IpInfo>(`${this.apiBaseUrl}/bizmatch/geo/ipinfo/georesult/wysiwyg`));
// Speichere die Daten im sessionStorage
sessionStorage.setItem(this.storageKey, JSON.stringify(data));
return data;
} catch (error) {
console.error('Error fetching IP info:', error);
return null;
}
}
}