2024-11-09 10:28:45 +00:00
|
|
|
import 'dart:developer';
|
2024-11-08 16:09:46 +00:00
|
|
|
|
2024-11-09 10:28:45 +00:00
|
|
|
import 'package:flutter/material.dart';
|
2024-12-20 17:58:49 +00:00
|
|
|
import 'package:path/path.dart';
|
2024-11-09 10:28:45 +00:00
|
|
|
import 'package:provider/provider.dart';
|
2024-11-23 11:54:38 +00:00
|
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
2024-12-20 17:58:49 +00:00
|
|
|
import 'package:surface/providers/config.dart';
|
2024-11-09 10:28:45 +00:00
|
|
|
import 'package:surface/providers/sn_network.dart';
|
2024-12-14 10:18:13 +00:00
|
|
|
import 'package:surface/providers/widget.dart';
|
2024-11-09 10:28:45 +00:00
|
|
|
import 'package:surface/types/account.dart';
|
|
|
|
|
|
|
|
class UserProvider extends ChangeNotifier {
|
|
|
|
bool isAuthorized = false;
|
|
|
|
SnAccount? user;
|
|
|
|
|
2024-11-09 11:32:21 +00:00
|
|
|
late final SnNetworkProvider _sn;
|
2024-12-14 10:18:13 +00:00
|
|
|
late final HomeWidgetProvider _home;
|
2024-12-20 17:58:49 +00:00
|
|
|
late final ConfigProvider _config;
|
2024-12-14 10:18:13 +00:00
|
|
|
|
|
|
|
UserProvider(BuildContext context) {
|
|
|
|
_sn = context.read<SnNetworkProvider>();
|
|
|
|
_home = context.read<HomeWidgetProvider>();
|
2024-12-20 17:58:49 +00:00
|
|
|
_config = context.read<ConfigProvider>();
|
2024-12-14 10:18:13 +00:00
|
|
|
}
|
2024-11-09 10:28:45 +00:00
|
|
|
|
2024-11-23 11:54:38 +00:00
|
|
|
Future<String?> get atk async {
|
|
|
|
final prefs = await SharedPreferences.getInstance();
|
|
|
|
return prefs.getString(kAtkStoreKey);
|
|
|
|
}
|
2024-11-14 16:24:46 +00:00
|
|
|
|
2024-12-13 17:32:13 +00:00
|
|
|
Future<void> initialize() async {
|
2024-12-20 17:58:49 +00:00
|
|
|
final value = _config.prefs.getString(kAtkStoreKey);
|
2024-12-13 17:32:13 +00:00
|
|
|
isAuthorized = value != null;
|
|
|
|
notifyListeners();
|
|
|
|
refreshUser().then((value) {
|
|
|
|
if (value != null) {
|
|
|
|
log('Logged in as @${value.name}');
|
2024-12-14 10:18:13 +00:00
|
|
|
_home.saveWidgetData('user', value.toJson());
|
2024-12-13 17:32:13 +00:00
|
|
|
}
|
2024-11-09 10:28:45 +00:00
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
Future<SnAccount?> refreshUser() async {
|
2024-11-09 11:32:21 +00:00
|
|
|
final resp = await _sn.client.get('/cgi/id/users/me');
|
2024-11-09 10:28:45 +00:00
|
|
|
final out = SnAccount.fromJson(resp.data);
|
|
|
|
|
2024-11-09 13:47:40 +00:00
|
|
|
isAuthorized = true;
|
2024-11-09 10:28:45 +00:00
|
|
|
user = out;
|
|
|
|
notifyListeners();
|
|
|
|
|
|
|
|
return out;
|
|
|
|
}
|
2024-11-09 11:32:21 +00:00
|
|
|
|
|
|
|
void logoutUser() async {
|
2024-11-23 11:54:38 +00:00
|
|
|
_sn.clearTokenPair();
|
2024-11-09 11:32:21 +00:00
|
|
|
isAuthorized = false;
|
|
|
|
user = null;
|
|
|
|
notifyListeners();
|
|
|
|
}
|
2024-11-09 10:28:45 +00:00
|
|
|
}
|