100 lines
2.6 KiB
Dart
100 lines
2.6 KiB
Dart
import 'dart:io';
|
|
|
|
import 'package:didvan/models/enums.dart';
|
|
import 'package:didvan/models/user.dart';
|
|
import 'package:didvan/models/view/alert_data.dart';
|
|
import 'package:didvan/providers/core_provider.dart';
|
|
import 'package:didvan/services/network/request.dart';
|
|
import 'package:didvan/services/network/request_helper.dart';
|
|
import 'package:didvan/utils/action_sheet.dart';
|
|
import 'package:hive/hive.dart';
|
|
|
|
class UserProvider extends CoreProvier {
|
|
late User user;
|
|
Future<String?> setAndGetToken({String? token}) async {
|
|
final box = await Hive.openBox('autherization');
|
|
if (token != null) {
|
|
await box.put('token', token);
|
|
} else {
|
|
return box.toMap()['token'];
|
|
}
|
|
}
|
|
|
|
Future<void> getUserInfo() async {
|
|
final RequestService service = RequestService(RequestHelper.userInfo);
|
|
await service.httpGet();
|
|
if (service.isSuccess) {
|
|
user = User.fromJson(service.result['user']);
|
|
return;
|
|
}
|
|
throw 'Getting user from API failed!';
|
|
}
|
|
|
|
Future<bool> setProfilePhoto(File file) async {
|
|
appState = AppState.isolatedBusy;
|
|
final RequestService service =
|
|
RequestService(RequestHelper.updateUserProfile);
|
|
await service.multipart(file);
|
|
if (service.isSuccess) {
|
|
user =
|
|
user.copyWith(photo: RequestHelper.baseUrl + service.result['photo']);
|
|
appState = AppState.idle;
|
|
return true;
|
|
}
|
|
appState = AppState.failed;
|
|
return false;
|
|
}
|
|
|
|
Future<bool?> checkUsername(String username) async {
|
|
if (user.username == username) return true;
|
|
final RequestService service = RequestService(
|
|
RequestHelper.checkUsername,
|
|
body: {'username': username},
|
|
);
|
|
await service.post();
|
|
if (service.isSuccess) {
|
|
return service.result['available'];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
Future<void> editProfile(
|
|
String fullName,
|
|
String? username,
|
|
String? email,
|
|
) async {
|
|
appState = AppState.isolatedBusy;
|
|
final service = RequestService(
|
|
RequestHelper.updateProfile,
|
|
body: {
|
|
'fullName': fullName,
|
|
'email': email,
|
|
'username': username,
|
|
},
|
|
);
|
|
await service.put();
|
|
if (service.isSuccess) {
|
|
user = user.copyWith(
|
|
fullName: fullName,
|
|
email: email,
|
|
username: username,
|
|
);
|
|
appState = AppState.idle;
|
|
ActionSheetUtils.pop();
|
|
ActionSheetUtils.showAlert(
|
|
AlertData(
|
|
message: 'پروفایل با موفقیت ویرایش شد',
|
|
aLertType: ALertType.success,
|
|
),
|
|
);
|
|
return;
|
|
}
|
|
appState = AppState.idle;
|
|
ActionSheetUtils.showAlert(
|
|
AlertData(
|
|
message: service.errorMessage,
|
|
),
|
|
);
|
|
}
|
|
}
|