You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

218 lines
6.2 KiB

import 'dart:io';
import 'dart:typed_data';
3 years ago
import 'package:bot_toast/bot_toast.dart';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart' hide Response, FormData, MultipartFile;
import 'package:power_logger/power_logger.dart';
import 'package:provider/provider.dart';
import 'package:aku_new_community/constants/api.dart';
import 'package:aku_new_community/constants/sars_api.dart';
import 'package:aku_new_community/pages/sign/login/login_page.dart';
3 years ago
import 'package:aku_new_community/provider/user_provider.dart';
import 'package:aku_new_community/utils/developer_util.dart';
import 'package:aku_new_community/utils/network/base_list_model.dart';
import 'package:aku_new_community/utils/network/base_model.dart';
4 years ago
class NetUtil {
4 years ago
Dio? _dio;
4 years ago
static final NetUtil _netUtil = NetUtil._internal();
factory NetUtil() => _netUtil;
4 years ago
Dio? get dio => _dio;
4 years ago
NetUtil._internal() {
BaseOptions options = BaseOptions(
baseUrl: SARSAPI.baseURL,
connectTimeout: SARSAPI.networkTimeOut,
receiveTimeout: SARSAPI.networkTimeOut,
sendTimeout: SARSAPI.networkTimeOut,
4 years ago
headers: {},
);
if (_dio == null) _dio = Dio(options);
4 years ago
dio!.interceptors.add(InterceptorsWrapper(
4 years ago
onRequest: (options, handler) async => handler.next(options),
onResponse: (response, handler) async {
LoggerData.addData(response);
4 years ago
return handler.next(response);
},
4 years ago
onError: (error, handler) async {
_parseErr(error);
4 years ago
return handler.next(error);
},
));
4 years ago
}
4 years ago
///call auth after login
auth(String token) {
_dio!.options.headers['app-login-token'] = token;
4 years ago
}
static String getDate(DateTime date) =>
DateUtil.formatDate(date, format: 'yyyy-MM-dd HH:mm:ss');
/// ## alias of Dio().get
///
/// GET method
4 years ago
Future<BaseModel> get(
String path, {
4 years ago
Map<String, dynamic>? params,
bool showMessage = false,
4 years ago
}) async {
var _baseModel;
4 years ago
try {
4 years ago
Response res = await _dio!.get(path, queryParameters: params);
if (!res.data['success']) {
3 years ago
_baseModel = BaseModel.error(
message: res.data['msg'],
success: res.data['success'],
data: res.data['data'],
code: res.data['code']);
_parseRequestError(_baseModel, showMessage: showMessage);
} else {
_baseModel = BaseModel.fromJson(res.data);
}
} on DioError catch (e) {
_parseErr(e);
_baseModel = BaseModel(code: 0, msg: '未知错误', success: false, data: null);
}
return _baseModel;
}
/// ## alias of Dio().post
///
/// POST method
///
/// only work with JSON.
Future<BaseModel> post(
String path, {
4 years ago
Map<String, dynamic>? params,
bool showMessage = false,
}) async {
var _baseModel;
try {
4 years ago
Response res = await _dio!.post(path, data: params);
if (!res.data['success']) {
3 years ago
_baseModel = BaseModel.error(
message: res.data['msg'],
success: res.data['success'],
data: res.data['data'],
code: res.data['code']);
_parseRequestError(_baseModel, showMessage: showMessage);
} else {
_baseModel = BaseModel.fromJson(res.data);
}
4 years ago
} on DioError catch (e) {
_parseErr(e);
_baseModel = BaseModel(code: 0, msg: '未知错误', success: false, data: null);
4 years ago
}
return _baseModel;
4 years ago
}
Future<BaseListModel> getList(
String path, {
4 years ago
Map<String, dynamic>? params,
}) async {
try {
4 years ago
Response res = await _dio!.get(path, queryParameters: params);
3 years ago
var base = BaseModel.fromJson(res.data);
if (base.success) {
BaseListModel baseListModel = BaseListModel.fromJson(base.data);
return baseListModel;
} else {
return BaseListModel.err();
}
} on DioError catch (e) {
_parseErr(e);
}
return BaseListModel.err();
}
3 years ago
Future<BaseModel> upload(String path, File file) async {
try {
4 years ago
Response res = await _dio!.post(path,
data: FormData.fromMap({
'file': await MultipartFile.fromFile(file.path),
}));
3 years ago
BaseModel baseListModel = BaseModel.fromJson(res.data);
return baseListModel;
} on DioError catch (e) {
print(e);
}
3 years ago
return BaseModel.error();
}
3 years ago
Future<BaseModel> uploadUnit8List(String path, Uint8List bytes) async {
try {
Response res = await _dio!.post(path,
data: FormData.fromMap({
3 years ago
'file':
await MultipartFile.fromBytes(bytes, filename: 'signName.png'),
}));
3 years ago
BaseModel baseListModel = BaseModel.fromJson(res.data);
return baseListModel;
} on DioError catch (e) {
print(e);
}
3 years ago
return BaseModel.error();
}
Future<List<String>> uploadFiles(List<File> files, String api) async {
List<String> urls = [];
if (files.isEmpty) {
return [];
} else {
for (var item in files) {
3 years ago
BaseModel model = await NetUtil().upload(api, item);
if (model.data != null) {
urls.add(model.data as String);
}
}
}
return urls;
}
4 years ago
_parseErr(DioError err) {
4 years ago
LoggerData.addData(err);
4 years ago
_makeToast(String message) {
4 years ago
if (DeveloperUtil.dev)
BotToast.showText(text: '$message\_${err.response?.statusCode ?? ''}');
else
BotToast.showText(text: '网络出现问题');
4 years ago
}
switch (err.type) {
4 years ago
case DioErrorType.connectTimeout:
case DioErrorType.sendTimeout:
case DioErrorType.receiveTimeout:
4 years ago
_makeToast('连接超时');
break;
4 years ago
case DioErrorType.response:
4 years ago
_makeToast('服务器出错');
break;
4 years ago
case DioErrorType.cancel:
4 years ago
break;
4 years ago
case DioErrorType.other:
4 years ago
_makeToast('未知错误');
break;
}
}
_parseRequestError(BaseModel model, {bool showMessage = false}) {
4 years ago
final userProvider = Provider.of<UserProvider>(Get.context!, listen: false);
if (!model.success &&
(model.code == 10010 || model.msg == '登录失效,请重新登录') &&
userProvider.isLogin) {
userProvider.logout();
Get.offAll(() => LoginPage());
4 years ago
}
if (!model.success && showMessage) {
BotToast.showText(text: model.msg);
}
4 years ago
}
}