Surface/lib/providers/sn_network.dart

151 lines
4.0 KiB
Dart
Raw Normal View History

2024-11-09 10:28:45 +00:00
import 'dart:convert';
import 'dart:developer';
2024-11-08 16:09:46 +00:00
import 'package:dio/dio.dart';
import 'package:dio_smart_retry/dio_smart_retry.dart';
2024-11-09 10:28:45 +00:00
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
2024-11-10 14:14:27 +00:00
import 'package:shared_preferences/shared_preferences.dart';
import 'package:surface/providers/adapters/sn_network_universal.dart';
2024-11-08 16:09:46 +00:00
2024-11-09 10:28:45 +00:00
const kAtkStoreKey = 'nex_user_atk';
const kRtkStoreKey = 'nex_user_rtk';
2024-11-10 14:14:27 +00:00
const kNetworkServerDefault = 'https://api.sn-next.solsynth.dev';
const kNetworkServerStoreKey = 'app_server_url';
const kNetworkServerDirectory = [
('SN Preview', 'https://api.sn-next.solsynth.dev'),
('SN Stable', 'https://api.sn.solsynth.dev'),
('Local', 'http://localhost:8001'),
];
2024-11-08 16:09:46 +00:00
class SnNetworkProvider {
late Dio client;
2024-11-08 16:09:46 +00:00
2024-11-10 14:14:27 +00:00
late final SharedPreferences _prefs;
2024-11-09 10:28:45 +00:00
late final FlutterSecureStorage _storage = FlutterSecureStorage();
2024-11-08 16:09:46 +00:00
SnNetworkProvider() {
client = Dio();
client.interceptors.add(RetryInterceptor(
dio: client,
retries: 3,
retryDelays: const [
Duration(milliseconds: 300),
Duration(milliseconds: 1000),
Duration(milliseconds: 3000),
],
));
2024-11-08 16:09:46 +00:00
2024-11-09 10:28:45 +00:00
client.interceptors.add(
InterceptorsWrapper(
onRequest: (
RequestOptions options,
RequestInterceptorHandler handler,
) async {
2024-11-14 16:24:46 +00:00
final atk = await getFreshAtk();
if (atk != null) {
options.headers['Authorization'] = 'Bearer $atk';
2024-11-09 10:28:45 +00:00
}
2024-11-14 16:24:46 +00:00
return handler.next(options);
2024-11-09 10:28:45 +00:00
},
),
);
client = addClientAdapter(client);
2024-11-10 14:14:27 +00:00
SharedPreferences.getInstance().then((prefs) {
_prefs = prefs;
client.options.baseUrl =
_prefs.getString(kNetworkServerStoreKey) ?? kNetworkServerDefault;
});
2024-11-08 16:09:46 +00:00
}
2024-11-09 03:16:14 +00:00
2024-11-14 16:24:46 +00:00
Future<String?> getFreshAtk() async {
try {
var atk = await _storage.read(key: kAtkStoreKey);
if (atk != null) {
final atkParts = atk.split('.');
if (atkParts.length != 3) {
throw Exception('invalid format of access token');
}
var rawPayload = atkParts[1].replaceAll('-', '+').replaceAll('_', '/');
switch (rawPayload.length % 4) {
case 0:
break;
case 2:
rawPayload += '==';
break;
case 3:
rawPayload += '=';
break;
default:
throw Exception('illegal format of access token payload');
}
final b64 = utf8.fuse(base64Url);
final payload = b64.decode(rawPayload);
final exp = jsonDecode(payload)['exp'];
if (exp <= DateTime.now().millisecondsSinceEpoch ~/ 1000) {
log('Access token need refresh, doing it at ${DateTime.now()}');
atk = await refreshToken();
}
if (atk != null) {
return atk;
} else {
log('Access token refresh failed...');
}
}
} catch (err) {
log('Failed to authenticate user: $err');
}
return null;
}
2024-11-09 03:16:14 +00:00
String getAttachmentUrl(String ky) {
if (ky.startsWith("http")) return ky;
2024-11-09 03:16:14 +00:00
return '${client.options.baseUrl}/cgi/uc/attachments/$ky';
}
2024-11-09 10:28:45 +00:00
Future<void> setTokenPair(String atk, String rtk) async {
await Future.wait([
_storage.write(key: kAtkStoreKey, value: atk),
_storage.write(key: kRtkStoreKey, value: rtk),
]);
}
Future<void> clearTokenPair() async {
await Future.wait([
_storage.delete(key: kAtkStoreKey),
_storage.delete(key: kRtkStoreKey),
]);
}
Future<String?> refreshToken() async {
final rtk = await _storage.read(key: kRtkStoreKey);
if (rtk == null) return null;
2024-11-09 11:32:21 +00:00
final dio = Dio();
2024-11-10 14:14:27 +00:00
dio.options.baseUrl = client.options.baseUrl;
2024-11-09 11:32:21 +00:00
final resp = await dio.post('/cgi/id/auth/token', data: {
2024-11-09 10:28:45 +00:00
'grant_type': 'refresh_token',
'refresh_token': rtk,
});
final atk = resp.data['access_token'];
final nRtk = resp.data['refresh_token'];
await setTokenPair(atk, nRtk);
return atk;
}
2024-11-10 14:14:27 +00:00
void setBaseUrl(String url) {
client.options.baseUrl = url;
}
2024-11-08 16:09:46 +00:00
}