Files
maps_bookmarks/lib/service/share_intent_service.dart
2025-11-02 16:14:10 +01:00

117 lines
3.2 KiB
Dart

import 'package:flutter/services.dart';
class ShareIntentService {
static const _platform = MethodChannel('app.channel.shared.data');
static ShareIntentService? _instance;
// Singleton pattern
factory ShareIntentService() {
_instance ??= ShareIntentService._internal();
return _instance!;
}
ShareIntentService._internal();
/// Retrieves shared text from the platform channel
/// Returns null if no shared text is available
Future<String?> getSharedText() async {
try {
final String? sharedText = await _platform.invokeMethod('getSharedText');
return sharedText;
} on PlatformException catch (e) {
// Log error in production app
print('Failed to get shared text: ${e.message}');
return null;
}
}
/// Checks if the text is a Google Maps link
bool isGoogleMapsLink(String text) {
return text.contains('maps.google.com') ||
text.contains('maps.app.goo.gl') ||
text.contains('goo.gl/maps');
}
/// Extracts metadata from a Google Maps link
MapsLinkMetadata extractMetadata(String mapsLink) {
String? placeName;
String? latitude;
String? longitude;
String? address;
// Extract place name from URL
final placeMatch = RegExp(r'/place/([^/]+)').firstMatch(mapsLink);
if (placeMatch != null) {
placeName = Uri.decodeComponent(
placeMatch.group(1)!,
).replaceAll('+', ' ');
}
// Extract coordinates
final coordMatch = RegExp(
r'@(-?\d+\.\d+),(-?\d+\.\d+)',
).firstMatch(mapsLink);
if (coordMatch != null) {
latitude = coordMatch.group(1);
longitude = coordMatch.group(2);
}
// Extract search query/address
final searchMatch = RegExp(r'/search/([^/?]+)').firstMatch(mapsLink);
if (searchMatch != null) {
address = Uri.decodeComponent(searchMatch.group(1)!).replaceAll('+', ' ');
// Use address as place name if name not found
placeName ??= address;
}
// Extract from data parameter (alternative format)
final dataMatch = RegExp(r'[?&]q=([^&]+)').firstMatch(mapsLink);
if (dataMatch != null && placeName == null) {
final query = Uri.decodeComponent(dataMatch.group(1)!);
// Check if it's coordinates
final coordPattern = RegExp(r'^(-?\d+\.\d+),(-?\d+\.\d+)$');
final coords = coordPattern.firstMatch(query);
if (coords != null) {
latitude ??= coords.group(1);
longitude ??= coords.group(2);
} else {
placeName = query.replaceAll('+', ' ');
}
}
return MapsLinkMetadata(
url: mapsLink,
placeName: placeName ?? 'Unknown Location',
latitude: latitude,
longitude: longitude,
address: address,
);
}
}
/// Data class for Google Maps link metadata
class MapsLinkMetadata {
final String url;
final String placeName;
final String? latitude;
final String? longitude;
final String? address;
const MapsLinkMetadata({
required this.url,
required this.placeName,
this.latitude,
this.longitude,
this.address,
});
String get coordinates {
if (latitude != null && longitude != null) {
return '$latitude, $longitude';
}
return '';
}
bool get hasCoordinates => latitude != null && longitude != null;
}