93 lines
2.4 KiB
Dart
93 lines
2.4 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
|
|
import '../config/api_config.dart';
|
|
|
|
class PushApi {
|
|
static Map<String, String> _headers(String token) => {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/json',
|
|
'Authorization': 'Bearer $token',
|
|
};
|
|
|
|
static Future<String> registerDevice({
|
|
required String token,
|
|
required String deviceToken,
|
|
required String platform,
|
|
String? appVersion,
|
|
}) async {
|
|
final uri = Uri.parse('${ApiConfig.laravelApiBase}/register_device.php');
|
|
|
|
final res = await http.post(
|
|
uri,
|
|
headers: _headers(token),
|
|
body: jsonEncode({
|
|
'device_token': deviceToken,
|
|
'platform': platform,
|
|
if (appVersion != null) 'app_version': appVersion,
|
|
}),
|
|
);
|
|
|
|
final data = _decode(res.body, res.statusCode);
|
|
|
|
return (data['push_enabled'] ?? 'Y').toString();
|
|
}
|
|
|
|
static Future<void> unregisterDevice({
|
|
required String token,
|
|
required String deviceToken,
|
|
}) async {
|
|
final uri = Uri.parse('${ApiConfig.laravelApiBase}/register_device.php');
|
|
|
|
final res = await http.delete(
|
|
uri,
|
|
headers: _headers(token),
|
|
body: jsonEncode({'device_token': deviceToken}),
|
|
);
|
|
|
|
_decode(res.body, res.statusCode);
|
|
}
|
|
|
|
static Future<bool> fetchPreference({required String token}) async {
|
|
final uri = Uri.parse('${ApiConfig.laravelApiBase}/push_preference.php');
|
|
|
|
final res = await http.get(uri, headers: _headers(token));
|
|
final data = _decode(res.body, res.statusCode);
|
|
|
|
return (data['push_enabled'] ?? 'Y').toString().toUpperCase() == 'Y';
|
|
}
|
|
|
|
static Future<bool> updatePreference({
|
|
required String token,
|
|
required bool enabled,
|
|
}) async {
|
|
final uri = Uri.parse('${ApiConfig.laravelApiBase}/push_preference.php');
|
|
|
|
final res = await http.post(
|
|
uri,
|
|
headers: _headers(token),
|
|
body: jsonEncode({'enabled': enabled}),
|
|
);
|
|
|
|
final data = _decode(res.body, res.statusCode);
|
|
|
|
return (data['push_enabled'] ?? 'Y').toString().toUpperCase() == 'Y';
|
|
}
|
|
|
|
static Map<String, dynamic> _decode(String body, int statusCode) {
|
|
Map<String, dynamic> data;
|
|
|
|
try {
|
|
data = jsonDecode(body) as Map<String, dynamic>;
|
|
} catch (_) {
|
|
throw Exception('Risposta non valida ($statusCode): $body');
|
|
}
|
|
|
|
if (statusCode != 200 || data['success'] != true) {
|
|
throw Exception(data['error'] ?? data['message'] ?? 'Errore notifiche');
|
|
}
|
|
|
|
return data;
|
|
}
|
|
}
|