import 'dart:convert'; import 'dart:io'; import 'dart:typed_data'; import 'package:dio/dio.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_styled_toast/flutter_styled_toast.dart'; import 'package:path_provider/path_provider.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'Entities.dart'; const api = "http://api.ignatz.xyz"; final method = Method._(); class Method { Method._(); var dio = Dio(); var options = Options(); Future home() async { try { final res = await dio.get("$api/home"); if (res.statusCode == HttpStatus.ok) { var data = jsonDecode(res.toString()); final uid = data["uid"]; if (await setUID(uid)) return uid; } } on Exception catch(e) { debugPrint("home 网络错误"); // debugPrint(e.toString()); return 0; } return 0; } Future login() async { final username = await getUsername(); final password = await getPassword(); debugPrint('login: username=$username password=$password'); if (username.isEmpty || password.isEmpty) return false; try { final res = await dio.post("$api/token", data: { "username": username, "password": password}); if (res.statusCode == HttpStatus.ok) { var data = jsonDecode(res.toString()); final token = data['token']; dio = Dio(BaseOptions(headers: { HttpHeaders.authorizationHeader: "Bearer $token" })); debugPrint('token=$token'); setToken(token); return true; } } on Exception catch(e) { debugPrint("login 网络错误"); return false; } return false; } Future> getFriends({int depth=0}) async { try { final res = await dio.get('$api/friends'); switch (res.statusCode) { case HttpStatus.ok: var data = jsonDecode(res.toString()); List friends = []; data["friends"].forEach((v) => friends.add(UserProfile.fromJson(v))); debugPrint(friends.toString()); return friends; case HttpStatus.unauthorized: if (depth < 3) { login(); return getFriends(depth: depth+1); } } } on Exception catch (e) { debugPrint("网络错误"); return []; } return []; } Future getUsername() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString("username") ?? ""; } Future getPassword() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString("password") ?? ""; } Future setUsername(String username) async { final prefs = await SharedPreferences.getInstance(); return prefs.setString("username", username); } Future setUID(int uid) async { final prefs = await SharedPreferences.getInstance(); return prefs.setInt("uid", uid); } Future getUID() async { final prefs = await SharedPreferences.getInstance(); int uid = prefs.getInt("uid") ?? 0; if (uid == 0) uid = await home(); print('uid=$uid'); return uid; } Future setPassword(String password) async { final prefs = await SharedPreferences.getInstance(); return prefs.setString("password", password); } Future clearPassword() async { final prefs = await SharedPreferences.getInstance(); return prefs.remove("password"); } Future clearToken() async { final prefs = await SharedPreferences.getInstance(); return prefs.remove("token"); } Future clearUID() async { final prefs = await SharedPreferences.getInstance(); return prefs.remove("uid"); } Future getToken() async { final prefs = await SharedPreferences.getInstance(); return prefs.getString("token") ?? ""; } Future setToken(String token) async { final prefs = await SharedPreferences.getInstance(); return prefs.setString("token", token); } Future preLogin() async { if (await home() > 0) { return true; } return login(); } logout() async { await method.clearToken(); await method.clearPassword(); await method.clearUID(); dio = Dio(); } Future getProfile([String? name]) async { name = name ?? await getUsername(); debugPrint("get profile of $name"); final res = await dio.get("$api/profile/$name"); if (res.statusCode == HttpStatus.ok) { final data = jsonDecode(res.toString()); final profile = UserProfile.fromJson(data["profile"]); debugPrint("profile get, name=${profile.name}"); return profile; } return null; } Future download( String url, String savePath, { Map? queryParams, CancelToken? cancelToken, dynamic data, Options? options, void Function(int, int)? onReceiveProgress, }) async { try { return await dio.download( url, savePath, queryParameters: queryParams, cancelToken: cancelToken, onReceiveProgress: onReceiveProgress, ); } on DioError catch (e) { print(e); if (CancelToken.isCancel(e)) { EasyLoading.showInfo('下载已取消!'); } else { if (e.response != null) { // _handleErrorResponse(e.response); } else { EasyLoading.showError(e.message); } } } on Exception catch (e) { EasyLoading.showError(e.toString()); } } Future downloadImage(String path, String fileServer) async { Directory dir = await getApplicationDocumentsDirectory(); String dirPath = dir.path; final savePath = "$dirPath/$path"; File file = File(savePath); debugPrint("savePath=$savePath"); if (file.existsSync()) return savePath; try { final res = await dio.download('$fileServer/$path', savePath); debugPrint(res.toString()); } on Exception catch (e) { debugPrint("文件下载失败"); return null; } return savePath; } Future updateAvatar(Uint8List buff, String suf) async { final file = MultipartFile.fromBytes(buff, filename: 'avatar$suf'); final res = await dio.post("$api/avatar", data: FormData.fromMap({"file": file})); if (res.statusCode == HttpStatus.ok) { return true; } return false; } }