64 lines
1.8 KiB
Dart
64 lines
1.8 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
import '../models/sms_message.dart';
|
|
|
|
class ApiService {
|
|
String _baseUrl = '';
|
|
String? _token;
|
|
|
|
void configure(String baseUrl, String token) {
|
|
_baseUrl = baseUrl.endsWith('/') ? baseUrl.substring(0, baseUrl.length - 1) : baseUrl;
|
|
_token = token;
|
|
}
|
|
|
|
Map<String, String> get _headers => {
|
|
'Content-Type': 'application/json',
|
|
if (_token != null) 'Authorization': 'Bearer $_token',
|
|
};
|
|
|
|
Future<bool> verifyToken(String token) async {
|
|
final res = await http.post(
|
|
Uri.parse('$_baseUrl/api/auth/verify'),
|
|
headers: {'Content-Type': 'application/json'},
|
|
body: jsonEncode({'token': token}),
|
|
);
|
|
return res.statusCode == 200;
|
|
}
|
|
|
|
Future<List<Map<String, dynamic>>> fetchServerSms() async {
|
|
final res = await http.get(
|
|
Uri.parse('$_baseUrl/api/sms?limit=999999'),
|
|
headers: _headers,
|
|
);
|
|
if (res.statusCode != 200) throw Exception(_error(res));
|
|
final data = jsonDecode(res.body);
|
|
return List<Map<String, dynamic>>.from(data['messages']);
|
|
}
|
|
|
|
Future<int> uploadSms(List<SmsMessage> messages) async {
|
|
final res = await http.post(
|
|
Uri.parse('$_baseUrl/api/sms/upload'),
|
|
headers: _headers,
|
|
body: jsonEncode(messages.map((m) => m.toJson()).toList()),
|
|
);
|
|
if (res.statusCode != 200) throw Exception(_error(res));
|
|
return jsonDecode(res.body)['uploaded'];
|
|
}
|
|
|
|
Future<void> registerDevice(String deviceName) async {
|
|
await http.post(
|
|
Uri.parse('$_baseUrl/api/devices/register'),
|
|
headers: _headers,
|
|
body: jsonEncode({'device_name': deviceName}),
|
|
);
|
|
}
|
|
|
|
String _error(http.Response res) {
|
|
try {
|
|
return jsonDecode(res.body)['error'] ?? 'Request failed';
|
|
} catch (_) {
|
|
return 'Request failed (${res.statusCode})';
|
|
}
|
|
}
|
|
}
|