This commit is contained in:
wuxu
2026-04-28 17:34:03 +08:00
commit 80ee99e564
43 changed files with 6330 additions and 0 deletions

View File

@@ -0,0 +1,64 @@
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<String> login(String username, String password) async {
final res = await http.post(
Uri.parse('$_baseUrl/api/auth/login'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'username': username, 'password': password}),
);
if (res.statusCode != 200) throw Exception(_error(res));
return jsonDecode(res.body)['token'];
}
Future<String> register(String username, String password) async {
final res = await http.post(
Uri.parse('$_baseUrl/api/auth/register'),
headers: {'Content-Type': 'application/json'},
body: jsonEncode({'username': username, 'password': password}),
);
if (res.statusCode != 201) throw Exception(_error(res));
return jsonDecode(res.body)['token'];
}
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})';
}
}
}